code
stringlengths 2
1.05M
|
---|
/**
* @module map-tile-scraper
*/
/**
* @namespace Typedefs
*/
/**
* @typedef {Object} CoordinatesObjectType
* @property {Number} lat - latitude degrees(must be between -90 and 90 degrees)
* @property {Number} lng - longitude degrees (must be between -180 and 180)
* @property {Number} sqKms - the number of square kilometers in the radius
* calculation. Must be positive and less then 509e6 (surface area of earth)
* @memberOf Typedefs
*/
/**
* @typedef {Object} ZoomObjectType
* @property {Number} max - maximum zoom level (zoomed in).
* @property {Number} min - minimum zoom level (zoomed out)
* @memberOf Typedefs
*/
/**
* @typedef {Object} OptionsObjectType
* @property {String} baseUrl - Base URL of the map tile server
* @property {String} rootDir - Root path of where the images will be stored
* @property {String} mapSource - Map source selectors that serve as an easier
* method of providing known good baseUrls for map tile servers
* @property {String} mapSourceSuffix - File extensions of each map tile on the server
* @property {CoordinatesObjectType} inputCoordinates - Lattitude/longitude coordinates
* to base the area calculation on
* @property {ZoomObjectType} zoom - Max and min zoom levels
* @property {Number} maxDelay - Provides a way to throttle the requests
* @property {Boolean} xBeforeY - A Switch that provides a way to flip x and y
* coordinates since some map servers do it that way
* @memberOf Typedefs
*/
/**
* Constructor for module.
* @param {OptionsType} options - input options. can also set via setOptions() method
*/
module.exports = function(options){
var defaults = require('./map-tile-downloader-defaults.js');
var override = require('json-override');
var newOptions = override(defaults.defaults, options, true);
var tileCount = 0;
/**
* Main execution function. Once all the parameters are set, this function starts
* the process of calculating the square area and asynchronously downloading the tiles
* in randomish order.
* @param {Function} callback - This function is only when errors occur with error as
* the first argument
*/
function run(callback){
var d = require('domain').create();
d.on('error', function(err){
callback(err);
});
d.run(function(){
fs = require('fs');
var inputValid = checkBounds(newOptions.inputCoordinates);
if (inputValid){
var vertices = calcVertices(newOptions.inputCoordinates);
var numTiles = 0;
try {fs.mkdirSync(newOptions.rootDir, 0777);}
catch(err){
if (err.code !== 'EEXIST') callback(err);
}
console.log('getting resources from: ' + newOptions.baseUrl);
// for each zoom level
for (var zoomIdx=newOptions.zoom.min; zoomIdx<newOptions.zoom.max; zoomIdx++){
// calculate min and max tile values
var minAndMaxValues = calcMinAndMaxValues(vertices, zoomIdx);
zoomFilePath = newOptions.rootDir+zoomIdx.toString() + '/';
try{fs.mkdirSync(zoomFilePath, 0777);}
catch (err){
if (err.code !== 'EEXIST') callback(err);
}
for (var yIdx=minAndMaxValues.yMin; yIdx<=minAndMaxValues.yMax; yIdx++){
for (var xIdx=minAndMaxValues.xMin; xIdx<=minAndMaxValues.xMax; xIdx++){
var delay = Math.random()*newOptions.maxDelay;
setTimeout(getAndStoreTile(newOptions.baseUrl, zoomIdx, xIdx, yIdx, newOptions.rootDir), delay);
numTiles++;
}
}
}
console.log('total number of tiles: ', numTiles);
} else {
callback(new Error('Invalid input coordinates'));
}
});
}
/* Diagram of Vertices
(xMin, yMax) (xMax, yMax)
+-----------------+
| |
| |
| |
| * |
| (Center) |
| |
| |
+-----------------+
(xMin, yMin) (xMax, yMin)
*/
/* Function Declarations */
function mkdirErr(err){
if (err){
if (err.code !== 'EEXIST'){
throw err;
}
}
}
function getAndStoreTile(baseUrl, zoom, x, y, rootDir){
return function(){
var http = require('http-get');
var fullUrl = buildUrl(baseUrl, zoom, x, y);
var fullPath = buildPath(rootDir, zoom, x, y);
var dirPath = (!newOptions.xBeforeY) ?
buildDirPath(rootDir, zoom, y) :
buildDirPath(rootDir, zoom, x);
fullUrl += newOptions.mapSourceSuffix;
try {fs.mkdirSync(dirPath, 0777);}
catch(err){
if (err.code !== 'EEXIST') throw err;
}
http.get(fullUrl, fullPath, function(err){
if (err) throw err;
tileCount += 1;
});
};
}
function buildDirPath(rootDir, zoom, secondParam){
return (rootDir + zoom.toString() + '/' + secondParam.toString() + '/');
}
function buildPath(rootDir, zoom, x, y){
return (rootDir + buildSuffixPath(zoom, x, y));
}
function buildUrl(baseUrl, zoom, x, y){
return (baseUrl + buildSuffixPath(zoom, x, y));
}
function buildSuffixPath(zoom, x, y){
var rtnString;
if (!newOptions.xBeforeY){
rtnString = zoom.toString() + '/' + y.toString() +
'/' + x.toString();
}
else if (newOptions.xBeforeY){
rtnString = zoom.toString() + '/' + x.toString() +
'/' + y.toString();
}
return (rtnString);
}
function calcMinAndMaxValues(vertices, zoom){
var minAndMaxObj = {};
/* Not sure why yMin and yMax are transposed on the tile coordinate system */
minAndMaxObj.yMax = convLat2YTile(vertices.lowerLeft.lat, zoom);
minAndMaxObj.xMin = convLon2XTile(vertices.lowerLeft.lon, zoom);
minAndMaxObj.yMin = convLat2YTile(vertices.upperRight.lat, zoom);
minAndMaxObj.xMax = convLon2XTile(vertices.upperRight.lon, zoom);
return minAndMaxObj;
}
function calcVertices(result){
var vertices = {};
var radius = calcRadius(result.sqKms);
var distance = radius * Math.SQRT2;
var centerRadLat = convDecToRad(result.lat);
var centerRadLon = convDecToRad(result.lng);
vertices.upperRight = calcEndPoint(centerRadLat, centerRadLon,
distance, Math.PI/4);
vertices.lowerRight = calcEndPoint(centerRadLat, centerRadLon,
distance, 3*Math.PI/4);
vertices.lowerLeft = calcEndPoint(centerRadLat, centerRadLon,
distance, 5*Math.PI/4);
vertices.upperLeft = calcEndPoint(centerRadLat, centerRadLon,
distance, 7*Math.PI/4);
//printVertices(vertices);
return vertices;
}
function calcRadius(sqKms){
var radius = Math.sqrt(sqKms);
return radius;
}
function calcEndPoint(startX, startY, distance, bearing){
var d = distance;
var brng = bearing;
var R = 6371; // earth's radius in km
var endPoint = {};
endPoint.lat = Math.asin( Math.sin(startX)*Math.cos(d/R) +
Math.cos(startX)*Math.sin(d/R)*Math.cos(brng) );
endPoint.lon = startY + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(startX),
Math.cos(d/R)-Math.sin(startX)*Math.sin(endPoint.lat));
return endPoint;
}
function convLon2XTile(lon, zoom){
return (Math.floor(((lon*180/Math.PI)+180)/360*Math.pow(2,zoom)));
}
function convLat2YTile(lat, zoom){
return (Math.floor((1-Math.log(Math.tan(lat) +
1/Math.cos(lat))/Math.PI)/2 *Math.pow(2,zoom)));
}
function convDecToRad(dec){
return (dec*Math.PI/180);
}
function convRadToDec(rad){
return (rad*180/Math.PI);
}
function convRadToDecCoordinates(coordinates){
decCoordinates = {};
decCoordinates.lat = convRadToDec(coordinates.lat);
decCoordinates.lon = convRadToDec(coordinates.lon);
return decCoordinates;
}
function checkBounds(result) {
if (result.lat > 90 || result.lat < -90){
console.log('latitude should be less than 90 and greater than' +
'-90');
return false;
}
if (result.lng > 180 || result.lng < -180){
console.log('longitude should be less than 180 and greater than' +
'-180');
return false;
}
var SURFACE_AREA_OF_EARTH = 509000000;
if (result.sqKms > SURFACE_AREA_OF_EARTH || result.sqKms < 0){
console.log('sqKms should be greater than 0 and less than 10');
return false;
}
return true;
}
function printVertices(vertices){
console.log('Upper-right vertex: ', convRadToDecCoordinates(vertices.upperRight));
console.log('Lower-right vertex: ', convRadToDecCoordinates(vertices.lowerRight));
console.log('Lower-left vertex: ', convRadToDecCoordinates(vertices.lowerLeft));
console.log('Upper-left vertex: ', convRadToDecCoordinates(vertices.upperLeft));
}
function isDefinedNotNull(inputVar){
var valid = false;
if (typeof inputVar !== 'undefined' && inputVar !== null){
valid = true;
}
return valid;
}
function validateInputString(inputString){
var inputValid = false;
if (isDefinedNotNull(inputString) &&
typeof inputString === 'string'){
inputValid = true;
}
return inputValid;
}
function validateZoom(inputZoom){
var validParams = false;
var MAX_ZOOM = 19;
var MIN_ZOOM = 0;
if (isDefinedNotNull(inputZoom)){
if (isDefinedNotNull(inputZoom.max) && isDefinedNotNull(inputZoom.min) &&
inputZoom.max > inputZoom.min && inputZoom.max <= MAX_ZOOM && inputZoom.max > MIN_ZOOM &&
inputZoom.min < MAX_ZOOM && inputZoom.min > MIN_ZOOM){
validParams = true;
}
}
if (!validParams){
throw new Error('Invalid input zoom parameters (0-19), max greater than min');
}
return validParams;
}
/**
* If the input coordinates were not set in the constructor, then the user will
* use this method to do so. It also provides a way to dynamically set the
* coordinates without setting the other properties. The parameters basically
* depict a square with sqKms equaling half the length of one side.
* @param {Number} lat - Latitude
* @param {Number} lng - Longitude
* @param {Number} sqKms - The radius in square kilometers
*/
function setInputCoordinates(lat, lng, sqKms){
if (isDefinedNotNull(lat) && isDefinedNotNull(lng) &&
isDefinedNotNull(sqKms)){
newOptions.inputCoordinates.lat = lat;
newOptions.inputCoordinates.lng = lng;
newOptions.inputCoordinates.sqKms = sqKms;
}
}
/**
* Convenience method that figures out the advanced properties to generate
* the correct URLs for downloading.
* @param {String} inputMapSource - Input map source. Acceptable values are
* 'mapQuestAerial', 'mapQuestOsm' and 'arcGis'
*/
function setUrlByMapProvider(inputMapSource){
var inputValid = false;
if (validateInputString(inputMapSource)){
newOptions.mapSource = inputMapSource;
if (inputMapSource == 'mapQuestAerial' || inputMapSource == 'mapQuestOsm'){
newOptions.baseUrl = (inputMapSource == 'mapQuestAerial') ?
defaults.providerUrls.mapQuestAerial :
defaults.providerUrls.mapQuestOsm;
newOptions.mapSourceSuffix = '.jpg';
newOptions.xBeforeY = true;
inputValid = true;
}
else if (inputMapSource == 'arcGis'){
newOptions.baseUrl = defaults.providerUrls.arcGis;
newOptions.mapSourceSuffix = '';
newOptions.xBeforeY = false;
inputValid = true;
}
}
if (!inputValid){
throw new Error("Invalid host name (i.e., 'mapQuestAerial','mapQuestOsm)");
}
}
return {
run: run,
setInputCoordinates: setInputCoordinates,
/**
* Helper method used mainly for testing
* @returns {CoordinatesObjectType}
* @public
*/
getInputCoordinates: function(){
return newOptions.inputCoordinates;
},
/**
* Set the options for this module. They will override only the properties
* that are different
* @returns {CoordinatesObjectType}
*/
setOptions: function(inputOptions){
newOptions = override(newOptions, inputOptions, true);
},
/**
* Helper method used mainly for testing
* @returns {OptionsObjectType}
*/
getOptions: function(){
return newOptions;
},
setUrlByMapProvider: setUrlByMapProvider
};
};
|
/**
* @fileoverview This module provides the pure data object Document
*/
/**
* Create new document instance.
*
* @param {string} type The document type. E.g. 'xml' or 'json'
* @param {string} [name] The file name.
* @param {object} data A reference to the underlying document, the DOM.
* @param {object} [tree] The root node of the document tree. Use an instance
* of :js:class:`Node`.
* @param {string} [src] The serialized version of this document, e.g. the
* XML markup code.
* @param {object} [valueindex] The object necessary to lookup node values.
* E.g. an instance of :js:class:`NodeHashIndex`.
* @param {object} [treevalueindex] The object necessary to lookup the
* value of a whole subtree. E.g. an instance of
* :js:class:`TreeHashIndex`.
* @param {object} [nodeindex] The object necessary to resolve nodes relative
* to other nodes when generating and verifying context. Typically this
* should be an instance of :js:class:`DocumentOrderIndex`.
*
* @constructor
*/
function Document(type, name, data, tree, src, valueindex, treevalueindex, nodeindex) {
/**
* The document type. E.g. 'xml' or 'json'
*/
this.type = type;
/**
* The file name
*/
this.name = name;
/**
* A reference to the underlying document, e.g. the DOMDocument object.
*/
this.data = data;
/**
* The root node of the document tree.
*/
this.tree = tree;
/**
* The serialized version of this document.
*/
this.src = src;
/**
* An object used to lookup node values.
*/
this.valueindex = valueindex;
/**
* An object used to lookup the combined values of all nodes in a subtree.
*/
this.treevalueindex = treevalueindex;
/**
* An object used to lookup nodes relative to other nodes along a specified
* axis. Typically in document order.
*/
this.nodeindex = nodeindex;
}
exports.Document = Document;
|
/*
* jqCoolGallery
*
* Version: 1.8
* Requires jQuery 1.5+
* Docs: http://www.jqcoolgallery.com
*
* (c) copyright 2011-2012, Redtopia, LLC (http://www.redtopia.com). All rights reserved.
*
* Licensed under the GNU General Public License, version 3 (GPL-3.0)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
(function($){
"use strict";
var jqCoolGallery = function (element, options) {
/*
PRIVATE METHODS
*/
// PRIVATE: debug ()
var debug = function (msg) {
if (!$opts.debug) {
return;
}
if (window.console) {
var type = typeof (msg);
if (type === 'string') {
if (window.console.log) {
window.console.log ('jqCoolGallery: ' + msg);
}
}
else if (type === 'object') {
if (window.console.dir) {
window.console.dir (msg);
}
else if (window.console.log) {
window.console.log ('jqCoolGallery: ' + msg);
}
}
}
};
// PRIVATE: scaleRect ()
var scaleRect = function (rect, maxWidth, maxHeight) {
var rWidth = rect.width,
rHeight = rect.height,
deltaX = 0,
deltaY = 0,
percentDelta = 0,
ix;
for (ix = 1; ix <= 2; ix++) {
if (maxWidth > 0) {
deltaX = rWidth - maxWidth;
}
else {
deltaX = 0;
}
if (maxHeight > 0) {
deltaY = rHeight - maxHeight;
}
else {
deltaY = 0;
}
if (deltaX <= 0 && deltaY <= 0) {
break;
}
else {
if (deltaX >= deltaY) { // more tall than wide
percentDelta = Math.round ((100 * deltaX) / rWidth);
deltaY = Math.round ((rHeight * percentDelta) / 100);
}
else {
percentDelta = Math.round ((100 * deltaY) / rHeight);
deltaX = Math.round ((rWidth * percentDelta) / 100);
}
rWidth = rWidth - deltaX;
rHeight = rHeight - deltaY;
}
}
//debug ('scaleRect (), maxWidth: ' + maxWidth + ', maxHeight: ' + maxHeight + ', original: ' + rect.width + ' x ' + rect.height + ', scaled: ' + rWidth + ' x ' + rHeight);
return ({width: rWidth, height: rHeight});
}; // scaleRect ()
var showTooltip = function (text, e, side) {
$($ttContent).html (text);
moveTooltip (e, null, side);
};
var moveTooltip = function (e, text, side) {
if (text) {
$($ttContent).html (text);
}
var top = e.pageY - $($tooltip).outerHeight() - 5,
left = e.pageX - $($tooltip).outerWidth();
if (side === 'right') {
left = e.pageX - 10;
}
$($tooltip).css ({top: top, left: left});
$($tooltip).stop(true).fadeTo (200, 0.8, function () {
$($tooltip).fadeTo (2000, 0);
});
};
var hideTooltip = function (e, side) {
var top = e.pageY - $($tooltip).outerHeight() - 5,
left = e.pageX - $($tooltip).outerWidth();
if (side === 'right') {
left = e.pageX - 10;
}
$($tooltip).css ({top: top, left: left});
$($tooltip).stop(true).fadeTo (10, 0, function () {
$($tooltip).css({top: -1000, left: -1000});
});
};
var doPlay = function () {
$this.nextImage ();
};
var play = function () {
if ($playMode === 1) {
return;
}
debug ('playing');
$playMode = 1;
$($playCtl).addClass ('jqcg-ctl-pause');
if ($ixCurrentGallery < 0) {
showGallery (0);
}
$playInterval = setInterval (doPlay, $opts.playSpeed);
};
var stop = function () {
if ($playMode === 0) {
return;
}
debug ('stopping');
$playMode = 0;
$($playCtl).removeClass ('jqcg-ctl-pause');
clearInterval ($playInterval);
$playInterval = null;
};
// PRIVATE: loadImage ()
var loadImage = function (img, fnSuccess, fnFail) {
if (img.complete) {
//debug ('loadImage: [' + $(img).attr ('src') + '], loaded: [true], width: ' + $(img).width() + ' height: ' + $(img).height());
return (fnSuccess (img));
}
$(img).error (function () {
//debug ('image failed to load: [' + $(this).attr ('src') + ']');
$(this).unbind ('load'); // prevent the load function from being called again
return (null);
});
$(img).load (function () {
//debug ('loadImage: [' + $(this).attr ('src') + '], loaded: [false], width: ' +$(this).width() + ' height: ' + $(this).height());
$(img).unbind ('load');
return (fnSuccess ($(this)));
});
$(img).trigger ('load');
//return (callback (img));
};
// PRIVATE: addThumb ()
var addThumb = function (container, src, thWidth, thHeight, ixThumb) {
var rect = scaleRect ({width:thWidth, height:thHeight}, $opts.thumbWidth, $opts.thumbHeight),
liWidth = $opts.thumbWidth,
liHeight = $opts.thumbHeight,
topPadding = 0,
marginRight = 0,
marginBottom = 0,
helperRect,
thumb,
li = $('<li></li>').appendTo (container);
debug ('adding thumb: ' + src + ' [' + thWidth + ',' + thHeight + '], scaled to: [' + rect.width + ',' + rect.height + ']');
topPadding = Math.floor ((liHeight - rect.height) / 2);
helperRect = scaleRect ({width:thWidth, height:thHeight}, $opts.thumbHelperMaxWidth, $opts.thumbHelperMaxHeight);
if ($opts.thumbStyle === 'grid') {
marginBottom = $opts.thumbMargin;
if ((ixThumb+1) % $ctThumbsPerRow !== 0) {
marginRight = $opts.thumbMargin;
}
}
else {
switch ($opts.thumbLocation) {
case 'top':
case 'bottom':
marginRight = $opts.thumbMargin;
break;
case 'left':
case 'right':
marginBottom = $opts.thumbMargin;
break;
}
}
$(li).css ({
width: liWidth + 'px',
height: liHeight + 'px',
padding: $opts.thumbPadding + 'px',
borderWidth: $opts.thumbBorderWidth + 'px',
marginRight: marginRight + 'px',
marginBottom: marginBottom + 'px'
});
$(li).addClass ('jqcg-thumb-loading');
thumb = $('<img src="' + src + '" width="' + rect.width + '" height="' + rect.height + '" alt="" />').appendTo (li);
if (topPadding > 0) {
$(thumb).css ({paddingTop: topPadding + 'px'});
}
loadImage (thumb, function (imgThumb) {
//$(img).parent().css({backgroundImage:''});
$(li).removeClass ('jqcg-thumb-loading');
}, function (imgThumb) {
//$(img).parent().css({backgroundImage:'url(\'' + $opts.imagePath + $opts.urlErrorIcon + '\')'});
$(li).removeClass ('jqcg-thumb-loading');
$(li).addClass ('jqcg-thumb-error');
});
if ($opts.thumbStyle === 'list') {
if ($opts.thumbLocation === 'top' || $opts.thumbLocation === 'bottom') {
$(container).css ({width: (parseInt ($(container).css ('width'), 10) + $(li).outerWidth (true)) + 'px'});
}
else {
$(container).css ({height: (parseInt ($(container).css ('height'), 10) + $(li).outerHeight (true)) + 'px'});
}
}
$(li).hover (function (e) {
// hover over
$(this).addClass ('jqcg-thumb-hover');
if (!$opts.thumbHelper) {
return;
}
var width = $(thumb).outerWidth (),
height = $(thumb).outerHeight (),
offset = $(thumb).offset (),
liOffset = $(this).offset (),
thumbBarOffset = $($thumbBar).offset (),
thumbRight = ($(window).scrollLeft() + $(window).innerWidth())- (offset.left + width),
thumbBottom = ($(window).scrollTop() + $(window).innerHeight()) - (offset.top + height),
helperTop;
$($thumbHelperImg).attr ('src', src);
$($thumbHelperImg).css ({width: helperRect.width + 'px', height: helperRect.height + 'px'});
helperTop = (liOffset.top - $($thumbHelperDiv).outerHeight () - 5);
if ($opts.thumbStyle === 'list' && $opts.thumbLocation === 'top') {
helperTop = (liOffset.top + liHeight) + 5;
}
$($thumbHelperDiv).css ({
top: helperTop + 'px',
left: ((liOffset.left + (liWidth / 2)) - ($($thumbHelperDiv).outerWidth () / 2)) + 'px',
display:'block'
});
}, function () {
// hover out
$(this).removeClass ('jqcg-thumb-hover');
if (!$opts.thumbHelper) {
return;
}
$($thumbHelperImg).attr ('src', '');
$($thumbHelperDiv).css ({
display:'none'
});
});
$(li).click (function () {
var ix = $(this).index ();
stop ();
showImage (ix);
});
}; // addThumb()
// PRIVATE: forceImageReload ()
var forceImageReload = function (img) {
var newSrc = $(img).attr ('src') + '?x=' + Math.floor (Math.random()*100000);
$(img).attr ('src', newSrc);
};
// PRIVATE: addGalleryItem ()
var addGalleryItem = function (li, ix, thumbWidth, thumbHeight, gallery) {
debug ('adding gallery item: ' + ix);
// setup the gallery list item css
$(li).css ({display:'block', textAlign:$opts.imageAreaAlign, top:0, left:0, opacity:0, position:'absolute'});
// set the width and height for the item, if imageAreaWidth/height is specified in the settings
if (($opts).imageAreaWidth > 0) {
$(li).width (($opts).imageAreaWidth);
}
if (($opts).imageAreaHeight > 0) {
$(li).height (($opts).imageAreaHeight);
}
$(li).addClass ('jqcg-item-loading');
//$(li).css ({backgroundImage:'url(\'' + $opts.imagePath + $opts.urlLoader + '\')', backgroundRepeat:'no-repeat', backgroundPosition:'center center'});
$(li).find ('.caption').hide ();
// find the thumb list for the gallery
var galleryThumbs = $(gallery).children ('.jqcg-thumbs-list');
// get the image
var itemImage = $(li).children('img').first();
loadImage (itemImage, function (img) {
$(li).removeClass ('jqcg-item-loading');
var urlImage = $(img).attr ('src');
var imgWidth = $(img).width ();
var imgHeight = $(img).height ();
var rect = scaleRect ({width:imgWidth, height:imgHeight}, $opts.imageAreaWidth, $opts.imageAreaHeight);
$(img).width (rect.width);
$(img).height (rect.height);
debug ('loading image: ' + urlImage + ', width: ' + imgWidth + ', height: ' + imgHeight);
// add the thumbnail
var thWidth = thumbWidth;
var thHeight = thumbHeight;
var urlThumb = $(img).attr ('data-thumb');
if (typeof (urlThumb) === 'undefined') {
urlThumb = urlImage;
thWidth = imgWidth;
thHeight = imgHeight;
}
else {
var tmp = $(img).attr ('data-thumb-width');
if (typeof (tmp) !== 'undefined') {
thWidth = parseInt (tmp, 10);
}
tmp = $(img).attr ('data-thumb-height');
if (typeof (tmp) !== 'undefined') {
thHeight = parseInt (tmp, 10);
}
}
if (thWidth === -1 || thHeight === -1) {
urlThumb = urlImage;
thWidth = imgWidth;
thHeight = imgHeight;
}
debug ('using thumb: ' + urlThumb + ', width: ' + thWidth + ', height: ' + thHeight);
addThumb (galleryThumbs, urlThumb, thWidth, thHeight, ix);
});
}; // addGalleryItem ()
// PRIVATE: addGalleryItems ()
var addGalleryItems = function (gallery, galleryItems) {
// set the width/height for the list if it is specified in the settings
if (($opts).imageAreaWidth > 0) {
$(galleryItems).width (($opts).imageAreaWidth);
}
if (($opts).imageAreaHeight > 0) {
$(galleryItems).height (($opts).imageAreaHeight);
}
// hide the list
//$(galleryItems).hide ();
// set position to relative to support hover captions
$(galleryItems).css ('position', 'relative');
var thumbWidth = $opts.thumbImageWidth;
var thumbHeight = $opts.thumbImageHeight;
var tmp = $(galleryItems).attr ('data-thumb-width');
if (typeof (tmp) !== 'undefined') {
thumbWidth = parseInt (tmp, 10);
}
tmp = $(galleryItems).attr ('data-thumb-height');
if (typeof (tmp) !== 'undefined') {
thumbHeight = parseInt (tmp, 10);
}
// visit each item in the gallery itself
$(galleryItems).children('li').each (function (ix) {
addGalleryItem (this, ix, thumbWidth, thumbHeight, gallery);
});
}; // addGalleryItems ()
// PRIVATE: addGallery ()
var addGallery = function (thisGallery, ix) {
debug ('adding gallery: ' + ix);
$ctGalleries++;
$(thisGallery).width ($opts.galleryTileWidth);
$(thisGallery).height ($opts.galleryTileHeight);
$(thisGallery).attr ('data-gallery-ix', ix);
$(thisGallery).addClass ('jqcg-gallery-item');
$(thisGallery).addClass ('jqcg-preloader');
if ($opts.galleryColumnCount > 0) {
if ($ctGalleries % $opts.galleryColumnCount === 0) {
$(thisGallery).addClass ('jqcg-gallery-item-last');
}
}
// find the thumbnail for the gallery
var galleryThumb = $(thisGallery).children ('img');
if (!galleryThumb.length) {
galleryThumb = $(thisGallery).find ('a img'); // gallery thumb can be surrounded by a link
}
debug ('gallery thumb - found: ' + galleryThumb.length);
// setup thumbnail container
var galleryThumbs = $('<ul class="jqcg-thumbs-list"></ul>').appendTo (thisGallery);
if ($opts.thumbStyle === 'grid') {
$(galleryThumbs).css ({height: 'auto', width:$thumbListWidth+'px'});
}
else {
$(galleryThumbs).css ({height: $opts.thumbHeight + ($opts.thumbPadding * 2) + ($opts.thumbBorderWidth * 2) + 'px'});
}
$(galleryThumbs).hide ();
// Get the gallery caption
var htmlCaption = '';
var galleryCaption = $(thisGallery).children ('.caption');
if (galleryCaption.length) {
htmlCaption = $(galleryCaption).html ();
$(galleryCaption).remove ();
}
else {
// a .caption element is not found, create a caption from the title/desc
var galleryTitle = $(thisGallery).attr ('data-title');
var galleryDesc = $(thisGallery).attr ('data-desc');
if (galleryTitle && galleryTitle.length) {
htmlCaption = '<p class="jqcg-gallery-caption-title">' + galleryTitle + '</p>';
}
if (galleryDesc && galleryDesc.length) {
htmlCaption += '<p class="jqcg-gallery-caption-desc">' + galleryDesc + '</p>';
}
}
debug ('gallery caption: ' + htmlCaption);
if (htmlCaption.length && $opts.galleryHoverCaption) {
galleryCaption = $('<div class="jqcg-gallery-caption caption"><div class="jqcg-gallery-caption-content">' + htmlCaption + '</div></div>').appendTo (thisGallery);
}
loadImage (galleryThumb, function (img) {
debug ('loading gallery thumb: [' + $(img).attr ('src') + ']');
$(thisGallery).removeClass ('jqcg-preloader');
var captionWidth = $opts.galleryTileWidth;
$(img).attr ('jqcg-width', $opts.galleryTileWidth);
$(img).attr ('jqcg-height', $opts.galleryTileHeight);
$(img).css ('position', 'absolute');
var captionBottom = 0;
var captionLeft = 0;
if ($opts.galleryHoverExpand) {
captionWidth += ($opts.galleryHoverExpandPx * 2);
captionBottom = $opts.galleryHoverExpandPx * -1;
captionLeft = captionBottom;
}
$(galleryCaption).css({opacity:0, width:captionWidth+'px', position:'absolute', bottom:captionBottom, left:captionLeft, display:'block'});
}, function (img) {
debug ('FAILED gallery thumb: [' + $(img).attr ('src') + ']');
$(thisGallery).removeClass ('jqcg-preloader');
$(thisGallery).addClass ('jqcg-failed');
$(img).width (0);
$(img).height (0);
$(img).attr ('src', '');
var captionWidth = $opts.galleryTileWidth;
});
// get the gallery's items
var galleryItems = $(thisGallery).children ('ul.jqcg-viewer-slides');
addGalleryItems (thisGallery, galleryItems);
// add hover handler for each gallery
$(thisGallery).hover (function (e) {
//debug ('over: [' + $(this).attr ('data-gallery-ix') + ']');
$(this).addClass ('jqcg-gallery-hover');
if ($galleryTooltip && $galleryTooltip.length) {
showTooltip ($galleryTooltip, e);
}
if ($opts.galleryHoverExpand) {
//debug ('bigger');
var img = $(this).children ('img').first();
if (!img.length) {
img = $(this).find ('a img');
}
//debug ('found image: [' + img.length + ']');
var w = parseInt ($(img).attr ('jqcg-width'), 10) + ($opts.galleryHoverExpandPx * 2);
var h = parseInt ($(img).attr ('jqcg-height'), 10) + ($opts.galleryHoverExpandPx * 2);
$(img).css ({zIndex:1000});
var animateTo = {
top:'-' + $opts.galleryHoverExpandPx + 'px',
left:'-' + $opts.galleryHoverExpandPx + 'px',
width:w + 'px',
height:h + 'px'
};
$(img).addClass ("jqcg-gallery-hover-expand");
$(img).stop(true);
$(galleryCaption).stop();
$(img).animate(animateTo, $opts.animateInSpeed, function () {
if ($opts.galleryHoverCaption) {
$(galleryCaption).fadeTo($opts.animateInSpeed, 0.7);
}
});
}
else if ($opts.galleryHoverCaption) {
$(galleryCaption).stop().fadeTo($opts.animateInSpeed, 0.7);
}
}, function (e) {
//debug ('out: [' + $(this).attr ('data-gallery-ix') + ']');
$(this).removeClass ('jqcg-gallery-hover');
hideTooltip (e);
if ($opts.galleryHoverExpand) {
//debug ('smaller');
var img = $(this).children ('img').first();
if (!img.length) {
img = $(this).find ('a img');
}
var caption = $(this).children ('.jqcg-gallery-caption');
var w = $(img).attr ('jqcg-width');
var h = $(img).attr ('jqcg-height');
$(img).css ({zIndex:1});
var animateTo = {
marginTop: 0,
marginLeft: 0,
top:0,
left:0,
width: w + 'px',
height: h + 'px'
};
$(img).removeClass ("jqcg-gallery-hover-expand");
// stop all animations
$(img).stop(true);
$(galleryCaption).stop(true);
if ($opts.galleryHoverCaption) {
// fade out the caption
$(galleryCaption).fadeTo($opts.animateOutSpeed, 0, function () {
// when done, return thumb to original size
$(img).animate(animateTo, $opts.animateOutSpeed);
});
}
else {
$(img).animate(animateTo, $opts.animateOutSpeed);
}
}
else if ($opts.galleryHoverCaption) {
$(galleryCaption).stop().fadeTo($opts.animateOutSpeed, 0);
}
});
if ($galleryTooltip && $galleryTooltip.length) {
$(thisGallery).mousemove (function (e) {
moveTooltip (e, $galleryTooltip);
});
}
// add click handler
$(thisGallery).click (function () {
$(this).trigger ('mouseout');
var ixGallery = parseInt ($(this).attr ('data-gallery-ix'), 10);
var flShow = true;
if ($opts.fnGalleryClick !== null && !$opts.fnGalleryClick (ixGallery, this)) {
flShow = false;
}
if (flShow) {
showGallery (ixGallery);
}
});
// hide the gallery
$(galleryItems).hide ();
}; // addGallery ()
var showLoader = function () {
//$($loader).fadeTo (100, 1);
//$($element).css ({backgroundImage:'url(\'' + $opts.imagePath + $opts.urlLoader + '\')'});
var o = $($element).offset ();
var w = $($element).width ();
var h = $($element).height ();
var loaderTop = o.top + (h/2) - ($($loader).height()/2);
var loaderLeft = o.left + (w/2) - ($($loader).width()/2);
$($loader).css ({top: loaderTop, left: loaderLeft});
$($loader).show ();
};
var hideLoader = function () {
//$($element).css ({backgroundImage:''});
$($loader).hide ();
};
// PRIVATE: loadGallery ()
var loadGallery = function (url, gallery, ix, success) {
if ($opts.forceDemandReload) {
if (url.indexOf ('?') > 0) {
url += '&';
}
else {
url += '?';
}
url += $opts.forceDemandReloadParam + '=' + $randomNum;
}
$.ajax ({
url: url,
type: 'get',
dataType: 'html',
success: function (data) {
$(gallery).removeAttr ('rel'); // remove the rel attribute so the load will not be attempted again
var galleryItems;
if ($(data).is ('ul')) {
galleryItems = data;
}
else {
galleryItems = $(data).find('ul');
}
if (!galleryItems.length) {
alert ('Failed to load gallery: element UL was not found.');
return;
}
galleryItems = $(galleryItems).appendTo (gallery).addClass ('jqcg-viewer-slides');
addGalleryItems (gallery, galleryItems);
if (success) {
success ();
}
},
error: function () {
hideLoader ();
$(gallery).removeAttr ('rel'); // remove the rel attribute so the load will not be attempted again
alert ('An error occurred while loading the specified gallery: [' + url + ']');
}
});
}; // loadGallery ()
// PRIVATE: resetViewer ()
var resetViewer = function (flHide) {
if ($ixCurrentGallery >= 0) {
if (flHide) {
$($viewer).hide ();
}
// move the current gallery back to its home (and optionally hide it)
var liHome = $($galleryList).find ("li[data-gallery-ix='" + $ixCurrentGallery + "']");
var gallery = $viewer.find ('ul.jqcg-viewer-slides');
var thumbs = $thumbBar.children ('ul.jqcg-thumbs-list');
if ($ixCurrentSlide > 0 && $ixCurrentSlide < $ctGalleryItems) {
// nth-child is base 1!
var curItem = $(gallery).children ('li:nth-child(' + ($ixCurrentSlide + 1) + ')');
$(curItem).css ('opacity', 0);
}
//$(gallery).removeClass ('jqcg-viewer-slides');
$(thumbs).appendTo (liHome);
$(thumbs).hide ();
$(gallery).appendTo (liHome);
$(gallery).hide ();
$($viewer).find ('.jqcg-viewer-pagedesc').html ('');
$ixCurrentGallery = -1;
$ctGalleryItems = 0;
$ixCurrentSlide = -1;
}
};
// PRIVATE: showImage ()
var showImage = function (ix) {
debug ('showing image: [' + ix + ']');
if ($ixCurrentGallery < 0) {
showGallery (0);
return;
}
if (ix === $ixCurrentSlide) {
return;
}
if ($ctGalleryItems === 0 || ix > $ctGalleryItems) {
if (!$opts.loopGalleries) {
return;
}
var nextGallery = $ixCurrentGallery + 1;
if (nextGallery > $ctGalleries) {
nextGallery = 0;
}
if (nextGallery !== $ixCurrentGallery) {
showGallery (nextGallery);
}
return;
}
var ixLastSlide = $ixCurrentSlide;
$ixCurrentSlide = ix;
var items = $($viewerImageWrapper).children ('ul').children ('li');
// if the current slide is shown
if (ixLastSlide >= 0 && ixLastSlide < $ctGalleryItems) {
// hide the current slide
$(items [ixLastSlide]).stop().fadeTo(500, 0, function () {
$(items [$ixCurrentSlide]).stop().fadeTo (500, 1);
});
}
else { // show the current slide
$(items [$ixCurrentSlide]).stop().fadeTo (500, 1);
}
// get the caption
var caption = $(items [ix]).children ('.caption').html ();
caption = caption ? caption : '';
$($viewerCaption).html (caption);
// update the page count
var pageDesc = $($viewer).find ('.jqcg-viewer-pagedesc');
if (pageDesc.length) {
var pageDescText = $opts.pageDescFormat.replace ('%pageNum%', ix+1);
pageDescText = pageDescText.replace ('%pageCount%', items.length);
$(pageDesc).html (pageDescText);
}
showThumb ($ixCurrentSlide, true);
}; // showImage ()
// PRIVATE: resetThumbBar ()
var resetThumbBar = function (thumbs) {
if ($opts.thumbStyle === 'list') {
$(thumbs).css ({margin: '0'});
if ($opts.thumbLocation === 'top' || $opts.thumbLocation === 'bottom') {
var totalWidth = $(thumbs).css ('width');
if (totalWidth < $viewerWidth) {
$($thumbLeftScroll).hide ();
$($thumbRightScroll).hide ();
$($thumbBar).css ({width: ($viewerWidth - ($thumbsPaddingLeft + $thumbsPaddingRight)) + 'px'});
}
else {
$($thumbLeftScroll).show ();
$($thumbRightScroll).show ();
$($thumbBar).css ({width: ($viewerWidth - ($thumbsPaddingLeft + $thumbsPaddingRight) - ($opts.thumbScrollButtonWidth * 2)) + 'px'});
}
}
else if ($opts.thumbLocation === 'left' || $opts.thumbLocation === 'right') {
var totalHeight = $(thumbs).css ('height');
}
}
$($thumbBar).find ('ul li.jqcg-thumb-current').removeClass ('jqcg-thumb-current'); // remove any reminant selected thumbs (when gallery was previously open)
$thumbBarInfo = getThumbBarInfo (thumbs);
debug ($thumbBarInfo);
}; // resetThumbBar ()
// PRIVATE: getThumbBarinfo ()
var getThumbBarInfo = function (thumbList) {
var info = {
ixFirst: -1,
ixLast: -1,
ctTotal: 0,
pxListLeft: 0,
pxListLength: 0,
pxBarRight: 0,
thumbBarWidth: 0,
thumbBarHeight: 0,
thumbList: thumbList,
thumbItems: null
};
if (!thumbList || !thumbList.length) {
return (info);
}
info.thumbItems = $(thumbList).children();
info.ctTotal = info.thumbItems.length;
if (!info.ctTotal) {
return;
}
info.thumbListOffset = $(thumbList).offset ();
info.thumbListPostion = $(thumbList).position ();
info.thumbBarOffset = $($thumbBar).offset ();
info.thumbBarPosition = $($thumbBar).position ();
info.thumbBarWidth = $($thumbBar).width ();
info.thumbBarHeight = $($thumbBar).height ();
if ($opts.thumbLocation === 'top' || $opts.thumbLocation === 'bottom') {
info.pxListLeft = parseInt ($(thumbList).css ('margin-left'), 10);
info.pxListLength = $(thumbList).width ();
info.pxBarRight = info.thumbBarOffset.left + info.thumbBarWidth;
}
$(info.thumbItems).each (function (ix, li) {
var offset = $(li).offset ();
if ($opts.thumbLocation === 'top' || $opts.thumbLocation === 'bottom') {
if (info.ixFirst < 0 && offset.left >= info.thumbBarOffset.left) {
info.ixFirst = ix;
}
if (info.ixLast < 0) {
if ((offset.left + $(li).outerWidth()) > info.pxBarRight) {
info.ixLast = ix - 1;
}
else if (ix === info.ctTotal - 1) {
info.ixLast = ix;
}
}
}
});
return (info);
}; // getThumbBarInfo ()
// PRIVATE: thumbScroll ()
var thumbScroll = function (direction, ctItems) {
if (!$thumbBarInfo || !$thumbBarInfo.ctTotal) {
return;
}
var ix = 0;
var newStyle = {};
var px = 0;
if (direction === 'left') {
if ($thumbBarInfo.ixLast === $thumbBarInfo.ctTotal - 1) {
return;
}
if ($thumbBarInfo.ixLast + ctItems >= $thumbBarInfo.ctTotal) {
ctItems = $thumbBarInfo.ctTotal - $thumbBarInfo.ixLast - 1;
}
for (ix = $thumbBarInfo.ixFirst; ix < $thumbBarInfo.ixFirst + ctItems; ix++) {
if ($opts.thumbLocation === 'top' || $opts.thumbLocation === 'bottom') {
px += $($thumbBarInfo.thumbItems[ix]).outerWidth (true);
}
}
$thumbBarInfo.pxListLeft -= px;
$thumbBarInfo.ixFirst += ctItems;
}
else {
if ($thumbBarInfo.ixFirst <= 0) {
return;
}
if ($thumbBarInfo.ixFirst - ctItems < 0) {
ctItems = $thumbBarInfo.ixFirst + 1;
}
for (ix = $thumbBarInfo.ixFirst - ctItems; ix < $thumbBarInfo.ixFirst; ix++) {
if ($opts.thumbLocation === 'top' || $opts.thumbLocation === 'bottom') {
px += $($thumbBarInfo.thumbItems[ix]).outerWidth (true);
}
}
$thumbBarInfo.pxListLeft += px;
$thumbBarInfo.ixFirst -= ctItems;
//$thumbBarInfo.ixLast -= ctItems;
}
if ($opts.thumbLocation === 'top' || $opts.thumbLocation === 'bottom') {
newStyle.marginLeft = $thumbBarInfo.pxListLeft + 'px';
}
$($thumbBarInfo.thumbList).stop().animate (newStyle, 400, function () {
// calculate the last item (thumb widths can vary)
var offset;
if ($opts.thumbLocation === 'top' || $opts.thumbLocation === 'bottom') {
//var thumbBarRight = $($thumbBar).offset ().left + $($thumbBar).width ();
var outerWidth;
for (ix = $thumbBarInfo.ixFirst + 1; ix < $thumbBarInfo.ctTotal; ix++) {
offset = $($thumbBarInfo.thumbItems [ix]).offset ();
outerWidth = $($thumbBarInfo.thumbItems [ix]).outerWidth();
var liRight = offset.left + outerWidth;
//debug ('ix: ' + ix + ', offset.left: ' + offset.left + ', outerWidth: ' + outerWidth + ', right: ' + liRight + ', thumbBarRight: ' + thumbBarRight);
if (liRight > $thumbBarInfo.pxBarRight) {
$thumbBarInfo.ixLast = ix - 1;
break;
}
else if (ix === $thumbBarInfo.ctTotal - 1) {
$thumbBarInfo.ixLast = ix;
}
}
}
});
//debug ($thumbBarInfo);
}; // thumbScroll ()
// PRIVATE: showThumb ()
var showThumb = function (ix, flPage) {
$($thumbBar).find ('ul li.jqcg-thumb-current').removeClass ('jqcg-thumb-current');
var curThumb = $($thumbBar).find ('li:nth-child(' + (ix + 1) + ')');
$(curThumb).addClass ('jqcg-thumb-current');
// scroll thumb into view
if (ix >= $thumbBarInfo.ixFirst && ix <= $thumbBarInfo.ixLast) {
return;
}
var ctScroll = 0;
var direction;
if (ix < $thumbBarInfo.ixFirst) {
direction = 'right';
if (!flPage) {
ctScroll = $thumbBarInfo.ixFirst - ix;
}
else {
ctScroll = $thumbBarInfo.ixFirst - ix;
}
}
else if (ix > $thumbBarInfo.ixLast) {
direction = 'left';
if (!flPage) {
ctScroll = ix - $thumbBarInfo.ixLast;
}
else {
ctScroll = ix - $thumbBarInfo.ixFirst;
}
}
if (ctScroll > 0) {
thumbScroll (direction, ctScroll);
}
};
// PRIVATE: showGalleryItems ()
var showGalleryItems = function (gallery, thumbs, galleryTitle, galleryDesc, ix) {
debug ('showing gallery items: [' + ix + ']');
// set the globals
$ctGalleryItems = $(gallery).children ('li').length;
debug ('item count: [' + $ctGalleryItems + ']');
$ixCurrentGallery = ix;
// move the specified gallery items into the viewer
// title and caption of the gallery
$($viewer).find ('.jqcg-viewer-gallery-title').html (galleryTitle);
$($viewer).find ('.jqcg-viewer-gallery-desc').html (galleryDesc);
// set the slideshow class to the gallery
$(gallery).addClass ('jqcg-viewer-slides');
// move the gallery into the viewer
$(gallery).prependTo ($viewerImageWrapper);
$(gallery).show ();
// move the thumbs into the viewer
$(thumbs).appendTo ($thumbBar);
$(thumbs).show ();
// show the viewer
$($viewer).show ();
resetThumbBar (thumbs);
// fade the gallery back in
$($viewer).fadeTo (500, 1, function () {
hideLoader ();
// show the first image
showImage (0);
});
}; // showGalleryItems ()
// PRIVATE: showGallery ()
var showGallery = function (ix) {
debug ('showing gallery: [' + ix + '], ixCurrentGallery: [' + $ixCurrentGallery + ']');
if (ix < 0 || ix >= $ctGalleries || ix === $ixCurrentGallery) {
debug ('invalid gallery or gallery already being shown.');
return;
}
var flResume = false;
if ($playMode === 1) {
stop ();
flResume = true;
}
showLoader ();
// get the required DOM elements
var galleryItem = $($galleryList).find ("li[data-gallery-ix='" + ix + "']");
var gallery = $(galleryItem).children ("ul.jqcg-viewer-slides");
var currentHeight = $($element).height ();
if (!gallery.length) {
debug ('gallery slides not found');
// there aren't any items in the gallery... see if we need to demand load
var urlData = $(galleryItem).attr ('rel');
if (urlData && urlData.length) {
debug ('getting gallery from rel attr: [' + urlData + ']');
if ($ixCurrentGallery < 0) {
$($galleryList).fadeTo ($opts.animateOutSpeed, 0, function () {
loadGallery (urlData, galleryItem, ix, function () {
showGallery (ix);
});
});
}
else {
$($element).css ({height: currentHeight + 'px'});
$($viewer).fadeTo (500, 0, function () {
resetViewer (true);
loadGallery (urlData, galleryItem, ix, function () {
showGallery (ix);
$($element).css ({height: 'auto'});
});
});
}
}
if (flResume) {
play ();
}
return;
}
var galleryTitle = $(galleryItem).attr ('data-title');
var galleryDesc = $(galleryItem).attr ('data-desc');
var thumbs = $(galleryItem).children ("ul.jqcg-thumbs-list");
if ($ixCurrentGallery >= 0) {
// fade out the viewer
$($element).css ({height: currentHeight + 'px'});
$($viewer).fadeTo (500, 0, function () {
// reset the viewer - move current gallery list back to its home
resetViewer (false);
showGalleryItems (gallery, thumbs, galleryTitle, galleryDesc, ix);
$($element).css ({height: 'auto'});
});
}
else {
if ($($galleryList).is(':visible')) {
// fade out the gallery list
$($galleryList).fadeTo (500, 0, function () {
$($galleryList).hide (); // hide the gallery list
showGalleryItems (gallery, thumbs, galleryTitle, galleryDesc, ix);
});
}
else {
showGalleryItems (gallery, thumbs, galleryTitle, galleryDesc, ix);
}
}
if (flResume) {
play ();
}
}; // showGallery()
var initControl = function (viewer, selector, toolTip, fnClick) {
$(viewer).find (selector).hover (
function (e) {
$(this).addClass ('jqcg-ctl-hover');
if (toolTip && toolTip.length > 0) {
showTooltip (toolTip, e);
}
},
function (e) {
$(this).removeClass ('jqcg-ctl-hover');
if (toolTip && toolTip.length > 0) {
hideTooltip (e);
}
}
).mousemove (function (e) {
if (toolTip && toolTip.length > 0) {
moveTooltip (e);
}
}).click (function () {
if (fnClick) {
fnClick ();
}
return (false);
});
};
/*
Variables
*/
// settings
var $opts = $.extend ({}, $.fn.jqCoolGallery.defaults, options);
var $element = element;
var $this = this;
var $playMode = 0; // 0 for stopped, 1 for playing
var $playInterval = null;
var $randomNum = Math.floor (Math.random()*100000);
// Make sure the element has an ID. If not, create one and store it
var $elementID = $($element).attr ('id');
if ($elementID === '') {
// if the element doesn't have an id, give it a random id
$elementID = 'jqcg-' + $randomNum;
$($element).attr ('id', $elementID);
}
var $ixCurrentGallery = -1;
var $ctGalleryItems = 0;
var $ixCurrentSlide = -1;
var $galleryList = $($element).find ('ul.jqcg-gallery');
var $ctGalleries = 0;
debug ('initializing: [' + $elementID + ']');
/*
DOM Mods
*/
$($element).addClass ('jqcoolgallery'); // give it the jqcoolgallery root class
//if ($opts.xmlData != '')
// getXMLData ();
if ($opts.forceImageReload) {
// ensure that all images load
//$($element).find ('img').removeAttr('src').attr('src', $(this).attr('src') + '?x=' + $randomNum);
$($element).find ('img').each (function () {
forceImageReload (this);
});
}
// setup the viewer for the image display
var $viewer = $($element).find ('.jqcg-viewer');
if (!$viewer.length) {
// create a generic viewer
var viewerControls = '<div class="jqcg-viewer-controls">' +
'<div class="jqcg-viewer-controls jqcg-gallery-controls">' +
'<ul>' +
'<li class="jqcg-ctl-arrow jqcg-ctl-prev-gallery"><span> </span></li>' +
'<li class="jqcg-ctl-home"><span>' + $opts.htmlHome + '</span></li>' +
'<li class="jqcg-ctl-arrow jqcg-ctl-next-gallery"><span> </span></li>' +
'</ul>' +
'</div>' +
'<div class="jqcg-viewer-controls jqcg-show-controls">' +
'<ul>' +
'<li class="jqcg-ctl-button jqcg-ctl-rewind"><span> </span></li>' +
'<li class="jqcg-ctl-button jqcg-ctl-prev-slide"><span> </span></li>' +
'<li class="jqcg-ctl-button jqcg-ctl-play"><span> </span></li>' +
'<li class="jqcg-ctl-button jqcg-ctl-next-slide"><span> </span></li>' +
'</ul>' +
'</div>' +
'<div class="jqcg-viewer-gallery-info">' +
'<' + $opts.galleryTitleElement + ' class="jqcg-viewer-gallery-title"></' + $opts.galleryTitleElement + '>' +
'<' + $opts.galleryDescElement + ' class="jqcg-viewer-gallery-desc"></' + $opts.galleryDescElement + '>' +
'</div>' +
'</div>';
$viewer = $('<div class="jqcg-viewer"><div class="jqcg-viewer-image-wrapper"></div><div class="jqcg-panel">' + viewerControls + '<div class="jqcg-viewer-text-panel"><div class="jqcg-viewer-caption"></div></div></div></div>').appendTo ($element);
}
// Previous Gallery
initControl ($viewer, '.jqcg-ctl-prev-gallery', $opts.prevGalleryToolTip, function (e) {
stop ();
$this.prevGallery ();
});
// Next Gallery
initControl ($viewer, '.jqcg-ctl-next-gallery', $opts.nextGalleryToolTip, function (e) {
stop ();
$this.nextGallery ();
});
// Gallery Home
initControl ($viewer, '.jqcg-ctl-home', $opts.homeToolTip, function (e) {
stop ();
$this.home ();
});
// Rewind
initControl ($viewer, '.jqcg-ctl-rewind', $opts.rewindToolTip, function (e) {
stop ();
$this.firstImage ();
});
// Previous Image
initControl ($viewer, '.jqcg-ctl-prev-slide', $opts.prevSlideToolTip, function (e) {
stop ();
$this.prevImage ();
});
// Next Image
initControl ($viewer, '.jqcg-ctl-next-slide', $opts.nextSlideToolTip, function (e) {
stop ();
$this.nextImage ();
});
// Play Slideshow
var $playCtl = $($viewer).find ('.jqcg-ctl-play').hover (
function (e) {
$(this).addClass ('jqcg-ctl-hover');
if ($playMode === 0 && $opts.playToolTip && $opts.playToolTip.length > 0) {
showTooltip ($opts.playToolTip, e);
}
else if ($playMode === 1 && $opts.pauseToolTip && $opts.pauseToolTip.length > 0) {
showTooltip ($opts.pauseToolTip, e);
}
},
function (e) {
$(this).removeClass ('jqcg-ctl-hover');
hideTooltip (e);
}
).mousemove (function (e) {
moveTooltip (e);
}).click (function () {
$this.togglePlay ();
if ($playMode === 1 && $opts.pauseToolTip && $opts.pauseToolTip.length > 0) {
$ttContent.html ($opts.pauseToolTip);
}
else if ($playMode === 1 && $opts.playToolTip && $opts.playToolTip.length > 0) {
$ttContent.html ($opts.playToolTip);
}
return (false);
});
var $viewerCaption = $($viewer).find ('.jqcg-viewer-caption');
var $panel = $($viewer).find ('.jqcg-panel');
var $viewerImageWrapper = $($viewer).find ('.jqcg-viewer-image-wrapper');
if (!$viewerImageWrapper.length) {
$viewerImageWrapper = $('<div class="jqcg-viewer-image-wrapper"></div>').prependTo ($viewer);
}
$($viewerImageWrapper).empty ();
$($viewerImageWrapper).css ({width:$opts.imageAreaWidth + 'px', height:$opts.imageAreaHeight + 'px'});
if ($opts.imageAreaPadding.length > 0) {
$($viewerImageWrapper).css ({padding: $opts.imageAreaPadding});
}
var $stepLeft = $('<div class="jqcg-step jqcg-step-left"></div>').appendTo ($viewerImageWrapper);
$($stepLeft).css ({opacity:0});
$($stepLeft).hover (function () {
$(this).animate({opacity:1},100);
}, function () {
$(this).animate({opacity:0},100);
}).click (function () {
$this.prevImage ();
});
var $stepRight = $('<div class="jqcg-step jqcg-step-right"></div>').appendTo ($viewerImageWrapper);
$($stepRight).css ({opacity:0});
$($stepRight).hover (function () {
$(this).animate({opacity:1},100);
}, function () {
$(this).animate({opacity:0},100);
}).click (function () {
$this.nextImage ();
});
var $viewerWidth = $($viewer).width ();
debug ('viewer width: [' + $viewerWidth + ']');
var $thumbs = $($viewer).find ('.jqcg-thumbs');
if (!$thumbs.length) {
if ($opts.thumbStyle === 'grid') {
$thumbs = $('<div class="jqcg-thumbs"></div>').appendTo ($panel);
}
else {
if ($opts.thumbLocation === 'top' || $opts.thumbLocation === 'left') {
$thumbs = $('<div class="jqcg-thumbs"></div>').prependTo ($viewer);
}
else {
$thumbs = $('<div class="jqcg-thumbs"></div>').appendTo ($viewer);
}
}
}
if ($opts.panelAreaWidth > 0) {
$($panel).width ($opts.panelAreaWidth + 'px');
}
var $thumbLeftScroll = null;
var $thumbRightScroll = null;
if ($opts.thumbStyle === 'list') {
$thumbLeftScroll = $('<div class="jqcg-thumbs-scrollleft"></div>').appendTo ($thumbs);
}
var $thumbBar = $('<div class="jqcg-thumbs-bar"></div>').appendTo ($thumbs);
if ($opts.thumbStyle === 'list') {
$thumbRightScroll = $('<div class="jqcg-thumbs-scrollright"></div>').appendTo ($thumbs);
}
var $totalThumbHeight = $opts.thumbHeight + ($opts.thumbPadding * 2) + ($opts.thumbBorderWidth * 2);
var $thumbsPaddingLeft = parseInt ($($thumbs).css ('padding-left'), 10);
var $thumbsPaddingRight = parseInt ($($thumbs).css ('padding-right'), 10);
var $thumbItemWidth = $opts.thumbWidth + ($opts.thumbPadding * 2) + ($opts.thumbBorderWidth * 2);
debug ('$thumbItemWidth: ' + $thumbItemWidth);
var $thumbListWidth = -1;
var $ctThumbsPerRow = -1;
var $thumbHelperDiv = null;
var $thumbHelperImg = null;
if ($opts.thumbHelper) {
$thumbHelperDiv = $('<div class="jqcg-thumb-helper"></div>').appendTo ('body');
$thumbHelperImg = $('<img src="" width="0" height="0" alt="" />').appendTo ($thumbHelperDiv);
}
if ($opts.thumbStyle === 'grid') {
$($thumbs).addClass ('jqcg-thumbs-gridstyle');
if ($opts.thumbAreaWidth === -1) {
$opts.thumbAreaWidth = $($panel).innerWidth ();
}
$($thumbs).css ({width: $opts.thumbAreaWidth + 'px', paddingTop: $opts.thumbMargin + 'px'});
$($thumbBar).css ({width: $opts.thumbAreaWidth + 'px'});
$ctThumbsPerRow = Math.floor (($opts.thumbAreaWidth+$opts.thumbMargin) / ($thumbItemWidth+$opts.thumbMargin));
$thumbListWidth = ($thumbItemWidth * $ctThumbsPerRow) + ($opts.thumbMargin * ($ctThumbsPerRow - 1));
debug ('$ctThumbsPerRow: ' + $ctThumbsPerRow + ', $opts.thumbMargin: ' + $opts.thumbMargin + ', $thumbListWidth: ' + $thumbListWidth);
if ($thumbHelperDiv !== null) {
$('<div class="jqcg-helper-arrow jqcg-helper-arrow-down"></div>').appendTo ($thumbHelperDiv);
}
debug ('thumbAreaWidth: ' + $opts.thumbAreaWidth + ', thumbItemWidth: ' + $thumbItemWidth + ', ctThumbsPerRow: ' + $ctThumbsPerRow);
}
else {
$($thumbs).addClass ('jqcg-thumbs-liststyle');
switch ($opts.thumbLocation) {
case 'top':
$($thumbs).addClass ('jqcg-thumbs-top');
// recalc padding after applying top class
$thumbsPaddingLeft = parseInt ($($thumbs).css ('padding-left'), 10);
$thumbsPaddingRight = parseInt ($($thumbs).css ('padding-right'), 10);
$($thumbs).css ({height:$totalThumbHeight+'px', width:($viewerWidth-$thumbsPaddingLeft-$thumbsPaddingRight)+'px'});
$($thumbLeftScroll).css ({width: $opts.thumbScrollButtonWidth + 'px', height: $totalThumbHeight+'px'});
$($thumbRightScroll).css ({width: $opts.thumbScrollButtonWidth + 'px', height: $totalThumbHeight+'px'});
if ($thumbHelperDiv !== null) {
$('<div class="jqcg-helper-arrow jqcg-helper-arrow-up"></div>').prependTo ($thumbHelperDiv);
}
break;
case 'bottom':
$($thumbs).addClass ('jqcg-thumbs-bottom');
// recalc padding after applying bot class
$thumbsPaddingLeft = parseInt ($($thumbs).css ('padding-left'), 10);
$thumbsPaddingRight = parseInt ($($thumbs).css ('padding-right'), 10);
$($thumbs).css ({height:$totalThumbHeight+'px', width:($viewerWidth-$thumbsPaddingLeft-$thumbsPaddingRight)+'px'});
$($thumbLeftScroll).css ({width: $opts.thumbScrollButtonWidth + 'px', height: $totalThumbHeight+'px'});
$($thumbRightScroll).css ({width: $opts.thumbScrollButtonWidth + 'px', height: $totalThumbHeight+'px'});
if ($thumbHelperDiv !== null) {
$('<div class="jqcg-helper-arrow jqcg-helper-arrow-down"></div>').appendTo ($thumbHelperDiv);
}
break;
case 'left':
$($thumbs).addClass ('jqcg-thumbs-left');
if ($thumbHelperDiv !== null) {
$('<div class="jqcg-helper-arrow jqcg-helper-arrow-left"></div>').appendTo ($thumbHelperDiv);
}
break;
case 'right':
$($thumbs).addClass ('jqcg-thumbs-right');
if ($thumbHelperDiv !== null) {
$('<div class="jqcg-helper-arrow jqcg-helper-arrow-right"></div>').appendTo ($thumbHelperDiv);
}
break;
}
}
if ($thumbLeftScroll !== null) {
$($thumbLeftScroll).hover (
function () {
if ($thumbBarInfo.ixFirst > 0) {
$(this).addClass ('jqcg-thumbs-scrollleft-hover');
}
},
function () {
$(this).removeClass ('jqcg-thumbs-scrollleft-hover');
}
);
$thumbLeftScroll.click (function () {
thumbScroll ('right', 1);
});
}
if ($thumbRightScroll !== null) {
$($thumbRightScroll).hover (
function () {
if ($thumbBarInfo.ixLast < $thumbBarInfo.ctTotal - 1) {
$(this).addClass ('jqcg-thumbs-scrollright-hover');
}
},
function () {
$(this).removeClass ('jqcg-thumbs-scrollright-hover');
}
);
$thumbRightScroll.click (function () {
thumbScroll ('left', 1);
});
}
if ($opts.keyboardInput === true) { // Add keyboard navigation support
$($element).attr ('tabindex', 100); // allow focus for keyboard input
$(document).keydown (function (e) {
if (!$($element).is (':focus')) {
return (true);
}
var code = (e.keyCode ? e.keyCode : e.which);
var row, col, newRow, ixMoveTo;
var flHandled = false;
switch (code) {
case 32: // space
$this.togglePlay ();
flHandled = true;
break;
case 35: // end
$this.stop ();
$this.lastImage ();
flHandled = true;
break;
case 36: // home
$this.stop ();
$this.firstImage ();
flHandled = true;
break;
case 37: // left arrow
$this.stop ();
$this.prevImage ();
flHandled = true;
break;
case 38: // up arrow
if ($opts.thumbStyle === 'grid') {
$this.stop ();
if ($ixCurrentSlide > $ctThumbsPerRow - 1) {
row = Math.floor ($ixCurrentSlide / $ctThumbsPerRow) + 1;
col = $ixCurrentSlide % $ctThumbsPerRow + 1;
newRow = Math.max (row - 1, 1);
ixMoveTo = (($ctThumbsPerRow * newRow) - 1) - ($ctThumbsPerRow - col);
debug ('MOVE UP - from: [row: ' + row + ', col: ' + col + '], newRow: ' + newRow + ', ixMoveTo: ' + ixMoveTo);
showImage (ixMoveTo);
}
flHandled = true;
}
break;
case 39: // right arrow
$this.stop ();
$this.nextImage ();
flHandled = true;
break;
case 40: // down arrow
if ($opts.thumbStyle === 'grid') {
$this.stop ();
row = Math.floor ($ixCurrentSlide / $ctThumbsPerRow) + 1;
col = $ixCurrentSlide % $ctThumbsPerRow + 1;
newRow = Math.max (row + 1, 1);
debug ('MOVE DOWN - from: [row: ' + row + ', col: ' + col + '], newRow: ' + newRow);
if (newRow > row) {
ixMoveTo = (($ctThumbsPerRow * newRow) - 1) - ($ctThumbsPerRow - col);
debug ('ixMoveTo: ' + ixMoveTo + ', $ctGalleryItems: ' + $ctGalleryItems);
if (ixMoveTo >= $ctGalleryItems) {
ixMoveTo = $ctGalleryItems - 1;
}
showImage (ixMoveTo);
}
flHandled = true;
}
break;
}
return (!flHandled);
});
}
var $thumbBarInfo = null;
// tooltip
var $tooltip = $('<div class="jqcg-tooltip" style="opacity:0;"></div>').appendTo ('body');
var $ttContent = $('<div class="jqcg-tooltip-content"></div>').appendTo ($tooltip);
var $loader = $('<div id="' + $elementID + '-loader" class="jqcg-loading" style="display:none;"></div>').appendTo ('body');
$($viewer).hide ();
$($viewer).css ('opacity', 0);
// move the galleryList off the screen
//$($galleryList).css ({position:'absolute', left:-10000});
var $galleryTooltip = $($galleryList).attr ('data-gallery-tooltip');
if (typeof ($galleryTooltip) === 'undefined' || !$galleryTooltip.length) {
$galleryTooltip = $opts.galleryTooltip;
}
// visit each item in the gallery list
$($galleryList).children ('li').each (function (ixElement) {
addGallery (this, ixElement);
});
// move the gallery list back to the screen, but set the opacity to 0
$($galleryList).css ({left:0, opacity:0});
if ($ctGalleries <= 0) {
$($viewer).empty ();
$($viewer).html ('<p>No galleries or images found.</p>');
}
else {
if ($ctGalleries === 1) {
var galleryCtls = $($viewer).find ('div.jqcg-gallery-controls');
$(galleryCtls).hide();
}
if ($opts.openGallery >= 0) {
showGallery ($opts.openGallery);
}
else {
$($galleryList).fadeTo ($opts.initialFadeSpeed, 1);
}
}
/*
PUBLIC METHODS
*/
// PUBLIC: home ()
this.home = function () {
debug ('going home');
stop ();
if ($ixCurrentGallery >= 0) {
showLoader ();
// fade out the viewer
$viewer.fadeTo(500, 0, function () {
resetViewer (true);
hideLoader ();
// show the gallery list
$($galleryList).show ();
// fade the gallery list back in
$($galleryList).stop().fadeTo(500, 1);
});
}
};
this.play = function () {
play ();
};
this.stop = function () {
stop ();
};
this.togglePlay = function () {
if ($playMode === 0) {
play ();
}
else {
stop ();
}
};
this.firstImage = function () {
debug ('firstImage');
if ($ixCurrentGallery < 0) {
showGallery (0);
return;
}
showImage (0);
};
this.lastImage = function () {
debug ('lastImage');
if ($ixCurrentGallery < 0) {
showGallery (0);
return;
}
showImage ($ctGalleryItems-1);
};
this.nextImage = function () {
debug ('nextImage');
if ($ixCurrentGallery < 0) {
showGallery (0);
return;
}
var ixNext = $ixCurrentSlide + 1;
if (ixNext >= $ctGalleryItems) {
if ($opts.loopGalleries) {
this.nextGallery ();
return;
}
ixNext = 0;
}
showImage (ixNext);
};
this.prevImage = function () {
debug ('prevImage');
if ($ixCurrentGallery < 0) {
showGallery (0);
return;
}
var ixPrev = $ixCurrentSlide - 1;
if (ixPrev < 0) {
if ($opts.loopGalleries) {
this.prevGallery ();
return;
}
ixPrev = $ctGalleryItems - 1;
}
showImage (ixPrev);
};
this.nextGallery = function () {
debug ('nextGallery');
var ixNext = $ixCurrentGallery + 1;
if (ixNext > $ctGalleries - 1) {
if (!$opts.loopGalleries) {
return;
}
ixNext = 0;
}
showGallery (ixNext);
};
this.prevGallery = function () {
debug ('prevGallery');
var ixPrev = $ixCurrentGallery - 1;
if (ixPrev < 0) {
if (!$opts.loopGalleries) {
return;
}
ixPrev = $ctGalleries - 1;
}
showGallery (ixPrev);
};
};
// PUBLIC: jqCoolGallery () - main plugin function
$.fn.jqCoolGallery = function (options, p) {
return this.each (function () {
var element = $(this);
var jq = element.data ('jqCoolGallery');
// handle when jqRadar exists, and options is a function call
if (jq && typeof (options) === 'string') {
var fn = jq [options];
if (typeof (fn) === 'function') {
return (fn(p));
}
return;
}
// return early if this element already has a plugin instance
if (jq) {
return;
}
// support the metadata plugin
if ($.metadata) {
options = $.extend ({}, options, element.metadata());
}
// store plugin object in this element's data
element.data ('jqCoolGallery', new jqCoolGallery (this, options));
});
};
$.fn.jqCoolGallery.defaults = {
galleryTileWidth: 200, // integer: width of gallery tiles
galleryTileHeight: 200, // integer: height of gallery tiles
galleryColumnCount: -1, // integer: adds the "jqcg-gallery-item-last" class to the last item in each row - used to eliminate right margin
galleryHoverCaption: true, // boolean: whether or not to show/hide a gallery captions when hovering
galleryHoverExpand: true, // boolean: whether or not to expand gallery items when hovering
galleryHoverExpandPx: 5, // integer: number of pixels to expand gallery items (when galleryHoverExpand is true)
galleryTitleElement: 'h3', // string: HTML element used to display gallery title in panel
galleryDescElement: 'p', // string: HTML element used to display gallery description in panel
openGallery: -1, // integer: 0 based index of gallery to open on initial view
playSpeed: 3000, // integer: milliseconds delay between slides when playing
animateInSpeed:200, // ingeger: milliseconds to animate gallery tiles IN
animateOutSpeed:200, // ingeger: milliseconds to animate gallery tiles OUT
initialFadeSpeed: 2000, // integer: milliseconds to fade in gallery after loading
loopGalleries: false, // boolean: true to auto-load next gallery after playing last slide in current gallery
imageAreaWidth:-1, // integer: width of the image area
imageAreaHeight:-1, // integer: height of the image area
imageAreaAlign: 'center', // string: CSS alignment of image area - 'center' or 'left' or 'right'
imageAreaPadding: '0', // string: CSS padding - '0' or '0 10px 0 0' or any other padding CSS to apply to image area
panelAreaWidth: -1, // integer: width of panel area, -1: don't apply width
thumbLocation: 'bottom', // string: 'left' or 'right' or 'top' or 'bottom'
thumbStyle: 'list', // string: 'list' or 'grid'
thumbAreaWidth: -1, // integer: only used for grid style, -1: use panelAreaWidth
thumbHelper: true, // boolean: true to show a larger thumbnail (thumbnail helper) next to a thumbnail
thumbHelperMaxWidth: 100, // integer: max width of thumbnail helper
thumbHelperMaxHeight: 100, // integer: max height of thumbnail helper
thumbWidth: 100, // integer: width of a thumbnail container
thumbHeight: 100, // integer: height of a thumbnail container
thumbPadding: 0, // integer: padding around thumbnail container
thumbMargin: 4, // integer: margin next to (and below-for thumbs in a grid) thumbnail
thumbBorderWidth: 1, // integer: border width for thumbnail container
thumbImageWidth: -1, // integer: used to specify width for all thumbnails
thumbImageHeight: -1, // integer: used to specify height for all thumbnails
thumbScrollButtonWidth: 25,
forceImageReload: true, // boolean: true to reload all images
forceDemandReload: true, // boolean: force reload of ajax content
forceDemandReloadParam: '_jqcg_', // string: param used to force reload of ajax content
htmlHome: 'All Galleries', // string: HTML to use to bring the user back home from a slideshow
homeToolTip: 'return to all galleries', // string: for gallery home text (see also htmlHome option)
galleryTooltip: '', // string: for gallery items, or use data-gallery-tooltip attribute in gallery item li element
playToolTip: 'start the slideshow', // string: for the play button
pauseToolTip: 'pause the slideshow', // string: for the pause button
prevGalleryToolTip: 'open the previous gallery', // string: for the previous gallery button
nextGalleryToolTip: 'open the next gallery', // string: for next gallery button
nextSlideToolTip: 'next slide', // string: for next slide button
prevSlideToolTip: 'previous slide', // string: for previous slide button
rewindToolTip: 'first slide', // string: for first slide button
fnGalleryClick: null, // function: do your own thing when a gallery item is clicked. Return false to not open the gallery
keyboardInput: true, // boolean: listen for keyboard input
debug: false // boolean: true to send debug info to the console
}; // jqlooper.defaults
})(jQuery);
|
(function(){
var express = require('express');
var router = express.Router();
var redirect = function(req, res) {
var url = req.url.substring(1);
console.log(url);
return res.redirect(url);
};
router.get('/*', redirect);
module.exports = router;
}());
|
const parseNum = require('parse-num')
/* global Intl */
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
const defaultOptions = {
nanZero: true,
locale: 'en-US',
localeMatcher: 'best fit',
useGrouping: true, // grouping separator determined by locale
maximumFractionDigits: 15
// OTHER
// minimumIntegerDigits
// minimumFractionDigits
// maximumFractionDigits
// minimumSignificantDigits
// maximumSignificantDigits
}
function formatNum (number, opts) {
opts = renameKeyShortcuts(Object.assign({}, defaultOptions, opts))
number = parseNum(number)
if (isNaN(number)) {
if (opts.nanZero === false) return 'NaN'
else number = 0
}
const nf = new Intl.NumberFormat([opts.locale], Object.assign({}, opts, { style: 'decimal' }))
return nf.format(number)
}
function renameKeyShortcuts (opts) {
// expand 'min' to 'minimum', 'max' to 'maximum'
Object.keys(opts).forEach(function (key) {
if (!key.includes('minimum') && key.startsWith('min')) {
opts[key.replace('min', 'minimum')] = opts[key]
delete opts[key]
}
if (!key.includes('maximum') && key.startsWith('max')) {
opts[key.replace('max', 'maximum')] = opts[key]
delete opts[key]
}
})
Object.keys(opts).forEach(function (key) {
if (key.startsWith('minimum') && !key.endsWith('Digits')) {
opts[key + 'Digits'] = opts[key]
delete opts[key]
}
if (key.startsWith('maximum') && !key.endsWith('Digits')) {
opts[key + 'Digits'] = opts[key]
delete opts[key]
}
})
return opts
}
module.exports = formatNum
|
/*
------------------------------------------------------
www.idiotminds.com
--------------------------------------------------------
*/
(function ($) {
/* For popup */
$.fn.oauthpopup = function (options) {
this.click(function(){
options.windowName = options.windowName || 'ConnectWithOAuth';
options.windowOptions = options.windowOptions || 'location=0,status=0,width='+options.width+',height='+options.height+',scrollbars=1,left='+options.left+',top='+options.top;
options.callback = options.callback || function () {
window.location.reload();
};
var that = this;
that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
that._oauthInterval = window.setInterval(function () {
if (that._oauthWindow.closed) {
window.clearInterval(that._oauthInterval);
options.callback();
}
},10);
});
};
$.oauthpopups = function(options)
{
if (!options || !options.path) {
throw new Error("options.path must not be empty");
}
options = $.extend({
windowName: 'ConnectWithOAuth' // should not include space for IE
, windowOptions: 'location=0,status=0,width='+options.width+',height='+options.height+',scrollbars=1,left='+options.left+',top='+options.top
, callback: function(){ window.location.reload(); }
}, options);
var oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
var oauthInterval = window.setInterval(function(){
if (oauthWindow.closed) {
window.clearInterval(oauthInterval);
options.callback();
}
}, 1000);
};
//bind to element and pop oauth when clicked
$.fn.oauthpopups = function(options) {
$this = $(this);
$this.click($.oauthpopups.bind(this, options));
};
/* For Google account logout */
$.fn.googlelogout=function(options){
options.google_logout= options.google_logout || "true";
options.iframe= options.iframe || "ggle_logout";
if(this.length && options.google_logout=='true'){
this.after('<iframe name="'+options.iframe+'" id="'+options.iframe+'" style="display:none"></iframe>'); }
if(options.iframe){
options.iframe='iframe#'+options.iframe;
}else{
options.iframe='iframe#ggle_logout';
}
this.click(function(){
if(options.google_logout=='true'){
$(options.iframe).attr('src','https://mail.google.com/mail/u/0/?logout');
var interval=window.setInterval(function () {
$(options.iframe).load(function() {
window.clearInterval(interval);
window.location=options.redirect_url;
});
});
}
else{
window.location=options.redirect_url;
}
});
};
})(jQuery);
|
class Timer {
constructor(minutes = 25, type = 'work') {
this.duration = minutes * 60000;
this.startTime = null;
this.state = null;
this.type = type;
}
get isWorkTimer() {
return this.type === 'work';
}
get isBreakTimer() {
return this.type === 'break';
}
generateStartTime(time = Date.now()) {
this.startTime = time;
return this;
}
get endTime() {
return this.startTime ? this.startTime + this.duration : null;
}
get elapsedTime() {
return this.startTime ? Date.now() - this.startTime : null;
}
get remainingTime() {
return this.startTime ? this.endTime - Date.now() : null;
}
get isElapsed() {
return Date.now() >= this.endTime;
}
}
module.exports = Timer;
|
'use strict';
const {ipcRenderer} = require('electron');
const ipcPlus = require('electron-ipc-plus');
const {ErrorNoPanel, ErrorNoMsg, resolveMessage} = require('../common');
let _id2panelFrame = {};
/**
* @module panel
*
* panel module for manipulate panels in renderer process
*/
let panel = {};
module.exports = panel;
/**
* @method send
*/
panel.send = function (panelID, message, ...args) {
if ( typeof message !== 'string' ) {
console.error(`The message "${message}" sent to panel "${panelID}" must be a string`);
return;
}
let opts = ipcPlus.internal._popReplyAndTimeout(args);
if ( !opts ) {
args = [`${ipcPlus.id}:renderer2panel`, panelID, message, ...args];
ipcRenderer.send.apply( ipcRenderer, args );
return;
}
let sessionId = ipcPlus.internal._newSession(message, `${panelID}@renderer`, opts.reply, opts.timeout);
args = [`${ipcPlus.id}:renderer2panel`, panelID, message, ...args, ipcPlus.option({
sessionId: sessionId,
waitForReply: true,
timeout: opts.timeout, // this is used in main to start a transfer-session timeout
})];
ipcRenderer.send.apply( ipcRenderer, args );
return sessionId;
};
/**
* @method contains
* @param {HTMLElement} el
* @return {boolean}
*
* Check if an element is a panel-frame or in a panel-frame
*/
panel.contains = function (el) {
while (1) {
if (!el) {
return null;
}
if ( el.tagName === 'UI-PANEL-FRAME' ) {
return el;
}
// get parent or shadow host
el = el.parentNode;
if (el && el.host) {
el = el.host;
}
}
};
/**
* @method find
* @param {string} panelID - The panelID
*
* Find panel frame via `panelID`.
*/
panel.find = function ( panelID ) {
let frameEL = _id2panelFrame[panelID];
if ( !frameEL ) {
return null;
}
return frameEL;
};
/**
* @method closeAll
*
* Close all panels. If any of the panel cancel close, none of the panel will be closed.
*/
panel.closeAll = function () {
let panelFrames = Object.values(_id2panelFrame);
for ( let i = 0; i < panelFrames.length; ++i ) {
let frameEL = panelFrames[i];
if ( frameEL.beforeUnload ) {
let stopUnload = frameEL.beforeUnload();
if ( stopUnload ) {
return false;
}
}
}
for ( let i = 0; i < panelFrames.length; ++i ) {
let frameEL = panelFrames[i];
frameEL._unload();
}
return true;
};
/**
* @property panels
*
* Get panels docked in current window
*/
Object.defineProperty(panel, 'panels', {
enumerable: true,
get () {
let results = [];
for ( let id in _id2panelFrame ) {
let frameEL = _id2panelFrame[id];
results.push(frameEL);
}
return results;
},
});
/**
* @method _add
*/
panel._add = function (frameEL) {
let panelID = frameEL.id;
_id2panelFrame[panelID] = frameEL;
ipcRenderer.send('electron-panel:add', panelID);
};
/**
* @method _remove
*/
panel._remove = function (frameEL) {
let panelID = frameEL.id;
delete _id2panelFrame[panelID];
ipcRenderer.send('electron-panel:remove', panelID);
};
/**
* @method _dispatch
*/
panel._dispatch = function (panelID, message, event, ...args) {
let frameEL = _id2panelFrame[panelID];
if ( !frameEL ) {
console.warn(`Failed to send ipc message ${message} to panel ${panelID}, panel not found`);
if ( event.reply ) {
event.reply( new ErrorNoPanel(panelID, message) );
}
return;
}
//
if ( !frameEL._messages ) {
return;
}
//
let fullMessage = resolveMessage(panelID, message);
let fn = frameEL._messages[fullMessage];
if ( !fn || typeof fn !== 'function' ) {
console.warn(`Failed to send ipc message ${message} to panel ${panelID}, message not found`);
if ( event.reply ) {
event.reply( new ErrorNoMsg(panelID, message) );
}
return;
}
fn.apply( frameEL, [event, ...args] );
};
|
var operationStats = {
operation_data: null,
initialize: function (data) {
this.operation_data = data;
this.addOperationData(data);
},
addOperationData: function(_data) {
$operation_skeleton = $("#operation_stat_skeleton");
var operation_dom_elements = [];
var that = this;
$.each(_data, function( index, operation ) {
var $operation_element = $operation_skeleton.clone();
$operation_element.removeAttr('id');
$operation_element.css("display", "");
$operation_element.find(".operation_title").text(operation["name"]);
$operation_element.find("table").append(that.statToTableRowString("Competitive Match Wins", operation["comp_wins"]));
$operation_element.find("table").append(that.statToTableRowString("Competitive Kills", operation["comp_kills"]));
$operation_element.find("table").append(that.statToTableRowString("3k Rounds", operation["comp_3k"]));
$operation_element.find("table").append(that.statToTableRowString("4k Rounds", operation["comp_4k"]));
$operation_element.find("table").append(that.statToTableRowString("5k Rounds", operation["comp_5k"]));
$operation_element.find("table").append(that.statToTableRowString("Headshot Percentage", operation["comp_hs"] == null ? "n/a" : (operation["comp_hs"].toFixed(2) + "%")));
$operation_element.find("table").append(that.statToTableRowString("Competitive MVPs", operation["comp_mvp"]));
operation_dom_elements.push($operation_element);
if((index + 1) % 3 == 0) {
if(index > 0 ) operation_dom_elements.push($("<br class='clear' />"));
}
});
$("#operation_stats_container").append(operation_dom_elements);
},
statToTableRowString: function(name, value) {
return "<tr><td class=\"stat_title\">" + name + "</td><td class=\"stat stat_accent\">" + value + "</td></tr>";
},
failed: function() {
$("#operation_stats_container").append("<div class='api_error'>Inventory is set to private or there was a Steam API error.</div>");
}
}
|
var Lab = require('lab');
var Code = require('code');
var Hapi = require('hapi');
var Proxyquire = require('proxyquire');
var Config = require('./config');
var lab = exports.lab = Lab.script();
var stub = {
BaseModel: {}
};
var ModelsPlugin = Proxyquire('..', {
'./lib/base-model': stub.BaseModel
});
lab.experiment('Plugin', function () {
lab.test('should return and error when the api connection fails', function (done) {
var realUser = Config.salesforce.auth.user;
Config.salesforce.auth.user = '';
var server = new Hapi.Server();
var Plugin = {
register: ModelsPlugin,
options: Config
};
server.connection({ port: 0 });
server.register(Plugin, function (err) {
Code.expect(err).to.be.an.object();
Config.salesforce.auth.user = realUser;
done();
});
});
lab.test('should successfuly connect to the api and exposes the base model', function (done) {
var server = new Hapi.Server();
var Plugin = {
register: ModelsPlugin,
options: Config
};
server.connection({ port: 0 });
server.register(Plugin, function (err) {
if (err) {
return done(err);
}
Code.expect(server.plugins['hapi-sfdc-models']).to.be.an.object();
Code.expect(server.plugins['hapi-sfdc-models'].BaseModel).to.exist();
server.plugins['hapi-sfdc-models'].BaseModel.disconnect();
done();
});
});
lab.test('should successfuly connect to the api and expose defined models', function (done) {
var server = new Hapi.Server();
var Plugin = {
register: ModelsPlugin,
options: {
salesforce: Config.salesforce,
models: {
Dummy: './test/fixtures/dummy-model'
}
}
};
server.connection({ port: 0 });
server.register(Plugin, function (err) {
if (err) {
return done(err);
}
Code.expect(server.plugins['hapi-sfdc-models']).to.be.an.object();
Code.expect(server.plugins['hapi-sfdc-models'].Dummy).to.exist();
server.plugins['hapi-sfdc-models'].BaseModel.disconnect();
done();
});
});
});
|
'use strict';
var exports = {};
exports.version = '2.1.2';
//http://stackoverflow.com/questions/6598945/detect-if-function-is-native-to-browser
var isFuncNative = function isFuncNative(f) {
return !!f && (typeof f).toLowerCase() === "function" &&
//jshint maxlen=300
(/^\s*function\s*(\b[a-z$_][a-z0-9$_]*\b)*\s*\((|([a-z$_][a-z0-9$_]*)(\s*,[a-z$_][a-z0-9$_]*)*)\)\s*\{\s*\[native code\]\s*}\s*$/i.test(String(f))
|| f === Function.prototype);
};
var shim = {
object: {},
_: {}
};
//noinspection Eslint
shim._.function_toString = Function.prototype.toString;
var call = Function.call;
function uncurryThis(f) {
return function () {
return call.apply(f, arguments);
};
}
var prototypeOfObject = Object.prototype;
shim.object.prototype = prototypeOfObject;
var owns = uncurryThis(prototypeOfObject.hasOwnProperty);
var isEnumerable = uncurryThis(prototypeOfObject.propertyIsEnumerable);
var toStr = uncurryThis(prototypeOfObject.toString);
// If JS engine supports accessors creating shortcuts.
var defineGetter;
var defineSetter;
var lookupGetter;
var lookupSetter;
var supportsAccessors = owns(prototypeOfObject, "__defineGetter__");
if (supportsAccessors) {
/* eslint-disable no-underscore-dangle */
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
/* eslint-enable no-underscore-dangle */
}
// Having a toString local variable name breaks in Opera so use to_string.
var to_string = prototypeOfObject.toString;
var isFunction = function (val) {
return to_string.call(val) === "[object Function]";
};
var isArray = function isArray(obj) {
return to_string.call(obj) === "[object Array]";
};
var isString = function isString(obj) {
return to_string.call(obj) === "[object String]";
};
var isArguments = function isArguments(value) {
var str = to_string.call(value);
var isArgs = str === "[object Arguments]";
if (!isArgs) {
isArgs = !isArray(value) &&
value !== null &&
typeof value === "object" &&
typeof value.length === "number" &&
value.length >= 0 &&
isFunction(value.callee);
}
return isArgs;
};
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = !({"toString": null}).propertyIsEnumerable("toString"),
hasProtoEnumBug = function () {
}.propertyIsEnumerable("prototype"),
hasStringEnumBug = !owns("x", "0"),
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
var toObject = function (o) {
/*jshint eqnull: true */
//noinspection Eslint
if (o == null) { // this matches both null and undefined
throw new TypeError("can\"t convert " + o + " to object");
}
return Object(o);
};
shim._.indexOf = Array.prototype.indexOf && isFuncNative(Array.prototype.indexOf) ?
function (arr, sought) {
return arr.indexOf(sought);
} :
function indexOf(arr, sought /*, fromIndex */) {
var length = arr.length >>> 0;
if (!length) {
return -1;
}
for (var i = 0; i < length; i++) {
if (i in arr && arr[i] === sought) {
return i;
}
}
return -1;
};
var array_forEach = function forEach(arr, fun) {
var thisp = arguments[2],
i = -1,
length = arr.length >>> 0;
// If no callback function or if callback is not a callable function
if (!isFunction(fun)) {
throw new TypeError(); // TODO message
}
while (++i < length) {
if (i in arr) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object
// context
fun.call(thisp, arr[i], i, arr);
}
}
};
shim.object.keys = Object.keys && isFuncNative(Object.keys) ? Object.keys : function keys(object) {
var isFn = isFunction(object),
isArgs = isArguments(object),
isObject = object !== null && typeof object === "object",
isStr = isObject && isString(object);
if (!isObject && !isFn && !isArgs) {
throw new TypeError("Object.keys called on a non-object");
}
var theKeys = [];
var skipProto = hasProtoEnumBug && isFn;
if ((isStr && hasStringEnumBug) || isArgs) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (!isArgs) {
for (var name in object) {
if (!(skipProto && name === "prototype") && owns(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var ctor = object.constructor,
skipConstructor = ctor && ctor.prototype === object;
for (var j = 0; j < dontEnumsLength; j++) {
var dontEnum = dontEnums[j];
if (!(skipConstructor && dontEnum === "constructor") && owns(object, dontEnum)) {
theKeys.push(dontEnum);
}
}
}
return theKeys;
};
shim.object.getPrototypeOf = Object.getPrototypeOf && isFuncNative(Object.getPrototypeOf) ? Object.getPrototypeOf :
function getPrototypeOf(object) {
/* jshint ignore:start */
var proto = object.__proto__;
/* jshint ignore:end */
if (proto || proto === null) {
return proto;
} else if (toStr(object.constructor) === "[object Function]") {
return object.constructor.prototype;
} else if (object instanceof Object) {
return prototypeOfObject;
} else {
// Correctly return null for Objects created with `Object.create(null)`
// (shammed or native) or `{ __proto__: null}`. Also returns null for
// cross-realm objects on browsers that lack `__proto__` support (like
// IE <11), but that"s the best we can do.
return null;
}
};
var doesGetOwnPropertyDescriptorWork = function doesGetOwnPropertyDescriptorWork(object) {
try {
object.sentinel = 0;
return Object.getOwnPropertyDescriptor(object, "sentinel").value === 0;
} catch (exception) {
return false;
}
};
// check whether getOwnPropertyDescriptor works if it"s given. Otherwise, shim partially.
var getOwnPropertyDescriptorFallback;
if (Object.defineProperty) {
var getOwnPropertyDescriptorWorksOnObject = doesGetOwnPropertyDescriptorWork({});
var getOwnPropertyDescriptorWorksOnDom = typeof document === "undefined" ||
doesGetOwnPropertyDescriptorWork(document.createElement("div"));
if (!getOwnPropertyDescriptorWorksOnDom || !getOwnPropertyDescriptorWorksOnObject) {
getOwnPropertyDescriptorFallback = Object.getOwnPropertyDescriptor;
}
}
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a non-object: ";
/* eslint-disable no-proto */
shim.object.getOwnPropertyDescriptor =
(Object.getOwnPropertyDescriptor && getOwnPropertyDescriptorFallback) && isFuncNative(Object.getOwnPropertyDescriptor) ?
Object.getOwnPropertyDescriptor :
function getOwnPropertyDescriptor(object, property) {
if ((typeof object !== "object" && typeof object !== "function") || object === null) {
throw new TypeError(ERR_NON_OBJECT + object);
}
// make a valiant attempt to use the real getOwnPropertyDescriptor
// for I8"s DOM elements.
if (getOwnPropertyDescriptorFallback) {
try {
return getOwnPropertyDescriptorFallback.call(Object, object, property);
} catch (exception) {
// try the shim if the real one doesn't work
}
}
var descriptor;
// If object does not owns property return undefined immediately.
if (!owns(object, property)) {
return descriptor;
}
// If object has a property then it"s for sure `configurable`, and
// probably `enumerable`. Detect enumerability though.
descriptor = {
enumerable: isEnumerable(object, property),
configurable: true
};
// If JS engine supports accessor properties then property may be a
// getter or setter.
if (supportsAccessors) {
// Unfortunately `__lookupGetter__` will return a getter even
// if object has own non getter property along with a same named
// inherited getter. To avoid misbehavior we temporary remove
// `__proto__` so that `__lookupGetter__` will return getter only
// if it"s owned by an object.
/* jshint ignore:start */
var prototype = object.__proto__;
/* jshint ignore:end */
var notPrototypeOfObject = object !== prototypeOfObject;
// avoid recursion problem, breaking in Opera Mini when
// Object.getOwnPropertyDescriptor(Object.prototype, "toString")
// or any other Object.prototype accessor
if (notPrototypeOfObject) {
/* jshint ignore:start */
object.__proto__ = prototypeOfObject;
/* jshint ignore:end */
}
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
if (notPrototypeOfObject) {
// Once we have getter and setter we can put values back.
object.__proto__ = prototype; //jshint ignore:line
}
if (getter || setter) {
if (getter) {
descriptor.get = getter;
}
if (setter) {
descriptor.set = setter;
}
// If it was accessor property we"re done and return here
// in order to avoid adding `value` to the descriptor.
return descriptor;
}
}
// If we got this far we know that object has an own property that is
// not an accessor so we set it as a value and return descriptor.
descriptor.value = object[property];
descriptor.writable = true;
return descriptor;
};
/* eslint-enable no-proto */
shim.object.getOwnPropertyNames = Object.getOwnPropertyNames && isFuncNative(Object.getOwnPropertyNames) ?
Object.getOwnPropertyNames :
function getOwnPropertyNames(object) {
return shim.object.keys(object);
};
if (!Object.create || !isFuncNative(Object.create)) {
// Contributed by Brandon Benvie, October, 2012
var createEmpty;
var supportsProto = !({__proto__: null} instanceof Object);//jshint ignore:line
// the following produces false positives
// in Opera Mini => not a reliable check
// Object.prototype.__proto__ === null
// Check for document.domain and active x support
// No need to use active x approach when document.domain is not set
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
/* global ActiveXObject */
var shouldUseActiveX = function shouldUseActiveX() {
// return early if document.domain not set
if (!document.domain) {
return false;
}
try {
return !!new ActiveXObject("htmlfile");
} catch (exception) {
return false;
}
};
// This supports IE8 when document.domain is used
// see https://github.com/es-shims/es5-shim/issues/150
// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
var getEmptyViaActiveX = function getEmptyViaActiveX() {
var empty;
var xDoc;
xDoc = new ActiveXObject("htmlfile");
xDoc.write("<script><\/script>");
xDoc.close();
empty = xDoc.parentWindow.Object.prototype;
xDoc = null;
return empty;
};
// The original implementation using an iframe
// before the activex approach was added
// see https://github.com/es-shims/es5-shim/issues/150
var getEmptyViaIFrame = function getEmptyViaIFrame() {
var iframe = document.createElement("iframe");
var parent = document.body || document.documentElement;
var empty;
iframe.style.display = "none";
parent.appendChild(iframe);
/* jshint ignore:start */
iframe.src = "javascript:";
/* jshint ignore:end */
empty = iframe.contentWindow.Object.prototype;
parent.removeChild(iframe);
iframe = null;
return empty;
};
/* global document */
if (supportsProto || typeof document === "undefined") {
createEmpty = function () {
return {__proto__: null}; //jshint ignore:line
};
} else {
// In old IE __proto__ can"t be used to manually set `null`, nor does
// any other method exist to make an object that inherits from nothing,
// aside from Object.prototype itself. Instead, create a new global
// object and *steal* its Object.prototype and strip it bare. This is
// used as the prototype to create nullary objects.
createEmpty = function () {
// Determine which approach to use
// see https://github.com/es-shims/es5-shim/issues/150
var empty = shouldUseActiveX() ? getEmptyViaActiveX() : getEmptyViaIFrame();
delete empty.constructor;
delete empty.hasOwnProperty;
delete empty.propertyIsEnumerable;
delete empty.isPrototypeOf;
delete empty.toLocaleString;
delete empty.toString;
delete empty.valueOf;
var Empty = function Empty() {
};
Empty.prototype = empty;
// short-circuit future calls
createEmpty = function () {
return new Empty();
};
return new Empty();
};
}
shim.object.create = function create(prototype, properties) {
var object;
var Type = function Type() {
}; // An empty constructor.
if (prototype === null) {
object = createEmpty();
} else {
if (typeof prototype !== "object" && typeof prototype !== "function") {
// In the native implementation `parent` can be `null`
// OR *any* `instanceof Object` (Object|Function|Array|RegExp|etc)
// Use `typeof` tho, b/c in old IE, DOM elements are not `instanceof Object`
// like they are in modern browsers. Using `Object.create` on DOM elements
// is...err...probably inappropriate, but the native version allows for it.
throw new TypeError("Object prototype may only be an Object or null"); // same msg as Chrome
}
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
/* eslint-disable no-proto */
object.__proto__ = prototype;//jshint ignore:line
/* eslint-enable no-proto */
}
if (properties !== void 0) {
shim.object.defineProperties(object, properties);
}
return object;
};
} else {
shim.object.create = Object.create;
}
var doesDefinePropertyWork = function doesDefinePropertyWork(object) {
try {
Object.defineProperty(object, "sentinel", {});
return "sentinel" in object;
} catch (exception) {
return false;
}
};
// check whether defineProperty works if it"s given. Otherwise,
// shim partially.
var definePropertyFallback;
var definePropertiesFallback;
if (Object.defineProperty && isFuncNative(Object.defineProperty)) {
var definePropertyWorksOnObject = doesDefinePropertyWork({});
var definePropertyWorksOnDom = typeof document === "undefined" ||
doesDefinePropertyWork(document.createElement("div"));
if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
definePropertyFallback = Object.defineProperty;
definePropertiesFallback = Object.defineProperties;
}
}
if (!Object.defineProperty || definePropertyFallback || !isFuncNative(Object.defineProperty)) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: ";
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined on this javascript engine";
shim.object.defineProperty = function defineProperty(object, property, descriptor) {
if ((typeof object !== "object" && typeof object !== "function") || object === null) {
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
}
if ((typeof descriptor !== "object" && typeof descriptor !== "function") || descriptor === null) {
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
}
// make a valiant attempt to use the real defineProperty
// for I8"s DOM elements.
if (definePropertyFallback) {
try {
return definePropertyFallback.call(Object, object, property, descriptor);
} catch (exception) {
// try the shim if the real one doesn't work
}
}
// If it"s a data property.
if ("value" in descriptor) {
if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) {
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don"t hit an inherited
// accessor.
/* jshint ignore:start */
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.__proto__ = prototype;
/* jshint ignore:end */
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors && (("get" in descriptor) || ("set" in descriptor))) {
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
}
// If we got that far then getters and setters can be defined !!
if ("get" in descriptor) {
defineGetter(object, property, descriptor.get);
}
if ("set" in descriptor) {
defineSetter(object, property, descriptor.set);
}
}
return object;
};
} else {
shim.object.defineProperty = Object.defineProperty;
}
// ES5 15.2.3.7
// http://es5.github.com/#x15.2.3.7
shim.object.defineProperties = Object.defineProperties && definePropertiesFallback && isFuncNative(Object.defineProperties) ?
Object.defineProperties :
function defineProperties(object, properties) {
// make a valiant attempt to use the real defineProperties
if (definePropertiesFallback) {
try {
return definePropertiesFallback.call(Object, object, properties);
} catch (exception) {
// try the shim if the real one doesn't work
}
}
array_forEach(shim.object.keys(properties), function (property) {
if (property !== "__proto__") {
shim.object.defineProperty(object, property, properties[property]);
}
});
return object;
};
// ES5 15.2.3.8
// http://es5.github.com/#x15.2.3.8
shim.object.seal = Object.seal && isFuncNative(Object.seal) ? Object.seal :
function seal(object) {
if (toObject(object) !== object) {
throw new TypeError("Object.seal can only be called on Objects.");
}
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
// ES5 15.2.3.9
// http://es5.github.com/#x15.2.3.9
shim.object.freeze = Object.freeze && isFuncNative(Object.freeze) ? Object.freeze :
function freeze(object) {
if (toObject(object) !== object) {
throw new TypeError("Object.freeze can only be called on Objects.");
}
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
// detect a Rhino bug and patch it
try {
Object.freeze(function () {
});
} catch (exception) {
shim.object.freeze = (function (freezeObject) {
return function freeze(object) {
if (typeof object === "function") {
return object;
} else {
return freezeObject(object);
}
};
}(shim.object.freeze));
}
// ES5 15.2.3.10
// http://es5.github.com/#x15.2.3.10
shim.object.preventExtensions = Object.preventExtensions && isFuncNative(Object.preventExtensions) ?
Object.preventExtensions : function preventExtensions(object) {
if (toObject(object) !== object) {
throw new TypeError("Object.preventExtensions can only be called on Objects.");
}
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
shim.object.isSealed = Object.isSealed && isFuncNative(Object.isSealed) ? Object.isSealed : function isSealed(object) {
if (toObject(object) !== object) {
throw new TypeError("Object.isSealed can only be called on Objects.");
}
return false;
};
// ES5 15.2.3.12
// http://es5.github.com/#x15.2.3.12
shim.object.isFrozen = Object.isFrozen && isFuncNative(Object.isFrozen) ? Object.isFrozen : function isFrozen(object) {
if (toObject(object) !== object) {
throw new TypeError("Object.isFrozen can only be called on Objects.");
}
return false;
};
// ES5 15.2.3.13
// http://es5.github.com/#x15.2.3.13
shim.object.isExtensible = Object.isExtensible && isFuncNative(Object.isExtensible) ? Object.isExtensible : function isExtensible(object) {
// 1. If Type(O) is not Object throw a TypeError exception.
if (toObject(object) !== object) {
throw new TypeError("Object.isExtensible can only be called on Objects.");
}
// 2. Return the Boolean value of the [[Extensible]] internal property of O.
var name = "";
while (owns(object, name)) {
name += "?";
}
object[name] = true;
var returnValue = owns(object, name);
delete object[name];
return returnValue;
};
(function(exports, Object, _){
var DependencyResolverException = function (message) {
this.name = "DependencyResolverException";
this.stack = null;
this.message = message || "A dependency resolver exception has occurred.";
var lines, i, tmp;
if ((typeof navigator !== "undefined" && navigator.userAgent.indexOf("Chrome") !== -1) ||
(typeof navigator === "undefined")) {
lines = new Error().stack.split("\n");
if (lines && lines.length > 2) {
tmp = [];
for (i = 2; i < lines.length; i++) {
if (lines[i]) {
tmp.push(lines[i].trim());
}
}
this.stack = tmp.join("\n");
}
} else if (typeof navigator !== "undefined" && navigator.userAgent.indexOf("Firefox") !== -1) {
lines = new Error().stack.split("\n");
if (lines && lines.length > 1) {
tmp = [];
for (i = 1; i < lines.length; i++) {
if (lines[i]) {
tmp.push("at " + lines[i].trim().replace("@", " (") + ")");
}
}
this.stack = tmp.join("\n");
}
} else if (typeof navigator !== "undefined" && navigator.userAgent.indexOf("Trident") !== -1) {
try {
throw new Error();
} catch (error) {
if ("stack" in error) {
lines = error.stack.split("\n");
if (lines && lines.length > 2) {
tmp = [];
for (i = 2; i < lines.length; i++) {
if (lines[i]) {
tmp.push(lines[i].trim());
}
}
this.stack = tmp.join("\n");
}
} else {
this.stack = "";
}
}
} else {
var error = new Error();
if ("stack" in error) {
this.stack = error.stack;
} else {
this.stack = "";
}
}
Object.defineProperty(this, "name", { enumerable: true });
Object.defineProperty(this, "message", { enumerable: true });
Object.defineProperty(this, "stack", { enumerable: true });
Object.seal(this);
};
DependencyResolverException.prototype = Object.create(Object.prototype, {
toString: {
value: function () {
var msg = this.name + ": " + this.message;
if (this.stack) {
msg += "\n\t" + this.stack.replace(/\n/g, "\n\t");
}
return msg;
},
enumerable: true
}
});
Object.seal(DependencyResolverException);
Object.seal(DependencyResolverException.prototype);
exports.DependencyResolverException = DependencyResolverException;
/* global DependencyResolverException */
var InstanceFactoryOptions = function (options) {
this.name = null;
this.type = null;
this.parameters = null;
if (options) {
for (var propertyName in options) {
if (propertyName in this) {
this[propertyName] = options[propertyName];
} else {
throw new DependencyResolverException("Class \"InstanceFactoryOptions\" doesn\"t have a property \"" +
propertyName + "\"");
}
}
}
Object.defineProperty(this, "name", { enumerable: true });
Object.defineProperty(this, "type", { enumerable: true });
Object.defineProperty(this, "parameters", { enumerable: true });
Object.seal(this);
};
InstanceFactoryOptions.prototype = Object.create(Object.prototype, {
toString: {
value: function () {
return "[object InstanceFactoryOptions]";
},
enumerable: true
}
});
Object.seal(InstanceFactoryOptions);
Object.seal(InstanceFactoryOptions.prototype);
exports.InstanceFactoryOptions = InstanceFactoryOptions;
var IInstanceFactory = Object.create(Object.prototype, {
create: {
value: function (options) {}, //eslint-disable-line no-unused-vars
enumerable: true
},
toString: {
value: function () {
return "[object IInstanceFactory]";
},
enumerable: true
}
});
Object.freeze(IInstanceFactory);
exports.IInstanceFactory = IInstanceFactory;
/* global DependencyResolverException */
var InstanceFactory = function () {
Object.seal(this);
};
InstanceFactory.prototype = Object.create(Object.prototype, {
create: {
value: function (options) {
if (!options) {
throw new DependencyResolverException("Parameter \"options\" is not set");
}
if ("type" in options && !options.type) {
throw new DependencyResolverException("Factory can't create object, because type is not set");
}
if (typeof options.type !== "function") {
throw new DependencyResolverException("Factory can't create object, because given type is not a function");
}
if (options.type === Number || options.type === Date || options.type === Boolean || options.type === String ||
options.type === Array || options.type === Function || options.type === RegExp) {
throw new DependencyResolverException("Basic type can not be instantiated using a factory");
}
var instance = null;
if (options.parameters && options.parameters.length > 0) {
if(Function.prototype.bind){ // ES5
var ClassType = Function.bind.apply(options.type,[null].concat(options.parameters));
instance = new ClassType();
} else{ //ES3
instance = Object.create(options.type.prototype);
options.type.apply(instance, options.parameters);
}
} else {
instance = new options.type();
}
return instance;
},
enumerable: true
},
toString: {
value: function () {
return "[object InstanceFactory]";
},
enumerable: true
}
});
Object.seal(InstanceFactory);
Object.seal(InstanceFactory.prototype);
exports.InstanceFactory = InstanceFactory;
var INameTransformer = Object.create(Object.prototype, {
transform: {
value: function (name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
toString: {
value: function () {
return "[object INameTransformer]";
},
enumerable: true
}
});
Object.freeze(INameTransformer);
exports.INameTransformer = INameTransformer;
/* global DependencyResolverException */
var NameTransformer = function () {
Object.seal(this);
};
NameTransformer.prototype = Object.create(Object.prototype, {
transform: {
value: function (name) {
if (!name) {
throw new DependencyResolverException("Parameter \"name\" is not passed to the method \"transform\"");
}
return name;
},
enumerable: true
},
toString: {
value: function () {
return "[object NameTransformer]";
},
enumerable: true
}
});
Object.seal(NameTransformer);
Object.seal(NameTransformer.prototype);
exports.NameTransformer = NameTransformer;
var IDependencyResolver = Object.create(Object.prototype, {
isAutowired: {
value: function () {},
enumerable: true
},
autowired: {
value: function (value) {},//eslint-disable-line no-unused-vars
enumerable: true
},
register: {
value: function (name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
as: {
value: function (type) {},//eslint-disable-line no-unused-vars
enumerable: true
},
instance: {
value: function (instance) {},//eslint-disable-line no-unused-vars
enumerable: true
},
asSingleton: {
value: function () {},
enumerable: true
},
withConstructor: {
value: function () {},
enumerable: true
},
param: {
value: function (name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
withProperties: {
value: function (name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
prop: {
value: function (name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
val: {
value: function (instance) {},//eslint-disable-line no-unused-vars
enumerable: true
},
ref: {
value: function (name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
setFactory: {
value: function (factory) {},//eslint-disable-line no-unused-vars
enumerable: true
},
create: {
value: function () {},
enumerable: true
},
inject: {
value: function (func, name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
contains: {
value: function (name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
resolve: {
value: function (name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
getDefaultFactory: {
value: function () {},
enumerable: true
},
setDefaultFactory: {
value: function (factory) {},//eslint-disable-line no-unused-vars
enumerable: true
},
getNameTransformer: {
value: function () {},
enumerable: true
},
setNameTransformer: {
value: function (transformer) {},//eslint-disable-line no-unused-vars
enumerable: true
},
getRegistration: {
value: function (name) {},//eslint-disable-line no-unused-vars
enumerable: true
},
dispose: {
value: function () {},
enumerable: true
},
toString: {
value: function () {
return "[object IDependencyResolver]";
},
enumerable: true
}
});
Object.freeze(IDependencyResolver);
exports.IDependencyResolver = IDependencyResolver;
/* global DependencyResolverException, InstanceFactory, NameTransformer, InstanceFactoryOptions, debug, index, args */
var DependencyResolver = function (parent) {
this.__parent = parent;
this.__defaultFactory = null;
this.__nameTransformer = null;
this.__autowired = false;
this.__container = null;
this.__registration = null;
this.__withProperties = false;
this.__withConstructor = false;
this.__parameter = null;
this.__property = null;
this.__function = null;
if (parent) {
this.__autowired = parent.isAutowired();
}
Object.defineProperty(this, "__parent", {enumerable: false});
Object.defineProperty(this, "__defaultFactory", {enumerable: false});
Object.defineProperty(this, "__nameTransformer", {enumerable: false});
Object.defineProperty(this, "__autowired", {enumerable: false});
Object.defineProperty(this, "__container", {enumerable: false});
Object.defineProperty(this, "__registration", {enumerable: false});
Object.defineProperty(this, "__withProperties", {enumerable: false});
Object.defineProperty(this, "__withConstructor", {enumerable: false});
Object.defineProperty(this, "__parameter", {enumerable: false});
Object.defineProperty(this, "__property", {enumerable: false});
Object.defineProperty(this, "__function", {enumerable: false});
Object.seal(this);
};
DependencyResolver.prototype = Object.create(Object.prototype, {
isAutowired: {
value: function () {
return this.__autowired;
},
enumerable: true
},
autowired: {
value: function (value) {
if (value === undefined || value === null) {
value = true;
}
if (typeof value !== "boolean") {
throw new DependencyResolverException("Parameter \"value\" passed to the method \"autowired\" has to " +
"be a \"boolean\"");
}
this.__autowired = value;
return this;
},
enumerable: true
},
register: {
value: function (name) {
if (!name) {
throw new DependencyResolverException("Parameter \"name\" is not passed to the method \"register\"");
}
if (typeof name !== "string") {
throw new DependencyResolverException("Parameter \"name\" passed to the method \"register\" has to be " +
"a \"string\"");
}
if (!this.__container) {
this.__container = Object.create(null);
}
this.__registration = {
name: name,
singleton: false,
type: null,
instance: null,
factory: null,
dependencies: null
};
if (!(name in this.__container)) {
this.__container[name] = this.__registration;
} else {
if (!(this.__container[name] instanceof Array)) {
this.__container[name] = [this.__container[name]];
}
this.__container[name].push(this.__registration);
}
this.__withConstructor = false;
this.__withProperties = false;
this.__parameter = null;
this.__property = null;
return this;
},
enumerable: true
},
as: {
value: function (type) {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (!type) {
throw new DependencyResolverException("Parameter \"type\" is not passed to the method \"as\" for " +
"registration \"" + this.__registration.name + "\"");
}
if (typeof type !== "function") {
throw new DependencyResolverException("Parameter \"type\" passed to the method \"as\" has to be a \"function\" " +
"for registration \"" + this.__registration.name + "\"");
}
this.__registration.instance = null;
this.__registration.type = type;
this.__registration.singleton = false;
this.__registration.dependencies = {
parameters: [],
properties: [],
functions: []
};
if(type.$inject && type.$inject instanceof Array){
this.__registration.dependencies.$inject = type.$inject;
}
this.__withConstructor = false;
this.__withProperties = false;
this.__parameter = null;
this.__property = null;
this.__function = null;
return this;
},
enumerable: true
},
instance: {
value: function (instance) {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (instance === null || instance === undefined) {
throw new DependencyResolverException("Parameter \"instance\" is not passed to the method \"instance\" for " +
"registration \"" + this.__registration.name + "\"");
}
this.__registration.instance = instance;
this.__registration.type = null;
this.__registration.factory = null;
this.__registration.singleton = true;
this.__registration.dependencies = null;
this.__withConstructor = false;
this.__withProperties = false;
this.__parameter = null;
this.__property = null;
this.__function = null;
return this;
},
enumerable: true
},
asSingleton: {
value: function () {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (!this.__registration.type) {
throw new DependencyResolverException("Type is not set for registration \"" +
this.__registration.name + "\"");
}
this.__registration.singleton = true;
this.__withConstructor = false;
this.__withProperties = false;
this.__parameter = null;
this.__property = null;
this.__function = null;
return this;
},
enumerable: true
},
withConstructor: {
value: function () {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (!this.__registration.type) {
throw new DependencyResolverException("Type is not set for registration \"" +
this.__registration.name + "\"");
}
this.__withConstructor = true;
this.__withProperties = false;
this.__parameter = null;
this.__property = null;
this.__function = null;
return this;
},
enumerable: true
},
param: {
value: function (name) {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (!this.__registration.type) {
throw new DependencyResolverException("Type is not set for registration \"" + this.__registration.name + "\"");
}
var parameters = null,
parameter = null,
index;
if (this.__withConstructor) {
parameters = this.__registration.dependencies.parameters;
if (this.__autowired && (name === undefined || name === null)) {
throw new DependencyResolverException("Parameter \"name\" has to be passed to the method, when dependency " +
"container has option \"autowired\" enabled");
}
parameter = this.__findParameter(name, parameters, this.__registration);
} else if (this.__withProperties) {
if (!this.__function) {
throw new DependencyResolverException("Function is not defined");
}
parameters = this.__function.parameters;
parameter = this.__findParameter(name, this.__function.parameters, this.__registration);
} else {
throw new DependencyResolverException("Invocation of method \"withConstructor\" or \"withProperties\" " +
"is missing for registration \"" + this.__registration.name + "\"");
}
if (!parameter) {
parameter = {
index: index,
name: name,
value: undefined,
reference: undefined
};
parameters.push(parameter);
}
this.__parameter = parameter;
this.__property = null;
return this;
},
enumerable: true
},
withProperties: {
value: function () {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (!this.__registration.type) {
throw new DependencyResolverException("Type is not set for registration \"" + this.__registration.name + "\"");
}
this.__withProperties = true;
this.__withConstructor = false;
this.__parameter = null;
this.__property = null;
this.__function = null;
return this;
},
enumerable: true
},
prop: {
value: function (name) {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (!name) {
throw new DependencyResolverException("Parameter \"name\" is not passed to the method \"prop\" for " +
"registration \"" + this.__registration.name + "\"");
}
if (typeof name !== "string") {
throw new DependencyResolverException("Parameter \"name\" passed to the method \"prop\" has to be" +
" a \"string\" for registration \"" + this.__registration.name + "\"");
}
if (!this.__registration.type) {
throw new DependencyResolverException("Type is not set for registration \"" + this.__registration.name + "\"");
}
if (!this.__withProperties) {
throw new DependencyResolverException("Invocation of method \"withProperties\" is missing for " +
"registration \"" + this.__registration.name + "\"");
}
var properties = this.__registration.dependencies.properties,
property = null;
for (var i = 0; i < properties.length; i++) {
if (properties[i].name === name) {
property = properties[i];
break;
}
}
if (!property) {
property = {
name: name,
value: undefined,
reference: undefined
};
properties.push(property);
}
this.__parameter = null;
this.__property = property;
this.__function = null;
return this;
},
enumerable: true
},
func: {
value: function (name) {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (!name) {
throw new DependencyResolverException("Parameter \"name\" is not passed to the method \"func\" for " +
"registration \"" + this.__registration.name + "\"");
}
if (typeof name !== "string") {
throw new DependencyResolverException("Parameter \"name\" passed to the method \"func\" has to be" +
" a \"string\" for registration \"" + this.__registration.name + "\"");
}
if (!this.__registration.type) {
throw new DependencyResolverException("Type is not set for registration \"" + this.__registration.name + "\"");
}
if (!this.__withProperties) {
throw new DependencyResolverException("Invocation of method \"withProperties\" is missing for " +
"registration \"" + this.__registration.name + "\"");
}
var functions = this.__registration.dependencies.functions,
func = null;
for (var i = 0; i < functions.length; i++) {
if (functions[i].name === name) {
func = functions[i];
break;
}
}
if (!func) {
func = {
name: name,
parameters: []
};
functions.push(func);
}
this.__parameter = null;
this.__property = null;
this.__function = func;
return this;
},
enumerable: true
},
val: {
value: function (instance) {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (instance === null || instance === undefined) {
throw new DependencyResolverException("Parameter \"instance\" is not passed to the method \"val\"");
}
if (!this.__withProperties && !this.__withConstructor) {
throw new DependencyResolverException("Invocation of method withConstructor\" or \"withProperties\" " +
"is missing");
}
if (this.__withConstructor && !this.__parameter) {
throw new DependencyResolverException("Parameter is not defined");
}
if (this.__withProperties && !this.__parameter && !this.__property) {
throw new DependencyResolverException("Parameter or property is not defined");
}
if (this.__parameter) {
this.__parameter.value = instance;
this.__parameter.reference = undefined;
} else if (this.__property) {
this.__property.value = instance;
this.__property.reference = undefined;
}
return this;
},
enumerable: true
},
ref: {
value: function (name) {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (!name) {
throw new DependencyResolverException("Parameter \"name\" is not passed to the method \"ref\" for " +
"registration \"" + this.__registration.name + "\"");
}
if (typeof name !== "string") {
throw new DependencyResolverException("Parameter \"name\" passed to the method \"ref\" has to " +
"be a \"string\" for registration \"" + this.__registration.name + "\"");
}
if (!this.__withProperties && !this.__withConstructor) {
throw new DependencyResolverException("Invocation of method \"withConstructor\" or \"withProperties\" " +
"is missing for registration \"" + this.__registration.name + "\"");
}
if (this.__withConstructor && !this.__parameter) {
throw new DependencyResolverException("Parameter is not defined");
}
if (this.__withProperties && !this.__parameter && !this.__property) {
throw new DependencyResolverException("Parameter or property is not defined");
}
if (!this.contains(name)) {
throw new DependencyResolverException("Type or instance is not registered with name \"" + name + "\"");
}
if (this.__parameter) {
this.__parameter.value = undefined;
this.__parameter.reference = name;
} else if (this.__property) {
this.__property.value = undefined;
this.__property.reference = name;
}
return this;
},
enumerable: true
},
setFactory: {
value: function (factory) {
if (!this.__registration) {
throw new DependencyResolverException("Registration's name is not defined");
}
if (!factory) {
throw new DependencyResolverException("Parameter \"factory\" is not passed to the method \"setFactory\"");
}
if (typeof factory !== "function" && typeof factory !== "object") {
throw new DependencyResolverException("Parameter \"factory\" passed to the method \"setFactory\" has to be " +
"a \"function\" or \"object\"");
}
if (typeof factory === "object" && !("create" in factory)) {
throw new DependencyResolverException("Factory's instance passed to the method \"setFactory\" has to have " +
"a method \"create\"");
}
if (!this.__registration.type) {
throw new DependencyResolverException("Type is not set for registration \"" + this.__registration.name);
}
this.__registration.factory = factory;
this.__withConstructor = false;
this.__withProperties = false;
this.__parameter = null;
this.__property = null;
this.__function = null;
return this;
},
enumerable: true
},
create: {
value: function () {
return new DependencyResolver(this);
},
enumerable: true
},
inject: {
value: function (func) {
if (!func) {
throw new DependencyResolverException("Parameter \"func\" is not passed to method \"inject\"");
}
var i,
parameters = [],
context = {resolving: []};
if (func instanceof Array) {
if (func.length === 0) {
throw new DependencyResolverException("The array passed to the method \"inject\" can't be empty");
}
for (i = 0; i < func.length - 1; i++) {
parameters.push(func[i]);
}
func = func[func.length - 1];
if (typeof func !== "function") {
throw new DependencyResolverException("The last item of the array passed to the method \"inject\" has " +
"to be a \"function\"");
}
for (i = 0; i < parameters.length; i++) {
if (typeof parameters[i] === "string" && this.contains(parameters[i])) {
parameters[i] = this.__resolve(parameters[i], context);
}
}
func.apply(null, parameters);
} else {
var registration = null;
if (arguments.length === 2 && typeof arguments[1] === "string") {
var name = arguments[1];
if (!this.contains(name)) {
throw new DependencyResolverException("Type with name \"" + name + "\" is not registered");
}
registration = this.getRegistration(name);
}
var dependencyName;
if (typeof func === "function") {
if (registration) {
parameters = this.__getConstructorParameters(registration, context);
} else {
var args = this.__getFunctionArguments(func);
for (i = 0; i < args.length; i++) {
dependencyName = this.__resolveDependencyName(args[i]);
if (this.contains(dependencyName)) {
parameters.push(this.__resolve(dependencyName, context));
} else {
parameters.push(null);
}
}
}
func.apply(null, parameters);
} else if (typeof func === "object") {
if (registration) {
this.__setProperties(func, registration, context);
this.__invokeFunctions(func, registration, context);
} else {
for (var propertyName in func) {//eslint-disable-line guard-for-in
dependencyName = this.__resolveDependencyName(propertyName);
if (this.contains(dependencyName)) {
parameters.push({
name: propertyName,
value: this.__resolve(dependencyName, context)
});
}
}
if (parameters.length > 0) {
for (i = 0; i < parameters.length; i++) {
func[parameters[i].name] = parameters[i].value;
}
}
}
} else {
throw new DependencyResolverException("Invalid parameter has been passed to the method \"inject\"");
}
}
return this;
},
enumerable: true
},
contains: {
value: function (name) {
if (!name) {
throw new DependencyResolverException("Parameter \"name\" is not passed to the method \"contains\"");
}
if (typeof name !== "string") {
throw new DependencyResolverException("Parameter \"name\" passed to the has to be a \"string\"");
}
var has = false;
if (this.__container) {
if (name in this.__container) {
has = true;
}
}
if (!has && this.__parent) {
if (!("contains" in this.__parent)) {
throw new DependencyResolverException("Dependency resolver's parent doesn't have a method \"contains\"");
}
has = this.__parent.contains(name);
}
return has;
},
enumerable: true
},
resolve: {
value: function (name) {
return this.__resolve(name, {
resolving: []
});
},
enumerable: true
},
getDefaultFactory: {
value: function () {
var factory = null;
if (this.__defaultFactory) {
factory = this.__defaultFactory;
} else if (this.__parent) {
if (!("getDefaultFactory" in this.__parent)) {
throw new DependencyResolverException("Dependency resolver's parent doesn't have a " +
"method \"getDefaultFactory\"");
}
factory = this.__parent.getDefaultFactory();
} else {
factory = new InstanceFactory();
}
return factory;
},
enumerable: true
},
setDefaultFactory: {
value: function (factory) {
if (!factory) {
throw new DependencyResolverException("Parameter \"factory\" is not passed to the method " +
"\"setDefaultFactory\"");
}
if (typeof factory !== "function" && typeof factory !== "object") {
throw new DependencyResolverException("Parameter \"factory\" passed to the method \"setDefaultFactory\" has " +
" to be a \"function\" or \"object\"");
}
if (typeof factory === "object" && !("create" in factory)) {
throw new DependencyResolverException("Factory's instance passed to the method \"setDefaultFactory\" has " +
"to have a method \"create\"");
}
this.__defaultFactory = factory;
return this;
},
enumerable: true
},
getNameTransformer: {
value: function () {
var transformer = null;
if (this.__nameTransformer) {
transformer = this.__nameTransformer;
} else if (this.__parent) {
if (!("getNameTransformer" in this.__parent)) {
throw new DependencyResolverException("Dependency resolver's parent doesn't have a " +
"method \"getNameTransformer\"");
}
transformer = this.__parent.getNameTransformer();
} else {
transformer = new NameTransformer();
}
return transformer;
},
enumerable: true
},
setNameTransformer: {
value: function (transformer) {
if (!transformer) {
throw new DependencyResolverException("Parameter \"transformer\" is not passed to the method " +
"\"setNameTransformer\"");
}
if (typeof transformer !== "function" && typeof transformer !== "object") {
throw new DependencyResolverException("Parameter \"transformer\" passed to the method \"setNameTransformer\" " +
"has to be a \"function\" or \"object\"");
}
if (typeof transformer === "object" && !("transform" in transformer)) {
throw new DependencyResolverException("Transformers's instance passed to the method \"setNameTransformer\" " +
"has to have a method \"transform\"");
}
this.__nameTransformer = transformer;
return this;
},
enumerable: true
},
getRegistration: {
value: function (name) {
var registration = null;
if (this.__container && name in this.__container) {
registration = this.__container[name];
} else if (this.__parent) {
if (!("getRegistration" in this.__parent)) {
throw new DependencyResolverException("Dependency resolver\"s parent doesn't have a " +
"method \"getRegistration\"");
}
registration = this.__parent.getRegistration(name);
}
return registration;
},
enumerable: true
},
dispose: {
value: function () {
var registration = null,
i = 0;
if (this.__container) {
for (var name in this.__container) {
if (!(this.__container[name] instanceof Array)) {
registration = this.__container[name];
if (registration.instance && ("dispose" in registration.instance)) {
registration.instance.dispose();
}
registration.instance = null;
registration.factory = null;
} else {
var registrations = this.__container[name];
for (i = 0; i < registrations.length; i++) {
registration = registrations[i];
if (registration.instance && ("dispose" in registration.instance)) {
registration.instance.dispose();
}
registration.instance = null;
registration.factory = null;
}
}
}
}
this.__parent = null;
this.__defaultFactory = null;
this.__nameTransformer = null;
this.__autowired = false;
this.__container = null;
this.__registration = null;
this.__withProperties = false;
this.__withConstructor = false;
this.__parameter = null;
this.__property = null;
this.__function = null;
},
enumerable: true
},
toString: {
value: function () {
return "[object DependencyResolver]";
},
enumerable: true
},
__getFunctionArguments: {
value: function (func) {
if (func && typeof func === "function" && "toString" in func) {
var str = null;
var result = _.function_toString.call(func)
.match(/^[\s\(]*function[^(]*\(([^)]*)\)/);
if (result && result.length > 1) {
str = result[1]
.replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, "")
.replace(/\s+/g, "");
}
if (str) {
return str.split(",");
}
}
return [];
}
},
__isClass: {
value: function (func) {
return func && typeof func === 'function' && 'toString' in func
&& /^class\s/.test(func.toString());
}
},
__getClassConstructorArguments: {
value: function (constr) {
if (constr && typeof constr === 'function' && 'toString' in constr) {
var str = null;
var result = constr
.toString()
.match(/^class[\s\S]*constructor[\s]*\(([^)]*)\)/);
if (result && result.length > 1) {
str = result[1]
.replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
.replace(/\s+/g, '');
}
if (str) {
return str.split(',');
}
}
return [];
}
},
__resolve: {
value: function (name, context) {
if (!name) {
throw new DependencyResolverException("Parameter \"name\" is not passed to the method \"resolve\"");
}
if (typeof name !== "string") {
throw new DependencyResolverException("Parameter \"name\" passed to the method \"resolve\" has to be " +
"a \"string\"");
}
if (debug && console && "log" in console) {
var message = "-> \"" + name + "\"";
for (var j = 0; j < context.resolving.length; j++) {
message = " " + message;
}
console.log(message);
}
if (!this.contains(name)) {
throw new DependencyResolverException("Type or instance with name \"" + name + "\" is not registered");
}
var index = _.indexOf(context.resolving, name);
if (index !== -1) {
throw new DependencyResolverException("Can not resolve circular dependency \"" + name + "\"");
}
context.resolving.push(name);
var instance = null,
registration = this.getRegistration(name);
if (!(registration instanceof Array)) {
instance = this.__resolveInstance(registration, context);
} else {
instance = [];
for (var i = 0; i < registration.length; i++) {
instance.push(this.__resolveInstance(registration[i], context));
}
}
index = _.indexOf(context.resolving, name);
if (index > -1) {
context.resolving.splice(index, 1);
}
return instance;
}
},
__resolveInstance: {
value: function (registration, context) {
var instance = null;
if (registration.instance !== null && registration.instance !== undefined) {
instance = registration.instance;
} else {
instance = this.__createInstance(registration, context);
this.__setProperties(instance, registration, context);
this.__invokeFunctions(instance, registration, context);
if (instance && registration.singleton) {
registration.instance = instance;
}
if (!instance) {
throw new DependencyResolverException("Failed to resolve instance by name \"" + registration.name + "\"");
}
}
return instance;
}
},
__resolveDependencyName: {
value: function (name) {
var transform = this.getNameTransformer();
if (typeof transform === "function") {
name = transform(name);
} else {
name = transform.transform(name);
}
if (!name) {
throw new DependencyResolverException("Failed to resolve dependency name");
}
return name;
}
},
__createInstance: {
value: function (registration, context) {
var i,//eslint-disable-line no-unused-vars
instance;
var parameters = this.__getConstructorParameters(registration, context);
var options = new InstanceFactoryOptions({
name: registration.name,
type: registration.type,
parameters: parameters
});
var factory = null;
if (registration.factory) {
factory = registration.factory;
} else {
factory = this.getDefaultFactory();
}
if (factory) {
if (typeof factory === "function") {
instance = factory.call(null, options);
} else {
instance = factory.create(options);
}
} else {
throw new DependencyResolverException("Default factory is not defined");
}
return instance;
}
},
__getConstructorParameters: {
value: function (registration, context) {
var parameters = [];
if (registration && registration.dependencies) {
var i,
parameter,
value,
args,
index;
if (this.__autowired) {
args = this.__isClass(registration.type) ?
this.__getClassConstructorArguments(registration.type) : this.__getFunctionArguments(registration.type);
if(registration.dependencies.$inject){
if(registration.dependencies.$inject.length !== args.length){
throw new DependencyResolverException("Constructor in registration \"" + registration.name +
"\" have $inject property with wrong arguments length.");
}
args = registration.dependencies.$inject;
}
var dependencyName;
for (i = 0; i < args.length; i++) {
dependencyName = this.__resolveDependencyName(args[i]);
if (this.contains(dependencyName)) {
parameters.push(this.__resolve(dependencyName, context));
} else {
parameters.push(null);
}
}
}
for (i = 0; i < registration.dependencies.parameters.length; i++) {
parameter = registration.dependencies.parameters[i];
if (parameter.value !== undefined) {
value = parameter.value;
} else if (parameter.reference !== undefined) {
value = this.__resolve(parameter.reference, context);
} else {
value = null;
}
if (parameter.index !== undefined && parameter.index !== null) {
parameters[parameter.index] = value;
} else if (parameter.name) {
if (!args) {
args = this.__getFunctionArguments(registration.type);
}
index = _.indexOf(args, parameter.name);
if (index === -1) {
throw new DependencyResolverException("Constructor in registration \"" + registration.name +
"\" doesn't have defined parameter \"" + parameter.name + "\"");
}
parameters[index] = value;
} else {
parameters.push(value);
}
}
}
return parameters;
}
},
__hasProperty: {
value: function (registration, name) {
var has = false;
if (registration.dependencies) {
var property;
for (var i = 0; i < registration.dependencies.properties.length; i++) {
property = registration.dependencies.properties[i];
if (property.name === name) {
has = true;
break;
}
}
}
return has;
}
},
__findParameter: {
value: function (name, parameters, registration) {
var parameter = null;
if (name !== null && name !== undefined && registration !== null) {
if (typeof name === "number") {
index = name;
name = undefined;
if (index < 0) {
throw new DependencyResolverException("Parameter \"name\" passed to the method \"param\" is out of " +
"range for registration \"" + registration.name + "\"");
}
if (index < parameters.length) {
parameter = parameters[index];
}
} else if (typeof name === "string") {
for (var i = 0; i < parameters.length; i++) {
if (parameters[i].name === name) {
parameter = parameters[i];
break;
}
}
} else {
throw new DependencyResolverException("Parameter \"name\" passed to the method \"param\" has to " +
"be a \"number\" or a \"string\" for registration \"" + registration.name + "\"");
}
}
return parameter;
}
},
__setProperties: {
value: function (instance, registration, context) {
if (registration.dependencies) {
if (this.__autowired) {
for (var propertyName in instance) {//eslint-disable-line guard-for-in
if (propertyName === "__proto__") {
continue;
}
var dependencyName = this.__resolveDependencyName(propertyName);
if (!this.__hasProperty(registration, propertyName) && this.contains(dependencyName)) {
instance[propertyName] = this.__resolve(dependencyName, context);
}
}
}
for (var i = 0; i < registration.dependencies.properties.length; i++) {
var property = registration.dependencies.properties[i];
if (!(property.name in instance)) {
throw new DependencyResolverException("Resolved object \"" + registration.name +
"\" doesn't have property \"" + property.name + "\"");
}
if (property.value !== undefined) {
instance[property.name] = property.value;
} else if (property.reference !== undefined) {
instance[property.name] = this.__resolve(property.reference, context);
}
}
}
}
},
__invokeFunctions: {
value: function (instance, registration, context) {
if (registration.dependencies) {
var i,
j,
parameter,
value;
for (i = 0; i < registration.dependencies.functions.length; i++) {
var func = registration.dependencies.functions[i];
if (!(func.name in instance)) {
throw new DependencyResolverException("Resolved object \"" + registration.name +
"\" doesn't have function \"" + func.name + "\"");
}
var parameters = [];
for (j = 0; j < func.parameters.length; j++) {
parameter = func.parameters[j];
if (parameter.value !== undefined) {
value = parameter.value;
} else if (parameter.reference !== undefined) {
value = this.__resolve(parameter.reference, context);
} else {
value = null;
}
if (parameter.index !== undefined && parameter.index !== null) {
parameters[parameter.index] = value;
} else if (parameter.name) {
if (!args) {
args = this.__getFunctionArguments(instance[func.name]);//eslint-disable-line
}
index = _.indexOf(args, parameter.name);
if (index === -1) {
throw new DependencyResolverException("Function doesn't have defined parameter \"" +
parameter.name + "\"");
}
parameters[index] = value;
} else {
parameters.push(value);
}
}
instance[func.name].apply(instance, parameters);
}
}
}
}
});
Object.seal(DependencyResolver);
Object.seal(DependencyResolver.prototype);
exports.DependencyResolver = DependencyResolver;
/* global DependencyResolver*/
var defaultDependencyResolver = null,
debug = false;
Object.defineProperty(exports, "getDefaultDependencyResolver", {
value: function () {
if (!defaultDependencyResolver) {
defaultDependencyResolver = new DependencyResolver();
}
return defaultDependencyResolver;
},
enumerable: true
});
Object.defineProperty(exports, "setDefaultDependencyResolver", {
value: function (value) {
defaultDependencyResolver = value;
},
enumerable: true
});
Object.defineProperty(exports, "isAutowired", {
value: function () {
return exports
.getDefaultDependencyResolver()
.isAutowired();
},
enumerable: true
});
Object.defineProperty(exports, "autowired", {
value: function (value) {
return exports
.getDefaultDependencyResolver()
.autowired(value);
},
enumerable: true
});
Object.defineProperty(exports, "register", {
value: function (name) {
return exports
.getDefaultDependencyResolver()
.register(name);
},
enumerable: true
});
Object.defineProperty(exports, "as", {
value: function (type) {
return exports
.getDefaultDependencyResolver()
.as(type);
},
enumerable: true
});
Object.defineProperty(exports, "instance", {
value: function (instance) {
return exports
.getDefaultDependencyResolver()
.instance(instance);
},
enumerable: true
});
Object.defineProperty(exports, "asSingleton", {
value: function () {
return exports
.getDefaultDependencyResolver()
.asSingleton();
},
enumerable: true
});
Object.defineProperty(exports, "withConstructor", {
value: function () {
return exports
.getDefaultDependencyResolver()
.withConstructor();
},
enumerable: true
});
Object.defineProperty(exports, "param", {
value: function (name) {
return exports
.getDefaultDependencyResolver()
.param(name);
},
enumerable: true
});
Object.defineProperty(exports, "withProperties", {
value: function () {
return exports
.getDefaultDependencyResolver()
.withProperties();
},
enumerable: true
});
Object.defineProperty(exports, "prop", {
value: function (name) {
return exports
.getDefaultDependencyResolver()
.prop(name);
}
});
Object.defineProperty(exports, "func", {
value: function (name) {
return exports
.getDefaultDependencyResolver()
.func(name);
}
});
Object.defineProperty(exports, "val", {
value: function (instance) {
return exports
.getDefaultDependencyResolver()
.val(instance);
},
enumerable: true
});
Object.defineProperty(exports, "ref", {
value: function (name) {
return exports
.getDefaultDependencyResolver()
.ref(name);
},
enumerable: true
});
Object.defineProperty(exports, "setFactory", {
value: function (factory) {
return exports
.getDefaultDependencyResolver()
.setFactory(factory);
},
enumerable: true
});
Object.defineProperty(exports, "create", {
value: function () {
return exports
.getDefaultDependencyResolver()
.create();
},
enumerable: true
});
Object.defineProperty(exports, "inject", {
value: function (func, name) {
return exports
.getDefaultDependencyResolver()
.inject(func, name);
},
enumerable: true
});
Object.defineProperty(exports, "contains", {
value: function (name) {
return exports
.getDefaultDependencyResolver()
.contains(name);
},
enumerable: true
});
Object.defineProperty(exports, "resolve", {
value: function (name) {
return exports
.getDefaultDependencyResolver()
.resolve(name);
},
enumerable: true
});
Object.defineProperty(exports, "getDefaultFactory", {
value: function () {
return exports
.getDefaultDependencyResolver()
.getDefaultFactory();
},
enumerable: true
});
Object.defineProperty(exports, "setDefaultFactory", {
value: function (factory) {
return exports
.getDefaultDependencyResolver()
.setDefaultFactory(factory);
},
enumerable: true
});
Object.defineProperty(exports, "getNameTransformer", {
value: function () {
return exports
.getDefaultDependencyResolver()
.getNameTransformer();
},
enumerable: true
});
Object.defineProperty(exports, "setNameTransformer", {
value: function (transformer) {
return exports
.getDefaultDependencyResolver()
.setNameTransformer(transformer);
},
enumerable: true
});
Object.defineProperty(exports, "getRegistration", {
value: function (name) {
return exports
.getDefaultDependencyResolver()
.getRegistration(name);
},
enumerable: true
});
Object.defineProperty(exports, "debug", {
value:debug,
enumerable: true
});
Object.defineProperty(exports, "dispose", {
value: function () {
return exports
.getDefaultDependencyResolver()
.dispose();
},
enumerable: true
});
} (exports, shim.object, shim._));
module.exports = exports;
|
'use strict'
const {WEBPACK_DONT_ALWAYS_PRINT_STDIO = 'false'} = require('process').env
const main = require('./lib/test-spawn')
main({
alwaysPrintStdIO: WEBPACK_DONT_ALWAYS_PRINT_STDIO !== 'true',
defaultExecutable: 'webpack',
envMiddleName: 'WEBPACK'
})
|
/*global history */
sap.ui.define([
"md/standalone/no/unit/line/no/line/unit/controller/BaseController",
"sap/ui/model/json/JSONModel",
"sap/ui/model/Filter",
"sap/ui/model/FilterOperator",
"sap/m/GroupHeaderListItem",
"sap/ui/Device",
"md/standalone/no/unit/line/no/line/unit/model/formatter"
], function (BaseController, JSONModel, Filter, FilterOperator, GroupHeaderListItem, Device, formatter) {
"use strict";
return BaseController.extend("md.standalone.no.unit.line.no.line.unit.controller.Master", {
formatter: formatter,
/* =========================================================== */
/* lifecycle methods */
/* =========================================================== */
/**
* Called when the master list controller is instantiated. It sets up the event handling for the master/detail communication and other lifecycle tasks.
* @public
*/
onInit : function () {
// Control state model
var oList = this.byId("list"),
oViewModel = this._createViewModel(),
// Put down master list's original value for busy indicator delay,
// so it can be restored later on. Busy handling on the master list is
// taken care of by the master list itself.
iOriginalBusyDelay = oList.getBusyIndicatorDelay();
this._oList = oList;
// keeps the filter and search state
this._oListFilterState = {
aFilter : [],
aSearch : []
};
this.setModel(oViewModel, "masterView");
// Make sure, busy indication is showing immediately so there is no
// break after the busy indication for loading the view's meta data is
// ended (see promise 'oWhenMetadataIsLoaded' in AppController)
oList.attachEventOnce("updateFinished", function(){
// Restore original busy indicator delay for the list
oViewModel.setProperty("/delay", iOriginalBusyDelay);
});
this.getView().addEventDelegate({
onBeforeFirstShow: function () {
this.getOwnerComponent().oListSelector.setBoundMasterList(oList);
}.bind(this)
});
this.getRouter().getRoute("master").attachPatternMatched(this._onMasterMatched, this);
this.getRouter().attachBypassed(this.onBypassed, this);
},
/* =========================================================== */
/* event handlers */
/* =========================================================== */
/**
* After list data is available, this handler method updates the
* master list counter and hides the pull to refresh control, if
* necessary.
* @param {sap.ui.base.Event} oEvent the update finished event
* @public
*/
onUpdateFinished : function (oEvent) {
// update the master list object counter after new data is loaded
this._updateListItemCount(oEvent.getParameter("total"));
// hide pull to refresh if necessary
this.byId("pullToRefresh").hide();
},
/**
* Event handler for the master search field. Applies current
* filter value and triggers a new search. If the search field's
* 'refresh' button has been pressed, no new search is triggered
* and the list binding is refresh instead.
* @param {sap.ui.base.Event} oEvent the search event
* @public
*/
onSearch : function (oEvent) {
if (oEvent.getParameters().refreshButtonPressed) {
// Search field's 'refresh' button has been pressed.
// This is visible if you select any master list item.
// In this case no new search is triggered, we only
// refresh the list binding.
this.onRefresh();
return;
}
var sQuery = oEvent.getParameter("query");
if (sQuery) {
this._oListFilterState.aSearch = [new Filter("Description", FilterOperator.Contains, sQuery)];
} else {
this._oListFilterState.aSearch = [];
}
this._applyFilterSearch();
},
/**
* Event handler for refresh event. Keeps filter, sort
* and group settings and refreshes the list binding.
* @public
*/
onRefresh : function () {
this._oList.getBinding("items").refresh();
},
/**
* Event handler for the list selection event
* @param {sap.ui.base.Event} oEvent the list selectionChange event
* @public
*/
onSelectionChange : function (oEvent) {
// get the list item, either from the listItem parameter or from the event's source itself (will depend on the device-dependent mode).
this._showDetail(oEvent.getParameter("listItem") || oEvent.getSource());
},
/**
* Event handler for the bypassed event, which is fired when no routing pattern matched.
* If there was an object selected in the master list, that selection is removed.
* @public
*/
onBypassed : function () {
this._oList.removeSelections(true);
},
/**
* Used to create GroupHeaders with non-capitalized caption.
* These headers are inserted into the master list to
* group the master list's items.
* @param {Object} oGroup group whose text is to be displayed
* @public
* @returns {sap.m.GroupHeaderListItem} group header with non-capitalized caption.
*/
createGroupHeader : function (oGroup) {
return new GroupHeaderListItem({
title : oGroup.text,
upperCase : false
});
},
/**
* Event handler for navigating back.
* We navigate back in the browser historz
* @public
*/
onNavBack : function() {
history.go(-1);
},
/* =========================================================== */
/* begin: internal methods */
/* =========================================================== */
_createViewModel : function() {
return new JSONModel({
isFilterBarVisible: false,
filterBarLabel: "",
delay: 0,
title: this.getResourceBundle().getText("masterTitleCount", [0]),
noDataText: this.getResourceBundle().getText("masterListNoDataText"),
sortBy: "Description",
groupBy: "None"
});
},
/**
* If the master route was hit (empty hash) we have to set
* the hash to to the first item in the list as soon as the
* listLoading is done and the first item in the list is known
* @private
*/
_onMasterMatched : function() {
this.getOwnerComponent().oListSelector.oWhenListLoadingIsDone.then(
function (mParams) {
if (mParams.list.getMode() === "None") {
return;
}
var sObjectId = mParams.firstListitem.getBindingContext().getProperty("ID");
this.getRouter().navTo("object", {objectId : sObjectId}, true);
}.bind(this),
function (mParams) {
if (mParams.error) {
return;
}
this.getRouter().getTargets().display("detailNoObjectsAvailable");
}.bind(this)
);
},
/**
* Shows the selected item on the detail page
* On phones a additional history entry is created
* @param {sap.m.ObjectListItem} oItem selected Item
* @private
*/
_showDetail : function (oItem) {
var bReplace = !Device.system.phone;
this.getRouter().navTo("object", {
objectId : oItem.getBindingContext().getProperty("ID")
}, bReplace);
},
/**
* Sets the item count on the master list header
* @param {integer} iTotalItems the total number of items in the list
* @private
*/
_updateListItemCount : function (iTotalItems) {
var sTitle;
// only update the counter if the length is final
if (this._oList.getBinding("items").isLengthFinal()) {
sTitle = this.getResourceBundle().getText("masterTitleCount", [iTotalItems]);
this.getModel("masterView").setProperty("/title", sTitle);
}
},
/**
* Internal helper method to apply both filter and search state together on the list binding
* @private
*/
_applyFilterSearch : function () {
var aFilters = this._oListFilterState.aSearch.concat(this._oListFilterState.aFilter),
oViewModel = this.getModel("masterView");
this._oList.getBinding("items").filter(aFilters, "Application");
// changes the noDataText of the list in case there are no filter results
if (aFilters.length !== 0) {
oViewModel.setProperty("/noDataText", this.getResourceBundle().getText("masterListNoDataWithFilterOrSearchText"));
} else if (this._oListFilterState.aSearch.length > 0) {
// only reset the no data text to default when no new search was triggered
oViewModel.setProperty("/noDataText", this.getResourceBundle().getText("masterListNoDataText"));
}
},
/**
* Internal helper method to apply both group and sort state together on the list binding
* @param {sap.ui.model.Sorter[]} aSorters an array of sorters
* @private
*/
_applyGroupSort : function (aSorters) {
this._oList.getBinding("items").sort(aSorters);
},
/**
* Internal helper method that sets the filter bar visibility property and the label's caption to be shown
* @param {string} sFilterBarText the selected filter value
* @private
*/
_updateFilterBar : function (sFilterBarText) {
var oViewModel = this.getModel("masterView");
oViewModel.setProperty("/isFilterBarVisible", (this._oListFilterState.aFilter.length > 0));
oViewModel.setProperty("/filterBarLabel", this.getResourceBundle().getText("masterFilterBarText", [sFilterBarText]));
}
});
}
);
|
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'assets/js/*.js',
'!assets/js/scripts.min.js'
]
},
sass: {
dist: {
options: {
style: 'expanded',
compass: true,
// Source maps are available, but require Sass 3.3.0 to be installed
// https://github.com/gruntjs/grunt-contrib-sass#sourcemap
sourcemap: false,
require: "breakpoint",
},
files: {
// 'assets/css/main.min.css': [
// 'assets/sass/app.scss'
// ],
'assets/css/master.min.css': [
'assets/sass/master.scss'
]
}
}
},
uglify: {
dist: {
files: {
'assets/js/scripts.min.js': [
'assets/js/plugins/bootstrap/transition.js',
'assets/js/plugins/bootstrap/alert.js',
'assets/js/plugins/bootstrap/button.js',
'assets/js/plugins/bootstrap/carousel.js',
'assets/js/plugins/bootstrap/collapse.js',
'assets/js/plugins/bootstrap/dropdown.js',
'assets/js/plugins/bootstrap/modal.js',
'assets/js/plugins/bootstrap/tooltip.js',
'assets/js/plugins/bootstrap/popover.js',
'assets/js/plugins/bootstrap/scrollspy.js',
'assets/js/plugins/bootstrap/tab.js',
'assets/js/plugins/bootstrap/affix.js',
'assets/js/plugins/*.js',
'assets/js/_*.js'
]
},
options: {
// JS source map: to enable, uncomment the lines below and update sourceMappingURL based on your install
// sourceMap: 'assets/js/scripts.min.js.map',
// sourceMappingURL: '/app/themes/roots/assets/js/scripts.min.js.map'
}
}
},
version: {
options: {
file: 'lib/scripts.php',
css: 'assets/css/main.min.css',
cssHandle: 'roots_main',
js: 'assets/js/scripts.min.js',
jsHandle: 'roots_scripts'
}
},
watch: {
sass: {
files: [
//'assets/sass/*.scss',
//'assets/sass/**/*',
'assets/sass/components/*.scss',
'assets/sass/elements/*.scss',
//'assets/sass/includes/*.scss',
'assets/sass/page-templates/*.scss',
'assets/sass/vendors/*.scss',
'assets/sass/master.scss',
//'assets/sass/bootstrap/*.scss'
],
tasks: ['sass', 'version']
},
js: {
files: [
'<%= jshint.all %>'
],
// tasks: ['jshint', 'uglify', 'version']
tasks: ['uglify', 'version']
},
livereload: {
// Browser live reloading
// https://github.com/gruntjs/grunt-contrib-watch#live-reloading
options: {
livereload: true
},
files: [
// 'assets/css/main.min.css',
'assets/css/master.css',
'assets/js/scripts.min.js',
'templates/*.php',
'*.php'
]
}
},
clean: {
dist: [
//'assets/css/main.min.css',
'assets/css/master.css',
'assets/js/scripts.min.js'
]
}
});
// Load tasks
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-wp-version');
// Register tasks
grunt.registerTask('default', [
//'clean',
'sass',
//'uglify',
//'version'
]);
grunt.registerTask('dev', [
'watch'
]);
};
|
var dir_dacb3312737b682230fbf101b5a77450 =
[
[ "utilities", "dir_45f8a1cbe1d055833100269ade1d303b.html", "dir_45f8a1cbe1d055833100269ade1d303b" ],
[ "c.h", "c_8h_source.html", null ],
[ "cache.h", "cache_8h_source.html", null ],
[ "compaction_filter.h", "compaction__filter_8h_source.html", null ],
[ "compaction_job_stats.h", "compaction__job__stats_8h_source.html", null ],
[ "comparator.h", "comparator_8h_source.html", null ],
[ "convenience.h", "convenience_8h_source.html", null ],
[ "db.h", "db_8h_source.html", null ],
[ "db_bench_tool.h", "db__bench__tool_8h_source.html", null ],
[ "db_dump_tool.h", "db__dump__tool_8h_source.html", null ],
[ "env.h", "env_8h_source.html", null ],
[ "experimental.h", "experimental_8h_source.html", null ],
[ "filter_policy.h", "filter__policy_8h_source.html", null ],
[ "flush_block_policy.h", "flush__block__policy_8h_source.html", null ],
[ "immutable_options.h", "immutable__options_8h_source.html", null ],
[ "iostats_context.h", "iostats__context_8h_source.html", null ],
[ "iterator.h", "iterator_8h_source.html", null ],
[ "ldb_tool.h", "ldb__tool_8h_source.html", null ],
[ "listener.h", "listener_8h_source.html", null ],
[ "memtablerep.h", "memtablerep_8h_source.html", null ],
[ "merge_operator.h", "merge__operator_8h_source.html", null ],
[ "metadata.h", "metadata_8h_source.html", null ],
[ "options.h", "options_8h_source.html", null ],
[ "perf_context.h", "perf__context_8h_source.html", null ],
[ "perf_level.h", "perf__level_8h_source.html", null ],
[ "rate_limiter.h", "rate__limiter_8h_source.html", null ],
[ "slice.h", "slice_8h_source.html", null ],
[ "slice_transform.h", "slice__transform_8h_source.html", null ],
[ "snapshot.h", "snapshot_8h_source.html", null ],
[ "sst_dump_tool.h", "sst__dump__tool_8h_source.html", null ],
[ "sst_file_manager.h", "sst__file__manager_8h_source.html", null ],
[ "sst_file_writer.h", "sst__file__writer_8h_source.html", null ],
[ "statistics.h", "statistics_8h_source.html", null ],
[ "status.h", "status_8h_source.html", null ],
[ "table.h", "table_8h_source.html", null ],
[ "table_properties.h", "table__properties_8h_source.html", null ],
[ "thread_status.h", "thread__status_8h_source.html", null ],
[ "transaction_log.h", "transaction__log_8h_source.html", null ],
[ "types.h", "types_8h_source.html", null ],
[ "universal_compaction.h", "universal__compaction_8h_source.html", null ],
[ "version.h", "version_8h_source.html", null ],
[ "wal_filter.h", "wal__filter_8h_source.html", null ],
[ "write_batch.h", "write__batch_8h_source.html", null ],
[ "write_batch_base.h", "write__batch__base_8h_source.html", null ]
];
|
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
mongoose = require('mongoose'),
User = mongoose.model('User');
/**
* User middleware
*/
exports.userByID = function(req, res, next, id) {
User.findById(id)
// .findOne({
// _id: id
// })
.exec(function(err, user) {
if (err) return next(err);
if (!user) return next(new Error('Failed to load User ' + id));
req.profile = user;
next();
});
};
/**
* List of Users
*/
exports.list = function(req, res, next) {
User.find().exec(function(err, users) {
res.jsonp(users);
next();
// what would happen if this was req?
// nothing apparently
// nothing works
// why
// I don't understand
});
};
/**
* Require login routing middleware
*/
exports.requiresLogin = function(req, res, next) {
if (!req.isAuthenticated()) {
return res.status(401).send({
message: 'User is not logged in'
});
}
next();
};
/**
* User authorizations routing middleware
*/
exports.hasAuthorization = function(roles) {
var _this = this;
return function(req, res, next) {
_this.requiresLogin(req, res, function() {
if (_.intersection(req.user.roles, roles).length) {
return next();
} else {
return res.status(403).send({
message: 'User is not authorized'
});
}
});
};
};
|
//==================================================================================================
//VALIDATORS
//==================================================================================================
Form.validators = (function() {
var validators = {};
validators.errMessages = {
required: 'Required',
regexp: 'Invalid',
number: 'Must be a number',
range: _.template('Must be a number between <%= min %> and <%= max %>', null, Form.templateSettings),
email: 'Invalid email address',
url: 'Invalid URL',
match: _.template('Must match field "<%= field %>"', null, Form.templateSettings)
};
validators.required = function(options) {
options = _.extend({
type: 'required',
message: this.errMessages.required
}, options);
return function required(value) {
options.value = value;
var err = {
type: options.type,
message: _.isFunction(options.message) ? options.message(options) : options.message
},
$ = Backbone.$;
if (value === null || value === undefined || value === false || value === '' || $.trim(value) === '' ) return err;
};
};
validators.regexp = function(options) {
if (!options.regexp) throw new Error('Missing required "regexp" option for "regexp" validator');
options = _.extend({
type: 'regexp',
match: true,
message: this.errMessages.regexp
}, options);
return function regexp(value) {
options.value = value;
var err = {
type: options.type,
message: _.isFunction(options.message) ? options.message(options) : options.message
};
//Don't check empty values (add a 'required' validator for this)
if (value === null || value === undefined || value === '') return;
//Create RegExp from string if it's valid
if ('string' === typeof options.regexp) options.regexp = new RegExp(options.regexp, options.flags);
if ((options.match) ? !options.regexp.test(value) : options.regexp.test(value)) return err;
};
};
validators.number = function(options) {
options = _.extend({
type: 'number',
message: this.errMessages.number,
regexp: /^[-+]?([0-9]*.[0-9]+|[0-9]+)$/
}, options);
return validators.regexp(options);
};
validators.range = function(options) {
options = _.extend({
type: 'range',
message: this.errMessages.range,
numberMessage: this.errMessages.number,
min: 0,
max: 100
}, options);
return function range(value) {
options.value = value;
var err = {
type: options.type,
message: _.isFunction(options.message) ? options.message(options) : options.message
};
//Don't check empty values (add a 'required' validator for this)
if (value === null || value === undefined || value === '') return;
// check value is a number
var numberCheck = validators.number({message: options.numberMessage})(value);
if (numberCheck) return numberCheck;
// check value is in range
var number = parseFloat(options.value);
if (number < options.min || number > options.max) return err;
}
}
validators.email = function(options) {
options = _.extend({
type: 'email',
message: this.errMessages.email,
regexp: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i
}, options);
return validators.regexp(options);
};
validators.url = function(options) {
options = _.extend({
type: 'url',
message: this.errMessages.url,
regexp: /^((http|https):\/\/)?(([A-Z0-9][A-Z0-9_\-]*)(\.[A-Z0-9][A-Z0-9_\-]*)+)(:(\d+))?\/?/i
}, options);
return validators.regexp(options);
};
validators.match = function(options) {
if (!options.field) throw new Error('Missing required "field" options for "match" validator');
options = _.extend({
type: 'match',
message: this.errMessages.match
}, options);
return function match(value, attrs) {
options.value = value;
var err = {
type: options.type,
message: _.isFunction(options.message) ? options.message(options) : options.message
};
//Don't check empty values (add a 'required' validator for this)
if (value === null || value === undefined || value === '') return;
if (value !== attrs[options.field]) return err;
};
};
return validators;
})();
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'list', 'nl', {
bulletedlist: 'Opsomming invoegen',
numberedlist: 'Genummerde lijst invoegen'
});
|
/*
Copyright 2013, KISSY UI Library v1.40dev
MIT Licensed
build time: Jul 3 13:57
*/
KISSY.add("rich-base",function(e,n){function p(b,a){return a.toUpperCase()}function l(){var b,a;n.apply(this,arguments);a=this.get("listeners");for(b in a)this.on(b,a[b]);this.callMethodByHierarchy("initializer","constructor");this.constructPlugins();this.callPluginsMethod("initializer");this.bindInternal();this.syncInternal()}function q(b){var a;b.target==this&&(a=this[m+b.type.slice(5).slice(0,-6)],a.call(this,b.newVal,b))}var i=e.ucfirst,m="_onSet",o=e.noop,r=/(?:^|-)([a-z])/ig;e.extend(l,n,{collectConstructorChains:function(){for(var b=
[],a=this.constructor;a;)b.push(a),a=a.superclass&&a.superclass.constructor;return b},callMethodByHierarchy:function(b,a,c){for(var d=this.constructor,f=[],e,g,h,j,k,c=c||[];d;){k=[];if(j=d.__ks_exts)for(h=0;h<j.length;h++)if(e=j[h])"constructor"!=a&&(e=e.prototype.hasOwnProperty(a)?e.prototype[a]:null),e&&k.push(e);d.prototype.hasOwnProperty(b)&&(g=d.prototype[b])&&k.push(g);k.length&&f.push.apply(f,k.reverse());d=d.superclass&&d.superclass.constructor}for(h=f.length-1;0<=h;h--)f[h]&&f[h].apply(this,
c)},callPluginsMethod:function(b,a){var c=this,a=a||[],b="plugin"+i(b);e.each(c.get("plugins"),function(d){var f=[c].concat(a);d[b]&&d[b].apply(d,f)})},constructPlugins:function(){var b=this.get("plugins");e.each(b,function(a,c){e.isFunction(a)&&(b[c]=new a)})},bindInternal:function(){var b=this.getAttrs(),a,c;for(a in b)if(c=m+i(a),this[c])this.on("after"+i(a)+"Change",q)},syncInternal:function(){var b,a,c,d,f,e={},g=this.collectConstructorChains(),h;for(c=g.length-1;0<=c;c--)if(d=g[c],h=d.ATTRS)for(f in h)e[f]||
(e[f]=1,d=m+i(f),(a=this[d])&&0!==h[f].sync&&void 0!==(b=this.get(f))&&a.call(this,b))},initializer:o,destructor:o,destroy:function(){if(!this.get("destroyed")){this.callPluginsMethod("destructor");for(var b=this.constructor,a,c,d;b;){b.prototype.hasOwnProperty("destructor")&&b.prototype.destructor.apply(this);if(a=b.__ks_exts)for(d=a.length-1;0<=d;d--)(c=a[d]&&a[d].prototype.__destructor)&&c.apply(this);b=b.superclass&&b.superclass.constructor}this.detach();this.set("destroyed",!0);this.fire("destroy")}},
plug:function(b){e.isFunction(b)&&(b=new b);b.pluginInitializer&&b.pluginInitializer(this);this.get("plugins").push(b);return this},unplug:function(b){var a=[],c=this,d="string"==typeof b;e.each(c.get("plugins"),function(f){var e=0,g;b&&(d?(g=f.get&&f.get("pluginId")||f.pluginId,g!=b&&(a.push(f),e=1)):f!=b&&(a.push(f),e=1));e||f.pluginDestructor(c)});c.setInternal("plugins",a);return c},getPlugin:function(b){var a=null;e.each(this.get("plugins"),function(c){if((c.get&&c.get("pluginId")||c.pluginId)==
b)return a=c,!1});return a}},{ATTRS:{plugins:{value:[]},destroyed:{value:!1},listeners:{value:[]}}});e.mix(l,{extend:function a(c,d,f){var i,g;e.isArray(c)||(f=d,d=c,c=[]);f=f||{};i=f.name||"RichBaseDerived";d=d||{};d.hasOwnProperty("constructor")?g=d.constructor:e.Config.debug?eval("C = function "+i.replace(r,p)+"(){ C.superclass.constructor.apply(this, arguments);}"):g=function(){g.superclass.constructor.apply(this,arguments)};e.extend(g,this,d,f);if(c){g.__ks_exts=c;var h={},j={};e.each(c.concat(g),
function(a){if(a){e.each(a.ATTRS,function(a,c){var d=h[c]=h[c]||{};e.mix(d,a)});var a=a.prototype,c;for(c in a)a.hasOwnProperty(c)&&(j[c]=a[c])}});g.ATTRS=h;e.augment(g,j);g.prototype.constructor=g}g.extend=g.extend||a;return g}});return l},{requires:["base"]});
|
'use strict';
angular.module('charactersApp')
.controller('MainCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('characters/characters.json')
.success(function (data) {
$scope.characters = data;
});
}]);
|
document.writeln ("Test.")
|
'use strict';
/*global console, Thenjs*/
function request(url) {
return function (callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = function () {
if (this.readyState !== 4) return;
callback(this.status === 200 ? null : xhr, xhr);
};
xhr.send();
};
}
Thenjs(request('http://www.w3school.com.cn/'))
.then(function (cont, data) {
console.log(data);
cont(null, data.responseText);
})
.then(function (cont, data) {
console.log(data);
})
.fail(function (cont, error) {
console.error(error.statusText);
});
|
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
import { Alias } from "./Alias";
import { JoinAttribute } from "./JoinAttribute";
import { RelationIdAttribute } from "./relation-id/RelationIdAttribute";
import { RelationCountAttribute } from "./relation-count/RelationCountAttribute";
/**
* Contains all properties of the QueryBuilder that needs to be build a final query.
*/
var QueryExpressionMap = /** @class */ (function () {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
function QueryExpressionMap(connection) {
this.connection = connection;
// -------------------------------------------------------------------------
// Public Properties
// -------------------------------------------------------------------------
/**
* Indicates if QueryBuilder used to select entities and not a raw results.
*/
this.queryEntity = false;
/**
* All aliases (including main alias) used in the query.
*/
this.aliases = [];
/**
* Represents query type. QueryBuilder is able to build SELECT, UPDATE and DELETE queries.
*/
this.queryType = "select";
/**
* Data needs to be SELECT-ed.
*/
this.selects = [];
/**
* Optional returning (or output) clause for insert, update or delete queries.
*/
this.returning = "";
/**
* Optional on conflict statement used in insertion query in postgres.
*/
this.onConflict = "";
/**
* JOIN queries.
*/
this.joinAttributes = [];
/**
* RelationId queries.
*/
this.relationIdAttributes = [];
/**
* Relation count queries.
*/
this.relationCountAttributes = [];
/**
* WHERE queries.
*/
this.wheres = [];
/**
* HAVING queries.
*/
this.havings = [];
/**
* ORDER BY queries.
*/
this.orderBys = {};
/**
* GROUP BY queries.
*/
this.groupBys = [];
/**
* Parameters used to be escaped in final query.
*/
this.parameters = {};
/**
* Indicates if alias, table names and column names will be ecaped by driver, or not.
*
* todo: rename to isQuotingDisabled, also think if it should be named "escaping"
*/
this.disableEscaping = true;
/**
* todo: needs more information.
*/
this.ignoreParentTablesJoins = false;
/**
* Indicates if virtual columns should be included in entity result.
*
* todo: what to do with it? is it properly used? what about persistence?
*/
this.enableRelationIdValues = false;
/**
* Extra where condition appended to the end of original where conditions with AND keyword.
* Original condition will be wrapped into brackets.
*/
this.extraAppendedAndWhereCondition = "";
/**
* Indicates if query builder creates a subquery.
*/
this.subQuery = false;
/**
* Indicates if property names are prefixed with alias names during property replacement.
* By default this is enabled, however we need this because aliases are not supported in UPDATE and DELETE queries,
* but user can use them in WHERE expressions.
*/
this.aliasNamePrefixingEnabled = true;
/**
* Indicates if query result cache is enabled or not.
*/
this.cache = false;
/**
* List of columns where data should be inserted.
* Used in INSERT query.
*/
this.insertColumns = [];
}
Object.defineProperty(QueryExpressionMap.prototype, "allOrderBys", {
// -------------------------------------------------------------------------
// Accessors
// -------------------------------------------------------------------------
/**
* Get all ORDER BY queries - if order by is specified by user then it uses them,
* otherwise it uses default entity order by if it was set.
*/
get: function () {
var _this = this;
if (!Object.keys(this.orderBys).length && this.mainAlias.hasMetadata) {
var entityOrderBy_1 = this.mainAlias.metadata.orderBy || {};
return Object.keys(entityOrderBy_1).reduce(function (orderBy, key) {
orderBy[_this.mainAlias.name + "." + key] = entityOrderBy_1[key];
return orderBy;
}, {});
}
return this.orderBys;
},
enumerable: true,
configurable: true
});
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Creates a main alias and adds it to the current expression map.
*/
QueryExpressionMap.prototype.setMainAlias = function (alias) {
// if main alias is already set then remove it from the array
if (this.mainAlias)
this.aliases.splice(this.aliases.indexOf(this.mainAlias));
// set new main alias
this.mainAlias = alias;
return alias;
};
/**
* Creates a new alias and adds it to the current expression map.
*/
QueryExpressionMap.prototype.createAlias = function (options) {
var aliasName = options.name;
if (!aliasName && options.tableName)
aliasName = options.tableName;
if (!aliasName && options.target instanceof Function)
aliasName = options.target.name;
if (!aliasName && typeof options.target === "string")
aliasName = options.target;
var alias = new Alias();
alias.type = options.type;
if (aliasName)
alias.name = aliasName;
if (options.metadata)
alias.metadata = options.metadata;
if (options.target && !alias.hasMetadata)
alias.metadata = this.connection.getMetadata(options.target);
if (options.tableName)
alias.tableName = options.tableName;
if (options.subQuery)
alias.subQuery = options.subQuery;
this.aliases.push(alias);
return alias;
};
/**
* Finds alias with the given name.
* If alias was not found it throw an exception.
*/
QueryExpressionMap.prototype.findAliasByName = function (aliasName) {
var alias = this.aliases.find(function (alias) { return alias.name === aliasName; });
if (!alias)
throw new Error("\"" + aliasName + "\" alias was not found. Maybe you forgot to join it?");
return alias;
};
QueryExpressionMap.prototype.findColumnByAliasExpression = function (aliasExpression) {
var _a = aliasExpression.split("."), aliasName = _a[0], propertyPath = _a[1];
var alias = this.findAliasByName(aliasName);
return alias.metadata.findColumnWithPropertyName(propertyPath);
};
Object.defineProperty(QueryExpressionMap.prototype, "relationMetadata", {
/**
* Gets relation metadata of the relation this query builder works with.
*
* todo: add proper exceptions
*/
get: function () {
if (!this.mainAlias)
throw new Error("Entity to work with is not specified!"); // todo: better message
var relationMetadata = this.mainAlias.metadata.findRelationWithPropertyPath(this.relationPropertyPath);
if (!relationMetadata)
throw new Error("Relation " + this.relationPropertyPath + " was not found in entity " + this.mainAlias.name); // todo: better message
return relationMetadata;
},
enumerable: true,
configurable: true
});
/**
* Copies all properties of the current QueryExpressionMap into a new one.
* Useful when QueryBuilder needs to create a copy of itself.
*/
QueryExpressionMap.prototype.clone = function () {
var _this = this;
var map = new QueryExpressionMap(this.connection);
map.queryType = this.queryType;
map.selects = this.selects.map(function (select) { return select; });
this.aliases.forEach(function (alias) { return map.aliases.push(new Alias(alias)); });
map.mainAlias = this.mainAlias;
map.valuesSet = this.valuesSet;
map.returning = this.returning;
map.onConflict = this.onConflict;
map.joinAttributes = this.joinAttributes.map(function (join) { return new JoinAttribute(_this.connection, _this, join); });
map.relationIdAttributes = this.relationIdAttributes.map(function (relationId) { return new RelationIdAttribute(_this, relationId); });
map.relationCountAttributes = this.relationCountAttributes.map(function (relationCount) { return new RelationCountAttribute(_this, relationCount); });
map.wheres = this.wheres.map(function (where) { return (__assign({}, where)); });
map.havings = this.havings.map(function (having) { return (__assign({}, having)); });
map.orderBys = Object.assign({}, this.orderBys);
map.groupBys = this.groupBys.map(function (groupBy) { return groupBy; });
map.limit = this.limit;
map.offset = this.offset;
map.skip = this.skip;
map.take = this.take;
map.lockMode = this.lockMode;
map.lockVersion = this.lockVersion;
map.parameters = Object.assign({}, this.parameters);
map.disableEscaping = this.disableEscaping;
map.ignoreParentTablesJoins = this.ignoreParentTablesJoins;
map.enableRelationIdValues = this.enableRelationIdValues;
map.extraAppendedAndWhereCondition = this.extraAppendedAndWhereCondition;
map.subQuery = this.subQuery;
map.aliasNamePrefixingEnabled = this.aliasNamePrefixingEnabled;
map.cache = this.cache;
map.cacheId = this.cacheId;
map.cacheDuration = this.cacheDuration;
map.relationPropertyPath = this.relationPropertyPath;
map.of = this.of;
return map;
};
return QueryExpressionMap;
}());
export { QueryExpressionMap };
//# sourceMappingURL=QueryExpressionMap.js.map
|
export default function ResourceService(ApiService, QueryBuilderService) {
'ngInject';
function Service() {
this.api = ApiService;
this.resource = '';
this.builder = QueryBuilderService.getInstance();
this.builder.build = (callback) => {
if (typeof callback === 'function') {
return callback(this.builder.getQuery());
}
return this.get(this.builder.getQuery());
};
this.add = (data) => {
return this.api.httpPost(this.resource, data)
.then(data => data)
.catch(this.api.requestFailed);
};
this.edit = (id, data) => {
return this.api.httpPut(this.resource + '/' + id, data)
.then(data => data)
.catch(this.api.requestFailed);
};
this.find = (id) => {
return this.api.httpGet(this.resource + '/' + id)
.then(data => data)
.catch(this.api.requestFailed);
};
this.get = (params = '') => {
params = params ? '?' + params : '';
return this.api.httpGet(this.resource + params)
.then(data => data)
.catch(this.api.requestFailed);
};
this.remove = (id) => {
return this.api.httpDelete(this.resource + '/' + id)
.then(data => data)
.catch(this.api.requestFailed);
};
this.setResource = (r) => {
this.resource = r;
};
}
return {
getInstance() {
return new Service();
}
};
}
|
/* eslint-disable no-case-declarations */
export const reducer = (state = {
friends: [],
eventHash: '',
yelpData: [],
liveData: [],
user: {},
connectedPeers: 0,
talliedVotes: 0,
coords: [],
edp: {},
homeEventPageData: {},
eventPageData: {},
parentPage: '/',
selectedView: 'Create',
selectedViewIndex: 0,
loadGoogleMaps: false,
loaded: false,
fbLoaded: false,
}, action) => {
switch (action.type) {
case 'UPDATE_INVITE_FRIENDS':
return {
...state,
friends: action.friends,
};
case 'UPDATE_EVENT_HASH':
return {
...state,
eventHash: action.eventHash,
};
case 'UPDATE_YELP_DATA':
return {
...state,
yelpData: action.yelpData,
};
case 'UPDATE_LIVE_DATA':
return {
...state,
liveData: action.newLiveData,
};
case 'UPDATE_USER':
return {
...state,
user: action.user,
};
case 'UPDATED_CONNECTED_PEERS':
return {
...state,
connectedPeers: action.connectedPeers,
};
case 'UPDATED_TALLIED_VOTES':
return {
...state,
talliedVotes: action.talliedVotes,
};
case 'UPDATE_COORDS':
return {
...state,
coords: action.coords,
};
case 'UPDATE_EDP':
return {
...state,
edp: action.edp,
};
case 'UPDATE_HOME_EVENT_PAGE':
return {
...state,
homeEventPageData: action.homeEventPageData,
};
case 'UPDATE_EVENT_PAGE':
return {
...state,
eventPageData: action.eventPageData,
};
case 'UPDATE_PARENT_PAGE':
return {
...state,
parentPage: action.parentPage,
};
case 'UPDATE_SELECTED_VIEW':
return {
...state,
selectedView: action.selectedView,
};
case 'UPDATE_SELECTED_INDEX':
return {
...state,
selectedViewIndex: action.selectedViewIndex,
};
case 'UPDATE_GOOGLEMAPS':
return {
...state,
loadGoogleMaps: action.loadGoogleMaps,
};
case 'LOAD':
return {
...state,
...action.state,
};
case 'LOAD_FB':
return {
...state,
fbLoaded: action.loaded,
};
default:
return state;
}
};
|
'use strict';
var StylieNotification = require('../../index'),
// classie = require('classie'),
notification1,
modalButtonContainer;
var openModalButtonHandler = function (e) {
// create the notification
var notification = new StylieNotification({
message: '<p>This is just a simple notice. Everything is in order and this is a <a href="#">simple link</a>.</p>',
ttl: 5000,
layout: e.target.getAttribute('data-layout'), //'bar',
effect: e.target.getAttribute('data-effect'), //'exploader',
type: e.target.getAttribute('data-type'), //'notice', // notice, warning, error or success
onClose: function () {
// bttn.disabled = false;
}
});
// show the notification
notification.show();
window.notification1 = notification1;
};
window.addEventListener('load', function () {
modalButtonContainer = document.querySelector('#td-notification-buttons');
modalButtonContainer.addEventListener('click', openModalButtonHandler, false);
}, false);
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _defineProperty2 = require('babel-runtime/helpers/defineProperty');
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _KeyCode = require('rc-util/lib/KeyCode');
var _KeyCode2 = _interopRequireDefault(_KeyCode);
var _classnames2 = require('classnames');
var _classnames3 = _interopRequireDefault(_classnames2);
var _rcAnimate = require('rc-animate');
var _rcAnimate2 = _interopRequireDefault(_rcAnimate);
var _componentClasses = require('component-classes');
var _componentClasses2 = _interopRequireDefault(_componentClasses);
var _util = require('./util');
var _SelectTrigger = require('./SelectTrigger');
var _SelectTrigger2 = _interopRequireDefault(_SelectTrigger);
var _PropTypes = require('./PropTypes');
var _rcMenu = require('rc-menu');
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function noop() {}
function saveRef(name, component) {
this[name] = component;
}
function chaining() {
for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
}
return function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
// eslint-disable-line
for (var i = 0; i < fns.length; i++) {
if (fns[i] && typeof fns[i] === 'function') {
fns[i].apply(this, args);
}
}
};
}
var Select = function (_React$Component) {
(0, _inherits3['default'])(Select, _React$Component);
function Select(props) {
(0, _classCallCheck3['default'])(this, Select);
var _this = (0, _possibleConstructorReturn3['default'])(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props));
_initialiseProps.call(_this);
var value = [];
if ('value' in props) {
value = (0, _util.toArray)(props.value);
} else {
value = (0, _util.toArray)(props.defaultValue);
}
value = _this.addLabelToValue(props, value);
value = _this.addTitleToValue(props, value);
var inputValue = '';
if (props.combobox) {
inputValue = value.length ? _this.getLabelFromProps(props, value[0].key) : '';
}
_this.saveInputRef = saveRef.bind(_this, 'inputInstance');
_this.saveInputMirrorRef = saveRef.bind(_this, 'inputMirrorInstance');
var open = props.open;
if (open === undefined) {
open = props.defaultOpen;
}
_this.state = {
value: value,
inputValue: inputValue,
open: open
};
_this.adjustOpenState();
return _this;
}
(0, _createClass3['default'])(Select, [{
key: 'componentWillUpdate',
value: function componentWillUpdate(nextProps, nextState) {
this.props = nextProps;
this.state = nextState;
this.adjustOpenState();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
if ((0, _util.isMultipleOrTags)(this.props)) {
var inputNode = this.getInputDOMNode();
var mirrorNode = this.getInputMirrorDOMNode();
if (inputNode.value) {
inputNode.style.width = '';
inputNode.style.width = mirrorNode.clientWidth + 'px';
} else {
inputNode.style.width = '';
}
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearFocusTime();
this.clearBlurTime();
this.clearAdjustTimer();
if (this.dropdownContainer) {
_reactDom2['default'].unmountComponentAtNode(this.dropdownContainer);
document.body.removeChild(this.dropdownContainer);
this.dropdownContainer = null;
}
}
// combobox ignore
}, {
key: 'render',
value: function render() {
var _rootCls;
var props = this.props;
var multiple = (0, _util.isMultipleOrTags)(props);
var state = this.state;
var className = props.className,
disabled = props.disabled,
allowClear = props.allowClear,
prefixCls = props.prefixCls;
var ctrlNode = this.renderTopControlNode();
var extraSelectionProps = {};
var open = this.state.open;
var options = this._options;
if (!(0, _util.isMultipleOrTagsOrCombobox)(props)) {
extraSelectionProps = {
onKeyDown: this.onKeyDown,
tabIndex: 0
};
}
var rootCls = (_rootCls = {}, (0, _defineProperty3['default'])(_rootCls, className, !!className), (0, _defineProperty3['default'])(_rootCls, prefixCls, 1), (0, _defineProperty3['default'])(_rootCls, prefixCls + '-open', open), (0, _defineProperty3['default'])(_rootCls, prefixCls + '-focused', open || !!this._focused), (0, _defineProperty3['default'])(_rootCls, prefixCls + '-combobox', (0, _util.isCombobox)(props)), (0, _defineProperty3['default'])(_rootCls, prefixCls + '-disabled', disabled), (0, _defineProperty3['default'])(_rootCls, prefixCls + '-enabled', !disabled), (0, _defineProperty3['default'])(_rootCls, prefixCls + '-allow-clear', !!props.allowClear), _rootCls);
var clearStyle = (0, _extends3['default'])({}, _util.UNSELECTABLE_STYLE, {
display: 'none'
});
if (state.inputValue || state.value.length) {
clearStyle.display = 'block';
}
var clear = _react2['default'].createElement('span', (0, _extends3['default'])({
key: 'clear',
onMouseDown: _util.preventDefaultEvent,
style: clearStyle
}, _util.UNSELECTABLE_ATTRIBUTE, {
className: prefixCls + '-selection__clear',
onClick: this.onClearSelection
}));
return _react2['default'].createElement(
_SelectTrigger2['default'],
{
onPopupFocus: this.onPopupFocus,
dropdownAlign: props.dropdownAlign,
dropdownClassName: props.dropdownClassName,
dropdownMatchSelectWidth: props.dropdownMatchSelectWidth,
defaultActiveFirstOption: props.defaultActiveFirstOption,
dropdownMenuStyle: props.dropdownMenuStyle,
transitionName: props.transitionName,
animation: props.animation,
prefixCls: props.prefixCls,
dropdownStyle: props.dropdownStyle,
combobox: props.combobox,
showSearch: props.showSearch,
options: options,
multiple: multiple,
disabled: disabled,
visible: open,
inputValue: state.inputValue,
value: state.value,
firstActiveValue: props.firstActiveValue,
onDropdownVisibleChange: this.onDropdownVisibleChange,
getPopupContainer: props.getPopupContainer,
onMenuSelect: this.onMenuSelect,
onMenuDeselect: this.onMenuDeselect,
ref: 'trigger'
},
_react2['default'].createElement(
'div',
{
style: props.style,
ref: 'root',
onBlur: this.onOuterBlur,
onFocus: this.onOuterFocus,
className: (0, _classnames3['default'])(rootCls)
},
_react2['default'].createElement(
'div',
(0, _extends3['default'])({
ref: 'selection',
key: 'selection',
className: prefixCls + '-selection\n ' + prefixCls + '-selection--' + (multiple ? 'multiple' : 'single'),
role: 'combobox',
'aria-autocomplete': 'list',
'aria-haspopup': 'true',
'aria-expanded': open
}, extraSelectionProps),
ctrlNode,
allowClear ? clear : null,
multiple || !props.showArrow ? null : _react2['default'].createElement(
'span',
(0, _extends3['default'])({
key: 'arrow',
className: prefixCls + '-arrow',
style: _util.UNSELECTABLE_STYLE
}, _util.UNSELECTABLE_ATTRIBUTE, {
onClick: this.onArrowClick
}),
_react2['default'].createElement('b', null)
)
)
)
);
}
}]);
return Select;
}(_react2['default'].Component);
Select.propTypes = _PropTypes.SelectPropTypes;
Select.defaultProps = {
prefixCls: 'rc-select',
defaultOpen: false,
labelInValue: false,
defaultActiveFirstOption: true,
showSearch: true,
allowClear: false,
placeholder: '',
onChange: noop,
onFocus: noop,
onBlur: noop,
onSelect: noop,
onSearch: noop,
onDeselect: noop,
showArrow: true,
dropdownMatchSelectWidth: true,
dropdownStyle: {},
dropdownMenuStyle: {},
optionFilterProp: 'value',
optionLabelProp: 'value',
notFoundContent: 'Not Found'
};
var _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.componentWillReceiveProps = function (nextProps) {
if ('value' in nextProps) {
var value = (0, _util.toArray)(nextProps.value);
value = _this2.addLabelToValue(nextProps, value);
value = _this2.addTitleToValue(nextProps, value);
_this2.setState({
value: value
});
if (nextProps.combobox) {
_this2.setState({
inputValue: value.length ? _this2.getLabelFromProps(nextProps, value[0].key) : ''
});
}
}
};
this.onInputChange = function (event) {
var tokenSeparators = _this2.props.tokenSeparators;
var val = event.target.value;
if ((0, _util.isMultipleOrTags)(_this2.props) && tokenSeparators && (0, _util.includesSeparators)(val, tokenSeparators)) {
var nextValue = _this2.tokenize(val);
_this2.fireChange(nextValue);
_this2.setOpenState(false, true);
_this2.setInputValue('', false);
return;
}
_this2.setInputValue(val);
_this2.setState({
open: true
});
if ((0, _util.isCombobox)(_this2.props)) {
_this2.fireChange([{
key: val
}]);
}
};
this.onDropdownVisibleChange = function (open) {
if (open && !_this2._focused) {
_this2.clearBlurTime();
_this2.timeoutFocus();
_this2._focused = true;
_this2.updateFocusClassName();
}
_this2.setOpenState(open);
};
this.onKeyDown = function (event) {
var props = _this2.props;
if (props.disabled) {
return;
}
var keyCode = event.keyCode;
if (_this2.state.open && !_this2.getInputDOMNode()) {
_this2.onInputKeyDown(event);
} else if (keyCode === _KeyCode2['default'].ENTER || keyCode === _KeyCode2['default'].DOWN) {
_this2.setOpenState(true);
event.preventDefault();
}
};
this.onInputKeyDown = function (event) {
var props = _this2.props;
if (props.disabled) {
return;
}
var state = _this2.state;
var keyCode = event.keyCode;
if ((0, _util.isMultipleOrTags)(props) && !event.target.value && keyCode === _KeyCode2['default'].BACKSPACE) {
event.preventDefault();
var value = state.value;
if (value.length) {
_this2.removeSelected(value[value.length - 1].key);
}
return;
}
if (keyCode === _KeyCode2['default'].DOWN) {
if (!state.open) {
_this2.openIfHasChildren();
event.preventDefault();
event.stopPropagation();
return;
}
} else if (keyCode === _KeyCode2['default'].ESC) {
if (state.open) {
_this2.setOpenState(false);
event.preventDefault();
event.stopPropagation();
}
return;
}
if (state.open) {
var menu = _this2.refs.trigger.getInnerMenu();
if (menu && menu.onKeyDown(event)) {
event.preventDefault();
event.stopPropagation();
}
}
};
this.onMenuSelect = function (_ref) {
var item = _ref.item;
var value = _this2.state.value;
var props = _this2.props;
var selectedValue = (0, _util.getValuePropValue)(item);
var selectedLabel = _this2.getLabelFromOption(item);
var event = selectedValue;
if (props.labelInValue) {
event = {
key: event,
label: selectedLabel
};
}
props.onSelect(event, item);
var selectedTitle = item.props.title;
if ((0, _util.isMultipleOrTags)(props)) {
if ((0, _util.findIndexInValueByKey)(value, selectedValue) !== -1) {
return;
}
value = value.concat([{
key: selectedValue,
label: selectedLabel,
title: selectedTitle
}]);
} else {
if ((0, _util.isCombobox)(props)) {
_this2.skipAdjustOpen = true;
_this2.clearAdjustTimer();
_this2.skipAdjustOpenTimer = setTimeout(function () {
_this2.skipAdjustOpen = false;
}, 0);
}
if (value.length && value[0].key === selectedValue) {
_this2.setOpenState(false, true);
return;
}
value = [{
key: selectedValue,
label: selectedLabel,
title: selectedTitle
}];
_this2.setOpenState(false, true);
}
_this2.fireChange(value);
var inputValue = void 0;
if ((0, _util.isCombobox)(props)) {
inputValue = (0, _util.getPropValue)(item, props.optionLabelProp);
} else {
inputValue = '';
}
_this2.setInputValue(inputValue, false);
};
this.onMenuDeselect = function (_ref2) {
var item = _ref2.item,
domEvent = _ref2.domEvent;
if (domEvent.type === 'click') {
_this2.removeSelected((0, _util.getValuePropValue)(item));
}
_this2.setInputValue('', false);
};
this.onArrowClick = function (e) {
e.stopPropagation();
if (!_this2.props.disabled) {
_this2.setOpenState(!_this2.state.open, !_this2.state.open);
}
};
this.onPlaceholderClick = function () {
if (_this2.getInputDOMNode()) {
_this2.getInputDOMNode().focus();
}
};
this.onOuterFocus = function (e) {
_this2.clearBlurTime();
if (!(0, _util.isMultipleOrTagsOrCombobox)(_this2.props) && e.target === _this2.getInputDOMNode()) {
return;
}
if (_this2._focused) {
return;
}
_this2._focused = true;
_this2.updateFocusClassName();
_this2.timeoutFocus();
};
this.onPopupFocus = function () {
// fix ie scrollbar, focus element again
_this2.maybeFocus(true, true);
};
this.onOuterBlur = function () {
_this2.blurTimer = setTimeout(function () {
_this2._focused = false;
_this2.updateFocusClassName();
var props = _this2.props;
var value = _this2.state.value;
var inputValue = _this2.state.inputValue;
if ((0, _util.isSingleMode)(props) && props.showSearch && inputValue && props.defaultActiveFirstOption) {
var options = _this2._options || [];
if (options.length) {
var firstOption = (0, _util.findFirstMenuItem)(options);
if (firstOption) {
value = [{
key: firstOption.key,
label: _this2.getLabelFromOption(firstOption)
}];
_this2.fireChange(value);
}
}
} else if ((0, _util.isMultipleOrTags)(props) && inputValue) {
// why not use setState?
_this2.state.inputValue = _this2.getInputDOMNode().value = '';
}
props.onBlur(_this2.getVLForOnChange(value));
_this2.setOpenState(false);
}, 10);
};
this.onClearSelection = function (event) {
var props = _this2.props;
var state = _this2.state;
if (props.disabled) {
return;
}
var inputValue = state.inputValue,
value = state.value;
event.stopPropagation();
if (inputValue || value.length) {
if (value.length) {
_this2.fireChange([]);
}
_this2.setOpenState(false, true);
if (inputValue) {
_this2.setInputValue('');
}
}
};
this.onChoiceAnimationLeave = function () {
_this2.refs.trigger.refs.trigger.forcePopupAlign();
};
this.getLabelBySingleValue = function (children, value) {
if (value === undefined) {
return null;
}
var label = null;
_react2['default'].Children.forEach(children, function (child) {
if (child.type.isSelectOptGroup) {
var maybe = _this2.getLabelBySingleValue(child.props.children, value);
if (maybe !== null) {
label = maybe;
}
} else if ((0, _util.getValuePropValue)(child) === value) {
label = _this2.getLabelFromOption(child);
}
});
return label;
};
this.getValueByLabel = function (children, label) {
if (label === undefined) {
return null;
}
var value = null;
_react2['default'].Children.forEach(children, function (child) {
if (child.type.isSelectOptGroup) {
var maybe = _this2.getValueByLabel(child.props.children, label);
if (maybe !== null) {
value = maybe;
}
} else if ((0, _util.toArray)(_this2.getLabelFromOption(child)).join('') === label) {
value = (0, _util.getValuePropValue)(child);
}
});
return value;
};
this.getLabelFromOption = function (child) {
return (0, _util.getPropValue)(child, _this2.props.optionLabelProp);
};
this.getLabelFromProps = function (props, value) {
return _this2.getLabelByValue(props.children, value);
};
this.getVLForOnChange = function (vls_) {
var vls = vls_;
if (vls !== undefined) {
if (!_this2.props.labelInValue) {
vls = vls.map(function (v) {
return v.key;
});
} else {
vls = vls.map(function (vl) {
return { key: vl.key, label: vl.label };
});
}
return (0, _util.isMultipleOrTags)(_this2.props) ? vls : vls[0];
}
return vls;
};
this.getLabelByValue = function (children, value) {
var label = _this2.getLabelBySingleValue(children, value);
if (label === null) {
return value;
}
return label;
};
this.getDropdownContainer = function () {
if (!_this2.dropdownContainer) {
_this2.dropdownContainer = document.createElement('div');
document.body.appendChild(_this2.dropdownContainer);
}
return _this2.dropdownContainer;
};
this.getPlaceholderElement = function () {
var props = _this2.props,
state = _this2.state;
var hidden = false;
if (state.inputValue) {
hidden = true;
}
if (state.value.length) {
hidden = true;
}
if ((0, _util.isCombobox)(props) && state.value.length === 1 && !state.value[0].key) {
hidden = false;
}
var placeholder = props.placeholder;
if (placeholder) {
return _react2['default'].createElement(
'div',
(0, _extends3['default'])({
onMouseDown: _util.preventDefaultEvent,
style: (0, _extends3['default'])({
display: hidden ? 'none' : 'block'
}, _util.UNSELECTABLE_STYLE)
}, _util.UNSELECTABLE_ATTRIBUTE, {
onClick: _this2.onPlaceholderClick,
className: props.prefixCls + '-selection__placeholder'
}),
placeholder
);
}
return null;
};
this.getInputElement = function () {
var props = _this2.props;
var inputElement = props.getInputElement ? props.getInputElement() : _react2['default'].createElement('input', { id: props.id });
var inputCls = (0, _classnames3['default'])(inputElement.props.className, (0, _defineProperty3['default'])({}, props.prefixCls + '-search__field', true));
// https://github.com/ant-design/ant-design/issues/4992#issuecomment-281542159
// Add space to the end of the inputValue as the width measurement tolerance
return _react2['default'].createElement(
'div',
{ className: props.prefixCls + '-search__field__wrap' },
_react2['default'].cloneElement(inputElement, {
ref: _this2.saveInputRef,
onChange: _this2.onInputChange,
onKeyDown: chaining(_this2.onInputKeyDown, inputElement.props.onKeyDown),
value: _this2.state.inputValue,
disabled: props.disabled,
className: inputCls
}),
_react2['default'].createElement(
'span',
{
ref: _this2.saveInputMirrorRef,
className: props.prefixCls + '-search__field__mirror'
},
_this2.state.inputValue,
'\xA0'
)
);
};
this.getInputDOMNode = function () {
return _this2.topCtrlNode ? _this2.topCtrlNode.querySelector('input,textarea,div[contentEditable]') : _this2.inputInstance;
};
this.getInputMirrorDOMNode = function () {
return _this2.inputMirrorInstance;
};
this.getPopupDOMNode = function () {
return _this2.refs.trigger.getPopupDOMNode();
};
this.getPopupMenuComponent = function () {
return _this2.refs.trigger.getInnerMenu();
};
this.setOpenState = function (open, needFocus) {
var props = _this2.props,
state = _this2.state;
if (state.open === open) {
_this2.maybeFocus(open, needFocus);
return;
}
var nextState = {
open: open
};
// clear search input value when open is false in singleMode.
if (!open && (0, _util.isSingleMode)(props) && props.showSearch) {
_this2.setInputValue('');
}
if (!open) {
_this2.maybeFocus(open, needFocus);
}
_this2.setState(nextState, function () {
if (open) {
_this2.maybeFocus(open, needFocus);
}
});
};
this.setInputValue = function (inputValue) {
var fireSearch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (inputValue !== _this2.state.inputValue) {
_this2.setState({
inputValue: inputValue
});
if (fireSearch) {
_this2.props.onSearch(inputValue);
}
}
};
this.filterOption = function (input, child) {
var defaultFilter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _util.defaultFilterFn;
if (!input) {
return true;
}
var filterFn = _this2.props.filterOption;
if ('filterOption' in _this2.props) {
if (_this2.props.filterOption === true) {
filterFn = defaultFilter;
}
} else {
filterFn = defaultFilter;
}
if (!filterFn) {
return true;
} else if (child.props.disabled) {
return false;
} else if (typeof filterFn === 'function') {
return filterFn.call(_this2, input, child);
}
return true;
};
this.timeoutFocus = function () {
if (_this2.focusTimer) {
_this2.clearFocusTime();
}
_this2.focusTimer = setTimeout(function () {
_this2.props.onFocus();
}, 10);
};
this.clearFocusTime = function () {
if (_this2.focusTimer) {
clearTimeout(_this2.focusTimer);
_this2.focusTimer = null;
}
};
this.clearBlurTime = function () {
if (_this2.blurTimer) {
clearTimeout(_this2.blurTimer);
_this2.blurTimer = null;
}
};
this.clearAdjustTimer = function () {
if (_this2.skipAdjustOpenTimer) {
clearTimeout(_this2.skipAdjustOpenTimer);
_this2.skipAdjustOpenTimer = null;
}
};
this.updateFocusClassName = function () {
var refs = _this2.refs,
props = _this2.props;
// avoid setState and its side effect
if (_this2._focused) {
(0, _componentClasses2['default'])(refs.root).add(props.prefixCls + '-focused');
} else {
(0, _componentClasses2['default'])(refs.root).remove(props.prefixCls + '-focused');
}
};
this.maybeFocus = function (open, needFocus) {
if (needFocus || open) {
var input = _this2.getInputDOMNode();
var _document = document,
activeElement = _document.activeElement;
if (input && (open || (0, _util.isMultipleOrTagsOrCombobox)(_this2.props))) {
if (activeElement !== input) {
input.focus();
_this2._focused = true;
}
} else {
var selection = _this2.refs.selection;
if (activeElement !== selection) {
selection.focus();
_this2._focused = true;
}
}
}
};
this.addLabelToValue = function (props, value_) {
var value = value_;
if (props.labelInValue) {
value.forEach(function (v) {
v.label = v.label || _this2.getLabelFromProps(props, v.key);
});
} else {
value = value.map(function (v) {
return {
key: v,
label: _this2.getLabelFromProps(props, v)
};
});
}
return value;
};
this.addTitleToValue = function (props, values) {
var nextValues = values;
var keys = values.map(function (v) {
return v.key;
});
_react2['default'].Children.forEach(props.children, function (child) {
if (child.type.isSelectOptGroup) {
nextValues = _this2.addTitleToValue(child.props, nextValues);
} else {
var value = (0, _util.getValuePropValue)(child);
var valueIndex = keys.indexOf(value);
if (valueIndex > -1) {
nextValues[valueIndex].title = child.props.title;
}
}
});
return nextValues;
};
this.removeSelected = function (selectedKey) {
var props = _this2.props;
if (props.disabled || _this2.isChildDisabled(selectedKey)) {
return;
}
var label = void 0;
var value = _this2.state.value.filter(function (singleValue) {
if (singleValue.key === selectedKey) {
label = singleValue.label;
}
return singleValue.key !== selectedKey;
});
var canMultiple = (0, _util.isMultipleOrTags)(props);
if (canMultiple) {
var event = selectedKey;
if (props.labelInValue) {
event = {
key: selectedKey,
label: label
};
}
props.onDeselect(event);
}
_this2.fireChange(value);
};
this.openIfHasChildren = function () {
var props = _this2.props;
if (_react2['default'].Children.count(props.children) || (0, _util.isSingleMode)(props)) {
_this2.setOpenState(true);
}
};
this.fireChange = function (value) {
var props = _this2.props;
if (!('value' in props)) {
_this2.setState({
value: value
});
}
props.onChange(_this2.getVLForOnChange(value));
};
this.isChildDisabled = function (key) {
return (0, _util.toArray)(_this2.props.children).some(function (child) {
var childValue = (0, _util.getValuePropValue)(child);
return childValue === key && child.props && child.props.disabled;
});
};
this.tokenize = function (string) {
var _props = _this2.props,
multiple = _props.multiple,
tokenSeparators = _props.tokenSeparators,
children = _props.children;
var nextValue = _this2.state.value;
(0, _util.splitBySeparators)(string, tokenSeparators).forEach(function (label) {
var selectedValue = { key: label, label: label };
if ((0, _util.findIndexInValueByLabel)(nextValue, label) === -1) {
if (multiple) {
var value = _this2.getValueByLabel(children, label);
if (value) {
selectedValue.key = value;
nextValue = nextValue.concat(selectedValue);
}
} else {
nextValue = nextValue.concat(selectedValue);
}
}
});
return nextValue;
};
this.adjustOpenState = function () {
if (_this2.skipAdjustOpen) {
return;
}
var open = _this2.state.open;
var options = [];
// If hidden menu due to no options, then it should be calculated again
if (open || _this2.hiddenForNoOptions) {
options = _this2.renderFilterOptions();
}
_this2._options = options;
if ((0, _util.isMultipleOrTagsOrCombobox)(_this2.props) || !_this2.props.showSearch) {
if (open && !options.length) {
open = false;
_this2.hiddenForNoOptions = true;
}
// Keep menu open if there are options and hidden for no options before
if (_this2.hiddenForNoOptions && options.length) {
open = true;
_this2.hiddenForNoOptions = false;
}
}
_this2.state.open = open;
};
this.renderFilterOptions = function (inputValue) {
return _this2.renderFilterOptionsFromChildren(_this2.props.children, true, inputValue);
};
this.renderFilterOptionsFromChildren = function (children, showNotFound, iv) {
var sel = [];
var props = _this2.props;
var inputValue = iv === undefined ? _this2.state.inputValue : iv;
var childrenKeys = [];
var tags = props.tags;
_react2['default'].Children.forEach(children, function (child) {
if (child.type.isSelectOptGroup) {
var innerItems = _this2.renderFilterOptionsFromChildren(child.props.children, false);
if (innerItems.length) {
var label = child.props.label;
var key = child.key;
if (!key && typeof label === 'string') {
key = label;
} else if (!label && key) {
label = key;
}
sel.push(_react2['default'].createElement(
_rcMenu.ItemGroup,
{ key: key, title: label },
innerItems
));
}
return;
}
(0, _warning2['default'])(child.type.isSelectOption, 'the children of `Select` should be `Select.Option` or `Select.OptGroup`, ' + ('instead of `' + (child.type.name || child.type.displayName || child.type) + '`.'));
var childValue = (0, _util.getValuePropValue)(child);
if (_this2.filterOption(inputValue, child)) {
sel.push(_react2['default'].createElement(_rcMenu.Item, (0, _extends3['default'])({
style: _util.UNSELECTABLE_STYLE,
attribute: _util.UNSELECTABLE_ATTRIBUTE,
value: childValue,
key: childValue
}, child.props)));
}
if (tags && !child.props.disabled) {
childrenKeys.push(childValue);
}
});
if (tags) {
// tags value must be string
var value = _this2.state.value || [];
value = value.filter(function (singleValue) {
return childrenKeys.indexOf(singleValue.key) === -1 && (!inputValue || String(singleValue.key).indexOf(String(inputValue)) > -1);
});
sel = sel.concat(value.map(function (singleValue) {
var key = singleValue.key;
return _react2['default'].createElement(
_rcMenu.Item,
{
style: _util.UNSELECTABLE_STYLE,
attribute: _util.UNSELECTABLE_ATTRIBUTE,
value: key,
key: key
},
key
);
}));
if (inputValue) {
var notFindInputItem = sel.every(function (option) {
// this.filterOption return true has two meaning,
// 1, some one exists after filtering
// 2, filterOption is set to false
// condition 2 does not mean the option has same value with inputValue
var filterFn = function filterFn() {
return (0, _util.getValuePropValue)(option) === inputValue;
};
if (_this2.props.filterOption !== false) {
return !_this2.filterOption.call(_this2, inputValue, option, filterFn);
}
return !filterFn();
});
if (notFindInputItem) {
sel.unshift(_react2['default'].createElement(
_rcMenu.Item,
{
style: _util.UNSELECTABLE_STYLE,
attribute: _util.UNSELECTABLE_ATTRIBUTE,
value: inputValue,
key: inputValue
},
inputValue
));
}
}
}
if (!sel.length && showNotFound && props.notFoundContent) {
sel = [_react2['default'].createElement(
_rcMenu.Item,
{
style: _util.UNSELECTABLE_STYLE,
attribute: _util.UNSELECTABLE_ATTRIBUTE,
disabled: true,
value: 'NOT_FOUND',
key: 'NOT_FOUND'
},
props.notFoundContent
)];
}
return sel;
};
this.renderTopControlNode = function () {
var _state = _this2.state,
value = _state.value,
open = _state.open,
inputValue = _state.inputValue;
var props = _this2.props;
var choiceTransitionName = props.choiceTransitionName,
prefixCls = props.prefixCls,
maxTagTextLength = props.maxTagTextLength,
showSearch = props.showSearch;
var className = prefixCls + '-selection__rendered';
// search input is inside topControlNode in single, multiple & combobox. 2016/04/13
var innerNode = null;
if ((0, _util.isSingleMode)(props)) {
var selectedValue = null;
if (value.length) {
var showSelectedValue = false;
var opacity = 1;
if (!showSearch) {
showSelectedValue = true;
} else {
if (open) {
showSelectedValue = !inputValue;
if (showSelectedValue) {
opacity = 0.4;
}
} else {
showSelectedValue = true;
}
}
var singleValue = value[0];
selectedValue = _react2['default'].createElement(
'div',
{
key: 'value',
className: prefixCls + '-selection-selected-value',
title: singleValue.title || singleValue.label,
style: {
display: showSelectedValue ? 'block' : 'none',
opacity: opacity
}
},
value[0].label
);
}
if (!showSearch) {
innerNode = [selectedValue];
} else {
innerNode = [selectedValue, _react2['default'].createElement(
'div',
{
className: prefixCls + '-search ' + prefixCls + '-search--inline',
key: 'input',
style: {
display: open ? 'block' : 'none'
}
},
_this2.getInputElement()
)];
}
} else {
var selectedValueNodes = [];
if ((0, _util.isMultipleOrTags)(props)) {
selectedValueNodes = value.map(function (singleValue) {
var content = singleValue.label;
var title = singleValue.title || content;
if (maxTagTextLength && typeof content === 'string' && content.length > maxTagTextLength) {
content = content.slice(0, maxTagTextLength) + '...';
}
var disabled = _this2.isChildDisabled(singleValue.key);
var choiceClassName = disabled ? prefixCls + '-selection__choice ' + prefixCls + '-selection__choice__disabled' : prefixCls + '-selection__choice';
return _react2['default'].createElement(
'li',
(0, _extends3['default'])({
style: _util.UNSELECTABLE_STYLE
}, _util.UNSELECTABLE_ATTRIBUTE, {
onMouseDown: _util.preventDefaultEvent,
className: choiceClassName,
key: singleValue.key,
title: title
}),
_react2['default'].createElement(
'div',
{ className: prefixCls + '-selection__choice__content' },
content
),
disabled ? null : _react2['default'].createElement('span', {
className: prefixCls + '-selection__choice__remove',
onClick: _this2.removeSelected.bind(_this2, singleValue.key)
})
);
});
}
selectedValueNodes.push(_react2['default'].createElement(
'li',
{
className: prefixCls + '-search ' + prefixCls + '-search--inline',
key: '__input'
},
_this2.getInputElement()
));
if ((0, _util.isMultipleOrTags)(props) && choiceTransitionName) {
innerNode = _react2['default'].createElement(
_rcAnimate2['default'],
{
onLeave: _this2.onChoiceAnimationLeave,
component: 'ul',
transitionName: choiceTransitionName
},
selectedValueNodes
);
} else {
innerNode = _react2['default'].createElement(
'ul',
null,
selectedValueNodes
);
}
}
return _react2['default'].createElement(
'div',
{ className: className, ref: function ref(node) {
return _this2.topCtrlNode = node;
} },
_this2.getPlaceholderElement(),
innerNode
);
};
};
exports['default'] = Select;
Select.displayName = 'Select';
module.exports = exports['default'];
|
'use strict';
describe('ui-select tests', function () {
var scope, $rootScope, $compile, $timeout, $injector, $q, uisRepeatParser;
var Key = {
Enter: 13,
Tab: 9,
Up: 38,
Down: 40,
Left: 37,
Right: 39,
Backspace: 8,
Delete: 46,
Escape: 27,
Comma: 188,
A: 65,
C: 67,
X: 88,
};
function isNil(value) {
return angular.isUndefined(value) || value === null;
}
//create a directive that wraps ui-select
angular.module('wrapperDirective', ['ui.select']);
angular.module('wrapperDirective').directive('wrapperUiSelect', function () {
return {
restrict: 'EA',
template: '<ui-select> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>',
require: 'ngModel',
scope: true,
link: function (scope, element, attrs, ctrl) {
}
};
});
/* Create a directive that can be applied to the ui-select instance to test
* the effects of Angular's validation process on the control.
*
* Does not currently work with single property binding. Looks at the
* selected object or objects for a "valid" property. If all selected objects
* have a "valid" property that is truthy, the validator passes.
*/
angular.module('testValidator', []);
angular.module('testValidator').directive('testValidator', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$validators.testValidator = function (modelValue, viewValue) {
if (isNil(modelValue)) {
return true;
} else if (angular.isArray(modelValue)) {
var allValid = true, idx = modelValue.length;
while (idx-- > 0 && allValid) {
allValid = allValid && modelValue[idx].valid;
}
return allValid;
} else {
return !!modelValue.valid;
}
}
}
}
});
beforeEach(module('ngSanitize', 'ui.select', 'wrapperDirective', 'testValidator'));
beforeEach(function () {
module(function ($provide) {
$provide.factory('uisOffset', function () {
return function (el) {
return { top: 100, left: 200, width: 300, height: 400 };
};
});
});
});
beforeEach(inject(function (_$rootScope_, _$compile_, _$timeout_, _$injector_, _$q_, _uisRepeatParser_) {
$rootScope = _$rootScope_;
scope = $rootScope.$new();
$compile = _$compile_;
$timeout = _$timeout_;
$injector = _$injector_;
$q = _$q_;
uisRepeatParser = _uisRepeatParser_;
scope.selection = {};
scope.getGroupLabel = function (person) {
return person.age % 2 ? 'even' : 'odd';
};
scope.filterInvertOrder = function (groups) {
return groups.sort(function (groupA, groupB) {
return groupA.name.toLocaleLowerCase() < groupB.name.toLocaleLowerCase();
});
};
scope.people = [
{ name: 'Adam', email: 'adam@email.com', group: 'Foo', age: 12 },
{ name: 'Amalie', email: 'amalie@email.com', group: 'Foo', age: 12 },
{ name: 'Estefanía', email: 'estefanía@email.com', group: 'Foo', age: 21 },
{ name: 'Adrian', email: 'adrian@email.com', group: 'Foo', age: 21 },
{ name: 'Wladimir', email: 'wladimir@email.com', group: 'Foo', age: 30 },
{ name: 'Samantha', email: 'samantha@email.com', group: 'bar', age: 30 },
{ name: 'Nicole', email: 'nicole@email.com', group: 'bar', age: 43 },
{ name: 'Natasha', email: 'natasha@email.com', group: 'Baz', age: 54 }
];
scope.peopleObj = {
'1': { name: 'Adam', email: 'adam@email.com', age: 12, country: 'United States' },
'2': { name: 'Amalie', email: 'amalie@email.com', age: 12, country: 'Argentina' },
'3': { name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina' },
'4': { name: 'Adrian', email: 'adrian@email.com', age: 21, country: 'Ecuador' },
'5': { name: 'Wladimir', email: 'wladimir@email.com', age: 30, country: 'Ecuador' },
'6': { name: 'Samantha', email: 'samantha@email.com', age: 30, country: 'United States' },
'7': { name: 'Nicole', email: 'nicole@email.com', age: 43, country: 'Colombia' },
'8': { name: 'Natasha', email: 'natasha@email.com', age: 54, country: 'Ecuador' },
'9': { name: 'Michael', email: 'michael@email.com', age: 15, country: 'Colombia' },
'10': { name: 'Nicolás', email: 'nicolas@email.com', age: 43, country: 'Colombia' }
};
scope.someObject = {};
scope.someObject.people = [
{ name: 'Adam', email: 'adam@email.com', group: 'Foo', age: 12 },
{ name: 'Amalie', email: 'amalie@email.com', group: 'Foo', age: 12 },
{ name: 'Estefanía', email: 'estefanía@email.com', group: 'Foo', age: 21 },
{ name: 'Adrian', email: 'adrian@email.com', group: 'Foo', age: 21 },
{ name: 'Wladimir', email: 'wladimir@email.com', group: 'Foo', age: 30 },
{ name: 'Samantha', email: 'samantha@email.com', group: 'bar', age: 30 },
{ name: 'Nicole', email: 'nicole@email.com', group: 'bar', age: 43 },
{ name: 'Natasha', email: 'natasha@email.com', group: 'Baz', age: 54 }
];
}));
// DSL (domain-specific language)
function compileTemplate(template) {
var el = $compile(angular.element(template))(scope);
scope.$digest();
return el;
}
function createUiSelect(attrs) {
var attrsHtml = '',
matchAttrsHtml = '',
choicesAttrsHtml = ''
if (attrs !== undefined) {
if (attrs.disabled !== undefined) { attrsHtml += ' ng-disabled="' + attrs.disabled + '"'; }
if (attrs.required !== undefined) { attrsHtml += ' ng-required="' + attrs.required + '"'; }
if (attrs.theme !== undefined) { attrsHtml += ' theme="' + attrs.theme + '"'; }
if (attrs.tabindex !== undefined) { attrsHtml += ' tabindex="' + attrs.tabindex + '"'; }
if (attrs.tagging !== undefined) { attrsHtml += ' tagging="' + attrs.tagging + '"'; }
if (attrs.taggingTokens !== undefined) { attrsHtml += ' tagging-tokens="' + attrs.taggingTokens + '"'; }
if (attrs.taggingTokenEscape !== undefined) { attrsHtml += ' tagging-token-escape="' + attrs.taggingTokenEscape + '"'; }
if (attrs.tagOnBlur !== undefined) { attrsHtml += ' tag-on-blur="' + attrs.tagOnBlur + '"'; }
if (attrs.title !== undefined) { attrsHtml += ' title="' + attrs.title + '"'; }
if (attrs.appendToBody !== undefined) { attrsHtml += ' append-to-body="' + attrs.appendToBody + '"'; }
if (attrs.appendDropdownToBody !== undefined) { attrsHtml += ' append-dropdown-to-body="' + attrs.appendDropdownToBody + '"'; }
if (attrs.allowClear !== undefined) { matchAttrsHtml += ' allow-clear="' + attrs.allowClear + '"'; }
if (attrs.inputId !== undefined) { attrsHtml += ' input-id="' + attrs.inputId + '"'; }
if (attrs.ngClass !== undefined) { attrsHtml += ' ng-class="' + attrs.ngClass + '"'; }
if (attrs.resetSearchInput !== undefined) { attrsHtml += ' reset-search-input="' + attrs.resetSearchInput + '"'; }
if (attrs.closeOnSelect !== undefined) { attrsHtml += ' close-on-select="' + attrs.closeOnSelect + '"'; }
if (attrs.spinnerEnabled !== undefined) { attrsHtml += ' spinner-enabled="' + attrs.spinnerEnabled + '"'; }
if (attrs.spinnerClass !== undefined) { attrsHtml += ' spinner-class="' + attrs.spinnerClass + '"'; }
if (attrs.refresh !== undefined) { choicesAttrsHtml += ' refresh="' + attrs.refresh + '"'; }
if (attrs.refreshDelay !== undefined) { choicesAttrsHtml += ' refresh-delay="' + attrs.refreshDelay + '"'; }
if (attrs.backspaceReset !== undefined) { attrsHtml += ' backspace-reset="' + attrs.backspaceReset + '"'; }
if (attrs.uiDisableChoice !== undefined) { choicesAttrsHtml += ' ui-disable-choice="' + attrs.uiDisableChoice + '"'; }
if (attrs.removeSelected !== undefined) { attrsHtml += ' remove-selected="' + attrs.removeSelected + '"'; }
if (attrs.trim !== undefined) { attrsHtml += ' trim="' + attrs.trim + '"'; }
}
return compileTemplate(
'<ui-select ng-model="selection.selected"' + attrsHtml + '> \
<ui-select-match placeholder="Pick one..."' + matchAttrsHtml + '>{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"'+ choicesAttrsHtml + '"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
function getMatchLabel(el) {
return $(el).find('.ui-select-match > span:first > span[ng-transclude]:not(.ng-hide)').text();
}
function clickItem(el, text) {
if (!isDropdownOpened(el)) {
openDropdown(el);
}
$(el).find('.ui-select-choices-row div:contains("' + text + '")').click();
scope.$digest();
}
function clickMatch(el) {
$(el).find('.ui-select-match > span:first').click();
scope.$digest();
}
function isDropdownOpened(el) {
// Does not work with jQuery 2.*, have to use jQuery 1.11.*
// This will be fixed in AngularJS 1.3
// See issue with unit-testing directive using karma https://github.com/angular/angular.js/issues/4640#issuecomment-35002427
return el.scope().$select.open && el.hasClass('open');
}
function triggerKeydown(element, keyCode, isMetaKey) {
var e = jQuery.Event("keydown");
e.which = keyCode;
e.keyCode = keyCode;
e.metaKey = isMetaKey;
element.trigger(e);
}
function triggerPaste(element, text, isClipboardEvent) {
var e = jQuery.Event("paste");
if (isClipboardEvent) {
e.clipboardData = {
getData: function () {
return text;
}
};
} else {
e.originalEvent = {
clipboardData: {
getData: function () {
return text;
}
}
};
}
element.trigger(e);
}
function setSearchText(el, text) {
el.scope().$select.search = text;
scope.$digest();
$timeout.flush();
}
function openDropdown(el) {
var $select = el.scope().$select;
$select.open = true;
scope.$digest();
}
function closeDropdown(el) {
var $select = el.scope().$select;
$select.open = false;
scope.$digest();
}
function showChoicesForSearch(el, search) {
setSearchText(el, search);
el.scope().$select.searchInput.trigger('keyup');
scope.$digest();
}
it('should initialize selected choices with an array if choices source is undefined', function () {
var el = createUiSelect(),
ctrl = el.scope().$select;
ctrl.setItemsFn(); // setPlainItems
expect(ctrl.items).toEqual([]);
});
// Tests
//uisRepeatParser
it('should parse simple repeat syntax', function () {
var locals = {};
locals.people = [{ name: 'Wladimir' }, { name: 'Samantha' }];
locals.person = locals.people[0];
var parserResult = uisRepeatParser.parse('person in people');
expect(parserResult.itemName).toBe('person');
expect(parserResult.modelMapper(locals)).toBe(locals.person);
expect(parserResult.source(locals)).toBe(locals.people);
var ngExp = parserResult.repeatExpression(false);
expect(ngExp).toBe('person in $select.items');
var ngExpGrouped = parserResult.repeatExpression(true);
expect(ngExpGrouped).toBe('person in $group.items');
});
it('should parse simple repeat syntax', function () {
var locals = {};
locals.people = [{ name: 'Wladimir' }, { name: 'Samantha' }];
locals.person = locals.people[0];
var parserResult = uisRepeatParser.parse('person.name as person in people');
expect(parserResult.itemName).toBe('person');
expect(parserResult.modelMapper(locals)).toBe(locals.person.name);
expect(parserResult.source(locals)).toBe(locals.people);
});
it('should parse simple property binding repeat syntax', function () {
var locals = {};
locals.people = [{ name: 'Wladimir' }, { name: 'Samantha' }];
locals.person = locals.people[0];
var parserResult = uisRepeatParser.parse('person.name as person in people');
expect(parserResult.itemName).toBe('person');
expect(parserResult.modelMapper(locals)).toBe(locals.person.name);
expect(parserResult.source(locals)).toBe(locals.people);
});
it('should parse simple property binding repeat syntax with a basic filter', function () {
var locals = {};
locals.people = [{ name: 'Wladimir' }, { name: 'Samantha' }];
locals.person = locals.people[1];
var parserResult = uisRepeatParser.parse('person.name as person in people | filter: { name: \'Samantha\' }');
expect(parserResult.itemName).toBe('person');
expect(parserResult.modelMapper(locals)).toBe(locals.person.name);
expect(parserResult.source(locals)).toEqual([locals.person]);
});
it('should parse simple property binding repeat syntax with track by', function () {
var locals = {};
locals.people = [{ name: 'Wladimir' }, { name: 'Samantha' }];
locals.person = locals.people[0];
var parserResult = uisRepeatParser.parse('person.name as person in people track by person.name');
expect(parserResult.itemName).toBe('person');
expect(parserResult.modelMapper(locals)).toBe(locals.person.name);
expect(parserResult.source(locals)).toBe(locals.people);
});
it('should parse (key, value) repeat syntax', function () {
var locals = {};
locals.people = { 'WC': { name: 'Wladimir' }, 'SH': { name: 'Samantha' } };
locals.person = locals.people[0];
var parserResult = uisRepeatParser.parse('(key,person) in people');
expect(parserResult.itemName).toBe('person');
expect(parserResult.keyName).toBe('key');
expect(parserResult.modelMapper(locals)).toBe(locals.person);
expect(parserResult.source(locals)).toBe(locals.people);
var ngExp = parserResult.repeatExpression(false);
expect(ngExp).toBe('person in $select.items');
var ngExpGrouped = parserResult.repeatExpression(true);
expect(ngExpGrouped).toBe('person in $group.items');
});
it('should parse simple property binding with (key, value) repeat syntax', function () {
var locals = {};
locals.people = { 'WC': { name: 'Wladimir' }, 'SH': { name: 'Samantha' } };
locals.person = locals.people['WC'];
var parserResult = uisRepeatParser.parse('person.name as (key, person) in people');
expect(parserResult.itemName).toBe('person');
expect(parserResult.keyName).toBe('key');
expect(parserResult.modelMapper(locals)).toBe(locals.person.name);
expect(parserResult.source(locals)).toBe(locals.people);
});
it('should should accept a "collection expresion" only if its not (key, value) repeat syntax', function () {
var locals = {};
locals.people = { 'WC': { name: 'Wladimir' }, 'SH': { name: 'Samantha' } };
locals.person = locals.people['WC'];
var parserResult = uisRepeatParser.parse('person.name as person in (peopleNothing || people)');
expect(parserResult.itemName).toBe('person');
expect(parserResult.modelMapper(locals)).toBe(locals.person.name);
// expect(parserResult.source(locals)).toBe(locals.people);
});
it('should should throw if "collection expresion" used and (key, value) repeat syntax', function () {
var locals = {};
locals.people = { 'WC': { name: 'Wladimir' }, 'SH': { name: 'Samantha' } };
locals.person = locals.people['WC'];
function errorFunctionWrapper() {
uisRepeatParser.parse('person.name as (key,person) in (people | someFilter)');
}
expect(errorFunctionWrapper).toThrow();
});
it('should not leak memory', function () {
var cacheLenght = Object.keys(angular.element.cache).length;
createUiSelect().remove();
scope.$destroy();
expect(Object.keys(angular.element.cache).length).toBe(cacheLenght);
});
it('should compile child directives', function () {
var el = createUiSelect();
var searchEl = $(el).find('.ui-select-search');
expect(searchEl.length).toEqual(1);
var matchEl = $(el).find('.ui-select-match');
expect(matchEl.length).toEqual(1);
var choicesContentEl = $(el).find('.ui-select-choices-content');
expect(choicesContentEl.length).toEqual(1);
var choicesContainerEl = $(el).find('.ui-select-choices');
expect(choicesContainerEl.length).toEqual(1);
openDropdown(el);
var choicesEls = $(el).find('.ui-select-choices-row');
expect(choicesEls.length).toEqual(8);
});
it('should correctly render initial state', function () {
scope.selection.selected = scope.people[0];
var el = createUiSelect();
expect(getMatchLabel(el)).toEqual('Adam');
});
it('should merge both ng-class attributes defined on ui-select and its templates', function () {
var el = createUiSelect({
ngClass: "{class: expression}"
});
expect($(el).attr('ng-class')).toEqual("{class: expression, open: $select.open}");
});
it('should correctly render initial state with track by feature', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search track by person.name"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
scope.selection.selected = { name: 'Samantha', email: 'something different than array source', group: 'bar', age: 30 };
scope.$digest();
expect(getMatchLabel(el)).toEqual('Samantha');
});
it('should correctly render initial state with track by $index', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people track by $index"> \
{{person.email}} \
</ui-select-choices> \
</ui-select>'
);
openDropdown(el);
var generatedId = el.scope().$select.generatedId;
expect($(el).find('[id="ui-select-choices-row-' + generatedId + '-0"]').length).toEqual(1);
});
it('should utilize wrapper directive ng-model', function () {
var el = compileTemplate('<wrapper-ui-select ng-model="selection.selected"/>');
scope.selection.selected = { name: 'Samantha', email: 'something different than array source', group: 'bar', age: 30 };
scope.$digest();
expect($(el).find('.ui-select-container > .ui-select-match > span:first > span[ng-transclude]:not(.ng-hide)').text()).toEqual('Samantha');
});
it('should display the choices when activated', function () {
var el = createUiSelect();
expect(isDropdownOpened(el)).toEqual(false);
clickMatch(el);
expect(isDropdownOpened(el)).toEqual(true);
});
it('should select an item', function () {
var el = createUiSelect();
clickItem(el, 'Samantha');
expect(getMatchLabel(el)).toEqual('Samantha');
});
it('should select an item (controller)', function () {
var el = createUiSelect();
el.scope().$select.select(scope.people[1]);
scope.$digest();
expect(getMatchLabel(el)).toEqual('Amalie');
});
it('should not select a non existing item', function () {
var el = createUiSelect();
clickItem(el, "I don't exist");
expect(getMatchLabel(el)).toEqual('');
});
it('should close the choices when an item is selected', function () {
var el = createUiSelect();
clickMatch(el);
expect(isDropdownOpened(el)).toEqual(true);
clickItem(el, 'Samantha');
expect(isDropdownOpened(el)).toEqual(false);
});
it('should re-focus the search input when an item is selected', function () {
var el = createUiSelect();
var searchInput = el.find('.ui-select-search');
openDropdown(el);
spyOn(el.scope().$select, 'setFocus');
clickItem(el, 'Samantha');
expect(el.scope().$select.setFocus).toHaveBeenCalled();
});
it('should open/close dropdown when clicking caret icon', function () {
var el = createUiSelect({ theme: 'select2' });
var searchInput = el.find('.ui-select-search');
var $select = el.scope().$select;
expect($select.open).toEqual(false);
el.find(".ui-select-toggle").click();
expect($select.open).toEqual(true);
el.find(".ui-select-toggle").click();
expect($select.open).toEqual(false);
});
it('should clear selection', function () {
scope.selection.selected = scope.people[0];
var el = createUiSelect({ theme: 'select2', allowClear: 'true' });
var $select = el.scope().$select;
// allowClear should be true.
expect($select.allowClear).toEqual(true);
// Trigger clear.
el.find('.select2-search-choice-close').click();
expect(scope.selection.selected).toEqual(null);
// If there is no selection the X icon should be gone.
expect(el.find('.select2-search-choice-close').length).toEqual(0);
});
it('should toggle allow-clear directive', function () {
scope.selection.selected = scope.people[0];
scope.isClearAllowed = false;
var el = createUiSelect({ theme: 'select2', allowClear: '{{isClearAllowed}}' });
var $select = el.scope().$select;
expect($select.allowClear).toEqual(false);
expect(el.find('.select2-search-choice-close').length).toEqual(0);
// Turn clear on
scope.isClearAllowed = true;
scope.$digest();
expect($select.allowClear).toEqual(true);
expect(el.find('.select2-search-choice-close').length).toEqual(1);
});
it('should clear selection (with object as source)', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected" theme="select2"> \
<ui-select-match placeholder="Pick one..." allow-clear="true">{{$select.selected.value.name}}</ui-select-match> \
<ui-select-choices repeat="person.value.name as (key,person) in peopleObj | filter: $select.search"> \
<div ng-bind-html="person.value.name | highlight: $select.search"></div> \
<div ng-bind-html="person.value.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
var $select = el.scope().$select;
clickItem(el, 'Samantha');
expect(scope.selection.selected).toEqual('Samantha');
// allowClear should be true.
expect($select.allowClear).toEqual(true);
// Trigger clear.
el.find('.select2-search-choice-close').click();
expect(scope.selection.selected).toEqual(null);
// If there is no selection the X icon should be gone.
expect(el.find('.select2-search-choice-close').length).toEqual(0);
});
it('should pass tabindex to focusser', function () {
var el = createUiSelect({ tabindex: 5 });
expect($(el).find('.ui-select-focusser').attr('tabindex')).toEqual('5');
expect($(el).attr('tabindex')).toEqual(undefined);
});
it('should pass tabindex to focusser when tabindex is an expression', function () {
scope.tabValue = 22;
var el = createUiSelect({ tabindex: '{{tabValue + 10}}' });
expect($(el).find('.ui-select-focusser').attr('tabindex')).toEqual('32');
expect($(el).attr('tabindex')).toEqual(undefined);
});
it('should not give focusser a tabindex when ui-select does not have one', function () {
var el = createUiSelect();
expect($(el).find('.ui-select-focusser').attr('tabindex')).toEqual(undefined);
expect($(el).attr('tabindex')).toEqual(undefined);
});
it('should be disabled if the attribute says so', function () {
var el1 = createUiSelect({ disabled: true });
expect(el1.scope().$select.disabled).toEqual(true);
clickMatch(el1);
expect(isDropdownOpened(el1)).toEqual(false);
var el2 = createUiSelect({ disabled: false });
expect(el2.scope().$select.disabled).toEqual(false);
clickMatch(el2);
expect(isDropdownOpened(el2)).toEqual(true);
var el3 = createUiSelect();
expect(el3.scope().$select.disabled).toBeFalsy();
clickMatch(el3);
expect(isDropdownOpened(el3)).toEqual(true);
});
it('should allow decline tags when tagging function returns null', function () {
scope.taggingFunc = function (name) {
return null;
};
var el = createUiSelect({ tagging: 'taggingFunc' });
clickMatch(el);
showChoicesForSearch(el, 'idontexist');
$(el).scope().$select.activeIndex = 0;
$(el).scope().$select.select('idontexist');
expect($(el).scope().$select.selected).not.toBeDefined();
});
it('should allow tagging if the attribute says so', function () {
var el = createUiSelect({ tagging: true });
clickMatch(el);
$(el).scope().$select.select("I don't exist");
expect($(el).scope().$select.selected).toEqual("I don't exist");
});
it('should format new items using the tagging function when the attribute is a function', function () {
scope.taggingFunc = function (name) {
return {
name: name,
email: name + '@email.com',
group: 'Foo',
age: 12
};
};
var el = createUiSelect({ tagging: 'taggingFunc' });
clickMatch(el);
$(el).scope().$select.search = 'idontexist';
$(el).scope().$select.activeIndex = 0;
$(el).scope().$select.select('idontexist');
expect($(el).scope().$select.selected).toEqual({
name: 'idontexist',
email: 'idontexist@email.com',
group: 'Foo',
age: 12
});
});
// See when an item that evaluates to false (such as "false" or "no") is selected, the placeholder is shown https://github.com/angular-ui/ui-select/pull/32
it('should not display the placeholder when item evaluates to false', function () {
scope.items = ['false'];
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match>{{$select.selected}}</ui-select-match> \
<ui-select-choices repeat="item in items | filter: $select.search"> \
<div ng-bind-html="item | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
expect(el.scope().$select.selected).toEqual(undefined);
clickItem(el, 'false');
expect(el.scope().$select.selected).toEqual('false');
expect(getMatchLabel(el)).toEqual('false');
});
it('should close an opened select when another one is opened', function () {
var el1 = createUiSelect();
var el2 = createUiSelect();
el1.appendTo(document.body);
el2.appendTo(document.body);
expect(isDropdownOpened(el1)).toEqual(false);
expect(isDropdownOpened(el2)).toEqual(false);
clickMatch(el1);
expect(isDropdownOpened(el1)).toEqual(true);
expect(isDropdownOpened(el2)).toEqual(false);
clickMatch(el2);
expect(isDropdownOpened(el1)).toEqual(false);
expect(isDropdownOpened(el2)).toEqual(true);
el1.remove();
el2.remove();
});
it('should bind model correctly (with object as source)', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.value.name}}</ui-select-match> \
<ui-select-choices repeat="person.value as (key,person) in peopleObj | filter: $select.search"> \
<div ng-bind-html="person.value.name | highlight: $select.search"></div> \
<div ng-bind-html="person.value.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
// scope.selection.selected = 'Samantha';
clickItem(el, 'Samantha');
scope.$digest();
expect(getMatchLabel(el)).toEqual('Samantha');
expect(scope.selection.selected).toBe(scope.peopleObj[6]);
});
it('should bind model correctly (with object as source) using a single property', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.value.name}}</ui-select-match> \
<ui-select-choices repeat="person.value.name as (key,person) in peopleObj | filter: $select.search"> \
<div ng-bind-html="person.value.name | highlight: $select.search"></div> \
<div ng-bind-html="person.value.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
// scope.selection.selected = 'Samantha';
clickItem(el, 'Samantha');
scope.$digest();
expect(getMatchLabel(el)).toEqual('Samantha');
expect(scope.selection.selected).toBe('Samantha');
});
it('should update choices when original source changes (with object as source)', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.value.name}}</ui-select-match> \
<ui-select-choices repeat="person.value.name as (key,person) in peopleObj | filter: $select.search"> \
<div ng-bind-html="person.value.name | highlight: $select.search"></div> \
<div ng-bind-html="person.value.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
scope.$digest();
openDropdown(el);
var choicesEls = $(el).find('.ui-select-choices-row');
expect(choicesEls.length).toEqual(10);
scope.peopleObj['11'] = { name: 'Camila', email: 'camila@email.com', age: 1, country: 'Ecuador' };
scope.$digest();
choicesEls = $(el).find('.ui-select-choices-row');
expect(choicesEls.length).toEqual(11);
});
it('should bind model correctly (with object as source) using the key of collection', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.value.name}}</ui-select-match> \
<ui-select-choices repeat="person.key as (key,person) in peopleObj | filter: $select.search"> \
<div ng-bind-html="person.value.name | highlight: $select.search"></div> \
<div ng-bind-html="person.value.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
// scope.selection.selected = 'Samantha';
clickItem(el, 'Samantha');
scope.$digest();
expect(getMatchLabel(el)).toEqual('Samantha');
expect(scope.selection.selected).toBe('6');
});
it('should correctly render initial state (with object as source) differentiating between falsy values', function () {
scope.items = [{
label: '-- None Selected --',
value: ''
}, {
label: 'Yes',
value: true
}, {
label: 'No',
value: false
}];
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match>{{ $select.selected.label }}</ui-select-match> \
<ui-select-choices repeat="item.value as item in items track by item.value">{{ item.label }}</ui-select-choices> \
</ui-select>'
);
scope.selection.selected = '';
scope.$digest();
expect(getMatchLabel(el)).toEqual('-- None Selected --');
});
describe('backspace reset option', function () {
it('should undefined model when pressing BACKSPACE key if backspaceReset=true', function () {
var el = createUiSelect();
var focusserInput = el.find('.ui-select-focusser');
clickItem(el, 'Samantha');
triggerKeydown(focusserInput, Key.Backspace);
expect(scope.selection.selected).toBeUndefined();
});
it('should NOT reset model when pressing BACKSPACE key if backspaceReset=false', function () {
var el = createUiSelect({ backspaceReset: false });
var focusserInput = el.find('.ui-select-focusser');
clickItem(el, 'Samantha');
triggerKeydown(focusserInput, Key.Backspace);
expect(scope.selection.selected).toBe(scope.people[5]);
});
});
describe('disabled options', function () {
function createUiSelect(attrs) {
var attrsDisabled = '';
if (attrs !== undefined) {
if (attrs.disabled !== undefined) {
attrsDisabled = ' ui-disable-choice="' + attrs.disabled + '"';
} else {
attrsDisabled = '';
}
}
return compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"' + attrsDisabled + '> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
function disablePerson(opts) {
opts = opts || {};
var key = opts.key || 'people',
disableAttr = opts.disableAttr || 'disabled',
disableBool = opts.disableBool === undefined ? true : opts.disableBool,
matchAttr = opts.match || 'name',
matchVal = opts.matchVal || 'Wladimir';
scope['_' + key] = angular.copy(scope[key]);
scope[key].map(function (model) {
if (model[matchAttr] == matchVal) {
model[disableAttr] = disableBool;
}
return model;
});
}
function resetScope(opts) {
opts = opts || {};
var key = opts.key || 'people';
scope[key] = angular.copy(scope['_' + key]);
}
describe('without disabling expression', function () {
beforeEach(function () {
disablePerson();
this.el = createUiSelect();
});
it('should not allow disabled options to be selected', function () {
clickItem(this.el, 'Wladimir');
expect(getMatchLabel(this.el)).toEqual('Wladimir');
});
it('should set a disabled class on the option', function () {
var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")');
var container = option.closest('.ui-select-choices-row');
expect(container.hasClass('disabled')).toBeFalsy();
});
});
describe('disable on truthy property', function () {
beforeEach(function () {
disablePerson({
disableAttr: 'inactive',
disableBool: true
});
this.el = createUiSelect({
disabled: 'person.inactive'
});
});
it('should allow the user to define the selected option', function () {
expect($(this.el).find('.ui-select-choices').attr('ui-disable-choice')).toBe('person.inactive');
});
it('should not allow disabled options to be selected', function () {
clickItem(this.el, 'Wladimir');
expect(getMatchLabel(this.el)).not.toEqual('Wladimir');
});
it('should set a disabled class on the option', function () {
openDropdown(this.el);
var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")');
var container = option.closest('.ui-select-choices-row');
expect(container.hasClass('disabled')).toBeTruthy();
});
});
describe('disable on inverse property check', function () {
beforeEach(function () {
disablePerson({
disableAttr: 'active',
disableBool: false
});
this.el = createUiSelect({
disabled: '!person.active'
});
});
it('should allow the user to define the selected option', function () {
expect($(this.el).find('.ui-select-choices').attr('ui-disable-choice')).toBe('!person.active');
});
it('should not allow disabled options to be selected', function () {
clickItem(this.el, 'Wladimir');
expect(getMatchLabel(this.el)).not.toEqual('Wladimir');
});
it('should set a disabled class on the option', function () {
openDropdown(this.el);
var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")');
var container = option.closest('.ui-select-choices-row');
expect(container.hasClass('disabled')).toBeTruthy();
});
});
describe('disable on expression', function () {
beforeEach(function () {
disablePerson({
disableAttr: 'status',
disableBool: 'inactive'
});
this.el = createUiSelect({
disabled: "person.status == 'inactive'"
});
});
it('should allow the user to define the selected option', function () {
expect($(this.el).find('.ui-select-choices').attr('ui-disable-choice')).toBe("person.status == 'inactive'");
});
it('should not allow disabled options to be selected', function () {
clickItem(this.el, 'Wladimir');
expect(getMatchLabel(this.el)).not.toEqual('Wladimir');
});
it('should set a disabled class on the option', function () {
openDropdown(this.el);
var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")');
var container = option.closest('.ui-select-choices-row');
expect(container.hasClass('disabled')).toBeTruthy();
});
});
afterEach(function () {
resetScope();
});
});
describe('choices group', function () {
function getGroupLabel(item) {
return item.parent('.ui-select-choices-group').find('.ui-select-choices-group-label');
}
function createUiSelect() {
return compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices group-by="\'group\'" repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
it('should create items group', function () {
var el = createUiSelect();
expect(el.find('.ui-select-choices-group').length).toBe(3);
});
it('should show label before each group', function () {
var el = createUiSelect();
expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () {
return this.textContent;
}).toArray()).toEqual(['Foo', 'bar', 'Baz']);
});
it('should hide empty groups', function () {
var el = createUiSelect();
el.scope().$select.search = 'd';
scope.$digest();
expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () {
return this.textContent;
}).toArray()).toEqual(['Foo']);
});
it('should change activeItem through groups', function () {
var el = createUiSelect();
el.scope().$select.search = 't';
scope.$digest();
openDropdown(el);
var choices = el.find('.ui-select-choices-row');
expect(choices.eq(0)).toHaveClass('active');
expect(getGroupLabel(choices.eq(0)).text()).toBe('Foo');
triggerKeydown(el.find('input'), 40 /*Down*/);
scope.$digest();
expect(choices.eq(1)).toHaveClass('active');
expect(getGroupLabel(choices.eq(1)).text()).toBe('bar');
});
});
describe('choices group by function', function () {
function createUiSelect() {
return compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices group-by="getGroupLabel" repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
it("should extract group value through function", function () {
var el = createUiSelect();
expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () {
return this.textContent;
}).toArray()).toEqual(['odd', 'even']);
});
});
describe('choices group filter function', function () {
function createUiSelect() {
return compileTemplate('\
<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices group-by="\'group\'" group-filter="filterInvertOrder" repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
it("should sort groups using filter", function () {
var el = createUiSelect();
expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () {
return this.textContent;
}).toArray()).toEqual(["Foo", "bar", "Baz"]);
});
});
describe('choices group filter array', function () {
function createUiSelect() {
return compileTemplate('\
<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices group-by="\'group\'" group-filter="[\'Foo\']" \
repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
it("should sort groups using filter", function () {
var el = createUiSelect();
expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () {
return this.textContent;
}).toArray()).toEqual(["Foo"]);
});
});
it('should format the model correctly using alias', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickItem(el, 'Samantha');
expect(scope.selection.selected).toBe(scope.people[5]);
});
it('should parse the model correctly using alias', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
scope.selection.selected = scope.people[5];
scope.$digest();
expect(getMatchLabel(el)).toEqual('Samantha');
});
it('should format the model correctly using property of alias', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person.name as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickItem(el, 'Samantha');
expect(scope.selection.selected).toBe('Samantha');
});
it('should parse the model correctly using property of alias', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person.name as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
scope.selection.selected = 'Samantha';
scope.$digest();
expect(getMatchLabel(el)).toEqual('Samantha');
});
it('should parse the model correctly using property of alias with async choices data', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person.name as person in peopleAsync | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
$timeout(function () {
scope.peopleAsync = scope.people;
});
scope.selection.selected = 'Samantha';
scope.$digest();
expect(getMatchLabel(el)).toEqual('');
$timeout.flush(); //After choices populated (async), it should show match correctly
expect(getMatchLabel(el)).toEqual('Samantha');
});
//TODO Is this really something we should expect?
it('should parse the model correctly using property of alias but passed whole object', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person.name as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
scope.selection.selected = scope.people[5];
scope.$digest();
expect(getMatchLabel(el)).toEqual('Samantha');
});
it('should format the model correctly without alias', function () {
var el = createUiSelect();
clickItem(el, 'Samantha');
expect(scope.selection.selected).toBe(scope.people[5]);
});
it('should parse the model correctly without alias', function () {
var el = createUiSelect();
scope.selection.selected = scope.people[5];
scope.$digest();
expect(getMatchLabel(el)).toEqual('Samantha');
});
it('should display choices correctly with child array', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in someObject.people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
scope.selection.selected = scope.people[5];
scope.$digest();
expect(getMatchLabel(el)).toEqual('Samantha');
});
it('should format the model correctly using property of alias and when using child array for choices', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person.name as person in someObject.people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickItem(el, 'Samantha');
expect(scope.selection.selected).toBe('Samantha');
});
it('should invoke select callback on select', function () {
scope.onSelectFn = function ($item, $model, $label) {
scope.$item = $item;
scope.$model = $model;
};
var el = compileTemplate(
'<ui-select on-select="onSelectFn($item, $model)" ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person.name as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
expect(scope.$item).toBeFalsy();
expect(scope.$model).toBeFalsy();
clickItem(el, 'Samantha');
$timeout.flush();
expect(scope.selection.selected).toBe('Samantha');
expect(scope.$item).toEqual(scope.people[5]);
expect(scope.$model).toEqual('Samantha');
});
it('should set $item & $model correctly when invoking callback on select and no single prop. binding', function () {
scope.onSelectFn = function ($item, $model, $label) {
scope.$item = $item;
scope.$model = $model;
};
var el = compileTemplate(
'<ui-select on-select="onSelectFn($item, $model)" ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
expect(scope.$item).toBeFalsy();
expect(scope.$model).toBeFalsy();
clickItem(el, 'Samantha');
expect(scope.$item).toEqual(scope.$model);
});
it('should invoke remove callback on remove', function () {
scope.onRemoveFn = function ($item, $model, $label) {
scope.$item = $item;
scope.$model = $model;
};
var el = compileTemplate(
'<ui-select multiple on-remove="onRemoveFn($item, $model)" ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person.name as person in people | filter: $select.search"> \
<div ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
expect(scope.$item).toBeFalsy();
expect(scope.$model).toBeFalsy();
clickItem(el, 'Samantha');
clickItem(el, 'Adrian');
el.find('.ui-select-match-item').first().find('.ui-select-match-close').click();
$timeout.flush();
expect(scope.$item).toBe(scope.people[5]);
expect(scope.$model).toBe('Samantha');
});
it('should set $item & $model correctly when invoking callback on remove and no single prop. binding', function () {
scope.onRemoveFn = function ($item, $model, $label) {
scope.$item = $item;
scope.$model = $model;
};
var el = compileTemplate(
'<ui-select multiple on-remove="onRemoveFn($item, $model)" ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
expect(scope.$item).toBeFalsy();
expect(scope.$model).toBeFalsy();
clickItem(el, 'Samantha');
clickItem(el, 'Adrian');
el.find('.ui-select-match-item').first().find('.ui-select-match-close').click();
$timeout.flush();
expect(scope.$item).toBe(scope.people[5]);
expect(scope.$model).toBe(scope.$item);
});
it('should call open-close callback with isOpen state as first argument on open and on close', function () {
var el = compileTemplate(
'<ui-select uis-open-close="onOpenCloseFn(isOpen)" ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person.name as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
scope.onOpenCloseFn = function () { };
spyOn(scope, 'onOpenCloseFn');
openDropdown(el);
$timeout.flush();
expect(scope.onOpenCloseFn).toHaveBeenCalledWith(true);
closeDropdown(el);
$timeout.flush();
expect(scope.onOpenCloseFn).toHaveBeenCalledWith(false);
expect(scope.onOpenCloseFn.calls.count()).toBe(2);
});
it('should allow creating tag in single select mode with tagging enabled', function () {
scope.taggingFunc = function (name) {
return name;
};
var el = compileTemplate(
'<ui-select ng-model="selection.selected" tagging="taggingFunc" tagging-label="false"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickMatch(el);
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'idontexist');
triggerKeydown(searchInput, Key.Enter);
expect($(el).scope().$select.selected).toEqual('idontexist');
});
it('should allow creating tag on ENTER in multiple select mode with tagging enabled, no labels', function () {
scope.taggingFunc = function (name) {
return name;
};
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selected" tagging="taggingFunc" tagging-label="false"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'idontexist');
triggerKeydown(searchInput, Key.Enter);
expect($(el).scope().$select.selected).toEqual(['idontexist']);
});
it('should create tag on ENTER when dropdown open and tag equals first dropdown option exactly', function () {
scope.taggingFunc = function (name) {
return scope.people.filter(function(person) {
return person.name === name;
})[0]
};
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selected" tagging="taggingFunc" tagging-label="false" tagging-tokens="ENTER|,"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name" | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'Samantha');
openDropdown(el);
triggerKeydown(searchInput, Key.Enter);
expect($(el).scope().$select.selected[0].name).toEqual('Samantha');
});
it('should allow selecting an item (click) in single select mode with tagging enabled', function () {
scope.taggingFunc = function (name) {
return name;
};
var el = compileTemplate(
'<ui-select ng-model="selection.selected" tagging="taggingFunc" tagging-label="false"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickMatch(el);
setSearchText(el, 'Sam');
clickItem(el, 'Samantha');
expect(scope.selection.selected).toBe(scope.people[5]);
expect(getMatchLabel(el)).toEqual('Samantha');
});
it('should remove a choice when multiple and remove-selected is not given (default is true)', function () {
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div class="person-name" ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickItem(el, 'Samantha');
clickItem(el, 'Adrian');
openDropdown(el);
var choicesEls = $(el).find('.ui-select-choices-row');
expect(choicesEls.length).toEqual(6);
['Adam', 'Amalie', 'Estefanía', 'Wladimir', 'Nicole', 'Natasha'].forEach(function (name, index) {
expect($(choicesEls[index]).hasClass('disabled')).toBeFalsy();
expect($(choicesEls[index]).find('.person-name').text()).toEqual(name);
});
});
it('should not remove a pre-selected choice when not multiple and remove-selected is not given (default is true)', function () {
scope.selection.selected = scope.people[5]; // Samantha
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div class="person-name" ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
expect(getMatchLabel(el)).toEqual("Samantha");
openDropdown(el);
var choicesEls = $(el).find('.ui-select-choices-row');
expect(choicesEls.length).toEqual(8);
['Adam', 'Amalie', 'Estefanía', 'Adrian', 'Wladimir', 'Samantha', 'Nicole', 'Natasha'].forEach(function (name, index) {
expect($(choicesEls[index]).hasClass('disabled')).toBeFalsy();
expect($(choicesEls[index]).find('.person-name').text()).toEqual(name);
});
});
it('should disable a choice instead of removing it when remove-selected is false', function () {
var el = compileTemplate(
'<ui-select multiple remove-selected="false" ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickItem(el, 'Samantha');
clickItem(el, 'Adrian');
openDropdown(el);
var choicesEls = $(el).find('.ui-select-choices-row');
expect(choicesEls.length).toEqual(8);
[false, false, false, true /* Adrian */, false, true /* Samantha */, false, false].forEach(function (bool, index) {
expect($(choicesEls[index]).hasClass('disabled')).toEqual(bool);
});
});
it('should append/transclude content (with correct scope) that users add at <match> tag', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match> \
<span ng-if="$select.selected.name!==\'Wladimir\'">{{$select.selected.name}}</span>\
<span ng-if="$select.selected.name===\'Wladimir\'">{{$select.selected.name | uppercase}}</span>\
</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickItem(el, 'Samantha');
expect(getMatchLabel(el).trim()).toEqual('Samantha');
clickItem(el, 'Wladimir');
expect(getMatchLabel(el).trim()).not.toEqual('Wladimir');
expect(getMatchLabel(el).trim()).toEqual('WLADIMIR');
});
it('should append/transclude content (with correct scope) that users add at <choices> tag', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match> \
</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-if="person.name==\'Wladimir\'"> \
<span class="only-once">I should appear only once</span>\
</div> \
</ui-select-choices> \
</ui-select>'
);
openDropdown(el);
expect($(el).find('.only-once').length).toEqual(1);
});
it('should call refresh function when search text changes', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match> \
</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search" \
refresh="fetchFromServer($select.search)" refresh-delay="0"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-if="person.name==\'Wladimir\'"> \
<span class="only-once">I should appear only once</span>\
</div> \
</ui-select-choices> \
</ui-select>'
);
scope.fetchFromServer = function () { };
spyOn(scope, 'fetchFromServer');
el.scope().$select.search = 'r';
scope.$digest();
$timeout.flush();
expect(scope.fetchFromServer).toHaveBeenCalledWith('r');
});
it('should call refresh function respecting minimum input length option', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match> \
</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search" \
refresh="fetchFromServer($select.search)" refresh-delay="0" minimum-input-length="3"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-if="person.name==\'Wladimir\'"> \
<span class="only-once">I should appear only once</span>\
</div> \
</ui-select-choices> \
</ui-select>'
);
scope.fetchFromServer = function () { };
spyOn(scope, 'fetchFromServer');
el.scope().$select.search = 'r';
scope.$digest();
$timeout.flush();
expect(scope.fetchFromServer).not.toHaveBeenCalledWith('r');
el.scope().$select.search = 'red';
scope.$digest();
$timeout.flush();
expect(scope.fetchFromServer).toHaveBeenCalledWith('red');
});
it('should call refresh function respecting minimum input length option with given refresh-delay', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match> \
</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search" \
refresh="fetchFromServer($select.search)" refresh-delay="1" minimum-input-length="3"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-if="person.name==\'Wladimir\'"> \
<span class="only-once">I should appear only once</span>\
</div> \
</ui-select-choices> \
</ui-select>'
);
scope.fetchFromServer = function () { };
spyOn(scope, 'fetchFromServer');
el.scope().$select.search = 'redd';
scope.$digest();
$timeout.flush();
expect(scope.fetchFromServer).toHaveBeenCalledWith('redd');
el.scope().$select.search = 'red';
scope.$digest();
el.scope().$select.search = 're';
scope.$digest();
el.scope().$select.search = 'r';
scope.$digest();
$timeout.flush();
expect(scope.fetchFromServer).not.toHaveBeenCalledWith('r');
});
it('should format view value correctly when using single property binding and refresh function', function () {
var el = compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match>{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person.name as person in people | filter: $select.search" \
refresh="fetchFromServer($select.search)" refresh-delay="0"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-if="person.name==\'Wladimir\'"> \
<span class="only-once">I should appear only once</span>\
</div> \
</ui-select-choices> \
</ui-select>'
);
scope.fetchFromServer = function (searching) {
if (searching == 's')
return scope.people;
if (searching == 'o') {
scope.people = []; //To simulate cases were previously selected item isnt in the list anymore
}
};
setSearchText(el, 'r');
clickItem(el, 'Samantha');
expect(getMatchLabel(el)).toBe('Samantha');
setSearchText(el, 'o');
expect(getMatchLabel(el)).toBe('Samantha');
});
it('should retain an invalid view value after refreshing items', function () {
scope.taggingFunc = function (name) {
return {
name: name,
email: name + '@email.com',
valid: name === "iamvalid"
};
};
var el = compileTemplate(
'<ui-select ng-model="selection.selected" tagging="taggingFunc" tagging-label="false" test-validator> \
<ui-select-match placeholder="Pick one...">{{$select.selected.email}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickMatch(el);
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'iamvalid');
triggerKeydown(searchInput, Key.Tab);
//model value defined because it's valid, view value defined as expected
var validTag = scope.taggingFunc("iamvalid");
expect(scope.selection.selected).toEqual(validTag);
expect($(el).scope().$select.selected).toEqual(validTag);
clickMatch(el);
setSearchText(el, 'notvalid');
triggerKeydown(searchInput, Key.Tab);
//model value undefined because it's invalid, view value STILL defined as expected
expect(scope.selection.selected).toEqual(undefined);
expect($(el).scope().$select.selected).toEqual(scope.taggingFunc("notvalid"));
});
describe('search-enabled option', function () {
var el;
function setupSelectComponent(searchEnabled, theme) {
el = compileTemplate(
'<ui-select ng-model="selection.selected" theme="' + theme + '" search-enabled="' + searchEnabled + '"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
describe('selectize theme', function () {
it('should show search input when true', function () {
setupSelectComponent(true, 'selectize');
expect($(el).find('.ui-select-search')).not.toHaveClass('ui-select-search-hidden');
});
it('should hide search input when false', function () {
setupSelectComponent(false, 'selectize');
expect($(el).find('.ui-select-search')).toHaveClass('ui-select-search-hidden');
});
});
describe('select2 theme', function () {
it('should show search input when true', function () {
setupSelectComponent('true', 'select2');
expect($(el).find('.search-container')).not.toHaveClass('ui-select-search-hidden');
});
it('should hide search input when false', function () {
setupSelectComponent('false', 'select2');
expect($(el).find('.search-container')).toHaveClass('ui-select-search-hidden');
});
});
describe('bootstrap theme', function () {
it('should show search input when true', function () {
setupSelectComponent('true', 'bootstrap');
clickMatch(el);
expect($(el).find('.ui-select-search')).not.toHaveClass('ui-select-search-hidden');
});
it('should hide search input when false', function () {
setupSelectComponent('false', 'bootstrap');
clickMatch(el);
expect($(el).find('.ui-select-search')).toHaveClass('ui-select-search-hidden');
});
});
});
describe('multi selection', function () {
function createUiSelectMultiple(attrs) {
var attrsHtml = '',
choicesAttrsHtml = '',
matchesAttrsHtml = '';
if (attrs !== undefined) {
if (attrs.disabled !== undefined) { attrsHtml += ' ng-disabled="' + attrs.disabled + '"'; }
if (attrs.required !== undefined) { attrsHtml += ' ng-required="' + attrs.required + '"'; }
if (attrs.tabindex !== undefined) { attrsHtml += ' tabindex="' + attrs.tabindex + '"'; }
if (attrs.closeOnSelect !== undefined) { attrsHtml += ' close-on-select="' + attrs.closeOnSelect + '"'; }
if (attrs.tagging !== undefined) { attrsHtml += ' tagging="' + attrs.tagging + '"'; }
if (attrs.taggingTokens !== undefined) { attrsHtml += ' tagging-tokens="' + attrs.taggingTokens + '"'; }
if (attrs.taggingLabel !== undefined) { attrsHtml += ' tagging-label="' + attrs.taggingLabel + '"'; }
if (attrs.taggingTokenEscape !== undefined) { attrsHtml += ' tagging-token-escape="' + attrs.taggingTokenEscape + '"'; }
if (attrs.tagOnBlur !== undefined) { attrsHtml += ' tag-on-blur="' + attrs.tagOnBlur + '"'; }
if (attrs.paste !== undefined) { attrsHtml += ' paste="' + attrs.paste + '"'; }
if (attrs.copying !== undefined) { attrsHtml += ' copying="' + attrs.copying + '"'; }
if (attrs.inputId !== undefined) { attrsHtml += ' input-id="' + attrs.inputId + '"'; }
if (attrs.groupBy !== undefined) { choicesAttrsHtml += ' group-by="' + attrs.groupBy + '"'; }
if (attrs.uiDisableChoice !== undefined) { choicesAttrsHtml += ' ui-disable-choice="' + attrs.uiDisableChoice + '"'; }
if (attrs.lockChoice !== undefined) { matchesAttrsHtml += ' ui-lock-choice="' + attrs.lockChoice + '"'; }
if (attrs.removeSelected !== undefined) { attrsHtml += ' remove-selected="' + attrs.removeSelected + '"'; }
if (attrs.resetSearchInput !== undefined) { attrsHtml += ' reset-search-input="' + attrs.resetSearchInput + '"'; }
if (attrs.limit !== undefined) { attrsHtml += ' limit="' + attrs.limit + '"'; }
if (attrs.onSelect !== undefined) { attrsHtml += ' on-select="' + attrs.onSelect + '"'; }
if (attrs.removeSelected !== undefined) { attrsHtml += ' remove-selected="' + attrs.removeSelected + '"'; }
if (attrs.appendDropdownToBody !== undefined) { attrsHtml += ' append-dropdown-to-body="' + attrs.appendDropdownToBody + '"'; }
}
return compileTemplate(
'<ui-select multiple ng-model="selection.selectedMultiple"' + attrsHtml + ' theme="bootstrap" style="width: 800px;"> \
<ui-select-match "' + matchesAttrsHtml + ' placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"' + choicesAttrsHtml + '> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
it('should initialize selected choices with an empty array when choices source is undefined', function () {
var el = createUiSelectMultiple({ groupBy: "'age'" }),
ctrl = el.scope().$select;
ctrl.setItemsFn(); // updateGroups
expect(ctrl.items).toEqual([]);
});
it('should render initial state', function () {
var el = createUiSelectMultiple();
expect(el).toHaveClass('ui-select-multiple');
expect(el.scope().$select.selected.length).toBe(0);
expect(el.find('.ui-select-match-item').length).toBe(0);
});
it('should render intial state with data-multiple attribute', function () {
// ensure match template has been loaded by having more than one selection
scope.selection.selectedMultiple = [scope.people[0], scope.people[1]];
var el = compileTemplate(
'<ui-select data-multiple ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
expect(el).toHaveClass('ui-select-multiple');
expect(el.scope().$select.selected.length).toBe(2);
expect(el.find('.ui-select-match-item').length).toBe(2);
});
it('should render intial state with x-multiple attribute', function () {
// ensure match template has been loaded by having more than one selection
scope.selection.selectedMultiple = [scope.people[0], scope.people[1]];
var el = compileTemplate(
'<ui-select x-multiple ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
expect(el).toHaveClass('ui-select-multiple');
expect(el.scope().$select.selected.length).toBe(2);
expect(el.find('.ui-select-match-item').length).toBe(2);
});
it('should set model as an empty array if ngModel isnt defined after an item is selected', function () {
// scope.selection.selectedMultiple = [];
var el = createUiSelectMultiple();
expect(scope.selection.selectedMultiple instanceof Array).toBe(false);
clickItem(el, 'Samantha');
expect(scope.selection.selectedMultiple instanceof Array).toBe(true);
});
it('should render initial selected items', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha
var el = createUiSelectMultiple();
expect(el.scope().$select.selected.length).toBe(2);
expect(el.find('.ui-select-match-item').length).toBe(2);
});
it('should remove item by pressing X icon', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha
var el = createUiSelectMultiple();
expect(el.scope().$select.selected.length).toBe(2);
el.find('.ui-select-match-item').first().find('.ui-select-match-close').click();
expect(el.scope().$select.selected.length).toBe(1);
// $timeout.flush();
});
it('should pass tabindex to searchInput', function () {
var el = createUiSelectMultiple({ tabindex: 5 });
var searchInput = el.find('.ui-select-search');
expect(searchInput.attr('tabindex')).toEqual('5');
expect($(el).attr('tabindex')).toEqual(undefined);
});
it('should pass tabindex to searchInput when tabindex is an expression', function () {
scope.tabValue = 22;
var el = createUiSelectMultiple({ tabindex: '{{tabValue + 10}}' });
var searchInput = el.find('.ui-select-search');
expect(searchInput.attr('tabindex')).toEqual('32');
expect($(el).attr('tabindex')).toEqual(undefined);
});
it('should not give searchInput a tabindex when ui-select does not have one', function () {
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
expect(searchInput.attr('tabindex')).toEqual(undefined);
expect($(el).attr('tabindex')).toEqual(undefined);
});
it('should update size of search input after removing an item', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha
var el = createUiSelectMultiple();
spyOn(el.scope().$select, 'sizeSearchInput');
var searchInput = el.find('.ui-select-search');
var oldWidth = searchInput.css('width');
el.find('.ui-select-match-item').first().find('.ui-select-match-close').click();
expect(el.scope().$select.sizeSearchInput).toHaveBeenCalled();
});
it('should move to last match when pressing BACKSPACE key from search', function() {
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Backspace);
expect(isDropdownOpened(el)).toEqual(false);
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(el.scope().$select.selected.length - 1);
});
it('should remove highlighted match when pressing BACKSPACE key and decrease activeMatchIndex', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
var copyInput = el.find('.ui-select-copy-input');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Left);
triggerKeydown(copyInput, Key.Left);
triggerKeydown(copyInput, Key.Backspace);
expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[6]]); //Wladimir & Nicole
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(0);
});
it('should remove highlighted match when pressing DELETE key and keep same activeMatchIndex', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
var copyInput = el.find('.ui-select-copy-input');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Left);
triggerKeydown(copyInput, Key.Left);
triggerKeydown(copyInput, Key.Delete);
expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[6]]); //Wladimir & Nicole
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(1);
});
it('should remove highlighted match when pressing meta+X key and keep same activeMatchIndex', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
var copyInput = el.find('.ui-select-copy-input');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Left);
triggerKeydown(copyInput, Key.Left);
triggerKeydown(copyInput, Key.X, true);
expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[6]]); //Wladimir & Nicole
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(1);
});
it('should NOT remove highlighted match when pressing BACKSPACE key on a locked choice', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole
var el = createUiSelectMultiple({ lockChoice: "$item.name == '" + scope.people[6].name + "'" });
var searchInput = el.find('.ui-select-search');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Left);
triggerKeydown(searchInput, Key.Backspace);
expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[5], scope.people[6]]); //Wladimir, Samantha & Nicole
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(scope.selection.selectedMultiple.length - 1);
});
it('should NOT remove highlighted match when pressing DELETE key on a locked choice', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole
var el = createUiSelectMultiple({ lockChoice: "$item.name == '" + scope.people[6].name + "'" });
var searchInput = el.find('.ui-select-search');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Left);
triggerKeydown(searchInput, Key.Delete);
expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[5], scope.people[6]]); //Wladimir, Samantha & Nicole
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(scope.selection.selectedMultiple.length - 1);
});
it('should move to last match when pressing LEFT key from search', function () {
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Left);
expect(isDropdownOpened(el)).toEqual(false);
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(el.scope().$select.selected.length - 1);
});
it('should clear searchInput when pressing LEFT key from search with tag-on-blur', function () {
var el = createUiSelectMultiple({tagOnBlur: true});
var searchInput = el.find('.ui-select-search');
el.scope().$select.search = 'r';
scope.$digest()
searchInput[0].setSelectionRange(0,0)
triggerKeydown(searchInput, Key.Left);
expect(el.scope().$select.search).toBe("");
});
it('should move between matches when pressing LEFT key from search', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Left);
triggerKeydown(searchInput, Key.Left);
expect(isDropdownOpened(el)).toEqual(false);
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(el.scope().$select.selected.length - 2);
triggerKeydown(searchInput, Key.Left);
triggerKeydown(searchInput, Key.Left);
triggerKeydown(searchInput, Key.Left);
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(0);
});
it('should decrease $selectMultiple.activeMatchIndex when pressing LEFT key', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
el.scope().$selectMultiple.activeMatchIndex = 3;
triggerKeydown(searchInput, Key.Left);
triggerKeydown(searchInput, Key.Left);
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(1);
});
it('should increase $selectMultiple.activeMatchIndex when pressing RIGHT key', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
el.scope().$selectMultiple.activeMatchIndex = 0;
triggerKeydown(searchInput, Key.Right);
triggerKeydown(searchInput, Key.Right);
expect(el.scope().$selectMultiple.activeMatchIndex).toBe(2);
});
it('should open dropdown when pressing DOWN key', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Down);
expect(isDropdownOpened(el)).toEqual(true);
});
it('should search/open dropdown when writing to search input', function () {
scope.selection.selectedMultiple = [scope.people[5]]; //Wladimir & Samantha
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
el.scope().$select.search = 'r';
scope.$digest();
expect(isDropdownOpened(el)).toEqual(true);
});
it('should add selected match to selection array', function () {
scope.selection.selectedMultiple = [scope.people[5]]; //Samantha
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
clickItem(el, 'Wladimir');
expect(scope.selection.selectedMultiple).toEqual([scope.people[5], scope.people[4]]); //Samantha & Wladimir
});
it('should close dropdown after selecting', function () {
scope.selection.selectedMultiple = [scope.people[5]]; //Samantha
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Down);
expect(isDropdownOpened(el)).toEqual(true);
clickItem(el, 'Wladimir');
expect(isDropdownOpened(el)).toEqual(false);
});
it('should not close dropdown after selecting if closeOnSelect=false', function () {
scope.selection.selectedMultiple = [scope.people[5]]; //Samantha
var el = createUiSelectMultiple({ closeOnSelect: false });
var searchInput = el.find('.ui-select-search');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Down);
expect(isDropdownOpened(el)).toEqual(true);
clickItem(el, 'Wladimir');
expect(isDropdownOpened(el)).toEqual(true);
});
it('should closes dropdown when pressing ESC key from search input', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
expect(isDropdownOpened(el)).toEqual(false);
triggerKeydown(searchInput, Key.Down);
expect(isDropdownOpened(el)).toEqual(true);
triggerKeydown(searchInput, Key.Escape);
expect(isDropdownOpened(el)).toEqual(false);
});
it('should select highlighted match when pressing ENTER key from dropdown', function () {
scope.selection.selectedMultiple = [scope.people[5]]; //Samantha
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Enter);
expect(scope.selection.selectedMultiple.length).toEqual(2);
});
it('should stop the propagation when pressing ENTER key from dropdown', function () {
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
spyOn(jQuery.Event.prototype, 'preventDefault');
spyOn(jQuery.Event.prototype, 'stopPropagation');
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Enter);
expect(jQuery.Event.prototype.preventDefault).toHaveBeenCalled();
expect(jQuery.Event.prototype.stopPropagation).toHaveBeenCalled();
});
it('should stop the propagation when pressing ESC key from dropdown', function () {
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
spyOn(jQuery.Event.prototype, 'preventDefault');
spyOn(jQuery.Event.prototype, 'stopPropagation');
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Escape);
expect(jQuery.Event.prototype.preventDefault).toHaveBeenCalled();
expect(jQuery.Event.prototype.stopPropagation).toHaveBeenCalled();
});
it('should increase $select.activeIndex when pressing DOWN key from dropdown', function () {
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
triggerKeydown(searchInput, Key.Down); //Open dropdown
el.scope().$select.activeIndex = 0;
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Down);
expect(el.scope().$select.activeIndex).toBe(2);
});
it('should decrease $select.activeIndex when pressing UP key from dropdown', function () {
var el = createUiSelectMultiple();
var searchInput = el.find('.ui-select-search');
triggerKeydown(searchInput, Key.Down); //Open dropdown
el.scope().$select.activeIndex = 5;
triggerKeydown(searchInput, Key.Up);
triggerKeydown(searchInput, Key.Up);
expect(el.scope().$select.activeIndex).toBe(3);
});
it('should render initial selected items', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha
var el = createUiSelectMultiple();
expect(el.scope().$select.selected.length).toBe(2);
expect(el.find('.ui-select-match-item').length).toBe(2);
});
it('should parse the items correctly using single property binding', function () {
scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com'];
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[5]]);
});
it('should add selected match to selection array using single property binding', function () {
scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com'];
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
var searchInput = el.find('.ui-select-search');
clickItem(el, 'Natasha');
expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[5], scope.people[7]]);
scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com', 'natasha@email.com'];
});
it('should format view value correctly when using single property binding and refresh function', function () {
scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com'];
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search" \
refresh="fetchFromServer($select.search)" refresh-delay="0"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
var searchInput = el.find('.ui-select-search');
scope.fetchFromServer = function (searching) {
if (searching == 'n')
return scope.people;
if (searching == 'o') {
scope.people = []; //To simulate cases were previously selected item isnt in the list anymore
}
};
setSearchText(el, 'n');
clickItem(el, 'Nicole');
expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text())
.toBe("Wladimir <wladimir@email.com>Samantha <samantha@email.com>Nicole <nicole@email.com>");
setSearchText(el, 'o');
expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text())
.toBe("Wladimir <wladimir@email.com>Samantha <samantha@email.com>Nicole <nicole@email.com>");
});
it('should watch changes for $select.selected and update formatted value correctly', function () {
scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com'];
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select> \
'
);
var el2 = compileTemplate('<span class="resultDiv" ng-bind="selection.selectedMultiple"></span>');
expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text())
.toBe("Wladimir <wladimir@email.com>Samantha <samantha@email.com>");
clickItem(el, 'Nicole');
expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text())
.toBe("Wladimir <wladimir@email.com>Samantha <samantha@email.com>Nicole <nicole@email.com>");
expect(scope.selection.selectedMultiple.length).toBe(3);
});
it('should watch changes for $select.selected and refresh choices correctly', function () {
scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com'];
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select> \
'
);
scope.selection.selectedMultiple.splice(0, 1); // Remove Wladimir from selection
var searchInput = el.find('.ui-select-search');
triggerKeydown(searchInput, Key.Down); //Open dropdown
expect(el.find('.ui-select-choices-content').text())
.toContain("wladimir@email.com");
});
it('should ensure the multiple selection limit is respected', function () {
scope.selection.selectedMultiple = ['wladimir@email.com'];
var el = compileTemplate(
'<ui-select multiple limit="2" ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select> \
'
);
var el2 = compileTemplate('<span class="resultDiv" ng-bind="selection.selectedMultiple"></span>');
expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text())
.toBe("Wladimir <wladimir@email.com>");
clickItem(el, 'Samantha');
expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text())
.toBe("Wladimir <wladimir@email.com>Samantha <samantha@email.com>");
clickItem(el, 'Nicole');
expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text())
.toBe("Wladimir <wladimir@email.com>Samantha <samantha@email.com>");
expect(scope.selection.selectedMultiple.length).toBe(2);
});
it('should change viewvalue only once when updating modelvalue', function () {
scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com'];
var el = compileTemplate(
'<ui-select ng-change="onlyOnce()" multiple ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select> \
'
);
scope.counter = 0;
scope.onlyOnce = function () {
scope.counter++;
};
clickItem(el, 'Nicole');
expect(scope.counter).toBe(1);
});
it('should retain an invalid view value after refreshing items', function () {
scope.taggingFunc = function (name) {
return {
name: name,
email: name + '@email.com',
valid: name === "iamvalid"
};
};
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selectedMultiple" tagging="taggingFunc" tagging-label="false" test-validator> \
<ui-select-match placeholder="Pick one...">{{$select.selected.email}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name" | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
clickMatch(el);
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'iamvalid');
triggerKeydown(searchInput, Key.Tab);
//model value defined because it's valid, view value defined as expected
var validTag = scope.taggingFunc("iamvalid");
expect(scope.selection.selectedMultiple).toEqual([jasmine.objectContaining(validTag)]);
expect($(el).scope().$select.selected).toEqual([jasmine.objectContaining(validTag)]);
clickMatch(el);
setSearchText(el, 'notvalid');
triggerKeydown(searchInput, Key.Tab);
//model value undefined because it's invalid, view value STILL defined as expected
var invalidTag = scope.taggingFunc("notvalid");
expect(scope.selection.selected).toEqual(undefined);
expect($(el).scope().$select.selected).toEqual([jasmine.objectContaining(validTag), jasmine.objectContaining(invalidTag)]);
});
it('should run $formatters when changing model directly', function () {
scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com'];
var el = compileTemplate(
'<ui-select multiple ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select> \
'
);
// var el2 = compileTemplate('<span class="resultDiv" ng-bind="selection.selectedMultiple"></span>');
scope.selection.selectedMultiple.push("nicole@email.com");
scope.$digest();
scope.$digest(); //2nd $digest needed when using angular 1.3.0-rc.1+, might be related with the fact that the value is an array
expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text())
.toBe("Wladimir <wladimir@email.com>Samantha <samantha@email.com>Nicole <nicole@email.com>");
});
it('should support multiple="multiple" attribute', function () {
var el = compileTemplate(
'<ui-select multiple="multiple" ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select> \
'
);
expect(el.scope().$select.multiple).toBe(true);
});
it('should preserve the model if tagging is enabled on select multiple', function () {
scope.selection.selectedMultiple = ["I am not on the list of choices"];
var el = compileTemplate(
'<ui-select multiple="multiple" tagging ng-model="selection.selectedMultiple" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select> \
'
);
scope.$digest();
expect(scope.selection.selectedMultiple)
.toEqual(["I am not on the list of choices"]);
});
it('should not call tagging function needlessly', function () {
scope.slowTaggingFunc = function (name) {
// for (var i = 0; i < 100000000; i++);
return { name: name };
};
spyOn(scope, 'slowTaggingFunc').and.callThrough();
var el = createUiSelectMultiple({ tagging: 'slowTaggingFunc' });
showChoicesForSearch(el, 'Foo');
expect(el.find('.ui-select-choices-row-inner').size()).toBe(6);
showChoicesForSearch(el, 'a');
expect(el.find('.ui-select-choices-row-inner').size()).toBe(9);
expect(scope.slowTaggingFunc.calls.count()).toBe(2);
expect(scope.slowTaggingFunc.calls.count()).not.toBe(15);
});
it('should allow decline tags when tagging function returns null in multiple select mode', function () {
scope.taggingFunc = function (name) {
if (name == 'idontexist') return null;
return {
name: name,
email: name + '@email.com',
group: 'Foo',
age: 12
};
};
var el = createUiSelectMultiple({ tagging: 'taggingFunc' });
showChoicesForSearch(el, 'amalie');
expect(el.find('.ui-select-choices-row-inner').size()).toBe(2);
expect(el.scope().$select.items[0]).toEqual(jasmine.objectContaining({ name: 'amalie', isTag: true }));
expect(el.scope().$select.items[1]).toEqual(jasmine.objectContaining({ name: 'Amalie' }));
showChoicesForSearch(el, 'idoexist');
expect(el.find('.ui-select-choices-row-inner').size()).toBe(1);
expect(el.find('.ui-select-choices-row-inner').is(':contains(idoexist@email.com)')).toBeTruthy();
showChoicesForSearch(el, 'idontexist');
expect(el.find('.ui-select-choices-row-inner').size()).toBe(0);
});
it('should allow creating tag in multi select mode with tagging and group-by enabled', function () {
scope.taggingFunc = function (name) {
return {
name: name,
email: name + '@email.com',
group: 'Foo',
age: 12
};
};
var el = createUiSelectMultiple({ tagging: 'taggingFunc', groupBy: "'age'" });
showChoicesForSearch(el, 'amal');
expect(el.find('.ui-select-choices-row-inner').size()).toBe(2);
expect(el.scope().$select.items[0]).toEqual(jasmine.objectContaining({ name: 'amal', email: 'amal@email.com', isTag: true }));
expect(el.scope().$select.items[1]).toEqual(jasmine.objectContaining({ name: 'Amalie', email: 'amalie@email.com' }));
});
it('should have tolerance for undefined values', function () {
scope.modelValue = undefined;
var el = compileTemplate(
'<ui-select multiple ng-model="modelValue" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select> \
'
);
expect($(el).scope().$select.selected).toEqual([]);
});
it('should have tolerance for null values', function () {
scope.modelValue = null;
var el = compileTemplate(
'<ui-select multiple ng-model="modelValue" theme="bootstrap" style="width: 800px;"> \
<ui-select-match placeholder="Pick one...">{{$item.name}} <{{$item.email}}></ui-select-match> \
<ui-select-choices repeat="person.email as person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select> \
'
);
expect($(el).scope().$select.selected).toEqual([]);
});
it('should allow paste tag from clipboard', function () {
scope.taggingFunc = function (name) {
return {
name: name,
email: name + '@email.com',
group: 'Foo',
age: 12
};
};
var el = createUiSelectMultiple({ tagging: 'taggingFunc', taggingTokens: ",|ENTER" });
clickMatch(el);
triggerPaste(el.find('input'), 'tag1');
expect($(el).scope().$select.selected.length).toBe(1);
expect($(el).scope().$select.selected[0].name).toBe('tag1');
});
it('should allow paste tag from clipboard for generic ClipboardEvent', function () {
scope.taggingFunc = function (name) {
return {
name: name,
email: name + '@email.com',
group: 'Foo',
age: 12
};
};
var el = createUiSelectMultiple({ tagging: 'taggingFunc', taggingTokens: ",|ENTER" });
clickMatch(el);
triggerPaste(el.find('input'), 'tag1', true);
expect($(el).scope().$select.selected.length).toBe(1);
expect($(el).scope().$select.selected[0].name).toBe('tag1');
});
it('should allow paste multiple tags', function () {
scope.taggingFunc = function (name) {
return {
name: name,
email: name + '@email.com',
group: 'Foo',
age: 12
};
};
var el = createUiSelectMultiple({ tagging: 'taggingFunc', taggingTokens: ",|ENTER" });
clickMatch(el);
triggerPaste(el.find('input'), ',tag1,tag2,tag3,,tag5,');
expect($(el).scope().$select.selected.length).toBe(5);
});
it('should allow paste multiple tags with generic ClipboardEvent', function () {
scope.taggingFunc = function (name) {
return {
name: name,
email: name + '@email.com',
group: 'Foo',
age: 12
};
};
var el = createUiSelectMultiple({ tagging: 'taggingFunc', taggingTokens: ",|ENTER" });
clickMatch(el);
triggerPaste(el.find('input'), ',tag1,tag2,tag3,,tag5,', true);
expect($(el).scope().$select.selected.length).toBe(5);
});
it('should split pastes on ENTER (and with undefined tagging function)', function () {
var el = createUiSelectMultiple({ tagging: true, taggingTokens: "ENTER|," });
clickMatch(el);
triggerPaste(el.find('input'), "tag1\ntag2\ntag3");
expect($(el).scope().$select.selected.length).toBe(3);
});
it('should split pastes on TAB', function () {
var el = createUiSelectMultiple({ tagging: true, taggingTokens: "TAB|," });
clickMatch(el);
triggerPaste(el.find('input'), "tag1\ttag2\ttag3");
expect($(el).scope().$select.selected.length).toBe(3);
});
it('should split pastes on tagging token that is not the first token', function () {
var el = createUiSelectMultiple({ tagging: true, taggingTokens: ",|ENTER|TAB" });
clickMatch(el);
triggerPaste(el.find('input'), "tag1\ntag2\ntag3\ntag4");
expect($(el).scope().$select.selected).toEqual(['tag1', 'tag2', 'tag3', 'tag4']);
});
it('should split pastes only on first tagging token found in paste string', function () {
var el = createUiSelectMultiple({ tagging: true, taggingTokens: ",|ENTER|TAB" });
clickMatch(el);
triggerPaste(el.find('input'), "tag1\ntag2\ntag3\ttag4");
expect($(el).scope().$select.selected).toEqual(['tag1', 'tag2', 'tag3\ttag4']);
});
it('should allow paste with tagging-tokens and tagging-label=="false"', function () {
var el = createUiSelectMultiple({ tagging: true, taggingLabel: false, taggingTokens: "," });
clickMatch(el);
triggerPaste(el.find('input'), 'tag1');
expect($(el).scope().$select.selected).toEqual(['tag1']);
});
it('should use paste function with tagging-tokens', function() {
scope.pasteFunc = function(string){};
spyOn(scope, 'pasteFunc');
var el = createUiSelectMultiple({tagging: true, paste: "pasteFunc", taggingTokens: ","});
clickMatch(el);
triggerPaste(el.find('input'), 'tag1');
expect(scope.pasteFunc).toHaveBeenCalledWith('tag1');
});
it('should broadcast selected items when paste function returns pasted items', function() {
scope.pasteFunc = function(str) { return [str] };
spyOn(scope, '$broadcast');
var el = createUiSelectMultiple({tagging: true, paste: "pasteFunc", taggingTokens: ","});
clickMatch(el);
triggerPaste(el.find('input'), 'tag1');
expect(scope.$broadcast).not.toHaveBeenCalledWith('uis:select', 'tag1');
expect(scope.$broadcast).toHaveBeenCalledWith('uis:select-multiple', ['tag1']);
});
it('should broadcast pasted items once regardless of paste size', function() {
scope.pasteFunc = function(str) { return str.split(",") };
spyOn(scope, '$broadcast');
var el = createUiSelectMultiple({tagging: true, paste: "pasteFunc", taggingTokens: ","});
clickMatch(el);
triggerPaste(el.find('input'), 'tag1,tag2,tag3');
expect(scope.$broadcast).not.toHaveBeenCalledWith('uis:select', 'tag1');
expect(scope.$broadcast).toHaveBeenCalledWith('uis:select-multiple', ['tag1', 'tag2', 'tag3']);
});
it('should not broadcast if paste function does not return pasted items', function() {
scope.pasteFunc = function() {};
spyOn(scope, '$broadcast');
var el = createUiSelectMultiple({tagging: true, paste: "pasteFunc", taggingTokens: ","});
clickMatch(el);
triggerPaste(el.find('input'), 'tag1');
expect(scope.$broadcast).not.toHaveBeenCalledWith('uis:select-multiple', ['tag1']);
});
it('should add an id to the search input field', function () {
var el = createUiSelectMultiple({ inputId: 'inid' });
var searchEl = $(el).find('input.ui-select-search');
expect(searchEl.length).toEqual(1);
expect(searchEl[0].id).toEqual('inid');
});
it('should properly identify as empty if required', function () {
var el = createUiSelectMultiple({ required: true });
expect(el.hasClass('ng-empty')).toBeTruthy();
});
it('should properly identify as not empty if required', function () {
var el = createUiSelectMultiple({ required: true });
clickItem(el, 'Nicole');
clickItem(el, 'Samantha');
expect(el.hasClass('ng-not-empty')).toBeTruthy();
});
it('should be able to re-select the item with removeselected set to false', function () {
scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha
var el = createUiSelectMultiple({ removeSelected: true });
expect(el.scope().$select.selected.length).toBe(2);
el.find('.ui-select-match-item').first().find('.ui-select-match-close').click();
expect(el.scope().$select.selected.length).toBe(1);
clickItem(el, 'Wladimir');
expect(el.scope().$select.selected.length).toBe(2);
});
it('should set only 1 item in the selected items when limit = 1', function () {
var el = createUiSelectMultiple({ limit: 1 });
clickItem(el, 'Wladimir');
clickItem(el, 'Natasha');
expect(el.scope().$select.selected.length).toEqual(1);
});
it('should only have 1 item selected and onSelect function should only be handled once.', function () {
scope.onSelectFn = function ($item, $model) {
scope.$item = $item;
scope.$model = $model;
};
var el = createUiSelectMultiple({ limit: 1, onSelect: 'onSelectFn($item, $model)' });
expect(scope.$item).toBeFalsy();
expect(scope.$model).toBeFalsy();
clickItem(el, 'Samantha');
$timeout.flush();
clickItem(el, 'Natasha');
$timeout.flush();
expect(scope.selection.selectedMultiple[0].name).toBe('Samantha');
expect(scope.$model.name).toEqual('Samantha');
expect(el.scope().$select.selected.length).toEqual(1);
});
it('should only have 2 items selected and onSelect function should be handeld.', function () {
scope.onSelectFn = function ($item, $model) {
scope.$item = $item;
scope.$model = $model;
};
var el = createUiSelectMultiple({ onSelect: 'onSelectFn($item, $model)' });
expect(scope.$item).toBeFalsy();
expect(scope.$model).toBeFalsy();
clickItem(el, 'Samantha');
$timeout.flush();
expect(scope.$model.name).toEqual('Samantha');
clickItem(el, 'Natasha');
$timeout.flush();
expect(scope.$model.name).toEqual('Natasha');
expect(el.scope().$select.selected.length).toEqual(2);
});
describe('Test key down key up and activeIndex should skip disabled choice for uiMultipleSelect', function () {
it('should ignored disabled items going up', function () {
var el = createUiSelect({ uiDisableChoice: "person.age == 12" });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(0);
triggerKeydown(searchInput, Key.Down);
expect(el.scope().$select.activeIndex).toBe(2);
triggerKeydown(searchInput, Key.Up);
expect(el.scope().$select.activeIndex).toBe(0);
});
it('should ignored disabled items going up with tagging on', function () {
var el = createUiSelectMultiple({ uiDisableChoice: "person.age == 12", tagging: true });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(-1);
triggerKeydown(searchInput, Key.Down);
expect(el.scope().$select.activeIndex).toBe(2);
triggerKeydown(searchInput, Key.Up);
expect(el.scope().$select.activeIndex).toBe(-1);
});
it('should ignored disabled items going down', function () {
var el = createUiSelectMultiple({ uiDisableChoice: "person.age == 12" });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(0);
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Enter);
expect(el.scope().$select.activeIndex).toBe(2);
});
it('should ignored disabled items going down with tagging on', function () {
var el = createUiSelectMultiple({ uiDisableChoice: "person.age == 12", tagging: true });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(-1);
triggerKeydown(searchInput, Key.Down);
expect(el.scope().$select.activeIndex).toBe(2);
triggerKeydown(searchInput, Key.Up);
expect(el.scope().$select.activeIndex).toBe(-1);
});
it('should ignore disabled items, going down with remove-selected on false', function () {
var el = createUiSelectMultiple({ uiDisableChoice: "person.age == 12", removeSelected: false });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(0);
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Enter);
expect(el.scope().$select.activeIndex).toBe(2);
});
});
describe('copying token values', function() {
beforeEach(function() {
scope.copyingFunc = function (tokens) {
return tokens.join(",");
};
this.el = createUiSelectMultiple({copying: 'copyingFunc'});
this.searchInput = this.el.find('.ui-select-search');
this.copyInput = this.el.find('.ui-select-copy-input');
this.el.scope().$select.selected = ['tag1', 'tag2'];
});
it('should select highlighted token text in copy input', function() {
triggerKeydown(this.searchInput, Key.Left);
expect(this.copyInput[0].value).toEqual('tag2');
expect(this.copyInput[0].selectionStart).toEqual(0);
expect(this.copyInput[0].selectionEnd).toEqual(4);
});
it('should select all tokens in copy input when all are higlighted', function() {
triggerKeydown(this.searchInput, Key.A, true);
expect(this.copyInput[0].value).toEqual('tag1,tag2');
expect(this.copyInput[0].selectionStart).toEqual(0);
expect(this.copyInput[0].selectionEnd).toEqual(9);
});
it('should refocus searchInput when all tokens are deleted and a copying func is provided', function() {
spyOn(this.el.scope().$select, 'setFocus');
triggerKeydown(this.searchInput, Key.Backspace);
triggerKeydown(this.copyInput, Key.Backspace);
triggerKeydown(this.copyInput, Key.Backspace);
expect(this.el.scope().$select.selected).toEqual([])
expect(this.el.scope().$select.setFocus).toHaveBeenCalled();
});
});
describe('selecting all tags with mod+A', function() {
beforeEach(function() {
this.el = createUiSelectMultiple();
this.searchInput = this.el.find('.ui-select-search');
this.el.scope().$select.selected = ['tag1', 'tag2'];
triggerKeydown(this.searchInput, Key.A, true);
});
it('should select all tags with mod+A', function() {
expect(this.el.scope().$selectMultiple.allChoicesActive).toEqual(true);
});
it('should deselect all tags on blur', function() {
this.searchInput.trigger('blur');
$timeout.flush();
expect(this.el.scope().$selectMultiple.allChoicesActive).toEqual(false);
});
it('should deselect all tags on new keydown', function() {
triggerKeydown(this.searchInput, Key.A);
$timeout.flush();
expect(this.el.scope().$selectMultiple.allChoicesActive).toEqual(false);
});
it('should deselect all tags on horizontal movement key', function() {
triggerKeydown(this.searchInput, Key.Left);
$timeout.flush();
expect(this.el.scope().$selectMultiple.allChoicesActive).toEqual(false);
});
it('should delete all tags on backspace', function() {
triggerKeydown(this.searchInput, Key.Backspace);
expect(this.el.scope().$selectMultiple.allChoicesActive).toEqual(false);
expect(this.el.scope().$select.selected).toEqual([]);
});
it('should delete all tags on delete', function() {
triggerKeydown(this.searchInput, Key.Delete);
expect(this.el.scope().$selectMultiple.allChoicesActive).toEqual(false);
expect(this.el.scope().$select.selected).toEqual([]);
});
it('should delete all tags on meta+x', function() {
triggerKeydown(this.searchInput, Key.X, true);
expect(this.el.scope().$selectMultiple.allChoicesActive).toEqual(false);
expect(this.el.scope().$select.selected).toEqual([]);
});
});
describe('taggingTokenEscape option multiple', function() {
it('should have a set value', function () {
var el = createUiSelectMultiple({tagging: true, taggingTokenEscape: '^'});
expect(el.scope().$select.taggingTokenEscape).toEqual('^');
});
it('should tag normally if not set', function () {
var el = createUiSelectMultiple({tagging: true, taggingTokens: ','});
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'tag');
triggerKeydown(searchInput, Key.Comma);
$timeout.flush();
expect($(el).scope().$select.selected).toEqual(['tag']);
});
it('should not tag after escape sequence', function () {
var el = createUiSelectMultiple({tagging: true, taggingTokenEscape: '^', taggingTokens: ','});
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'tag^');
triggerKeydown(searchInput, Key.Comma);
expect(function() {$timeout.flush();}).toThrow(); // ensure there are no deferred tasks
expect($(el).scope().$select.selected).toEqual([]);
});
it('should convert escaped token to token when tagging happens', function () {
var el = createUiSelectMultiple({tagging: true, taggingTokenEscape: '^', taggingTokens: ','});
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'tag^,');
triggerKeydown(searchInput, Key.Comma);
$timeout.flush();
expect($(el).scope().$select.selected).toEqual(['tag,']);
});
it('should convert escaped token to token when tagging with ENTER with no tagging label', function () {
var el = createUiSelectMultiple({tagging: true, taggingTokenEscape: '^', taggingTokens: ',', taggingLabel: 'false'});
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'tag^,');
triggerKeydown(searchInput, Key.Enter);
expect($(el).scope().$select.selected).toEqual(['tag,']);
});
it('should convert escaped token to token when tagging with TAB with no tagging label', function () {
var el = createUiSelectMultiple({tagging: true, taggingTokenEscape: '^', taggingTokens: ',', taggingLabel: 'false'});
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'tag^,');
triggerKeydown(searchInput, Key.Tab);
expect($(el).scope().$select.selected).toEqual(['tag,']);
});
it('should not remove tagging token in the middle', function () {
var el = createUiSelectMultiple({tagging: true, taggingTokenEscape: '^', taggingTokens: ','});
var searchInput = el.find('.ui-select-search');
setSearchText(el, 'tag,^,tag');
triggerKeydown(searchInput, Key.Comma);
$timeout.flush();
expect($(el).scope().$select.selected).toEqual(['tag,,tag']);
});
});
describe('tagOnBlur option', function () {
it('should be false by default', function() {
var el = createUiSelect();
expect(el.scope().$select.tagOnBlur).toEqual(false);
});
it('should be true when set', function() {
var el = createUiSelect({tagOnBlur: true});
expect(el.scope().$select.tagOnBlur).toEqual(true);
});
it('should tag on blur when true', function () {
var el = createUiSelect({tagging: true, tagOnBlur: true});
setSearchText(el, 'tag');
el.scope().$select.searchInput.trigger('blur');
$timeout.flush();
expect(el.scope().$select.selected).toEqual('tag');
});
it('should tag on blur when true with multiple', function () {
var el = createUiSelectMultiple({tagging: true, tagOnBlur: true});
setSearchText(el, 'tag');
el.scope().$select.searchInput.trigger('blur');
$timeout.flush();
expect(el.scope().$select.selected).toEqual(['tag']);
});
it('should convert escaped token to token', function () {
var el = createUiSelectMultiple({tagging: true, taggingTokenEscape: '^', taggingTokens: ',', tagOnBlur: true});
setSearchText(el, 'tag^,tag');
el.scope().$select.searchInput.trigger('blur');
$timeout.flush();
expect(el.scope().$select.selected).toEqual(['tag,tag']);
});
it('should not remove tagging token unless at the end', function () {
var el = createUiSelectMultiple({tagging: true, taggingTokenEscape: '^', taggingTokens: ',', tagOnBlur: true});
setSearchText(el, 'tag,tag,');
el.scope().$select.searchInput.trigger('blur');
$timeout.flush();
expect(el.scope().$select.selected).toEqual(['tag,tag']);
});
it('should not tag on blur when blur event has related target', function () {
var el = createUiSelectMultiple({tagging: true, tagOnBlur: true});
setSearchText(el, 's');
openDropdown(el);
event = new jQuery.Event('blur');
event.relatedTarget = el.find('.ui-select-choices-row div:contains("Samantha")')[0];
el.scope().$select.searchInput.trigger(event);
$timeout.flush();
expect(el.scope().$select.selected).toEqual([])
});
});
describe('select with the append dropdown to body option multiple', function () {
var body;
beforeEach(inject(function ($document) {
body = $document.find('body')[0];
}));
it('should re-position dropdown when selecting item and closeOnSelect is false', function () {
var el = createUiSelectMultiple({ closeOnSelect: false, appendDropdownToBody: true });
var dropdown = el.find('.ui-select-dropdown');
spyOn(el.scope().$select, 'rePositionOnlyDropdown');
openDropdown(el);
expect(dropdown.parent()[0]).not.toBe(el[0]);
$(body).find('.ui-select-choices-row').click();
scope.$digest();
expect(el.scope().$select.rePositionOnlyDropdown).toHaveBeenCalled()
});
});
describe('resetSearchInput option multiple', function () {
it('should be true by default', function () {
expect(createUiSelectMultiple().scope().$select.resetSearchInput).toBe(true);
});
it('should be false when set.', function () {
expect(createUiSelectMultiple({ resetSearchInput: false }).scope().$select.resetSearchInput).toBe(false);
});
});
describe('Reset the search value', function () {
it('should clear the search input when resetSearchInput is true', function () {
var el = createUiSelectMultiple();
$(el).scope().$select.search = 'idontexist';
$(el).scope().$select.select('idontexist');
expect($(el).scope().$select.search).toEqual('');
});
it('should not clear the search input when resetSearchInput is false', function () {
var el = createUiSelectMultiple({ resetSearchInput: false });
$(el).scope().$select.search = 'idontexist';
$(el).scope().$select.select('idontexist');
expect($(el).scope().$select.search).toEqual('idontexist');
});
it('should clear the search input when resetSearchInput is default set', function () {
var el = createUiSelectMultiple();
$(el).scope().$select.search = 'idontexist';
$(el).scope().$select.select('idontexist');
expect($(el).scope().$select.search).toEqual('');
});
});
});
it('should add an id to the search input field', function () {
var el = createUiSelect({ inputId: 'inid' });
var searchEl = $(el).find('input.ui-select-search');
expect(searchEl.length).toEqual(1);
expect(searchEl[0].id).toEqual('inid');
});
describe('default configuration via uiSelectConfig', function () {
describe('searchEnabled option', function () {
function setupWithoutAttr() {
return compileTemplate(
'<ui-select ng-model="selection.selected"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
function setupWithAttr(searchEnabled) {
return compileTemplate(
'<ui-select ng-model="selection.selected" search-enabled="' + searchEnabled + '"> \
<ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \
<ui-select-choices repeat="person in people | filter: $select.search"> \
<div ng-bind-html="person.name | highlight: $select.search"></div> \
<div ng-bind-html="person.email | highlight: $select.search"></div> \
</ui-select-choices> \
</ui-select>'
);
}
it('should be true by default', function () {
var el = setupWithoutAttr();
expect(el.scope().$select.searchEnabled).toBe(true);
});
it('should disable search if default set to false', function () {
var uiSelectConfig = $injector.get('uiSelectConfig');
uiSelectConfig.searchEnabled = false;
var el = setupWithoutAttr();
expect(el.scope().$select.searchEnabled).not.toBe(true);
});
it('should be overridden by inline option search-enabled=true', function () {
var uiSelectConfig = $injector.get('uiSelectConfig');
uiSelectConfig.searchEnabled = false;
var el = setupWithAttr(true);
expect(el.scope().$select.searchEnabled).toBe(true);
});
it('should be overridden by inline option search-enabled=false', function () {
var uiSelectConfig = $injector.get('uiSelectConfig');
uiSelectConfig.searchEnabled = true;
var el = setupWithAttr(false);
expect(el.scope().$select.searchEnabled).not.toBe(true);
});
});
});
describe('resetSearchInput option', function () {
it('should be true by default', function () {
expect(createUiSelect().scope().$select.resetSearchInput).toBe(true);
});
it('should be overridden by inline option reset-search-input=false', function () {
expect(createUiSelect({ resetSearchInput: false }).scope().$select.resetSearchInput).toBe(false);
});
describe('Reset the search value', function () {
it('should clear the search input when resetSearchInput is true', function () {
var control = createUiSelect();
setSearchText(control, 'idontexist');
clickMatch(control);
expect(control.scope().$select.search).toEqual('');
});
it('should not clear the search input', function () {
var control = createUiSelect({ resetSearchInput: false });
setSearchText(control, 'idontexist');
clickMatch(control);
expect(control.scope().$select.search).toEqual('idontexist');
});
it('should clear the search input when resetSearchInput is true and closeOnSelect is true', function () {
var control = createUiSelect({ closeOnSelect: true });
setSearchText(control, 'idontexist');
clickMatch(control);
expect(control.scope().$select.search).toEqual('');
});
it('should clear the search input when resetSearchInput is true and closeOnSelect is false', function () {
var control = createUiSelect({ closeOnSelect: false });
setSearchText(control, 'idontexist');
clickMatch(control);
expect(control.scope().$select.search).toEqual('');
});
it('should not clear the search input when resetSearchInput is false and closeOnSelect is false', function () {
var control = createUiSelect({ resetSearchInput: false, closeOnSelect: false });
setSearchText(control, 'idontexist');
clickMatch(control);
expect(control.scope().$select.search).toEqual('idontexist');
});
it('should not clear the search input when resetSearchInput is false and closeOnSelect is true', function () {
var control = createUiSelect({ resetSearchInput: false, closeOnSelect: true });
setSearchText(control, 'idontexist');
clickMatch(control);
expect(control.scope().$select.search).toEqual('idontexist');
});
});
});
describe('accessibility', function () {
it('should have baseTitle in scope', function () {
expect(createUiSelect().scope().$select.baseTitle).toBe('Select box');
expect(createUiSelect().scope().$select.focusserTitle).toBe('Select box focus');
expect(createUiSelect({ title: 'Choose a person' }).scope().$select.baseTitle).toBe('Choose a person');
expect(createUiSelect({ title: 'Choose a person' }).scope().$select.focusserTitle).toBe('Choose a person focus');
});
it('should have aria-label on all input and button elements', function () {
checkTheme();
checkTheme('select2');
checkTheme('selectize');
checkTheme('bootstrap');
function checkTheme(theme) {
var el = createUiSelect({ theme: theme });
checkElements(el.find('input'));
checkElements(el.find('button'));
function checkElements(els) {
for (var i = 0; i < els.length; i++) {
expect(els[i].attributes['aria-label']).toBeTruthy();
}
}
}
});
});
describe('select with the append to body option', function () {
var body;
beforeEach(inject(function ($document) {
body = $document.find('body')[0];
}));
it('should only be moved to the body when the appendToBody option is true', function () {
var el = createUiSelect({ appendToBody: false });
openDropdown(el);
expect(el.parent()[0]).not.toBe(body);
});
it('should be moved to the body when the appendToBody is true in uiSelectConfig', inject(function (uiSelectConfig) {
var appendToBody = uiSelectConfig.appendToBody;
uiSelectConfig.appendToBody = true;
var el = createUiSelect();
openDropdown(el);
expect(el.parent()[0]).toBe(body);
uiSelectConfig.appendToBody = appendToBody;
}));
it('should be moved to the body when opened', function () {
var el = createUiSelect({ appendToBody: true });
openDropdown(el);
expect(el.parent()[0]).toBe(body);
closeDropdown(el);
expect(el.parent()[0]).not.toBe(body);
});
it('should remove itself from the body when the scope is destroyed', function () {
var el = createUiSelect({ appendToBody: true });
openDropdown(el);
expect(el.parent()[0]).toBe(body);
el.scope().$destroy();
expect(el.parent()[0]).not.toBe(body);
});
it('should have specific position and dimensions', function () {
var el = createUiSelect({ appendToBody: true });
var originalPosition = el.css('position');
var originalTop = el.css('top');
var originalLeft = el.css('left');
var originalWidth = el.css('width');
openDropdown(el);
expect(el.css('position')).toBe('absolute');
expect(el.css('top')).toBe('100px');
expect(el.css('left')).toBe('200px');
expect(el.css('width')).toBe('300px');
closeDropdown(el);
expect(el.css('position')).toBe(originalPosition);
expect(el.css('top')).toBe(originalTop);
expect(el.css('left')).toBe(originalLeft);
expect(el.css('width')).toBe(originalWidth);
});
});
describe('select with the append dropdown to body option', function () {
var body;
beforeEach(inject(function ($document) {
body = $document.find('body')[0];
}));
it('should only be moved to the body when the appendDropdownToBody option is true', function () {
var el = createUiSelect({ appendDropdownToBody: false });
var dropdown = el.find('.ui-select-dropdown');
openDropdown(el);
expect(dropdown.parent()[0]).toEqual(el[0]);
});
it('should be moved to the body when the appendDropdownToBody is true in uiSelectConfig', inject(function (uiSelectConfig) {
uiSelectConfig.appendDropdownToBody = true;
var el = createUiSelect();
var dropdown = el.find('.ui-select-dropdown');
openDropdown(el);
expect(dropdown.parent()[0]).not.toEqual(el[0]);
expect(dropdown.parent().parent()[0]).toBe(body);
uiSelectConfig.appendDropdownToBody = false;
}));
it('should be moved to the body when opened', function () {
var el = createUiSelect({ appendDropdownToBody: true });
var dropdown = el.find('.ui-select-dropdown');
openDropdown(el);
expect(dropdown.parent()[0]).not.toBe(el[0]);
closeDropdown(el);
expect(dropdown.parent()[0]).toBe(el[0]);
});
it('should remove itself from the body when the scope is destroyed', function () {
var el = createUiSelect({ appendDropdownToBody: true });
var dropdown = el.find('.ui-select-dropdown');
openDropdown(el);
expect(dropdown.parent()[0]).not.toBe(el[0]);
el.scope().$destroy();
expect(dropdown.parent()[0]).toBe(el[0]);
});
it('should have specific position and dimensions', function () {
var el = createUiSelect({ appendDropdownToBody: true });
var dropdown = el.find('.ui-select-dropdown');
var originalPosition = dropdown.css('position');
var originalTop = dropdown.css('top');
var originalLeft = dropdown.css('left');
var originalWidth = dropdown.css('width');
openDropdown(el);
expect(dropdown.css('position')).toBe('absolute');
expect(dropdown.css('top')).toBe('500px');
expect(dropdown.css('left')).toBe('200px');
expect(dropdown.css('width')).toBe('300px');
closeDropdown(el);
expect(dropdown.css('position')).toBe(originalPosition);
expect(dropdown.css('top')).toBe(originalTop);
expect(dropdown.css('left')).toBe(originalLeft);
expect(dropdown.css('width')).toBe(originalWidth);
});
});
describe('highlight filter', function () {
var highlight;
beforeEach(function () {
highlight = $injector.get('highlightFilter');
});
it('returns the item if there is no match', function () {
var query = 'January';
var item = 'December';
expect(highlight(item, query)).toBe('December');
});
it('wraps search strings matches in ui-select-highlight class', function () {
var query = 'er';
var item = 'December';
expect(highlight(item, query)).toBe('Decemb<span class="ui-select-highlight">er</span>');
});
it('properly highlights numeric items', function () {
var query = '15';
var item = 2015;
expect(highlight(item, query)).toBe('20<span class="ui-select-highlight">15</span>');
});
it('properly works with numeric queries', function () {
var query = 15;
var item = 2015;
expect(highlight(item, query)).toBe('20<span class="ui-select-highlight">15</span>');
});
});
describe('Test Spinner for promises', function () {
var deferred;
function getFromServer() {
deferred = $q.defer();
return deferred.promise;
}
it('should have a default value of false', function () {
var control = createUiSelect();
expect(control.scope().$select.spinnerEnabled).toEqual(false);
});
it('should have a set a value of true', function () {
var control = createUiSelect({ spinnerEnabled: true });
expect(control.scope().$select.spinnerEnabled).toEqual(true);
});
it('should have a default value of glyphicon-refresh ui-select-spin', function () {
var control = createUiSelect();
expect(control.scope().$select.spinnerClass).toEqual('glyphicon glyphicon-refresh ui-select-spin');
});
it('should have set a custom class value of randomclass', function () {
var control = createUiSelect({ spinnerClass: 'randomclass' });
expect(control.scope().$select.spinnerClass).toEqual('randomclass');
});
it('should not display spinner when disabled', function () {
scope.getFromServer = getFromServer;
var el = createUiSelect({ theme: 'bootstrap', refresh: "getFromServer($select.search)", refreshDelay: 0 });
openDropdown(el);
var spinner = el.find('.ui-select-refreshing');
expect(spinner.hasClass('ng-hide')).toBe(true);
setSearchText(el, 'a');
expect(spinner.hasClass('ng-hide')).toBe(true);
deferred.resolve();
scope.$digest();
expect(spinner.hasClass('ng-hide')).toBe(true);
});
it('should display spinner when enabled', function () {
scope.getFromServer = getFromServer;
var el = createUiSelect({ spinnerEnabled: true, theme: 'bootstrap', refresh: "getFromServer($select.search)", refreshDelay: 0 });
openDropdown(el);
var spinner = el.find('.ui-select-refreshing');
expect(spinner.hasClass('ng-hide')).toBe(true);
setSearchText(el, 'a');
expect(spinner.hasClass('ng-hide')).toBe(false);
deferred.resolve();
scope.$digest();
expect(spinner.hasClass('ng-hide')).toBe(true);
});
it('should not display spinner when enabled', function () {
var el = createUiSelect({ spinnerEnabled: true, theme: 'bootstrap', spinnerClass: 'randomclass' });
openDropdown(el);
var spinner = el.find('.ui-select-refreshing');
setSearchText(el, 'a');
expect(el.scope().$select.spinnerClass).toBe('randomclass');
});
});
describe('Test trim', function () {
it('should have a default value of true', function () {
var control = createUiSelect();
expect(control.scope().$select.trim).toEqual(true);
});
it('should have set a value of false', function () {
var control = createUiSelect({ trim: false });
expect(control.scope().$select.trim).toEqual(false);
});
['selectize', 'bootstrap', 'select2'].forEach(function (theme) {
describe(theme + ' theme', function () {
it('should define ng-trim to true when undefined', function () {
var el = createUiSelect({ theme});
expect($(el).find('.ui-select-search').attr('ng-trim')).toEqual('true');
});
it('should define ng-trim when true', function () {
var el = createUiSelect({ theme, trim: true });
expect($(el).find('.ui-select-search').attr('ng-trim')).toEqual('true');
});
it('should define ng-trim when false', function () {
var el = createUiSelect({ theme, trim: false });
expect($(el).find('.ui-select-search').attr('ng-trim')).toEqual('false');
});
describe('multiple', function () {
it('should define ng-trim to true when undefined', function () {
var el = createUiSelect({ multiple: 'multiple', theme });
expect($(el).find('.ui-select-search').attr('ng-trim')).toEqual('true');
});
it('should define ng-trim when true', function () {
var el = createUiSelect({ multiple: 'multiple', theme, trim: true });
expect($(el).find('.ui-select-search').attr('ng-trim')).toEqual('true');
});
it('should define ng-trim when false', function () {
var el = createUiSelect({ multiple: 'multiple', theme, trim: false });
expect($(el).find('.ui-select-search').attr('ng-trim')).toEqual('false');
});
});
});
});
});
describe('With refresh on active', function () {
it('should refresh when is activated', function () {
scope.fetchFromServer = function () { };
var el = createUiSelect({ refresh: "fetchFromServer($select.search)", refreshDelay: 0 });
spyOn(scope, 'fetchFromServer');
expect(el.scope().$select.open).toEqual(false);
el.scope().$select.activate();
$timeout.flush();
expect(el.scope().$select.open).toEqual(true);
expect(scope.fetchFromServer.calls.any()).toEqual(true);
});
it('should refresh when open is set to true', function () {
scope.fetchFromServer = function () { };
var el = createUiSelect({ refresh: "fetchFromServer($select.search)", refreshDelay: 0 });
spyOn(scope, 'fetchFromServer');
expect(el.scope().$select.open).toEqual(false);
openDropdown(el);
$timeout.flush();
expect(el.scope().$select.open).toEqual(true);
expect(scope.fetchFromServer.calls.any()).toEqual(true);
});
});
describe('Test key down key up and activeIndex should skip disabled choice', function () {
it('should ignore disabled items, going down', function () {
var el = createUiSelect({ uiDisableChoice: "person.age == 12" });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(0);
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Enter);
expect(el.scope().$select.activeIndex).toBe(2);
});
it('should ignore disabled items, going up', function () {
var el = createUiSelect({ uiDisableChoice: "person.age == 12" });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(0);
triggerKeydown(searchInput, Key.Down);
expect(el.scope().$select.activeIndex).toBe(2);
triggerKeydown(searchInput, Key.Up);
expect(el.scope().$select.activeIndex).toBe(0);
});
it('should ignored disabled items going up with tagging on', function () {
var el = createUiSelect({ uiDisableChoice: "person.age == 12", tagging: true });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(-1);
triggerKeydown(searchInput, Key.Down);
expect(el.scope().$select.activeIndex).toBe(2);
triggerKeydown(searchInput, Key.Up);
expect(el.scope().$select.activeIndex).toBe(-1);
});
it('should ignored disabled items in the down direction with tagging on', function () {
var el = createUiSelect({ uiDisableChoice: "person.age == 12", tagging: true });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(-1);
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Enter);
expect(el.scope().$select.activeIndex).toBe(2);
});
it('should ignored disabled items going up with tagging on and custom tag', function () {
var el = createUiSelect({ uiDisableChoice: "person.age == 12", tagging: true, taggingLabel: 'custom tag' });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(-1);
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Enter);
expect(el.scope().$select.activeIndex).toBe(2);
});
it('should ignore disabled items, going down with remove-selected on false', function () {
var el = createUiSelect({ uiDisableChoice: "person.age == 12", removeSelected: false });
openDropdown(el);
var searchInput = el.find('.ui-select-search');
expect(el.scope().$select.activeIndex).toBe(0);
triggerKeydown(searchInput, Key.Down);
triggerKeydown(searchInput, Key.Enter);
expect(el.scope().$select.activeIndex).toBe(2);
});
});
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
connections: [{
type: 'mongoose',
name: 'default',
url: 'mongodb://localhost:27017/testdb',
options: {
server: {
socketOptions: {
keepAlive: 1
}
}
}
}],
auth: {
model: 'users',
stateIn: {
type: 'jwt', // 'session',
options: {
secretOrKey: 'someSecret'
}
}
},
baseDir: __dirname
};
|
import angular from 'angular';
import harcWidgetComponent from './harc-widget-component';
import './harc-widget.css';
/**
* # Widget wrapper component <harc-widget>
*
* Wraps and visually normalizes all application widgets.
* There is an important, required binding on the harc-widget:
* - widgetName (widget-name attribute) - string with a widget identifier (used by dashboard api)
*
* Transclude containers:
* - widgetTitle (optional): put a title there
* - widgetIcon (optional): placeholder for an icon, show below or on the left of title
* - widgetContent: your widget content
*
* Usage:
* <harc-widget widget-name="lights">
* <widget-title>Lights</widget-title>
* <widget-icon>
* <md-icon md-font-icon="icon-sun"></md-icon>
* </widget-icon>
* <widget-content>
* This is the content of a widget
* </widget-content>
* </harc-widget>
*
* Be sure to check out harc-widget.css for helpful css classes (eg. harc-widget-row)
*/
const module = angular.module('harcWidget', [])
.component('harcWidget', harcWidgetComponent);
export default module.name;
|
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import DevTools from './DevTools';
import {syncHistoryWithStore} from 'react-router-redux'
import configureStore from './configureStore';
//import { createHistory } from 'history'
// import createHistory from 'history/lib/createHashHistory';
import routes from './routes';
import {Router, Route, hashHistory} from 'react-router'
const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store);
export default () =>
{
return (
<Provider store={store}>
<div>
<Router history={history}>
{routes}
</Router>
<DevTools />
</div>
</Provider>
);
}
|
var matricula_status = {
ATIVO: 1,
INATIVO: 2,
BLOQUEADO: 3,
HOMOLOGADO:4
};
function initializeGridMatrizCurricular(EDITABLE, urlMatriz, urlAlunos)
{
$('#divMatriculas').show();
var grid = $("#jqxgridmatriz");
var dataAdapterMatrizCurricular = new $.jqx.dataAdapter({
datatype: "json",
datafields: [
{ name: 'codigo' },
{ name: 'nome' },
{ name: 'horas' }
],
url: urlMatriz
},
{
autoBind: true,
selectedIndex: 0,
formatData: function (data) {
data.curso = $('#curso_codigo').val()
},
beforeLoadComplete: function(data) {
for(var i = 0; i < data.length; i++) {
data[i].nome = data[i].nome + " (" + data[i].horas + " horas)";
}
return data;
}
}
);
var statusSource = [
{ nome: 'Ativo', codigo: 1 },
{ nome: 'Inativo', codigo: 2 },
{ nome: 'Bloqueado', codigo: 3 }
];
var statusSourceComHomologado = [
{ nome: 'Ativo', codigo: 1 },
{ nome: 'Inativo', codigo: 2 },
{ nome: 'Bloqueado', codigo: 3 },
{ nome: 'Homologado', codigo: 4 }
];
var initializeComboBoxAlunos = function(editor)
{
// prepare the data
var source =
{
datatype: "json",
datafields: [
{ name: 'primeiro_nome' },
{ name: 'sobrenome' },
{ name: 'login' },
{ name: 'codigo' },
{ name: 'label' }
],
url: urlAlunos,
data: {
maxRows: 20
}
};
var dataAdapter = new $.jqx.dataAdapter(source,
{
formatData: function (data) {
if (editor.jqxComboBox('searchString') != undefined) {
data.search = editor.jqxComboBox('searchString');
return data;
}
},
beforeLoadComplete: function(data) {
var result = [];
for(var i = 0; i < data.length; i++) {
var item = data[i];
item.label = $.trim(item.primeiro_nome + " " + item.sobrenome) + ", " + item.login;
result.push(item);
}
return result;
}
}
);
var render = function (index, label, value) {
// monta a descrição do nome + RA
var item = dataAdapter.records[index];
if (item != null) {
var label = $.trim(item.primeiro_nome + " " + item.sobrenome) + ", " + item.login;
return label;
}
return "";
};
editor.jqxComboBox(
{
width: 300,
height: 36,
source: dataAdapter,
remoteAutoComplete: true,
autoDropDownHeight: true,
displayMember: 'label',
valueMember: "codigo",
placeHolder: "Digite o nome ou R.A. do aluno",
//renderer: render,
//renderSelectedItem: render,
search: function (searchString) {
dataAdapter.dataBind();
}
});
};
var initializarDropDownListMatrizCurricular = function(editor)
{
editor.jqxDropDownList(
{
width: 200,
height: 36,
autoDropDownHeight: true,
source: dataAdapterMatrizCurricular.records,
displayMember: 'nome',
valueMember: "codigo",
placeHolder: '...'
});
};
var criarDropDownListStatus = function(editor, row)
{
editor.jqxDropDownList(
{
width: 150,
height: 36,
autoDropDownHeight: true,
source: statusSourceComHomologado,
displayMember: 'nome',
valueMember: 'codigo'
});
};
var initializarDropDownListStatus = function(editor, row)
{
var data = grid.jqxGrid('getrowdata', row),
source;
// Só possívle homologar matrículas sem horas pendentes e com status ATIVO
if (data.permite_homologar == 1 && data.status == matricula_status.ATIVO)
source = statusSourceComHomologado;
else
source = statusSource;
editor.jqxDropDownList('source', source);
};
var validateEdit = function (row) {
var data = grid.jqxGrid('getrowdata', row);
if (!data.inserido)
return false;
};
// dados da grid
var source =
{
datatype: "json",
datafields: [
{ name: 'codigo', type: 'int' },
{ name: 'status_nome', value: 'status', values: { source: statusSourceComHomologado, value: 'codigo', name: 'nome' } },
{ name: 'permite_homologar', type: 'int'},
{ name: 'status', type: 'int' },
{ name: 'saldo_anterior', type: 'int' },
{ name: 'usuario_codigo', type: 'int' },
{ name: 'usuario_nome', type: 'string' },
{ name: 'matriz_curricular_codigo', type: 'int' },
{ name: 'matriz_curricular_nome', type: 'string' },
{ name: 'inserido', type: 'bool' }
],
id: 'codigo', // código do curso
localdata: JSON.parse($('#matriculas').val() || '[]')
};
var dataAdapter = new $.jqx.dataAdapter(source);
// inicializa o componente de grid
grid.jqxGrid(
{
width: '100%',
height: 350,
source: dataAdapter,
columnsresize: true,
showtoolbar: EDITABLE,
editable: EDITABLE,
rowsheight: 37,
localization: getGridLocalization(),
columns: [
{ text: 'Aluno', datafield: 'usuario_codigo', displayfield : 'usuario_nome', width: 300,
validation: function (cell, value) {
if (!$.trim(value.label))
return { result: false, message: "Campo obrigatório" };
return true;
},
columntype: 'combobox',
createeditor: function (row, column, editor) {
initializeComboBoxAlunos(editor);
},
// update the editor's value before saving it.
cellvaluechanging: function (row, column, columntype, oldvalue, newvalue) {
// return the old value, if the new value is empty.
if (newvalue == "") return oldvalue;
},
cellbeginedit: validateEdit
},
{ text: 'Matriz curricular', datafield: 'matriz_curricular_codigo', displayfield: 'matriz_curricular_nome', width: 200,
validation: function (cell, value) {
if (!$.trim(value))
return { result: false, message: "Campo obrigatório" };
return true;
},
columntype: 'dropdownlist',
createeditor: function (row, column, editor) {
initializarDropDownListMatrizCurricular(editor);
},
// update the editor's value before saving it.
cellvaluechanging: function (row, column, columntype, oldvalue, newvalue) {
// return the old value, if the new value is empty.
if (newvalue == "") return oldvalue;
},
cellbeginedit: validateEdit
},
{ text: 'Saldo anterior', datafield: 'saldo_anterior', columntype: 'int', width: 100 },
{ text: 'Status', datafield: 'status', displayfield: 'status_nome', columntype: 'dropdownlist', width: 110,
createeditor: function (row, column, editor) {
criarDropDownListStatus(editor, row);
},
initeditor: function (row, column, editor) {
initializarDropDownListStatus(editor, row);
},
cellbeginedit: function (row) {
var data = grid.jqxGrid('getrowdata', row);
if (data.status == matricula_status.HOMOLOGADO && !data.inserido)
return false;
}
},
{ text: '', datafield: 'Excluir', columntype: 'button', width: 80, hidden: !EDITABLE,
cellsrenderer: function () {
return "Excluir";
},
buttonclick: function (row) {
var data = grid.jqxGrid('getrowdata', row);
grid.jqxGrid('deleterow', data.uid);
}
}
],
rendertoolbar: function (toolbar) {
// Botão de inserir
var button = $(
'<a class="btn btn-success btn-sm fileinput-button" style="margin: 2px;">' +
' <i class="glyphicon glyphicon-plus"></i>' +
' Inserir' +
'</a>');
toolbar.append(button);
button.on('click', function(){
var matriz = dataAdapterMatrizCurricular.records.length ? dataAdapterMatrizCurricular.records[0] : {};
grid.jqxGrid('addrow', generateId(), { status: 1, status_nome: 'Ativo', matriz_curricular_codigo: matriz.codigo, matriz_curricular_nome: matriz.nome, inserido: true });
var rows = grid.jqxGrid('getrows');
var index = rows.length - 1;
var editable = grid.jqxGrid('begincelledit', index, "usuario_codigo");
});
}
});
$('#formCurso').on('submit', function(){
// Salva a lista de cursos do usuário em um input[hidden]
// para que seja enviada para o servidor junto com o formulário
var rows = grid.jqxGrid('getrows');
$('#matriculas').val(JSON.stringify(rows));
});
$('#curso_codigo').on('change', function(){
grid.jqxGrid('clear');
dataAdapterMatrizCurricular.dataBind();
});
}
|
// blah blah blah
|
You are given a function foo() that represents a biased coin. When foo() is called, it returns 0 with 60% probability, and 1 with 40% probability. Write a new function that returns 0 and 1 with 50% probability each. Your function should use only foo(), no other library method.Solution:
We know foo() returns 0 with 60% probability. How can we ensure that 0 and 1 are returned with 50% probability?
The solution is similar to this post. If we can somehow get two cases with equal probability, then we are done. We call foo() two times. Both calls will return 0 with 60% probability. So the two pairs (0, 1) and (1, 0) will be generated with equal probability from two calls of foo(). Let us see how.(0, 1): The probability to get 0 followed by 1 from two calls of foo() = 0.6 * 0.4 = 0.24
(1, 0): The probability to get 1 followed by 0 from two calls of foo() = 0.4 * 0.6 = 0.24So the two cases appear with equal probability. The idea is to return consider only the above two cases, return 0 in one case, return 1 in other case. For other cases [(0, 0) and (1, 1)], recur until you end up in any of the above two cases. The below program depicts how we can use foo() to return 0 and 1 with equal probability.References:
http://en.wikipedia.org/wiki/Fair_coin#Fair_results_from_a_biased_coinThis article is compiled by Shashank Sinha and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Tags: MathematicalAlgo
|
var fs = require('fs'),
M3U = require('../m3u'),
sinon = require('sinon'),
should = require('should');
describe('m3u', function() {
describe('#set', function() {
it('should set property on m3u', function() {
var m3u = getM3u();
m3u.set('EXT-X-I-FRAMES-ONLY', true);
m3u.properties.iframesOnly.should.be.true;
});
});
describe('#get', function() {
it('should get property from m3u', function() {
var m3u = getM3u();
m3u.properties.version = 4;
m3u.get('version').should.eql(4);
});
});
describe('#addItem', function() {
it('should add item to typed array', function() {
var m3u = getM3u();
m3u.items.PlaylistItem.length.should.eql(0);
m3u.addItem(new M3U.PlaylistItem);
m3u.items.PlaylistItem.length.should.eql(1);
});
});
describe('#addPlaylistItem', function() {
it('should create and add a PlaylistItem', function() {
var m3u = getM3u();
m3u.addPlaylistItem({});
m3u.items.PlaylistItem.length.should.eql(1);
});
});
describe('#addMediaItem', function() {
it('should create and add a MediaItem', function() {
var m3u = getM3u();
m3u.addMediaItem({});
m3u.items.MediaItem.length.should.eql(1);
});
});
describe('#addStreamItem', function() {
it('should create and add a StreamItem', function() {
var m3u = getM3u();
m3u.addStreamItem({});
m3u.items.StreamItem.length.should.eql(1);
});
});
describe('#addIframeStreamItem', function() {
it('should create and add a IframeStreamItem', function() {
var m3u = getM3u();
m3u.addIframeStreamItem({});
m3u.items.IframeStreamItem.length.should.eql(1);
});
});
describe('#totalDuration', function() {
it('should total duration of every PlaylistItem', function() {
var m3u = getM3u();
m3u.addPlaylistItem({ duration: 10 });
m3u.addPlaylistItem({ duration: 4.5 });
m3u.addPlaylistItem({ duration: 45 });
m3u.totalDuration().should.eql(59.5);
});
});
describe('#merge', function() {
it('should merge PlaylistItems from two m3us, creating a discontinuity', function() {
var m3u1 = getM3u();
m3u1.addPlaylistItem({});
m3u1.addPlaylistItem({});
m3u1.addPlaylistItem({});
var m3u2 = getM3u();
m3u2.addPlaylistItem({});
m3u2.addPlaylistItem({});
var itemWithDiscontinuity = m3u2.items.PlaylistItem[0];
m3u1.merge(m3u2);
itemWithDiscontinuity.get('discontinuity').should.be.true;
m3u1.items.PlaylistItem.filter(function(item) {
return item.get('discontinuity');
}).length.should.eql(1);
});
it('should use the largest targetDuration', function() {
var m3u1 = getM3u();
m3u1.set('targetDuration', 10);
m3u1.addPlaylistItem({});
var m3u2 = getM3u();
m3u2.set('targetDuration', 11);
m3u2.addPlaylistItem({});
m3u1.merge(m3u2);
m3u1.get('targetDuration').should.eql(11);
});
});
describe('#serialize', function(done) {
it('should return an object containing items and properties', function(done) {
getVariantM3U(function(error, m3u) {
var data = m3u.serialize();
data.properties.should.eql(m3u.properties);
data.items.IframeStreamItem.length.should.eql(m3u.items.IframeStreamItem.length);
data.items.MediaItem.length.should.eql(m3u.items.MediaItem.length);
data.items.PlaylistItem.length.should.eql(m3u.items.PlaylistItem.length);
data.items.StreamItem.length.should.eql(m3u.items.StreamItem.length);
data.items.MediaItem[0].should.eql(m3u.items.MediaItem[0].serialize());
done();
});
});
});
describe('unserialize', function() {
it('should return an M3U object with items and properties', function() {
var item = new M3U.PlaylistItem({ key: 'uri', value: '/path' });
var data = {
properties: {
targetDuration: 10
},
items: {
PlaylistItem: [ item.serialize() ]
}
};
var m3u = M3U.unserialize(data);
m3u.properties.should.eql(data.properties);
item.should.eql(m3u.items.PlaylistItem[0]);
});
});
describe('writeVOD', function() {
it('should return a string ending with #EXT-X-ENDLIST', function() {
var m3u1 = getM3u();
m3u1.set('playlistType', 'VOD');
m3u1.addPlaylistItem({ duration: 1 });
var output = m3u1.toString();
var endStr = '#EXT-X-ENDLIST\n';
output.indexOf(endStr).should.eql(output.length - endStr.length);
});
});
describe('writeLive', function() {
it('should return a string not ending with #EXT-X-ENDLIST', function() {
var m3u1 = getM3u();
m3u1.addPlaylistItem({});
var output = m3u1.toString();
output.indexOf('#EXT-X-ENDLIST\n').should.eql(-1);
});
});
});
function getM3u() {
var m3u = M3U.create();
return m3u;
}
function getVariantM3U(callback) {
var parser = require('../parser').createStream();
var variantFile = fs.createReadStream(
__dirname + '/fixtures/variant.m3u8'
);
variantFile.pipe(parser);
parser.on('m3u', function(m3u) {
callback(null, m3u);
});
}
|
const debugtrace = require('../debugtrace')
beforeAll(() => debugtrace.maximumDataOutputWidth = 60)
beforeEach(() => debugtrace.enter())
afterEach(() => debugtrace.leave())
class Contact {
constructor(firstName, lastName, birthday, phoneNumber) {
this.firstName = firstName
this.lastName = lastName
this.birthday = birthday
this.phoneNumber = phoneNumber
}
}
class Contacts {
constructor(contact1, contact2, contact3, contact4) {
this.contact1 = contact1
this.contact2 = contact2
this.contact3 = contact3
this.contact4 = contact4
}
}
test('line break of array', () => {
// setup:
const contacts = [
new Contact('Akane' , 'Apple' , new Date(2020, 1, 1), '080-1111-1111'),
new Contact('Yukari', 'Apple' , new Date(2020, 2, 2), '080-2222-2222'),
null,
null
]
// when:
debugtrace.print('contacts', contacts)
// then:
expect(debugtrace.lastLog).toContain('[\n| (Contact){')
expect(debugtrace.lastLog).toContain(' firstName:')
expect(debugtrace.lastLog).toContain(', lastName:')
expect(debugtrace.lastLog).toContain(' birthday:')
expect(debugtrace.lastLog).toContain(' phoneNumber:')
expect(debugtrace.lastLog).toContain('},\n| (Contact){')
expect(debugtrace.lastLog).toContain('},\n| null, null')
})
test('line break of Object', () => {
// setup:
const contacts = new Contacts(
new Contact('Akane' , 'Apple' , new Date(2020, 1, 1), '080-1111-1111'),
new Contact('Yukari', 'Apple' , new Date(2020, 2, 2), '080-2222-2222'),
null,
null
)
// when:
debugtrace.print('contacts', contacts)
// then:
expect(debugtrace.lastLog).toContain('{\n| contact1: (Contact){')
expect(debugtrace.lastLog).toContain(' firstName:')
expect(debugtrace.lastLog).toContain(', lastName:')
expect(debugtrace.lastLog).toContain(' birthday:')
expect(debugtrace.lastLog).toContain(' phoneNumber:')
expect(debugtrace.lastLog).toContain('},\n| contact2: (Contact){')
expect(debugtrace.lastLog).toContain('},\n| contact3: null, contact4: null')
})
test('line break of Map', () => {
// setup:
const contacts = new Map()
contacts.set(1, new Contact('Akane' , 'Apple' , new Date(2020, 1, 1), '080-1111-1111'))
contacts.set(2, new Contact('Yukari', 'Apple' , new Date(2020, 2, 2), '080-2222-2222'))
contacts.set(3, null)
contacts.set(4, null)
// when:
debugtrace.print('contacts', contacts)
// then:
expect(debugtrace.lastLog).toContain('{\n| 1: (Contact){')
expect(debugtrace.lastLog).toContain(' firstName:')
expect(debugtrace.lastLog).toContain(', lastName:')
expect(debugtrace.lastLog).toContain(' birthday:')
expect(debugtrace.lastLog).toContain(' phoneNumber:')
expect(debugtrace.lastLog).toContain('},\n| 2: (Contact){')
expect(debugtrace.lastLog).toContain('},\n| 3: null, 4: null')
})
/** @since 2.1.0 */
test('no line break: name = value', () => {
// setup
const foo = '000000000011111111112222222222333333333344444444445555555555'
// when:
debugtrace.print('foo', foo)
// then:
expect(debugtrace.lastLog).toContain('foo = (length:60)\'0000000000')
})
/** @since 2.1.0 */
test('no line break: Object: key: value', () => {
// setup
const foo = new Object()
foo.bar = '000000000011111111112222222222333333333344444444445555555555'
// when:
debugtrace.print('foo', foo)
// then:
expect(debugtrace.lastLog).toContain('bar: (length:60)\'0000000000')
})
/** @since 2.1.0 */
test('no line break: Map: key: value', () => {
// setup
const foo = new Map()
foo.set(1, '000000000011111111112222222222333333333344444444445555555555')
// when:
debugtrace.print('foo', foo)
// then:
expect(debugtrace.lastLog).toContain('1: (length:60)\'0000000000')
})
|
const path = require('path');
const NeDB = require('nedb');
const service = require('feathers-nedb');
const hooks = require('./hooks');
module.exports = function () { // 'function' needed as we use 'this'
const app = this;
const db = new NeDB({
filename: path.join(app.get('nedb'), 'users.db'),
autoload: true,
});
const options = {
Model: db,
paginate: {
default: 5,
max: 25,
},
};
// Initialize our service with any options it requires
app.use('/users', service(options));
// Get our initialize service to that we can bind hooks
const userService = app.service('/users');
// Set up our before hooks
userService.before(hooks.before);
// Set up our after hooks
userService.after(hooks.after);
};
|
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import SettingsComponent from "../../App/Components/Settings/SettingsComponent";
jest.mock('react-native-version-number', () => {
return {
appversion: 'test'
}
})
jest.mock('react-native-code-push', () => {
function MockCodePush(options = {}) {
return jest.fn()
}
Object.assign(MockCodePush, {
sync: jest.fn(),
installMode: null,
updateDialog: null,
CheckFrequency: {
ON_APP_RESUME: null
},
InstallMode: {
IMMEDIATE: null
}
})
return MockCodePush
})
jest.mock('../../App/Containers/Settings/FilterSettingsContainer', () => {
return require('react-native').View
})
jest.mock('../../App/Containers/Settings/ProfileContainer', () => {
return require('react-native').View
})
test('SettingsComponent renders correctly', () => {
const tree = renderer.create(
<SettingsComponent />
).toJSON();
expect(tree).toMatchSnapshot();
});
|
/*
* GET socket page.
*/
var express = require('express');
var http = require('http');
/**
* [Socket.io在线聊天室](http://blog.fens.me/nodejs-socketio-chat/)
* [node.js中Socket.IO的进阶使用技巧](http://www.jb51.net/article/57091.htm)
* [Server API](http://socket.io/docs/server-api/)
*
*
* @param app
* @param server
*/
module.exports = function(app,server) {
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
//把信息从Redis发送到客户端
socket.on('message', function(message){
console.log(message) ;
socket.emit("message",message);
});
}) ;
} ;
|
$(document).ready(function() {
$('#datatable tfoot th').each( function () {
var title = $('#example thead th').eq( $(this).index() ).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
});
$('#datatable').DataTable({
processing: true,
serverSide: true,
ajax: { url: "data" },
columns: [
{ data: "str", defaultContent: "" },
{ data: "date", defaultContent: "" },
{ name: 'bool', defaultContent: "",
render: function (data, type, full) {
return full.bool;
}
},
{ data: "num", defaultContent: "" },
{ data: "select_false", defaultContent: "not fetched" },
{ data: "datatable_select_false", defaultContent: "not fetched" },
{ data: "type", defaultContent: "" },
{ data: "type.id", defaultContent: "" },
{ data: "types.types.id", defaultContent: "",
render: function(data, type, full) {
return JSON.stringify(full.types); }
},
{ data: "messages.type.id", defaultContent: "", // Does not work
render: function(data, type, full) {
return JSON.stringify(full.messages); }
}
],
serverParams: function(data) { data.bChunkSearch = true; }
}).columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value, true )
.draw();
}
} );
} );
});
|
(() => {
/**
* @extract BasicFunc
* */
function basicFunc() {
// OK
}
/**
* @extract ArgsTest
* */
function argsTest(a, b, c, d) {
// OK
}
/**
* @extract FunctionLiteral
* */
var functionLiteral = function () {
// OK
};
var obj = {
/**
* @extract ObjectInFunction
* */
objInFunction: function () {
// OK
},
};
/**
* @extract AnonymousFunction
* */
(function () {
// OK
})();
function outerFunction() {
/**
* @extract InnerFunction
* */
function innerFunction() {
// OK
}
}
});
|
// require modules
var express = require('express');
var morgan = require('morgan');
var config = require('./config');
// instantiate app
var app = module.exports = express();
// logger
app.use(morgan('dev'));
require('./core/middleware.js');
require('./core/engine.js');
require('./core/session.js');
require('./core/passport.js');
require('./routes');
require('./core/errors.js');
// bind network on given port
app.listen(config.port, function () {
console.log('Example app listening at http://%s:%s', config.host, config.port);
});
|
/*
* grunt-uglifyid
* https://github.com/WihteCrow/grunt-uglifyid
*
* Copyright (c) 2016 crow
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested).
uglifyid: {
test: {
options: {
'root': 'tmp/'
},
files: {
'tmp/': ['test/expected/*.js', 'test/expected/*/*.js']
}
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['uglifyid']);
grunt.registerTask('clean', ['clean']);
};
|
var events = require('events');
var util = require('util');
var msgpack = require('msgpack-lite');
var helpers = require('./helpers');
var lua = require('./lua');
function Job(queue, jobId, data, options) {
this.queue = queue;
this.id = jobId;
this.progress = 0;
this.data = data || {};
this.options = options || {};
this.status = 'created';
}
util.inherits(Job, events.EventEmitter);
Job.fromId = function (queue, jobId, cb) {
queue.client.hget(queue.toKey('jobs'), jobId, function (err, data) {
/* istanbul ignore if */
if (err) return cb(err);
return cb(null, Job.fromData(queue, jobId, data));
});
};
Job.fromData = function (queue, jobId, data) {
// no need for try-catch here since we made the JSON ourselves in job#toData
data = msgpack.decode(data);
var job = new Job(queue, jobId, data.data, data.options);
job.status = data.status;
return job;
};
Job.prototype.toData = function () {
return msgpack.encode({
data: this.data,
options: this.options,
status: this.status
});
};
Job.prototype.save = function (cb) {
cb = cb || helpers.defaultCb;
var self = this;
this.queue.client.evalsha(lua.shas.addJob, 3,
this.queue.toKey('id'), this.queue.toKey('jobs'), this.queue.toKey('waiting'),
this.toData(),
function (err, jobId) {
/* istanbul ignore if */
if (err) return cb(err);
self.id = jobId;
self.queue.jobs[jobId] = self;
return cb(null, self);
}
);
return this;
};
Job.prototype.retries = function (n) {
if (n < 0) {
throw Error('Retries cannot be negative');
}
this.options.retries = n;
return this;
};
Job.prototype.timeout = function (ms) {
if (ms < 0) {
throw Error('Timeout cannot be negative');
}
this.options.timeout = ms;
return this;
};
Job.prototype.reportProgress = function (progress, cb) {
// right now we just send the pubsub event
// might consider also updating the job hash for persistence
cb = cb || helpers.defaultCb;
progress = Number(progress);
if (progress < 0 || progress > 100) {
return process.nextTick(cb.bind(null, Error('Progress must be between 0 and 100')));
}
this.progress = progress;
this.queue.client.publish(this.queue.toKey('events'), msgpack.encode({
id: this.id,
event: 'progress',
data: progress
}), cb);
};
Job.prototype.remove = function (cb) {
cb = cb || helpers.defaultCb;
this.queue.client.evalsha(lua.shas.removeJob, 6,
this.queue.toKey('succeeded'), this.queue.toKey('failed'), this.queue.toKey('waiting'),
this.queue.toKey('active'), this.queue.toKey('stalling'), this.queue.toKey('jobs'),
this.id,
cb
);
};
Job.prototype.retry = function (cb) {
cb = cb || helpers.defaultCb;
this.queue.client.multi()
.srem(this.queue.toKey('failed'), this.id)
.lpush(this.queue.toKey('waiting'), this.id)
.exec(cb);
};
Job.prototype.isInSet = function (set, cb) {
this.queue.client.sismember(this.queue.toKey(set), this.id, function (err, result) {
/* istanbul ignore if */
if (err) return cb(err);
return cb(null, result === 1);
});
};
module.exports = Job;
|
var shorthash = require('../index.js');
shorthash.setDictionary('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomNumber () {
var min=0, max;
switch(arguments.length) {
case 1:
max = arguments[0] - 1; // 一个参数的情况,不包括最大值本身,如randomNumber(10)永远取不到10
break;
case 2:
min = arguments[0];
max = arguments[1];
break;
case 0:
default:
max = 10;
break;
}
return min + Math.floor(Math.random() * (max - min + 1)); // 注意+1, 否则去不到最大值
}
function randomNumberByLength (len) {
var min = 1, max = 1;
len = len || 6;
for( var i=0; i< len-1; ++i) {
min += '0';
max += '0';
}
max += '0';
return randomNumber(parseInt(min, 10), parseInt(max, 10));
}
//people name, term
function randomEnglishWord (length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
i, word='',
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[randomNumber(consonants.length-1)],
randVowel = vowels[randomNumber(vowels.length-1)];
//word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += (i===0) ? randConsonant : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function randomEnglishName (minlength, maxlength, prefix, suffix) {
prefix = prefix || '';
suffix = suffix || '';
//these weird character sets are intended to cope with the nature of English (e.g. char 'x' pops up less frequently than char 's')
//note: 'h' appears as consonants and vocals
var vocals = 'aeiouyh' + 'aeiou' + 'aeiou';
var cons = 'bcdfghjklmnpqrstvwxz' + 'bcdfgjklmnprstvw' + 'bcdfgjklmnprst';
var allchars = vocals + cons;
//minlength += prefix.length;
//maxlength -= suffix.length;
var length = randomNumber(minlength, maxlength) - prefix.length - suffix.length;
if (length < 1) length = 1;
//alert(minlength + ' ' + maxlength + ' ' + length);
var consnum = 0;
//alert(prefix);
/*if ((prefix.length > 1) && (cons.indexOf(prefix[0]) != -1) && (cons.indexOf(prefix[1]) != -1)) {
//alert('a');
consnum = 2;
}*/
if (prefix.length > 0) {
for (var i = 0; i < prefix.length; i++) {
if (consnum == 2) consnum = 0;
if (cons.indexOf(prefix[i]) != -1) {
consnum++;
}
}
}
else {
consnum = 1;
}
var name = prefix;
for (var i = 0; i < length; i++)
{
//if we have used 2 consonants, the next char must be vocal.
if (consnum == 2)
{
touse = vocals;
consnum = 0;
}
else touse = allchars;
//pick a random character from the set we are goin to use.
c = touse.charAt(randomNumber(0, touse.length - 1));
name = name + c;
if (cons.indexOf(c) != -1) consnum++;
}
name = name.charAt(0).toUpperCase() + name.substring(1, name.length) + suffix;
return name;
}
function randomChineseChar () {
//var range = parseInt("9FFF", 16) - parseInt("4E00", 16);
var range = 3500;
//return '&#x' + (0x4E00 + Ytji.randomNumber(range)).toString(16) + ';';
return unescape('%u' + (0x4E00 + randomNumber(range)).toString(16));
}
function randomChineseSentence () {
var min=2, max;
var endPunctuations =['。', '; ', '! ', '? ', '......'], midPunctuations = ['.',',',', ',': ','、','', '-'], str = '';
switch(arguments.length) {
case 1:
max = arguments[0];
break;
case 2:
min = arguments[0], max = arguments[1];
break;
case 0:
default:
max = 20;
}
range = randomNumber(min, max);
for(var i =0; i<=range; i++){
str += randomChineseWord();
if( i%3 ==0 && i != range)
str += midPunctuations[randomNumber(midPunctuations.length-1)];
}
/*
if(randomNumber(100)<10)
str = randomNumberByLength(randomNumber(6)).toString() + str;
*/
return str + endPunctuations[randomNumber(endPunctuations.length-1)];
}
function randomChineseWord () {
var min = 2, max, str = '';
var punctuations =[['“','”'],['<','>'], ['‘','’'],['[',']'],['(',')']];
switch(arguments.length) {
case 1:
max = arguments[0];
break;
case 2:
min = arguments[0], max = arguments[1];
break;
case 0:
default:
max = 4;
}
for(var i=0;i<randomNumber(min, max);i++)
str += randomChineseChar();
if(randomNumber(100)<15){
var puncs = punctuations[randomNumber(punctuations.length-1)];
str = puncs[0] + str + puncs[1];
}
return str;
}
for (var i = 0; i<10; i++) {
var cn = randomChineseSentence(10);
var en = randomEnglishName(6, 30);
console.log(shorthash.unique(cn) + ' -> ' + cn);
console.log(shorthash.unique(en) + ' -> ' + en);
}
|
var events = require('events');
var util = require('util');
var debug = require('debug')('uri-beacon-scanner');
var noble = require('noble');
var uriDecode = require('uri-beacon-uri-encoding').decode;
var SERVICE_UUID = 'fed8';
var UriBeaconScanner = function() {
noble.on('discover', this.onDiscover.bind(this));
};
util.inherits(UriBeaconScanner, events.EventEmitter);
UriBeaconScanner.prototype.startScanning = function(allowDuplicates) {
debug('startScanning');
var startScanningOnPowerOn = function() {
if (noble.state === 'poweredOn') {
noble.startScanning([SERVICE_UUID], allowDuplicates);
} else {
noble.once('stateChange', startScanningOnPowerOn);
}
};
startScanningOnPowerOn();
};
UriBeaconScanner.prototype.stopScanning = function() {
debug('stopScanning');
noble.stopScanning();
};
UriBeaconScanner.prototype.onDiscover = function(peripheral) {
debug('onDiscover: %s', peripheral);
if (this.isUriBeacon(peripheral)) {
var uriBeacon = this.parseUriBeacon(peripheral);
debug('onDiscover: uriBeacon = %s', JSON.stringify(uriBeacon));
this.emit('discover', uriBeacon);
}
};
UriBeaconScanner.prototype.isUriBeacon = function(peripheral) {
var serviceData = peripheral.advertisement.serviceData;
// make sure service data is present, with the expected uuid and data length
return ( serviceData &&
serviceData.length > 0 &&
serviceData[0].uuid === SERVICE_UUID &&
serviceData[0].data.length > 2
);
};
UriBeaconScanner.prototype.parseUriBeacon = function(peripheral) {
var data = peripheral.advertisement.serviceData[0].data;
return {
flags: data.readUInt8(0),
txPower: data.readInt8(1),
uri: uriDecode(data.slice(2)),
rssi: peripheral.rssi
};
};
module.exports = UriBeaconScanner;
|
import React from 'react'
import { Router, Route } from 'react-router'
import { WiredCard } from 'wired-elements'
import Home from '@/home'
import Menu from '@/menu'
const prefix = process.env.prefix
// TODO prefix 前缀用法需要特殊处理
const AppRouter = ({ history }) => (
<Router history={history}>
<div id="content">
<Route exact path='/' render={() => (<wired-card>Index</wired-card>)} />
<Route path='/home' component={Home} />
<Route path='/menu' component={Menu} />
{/* <Route path={`${prefix}/home`} component={Home} /> */}
</div>
</Router>
)
export default AppRouter
|
// Minimize the toolbar
var ToolView = require( './ToolView.js' );
module.exports = ToolView.extend( {
id: 'mwe-pt-minimize',
icon: 'icon_minimize.png', // the default icon
title: '',
tooltip: 'pagetriage-toolbar-minimize',
initialize: function ( options ) {
this.eventBus = options.eventBus;
this.moduleConfig = options.moduleConfig || {};
this.toolbar = options.toolbar;
},
click: function () {
// minimize the toolbar.
this.toolbar.minimize( true );
}
} );
|
// configuration
var database = "moita"; // database name
var output = "timeslotsByDay"; // output collection name (for shell usage)
var semester = "20161"; // desired semester
// code
db = db.getSiblingDB(database);
var map = function() {
for (var _class of this.classes) {
for (var time of _class.timetable) {
for (var slot of time.time) {
if (slot == '1100' || slot =='1330') {
emit(time.day, _class.occupied + _class.special);
}
}
}
}
};
var reduce = function(key, values) {
return Array.sum(values);
};
var options = { query: { semester: semester }, out: output };
db.moita.mapReduce(map, reduce, options);
db[output].find().sort({ value: -1 }).forEach(printjson);
|
/**/// Public: initialize
/**///
/**/// Args
/**/// boombot - a boombot instance
/**///
/**/// Returns
/**/// return - initializes database connections if needed
exports.initialize = function(config) {
// Determine what database setup is chosen
// this only runs when database is set on so just assume configs fine....
if (config.database.mongo.use)
return require('./db/mongo')
else if (config.database.mysql.use)
return require('./db/mysql')
else if (config.database.sqlite.use)
return require('./db/sqlite')
}
|
var engine = {
posts : [],
target : null,
busy : false,
count : 5,
render : function(id, obj){
var xhtml = '<div class="singleQuestion" id=question_'+id+'>';
if (obj.user) {
xhtml += '<div class="userName">'+obj.user+'</div>';
}
if (obj.date) {
xhtml += '<div class="questionDate">'+obj.date+'</div>';
}
if (obj.text) {
xhtml += '<p class="questionText">' + obj.text + '</p>';
}
xhtml += '</div>';
return xhtml;
},
init : function(posts, target){
if (!target)
return;
this.target = $(target);
this.append(posts);
var that = this;
$(window).scroll(function(){
if ($(document).height() - $(window).height() <= $(window).scrollTop() + 50) {
that.scrollPosition = $(window).scrollTop();
that.get();
}
});
},
append : function(posts){
//posts = (posts instanceof Object) ? posts : [];
if(!posts) return;
//this.posts = this.posts.concat(posts);
this.posts = this.posts.concat(posts['categorized']);
for(var i in posts['categorized']){
var question = posts['categorized'][i];
this.target.append(this.render(i, question));
}
if (this.scrollPosition !== undefined && this.scrollPosition !== null) {
$(window).scrollTop(this.scrollPosition);
}
},
get : function() {
if (!this.target || this.busy) return;
if (this.posts && this.posts.length) {
var lastId = this.posts[this.posts.length-1].id;
} else {
var lastId = 0;
}
this.setBusy(true);
var that = this;
$.ajax({'url': '/ajax/getUpdate', 'type':'post', 'data':'last_time=0',
'success': function(data){
data = JSON.parse(data);
//if (data.length > 0) {
that.append(data);
//}
that.setBusy(false);
}
});
},
showLoading : function(bState){
var loading = $('#loading');
if (bState) {
$(this.target).append(loading);
loading.show('slow');
} else {
$('#loading').hide();
}
},
setBusy : function(bState){
this.showLoading(this.busy = bState);
}
};
// usage
$(document).ready(function(){
engine.init(null, "#showQuestion");
engine.get();
});
|
define([], function() {
'use strict';
return function($scope, $stateParams, $quotation, $state, localStorageService, $rootScope, $toast) {
var item_id = parseInt($stateParams.id);
$scope.vm = {
loading:false,
emptyTitle:''
};
$scope.initData = function (){
$scope.vm.loading = true;
$quotation.bindReceiveDetail($scope, 'receive', item_id)
.catch(function (errMsg) {
$scope.vm.emptyTitle = errMsg;
})
.finally(function () {
$scope.vm.loading = false;
});
};
$scope.goEdit = function (item){
if(!!item.trade_id && item.trade_id>0){
$state.go('trade-content',{id:item.trade_id,can_show_pro:true});
}else{
if ($scope.receive.quotation.status === -1) {
$toast.error('失效报价单无法还价');
return;
}
//选择是否本地缓存
var newItem = {
quotation: $scope.receive.quotation,
item: angular.copy(item)
};
localStorageService.set('quotation:offer', newItem);
$state.go('quotation-bargaining');
}
};
};
});
|
/**
* THIS FILE IS AUTO-GENERATED
* DON'T MAKE CHANGES HERE
*/
import { addDependencies } from './dependenciesAdd.generated'
import { compareDependencies } from './dependenciesCompare.generated'
import { divideDependencies } from './dependenciesDivide.generated'
import { partitionSelectDependencies } from './dependenciesPartitionSelect.generated'
import { typedDependencies } from './dependenciesTyped.generated'
import { createMedian } from '../../factoriesAny.js'
export const medianDependencies = {
addDependencies,
compareDependencies,
divideDependencies,
partitionSelectDependencies,
typedDependencies,
createMedian
}
|
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var Q = require('q'); /* jshint ignore:line */
var _ = require('lodash'); /* jshint ignore:line */
var util = require('util'); /* jshint ignore:line */
var Page = require('../../../../../base/Page'); /* jshint ignore:line */
var deserialize = require(
'../../../../../base/deserialize'); /* jshint ignore:line */
var serialize = require(
'../../../../../base/serialize'); /* jshint ignore:line */
var values = require('../../../../../base/values'); /* jshint ignore:line */
var UserChannelList;
var UserChannelPage;
var UserChannelInstance;
var UserChannelContext;
/* jshint ignore:start */
/**
* Initialize the UserChannelList
*
* @constructor Twilio.Chat.V2.ServiceContext.UserContext.UserChannelList
*
* @param {Twilio.Chat.V2} version - Version of the resource
* @param {string} serviceSid -
* The SID of the Service that the resource is associated with
* @param {string} userSid - The SID of the User the User Channel belongs to
*/
/* jshint ignore:end */
UserChannelList = function UserChannelList(version, serviceSid, userSid) {
/* jshint ignore:start */
/**
* @function userChannels
* @memberof Twilio.Chat.V2.ServiceContext.UserContext#
*
* @param {string} sid - sid of instance
*
* @returns {Twilio.Chat.V2.ServiceContext.UserContext.UserChannelContext}
*/
/* jshint ignore:end */
function UserChannelListInstance(sid) {
return UserChannelListInstance.get(sid);
}
UserChannelListInstance._version = version;
// Path Solution
UserChannelListInstance._solution = {serviceSid: serviceSid, userSid: userSid};
UserChannelListInstance._uri = `/Services/${serviceSid}/Users/${userSid}/Channels`;
/* jshint ignore:start */
/**
* Streams UserChannelInstance records from the API.
*
* This operation lazily loads records as efficiently as possible until the limit
* is reached.
*
* The results are passed into the callback function, so this operation is memory
* efficient.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @function each
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelList#
*
* @param {object} [opts] - Options for request
* @param {number} [opts.limit] -
* Upper limit for the number of records to return.
* each() guarantees never to return more than limit.
* Default is no limit
* @param {number} [opts.pageSize] -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no pageSize is defined but a limit is defined,
* each() will attempt to read the limit with the most efficient
* page size, i.e. min(limit, 1000)
* @param {Function} [opts.callback] -
* Function to process each record. If this and a positional
* callback are passed, this one will be used
* @param {Function} [opts.done] -
* Function to be called upon completion of streaming
* @param {Function} [callback] - Function to process each record
*/
/* jshint ignore:end */
UserChannelListInstance.each = function each(opts, callback) {
if (_.isFunction(opts)) {
callback = opts;
opts = {};
}
opts = opts || {};
if (opts.callback) {
callback = opts.callback;
}
if (_.isUndefined(callback)) {
throw new Error('Callback function must be provided');
}
var done = false;
var currentPage = 1;
var currentResource = 0;
var limits = this._version.readLimits({
limit: opts.limit,
pageSize: opts.pageSize
});
function onComplete(error) {
done = true;
if (_.isFunction(opts.done)) {
opts.done(error);
}
}
function fetchNextPage(fn) {
var promise = fn();
if (_.isUndefined(promise)) {
onComplete();
return;
}
promise.then(function(page) {
_.each(page.instances, function(instance) {
if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) {
done = true;
return false;
}
currentResource++;
callback(instance, onComplete);
});
if (!done) {
currentPage++;
fetchNextPage(_.bind(page.nextPage, page));
} else {
onComplete();
}
});
promise.catch(onComplete);
}
fetchNextPage(_.bind(this.page, this, _.merge(opts, limits)));
};
/* jshint ignore:start */
/**
* Lists UserChannelInstance records from the API as a list.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @function list
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelList#
*
* @param {object} [opts] - Options for request
* @param {number} [opts.limit] -
* Upper limit for the number of records to return.
* list() guarantees never to return more than limit.
* Default is no limit
* @param {number} [opts.pageSize] -
* Number of records to fetch per request,
* when not set will use the default value of 50 records.
* If no page_size is defined but a limit is defined,
* list() will attempt to read the limit with the most
* efficient page size, i.e. min(limit, 1000)
* @param {function} [callback] - Callback to handle list of records
*
* @returns {Promise} Resolves to a list of records
*/
/* jshint ignore:end */
UserChannelListInstance.list = function list(opts, callback) {
if (_.isFunction(opts)) {
callback = opts;
opts = {};
}
opts = opts || {};
var deferred = Q.defer();
var allResources = [];
opts.callback = function(resource, done) {
allResources.push(resource);
if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) {
done();
}
};
opts.done = function(error) {
if (_.isUndefined(error)) {
deferred.resolve(allResources);
} else {
deferred.reject(error);
}
};
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
this.each(opts);
return deferred.promise;
};
/* jshint ignore:start */
/**
* Retrieve a single page of UserChannelInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @function page
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelList#
*
* @param {object} [opts] - Options for request
* @param {string} [opts.pageToken] - PageToken provided by the API
* @param {number} [opts.pageNumber] -
* Page Number, this value is simply for client state
* @param {number} [opts.pageSize] - Number of records to return, defaults to 50
* @param {function} [callback] - Callback to handle list of records
*
* @returns {Promise} Resolves to a list of records
*/
/* jshint ignore:end */
UserChannelListInstance.page = function page(opts, callback) {
if (_.isFunction(opts)) {
callback = opts;
opts = {};
}
opts = opts || {};
var deferred = Q.defer();
var data = values.of({
'PageToken': opts.pageToken,
'Page': opts.pageNumber,
'PageSize': opts.pageSize
});
var promise = this._version.page({uri: this._uri, method: 'GET', params: data});
promise = promise.then(function(payload) {
deferred.resolve(new UserChannelPage(this._version, payload, this._solution));
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
/* jshint ignore:start */
/**
* Retrieve a single target page of UserChannelInstance records from the API.
*
* The request is executed immediately.
*
* If a function is passed as the first argument, it will be used as the callback
* function.
*
* @function getPage
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelList#
*
* @param {string} [targetUrl] - API-generated URL for the requested results page
* @param {function} [callback] - Callback to handle list of records
*
* @returns {Promise} Resolves to a list of records
*/
/* jshint ignore:end */
UserChannelListInstance.getPage = function getPage(targetUrl, callback) {
var deferred = Q.defer();
var promise = this._version._domain.twilio.request({method: 'GET', uri: targetUrl});
promise = promise.then(function(payload) {
deferred.resolve(new UserChannelPage(this._version, payload, this._solution));
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
/* jshint ignore:start */
/**
* Constructs a user_channel
*
* @function get
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelList#
*
* @param {string} channelSid -
* The SID of the Channel that has the User Channel to fetch
*
* @returns {Twilio.Chat.V2.ServiceContext.UserContext.UserChannelContext}
*/
/* jshint ignore:end */
UserChannelListInstance.get = function get(channelSid) {
return new UserChannelContext(
this._version,
this._solution.serviceSid,
this._solution.userSid,
channelSid
);
};
/* jshint ignore:start */
/**
* Provide a user-friendly representation
*
* @function toJSON
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelList#
*
* @returns Object
*/
/* jshint ignore:end */
UserChannelListInstance.toJSON = function toJSON() {
return this._solution;
};
UserChannelListInstance[util.inspect.custom] = function inspect(depth, options)
{
return util.inspect(this.toJSON(), options);
};
return UserChannelListInstance;
};
/* jshint ignore:start */
/**
* Initialize the UserChannelPage
*
* @constructor Twilio.Chat.V2.ServiceContext.UserContext.UserChannelPage
*
* @param {V2} version - Version of the resource
* @param {Response<string>} response - Response from the API
* @param {UserChannelSolution} solution - Path solution
*
* @returns UserChannelPage
*/
/* jshint ignore:end */
UserChannelPage = function UserChannelPage(version, response, solution) {
// Path Solution
this._solution = solution;
Page.prototype.constructor.call(this, version, response, this._solution);
};
_.extend(UserChannelPage.prototype, Page.prototype);
UserChannelPage.prototype.constructor = UserChannelPage;
/* jshint ignore:start */
/**
* Build an instance of UserChannelInstance
*
* @function getInstance
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelPage#
*
* @param {UserChannelPayload} payload - Payload response from the API
*
* @returns UserChannelInstance
*/
/* jshint ignore:end */
UserChannelPage.prototype.getInstance = function getInstance(payload) {
return new UserChannelInstance(
this._version,
payload,
this._solution.serviceSid,
this._solution.userSid
);
};
/* jshint ignore:start */
/**
* Provide a user-friendly representation
*
* @function toJSON
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelPage#
*
* @returns Object
*/
/* jshint ignore:end */
UserChannelPage.prototype.toJSON = function toJSON() {
let clone = {};
_.forOwn(this, function(value, key) {
if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
clone[key] = value;
}
});
return clone;
};
UserChannelPage.prototype[util.inspect.custom] = function inspect(depth,
options) {
return util.inspect(this.toJSON(), options);
};
/* jshint ignore:start */
/**
* Initialize the UserChannelContext
*
* @constructor Twilio.Chat.V2.ServiceContext.UserContext.UserChannelInstance
*
* @property {string} accountSid - The SID of the Account that created the resource
* @property {string} serviceSid -
* The SID of the Service that the resource is associated with
* @property {string} channelSid - The SID of the Channel the resource belongs to
* @property {string} userSid - The SID of the User the User Channel belongs to
* @property {string} memberSid - The SID of the User as a Member in the Channel
* @property {user_channel.channel_status} status -
* The status of the User on the Channel
* @property {number} lastConsumedMessageIndex -
* The index of the last Message in the Channel the Member has read
* @property {number} unreadMessagesCount -
* The number of unread Messages in the Channel for the User
* @property {string} links -
* Absolute URLs to access the Members, Messages , Invites and, if it exists, the last Message for the Channel
* @property {string} url - The absolute URL of the resource
* @property {user_channel.notification_level} notificationLevel -
* The push notification level of the User for the Channel
*
* @param {V2} version - Version of the resource
* @param {UserChannelPayload} payload - The instance payload
* @param {sid} serviceSid -
* The SID of the Service that the resource is associated with
* @param {sid} userSid - The SID of the User the User Channel belongs to
* @param {sid_like} channelSid -
* The SID of the Channel that has the User Channel to fetch
*/
/* jshint ignore:end */
UserChannelInstance = function UserChannelInstance(version, payload, serviceSid,
userSid, channelSid) {
this._version = version;
// Marshaled Properties
this.accountSid = payload.account_sid; // jshint ignore:line
this.serviceSid = payload.service_sid; // jshint ignore:line
this.channelSid = payload.channel_sid; // jshint ignore:line
this.userSid = payload.user_sid; // jshint ignore:line
this.memberSid = payload.member_sid; // jshint ignore:line
this.status = payload.status; // jshint ignore:line
this.lastConsumedMessageIndex = deserialize.integer(payload.last_consumed_message_index); // jshint ignore:line
this.unreadMessagesCount = deserialize.integer(payload.unread_messages_count); // jshint ignore:line
this.links = payload.links; // jshint ignore:line
this.url = payload.url; // jshint ignore:line
this.notificationLevel = payload.notification_level; // jshint ignore:line
// Context
this._context = undefined;
this._solution = {
serviceSid: serviceSid,
userSid: userSid,
channelSid: channelSid || this.channelSid,
};
};
Object.defineProperty(UserChannelInstance.prototype,
'_proxy', {
get: function() {
if (!this._context) {
this._context = new UserChannelContext(
this._version,
this._solution.serviceSid,
this._solution.userSid,
this._solution.channelSid
);
}
return this._context;
}
});
/* jshint ignore:start */
/**
* fetch a UserChannelInstance
*
* @function fetch
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelInstance#
*
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed UserChannelInstance
*/
/* jshint ignore:end */
UserChannelInstance.prototype.fetch = function fetch(callback) {
return this._proxy.fetch(callback);
};
/* jshint ignore:start */
/**
* remove a UserChannelInstance
*
* @function remove
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelInstance#
*
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed UserChannelInstance
*/
/* jshint ignore:end */
UserChannelInstance.prototype.remove = function remove(callback) {
return this._proxy.remove(callback);
};
/* jshint ignore:start */
/**
* update a UserChannelInstance
*
* @function update
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelInstance#
*
* @param {object} [opts] - Options for request
* @param {user_channel.notification_level} [opts.notificationLevel] -
* The push notification level to assign to the User Channel
* @param {number} [opts.lastConsumedMessageIndex] -
* The index of the last Message that the Member has read within the Channel
* @param {Date} [opts.lastConsumptionTimestamp] -
* The ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed UserChannelInstance
*/
/* jshint ignore:end */
UserChannelInstance.prototype.update = function update(opts, callback) {
return this._proxy.update(opts, callback);
};
/* jshint ignore:start */
/**
* Provide a user-friendly representation
*
* @function toJSON
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelInstance#
*
* @returns Object
*/
/* jshint ignore:end */
UserChannelInstance.prototype.toJSON = function toJSON() {
let clone = {};
_.forOwn(this, function(value, key) {
if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
clone[key] = value;
}
});
return clone;
};
UserChannelInstance.prototype[util.inspect.custom] = function inspect(depth,
options) {
return util.inspect(this.toJSON(), options);
};
/* jshint ignore:start */
/**
* Initialize the UserChannelContext
*
* @constructor Twilio.Chat.V2.ServiceContext.UserContext.UserChannelContext
*
* @param {V2} version - Version of the resource
* @param {sid} serviceSid -
* The SID of the Service to fetch the User Channel resource from
* @param {sid_like} userSid -
* The SID of the User to fetch the User Channel resource from
* @param {sid_like} channelSid -
* The SID of the Channel that has the User Channel to fetch
*/
/* jshint ignore:end */
UserChannelContext = function UserChannelContext(version, serviceSid, userSid,
channelSid) {
this._version = version;
// Path Solution
this._solution = {serviceSid: serviceSid, userSid: userSid, channelSid: channelSid, };
this._uri = `/Services/${serviceSid}/Users/${userSid}/Channels/${channelSid}`;
};
/* jshint ignore:start */
/**
* fetch a UserChannelInstance
*
* @function fetch
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelContext#
*
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed UserChannelInstance
*/
/* jshint ignore:end */
UserChannelContext.prototype.fetch = function fetch(callback) {
var deferred = Q.defer();
var promise = this._version.fetch({uri: this._uri, method: 'GET'});
promise = promise.then(function(payload) {
deferred.resolve(new UserChannelInstance(
this._version,
payload,
this._solution.serviceSid,
this._solution.userSid,
this._solution.channelSid
));
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
/* jshint ignore:start */
/**
* remove a UserChannelInstance
*
* @function remove
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelContext#
*
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed UserChannelInstance
*/
/* jshint ignore:end */
UserChannelContext.prototype.remove = function remove(callback) {
var deferred = Q.defer();
var promise = this._version.remove({uri: this._uri, method: 'DELETE'});
promise = promise.then(function(payload) {
deferred.resolve(payload);
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
/* jshint ignore:start */
/**
* update a UserChannelInstance
*
* @function update
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelContext#
*
* @param {object} [opts] - Options for request
* @param {user_channel.notification_level} [opts.notificationLevel] -
* The push notification level to assign to the User Channel
* @param {number} [opts.lastConsumedMessageIndex] -
* The index of the last Message that the Member has read within the Channel
* @param {Date} [opts.lastConsumptionTimestamp] -
* The ISO 8601 based timestamp string that represents the datetime of the last Message read event for the Member within the Channel
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed UserChannelInstance
*/
/* jshint ignore:end */
UserChannelContext.prototype.update = function update(opts, callback) {
if (_.isFunction(opts)) {
callback = opts;
opts = {};
}
opts = opts || {};
var deferred = Q.defer();
var data = values.of({
'NotificationLevel': _.get(opts, 'notificationLevel'),
'LastConsumedMessageIndex': _.get(opts, 'lastConsumedMessageIndex'),
'LastConsumptionTimestamp': serialize.iso8601DateTime(_.get(opts, 'lastConsumptionTimestamp'))
});
var promise = this._version.update({uri: this._uri, method: 'POST', data: data});
promise = promise.then(function(payload) {
deferred.resolve(new UserChannelInstance(
this._version,
payload,
this._solution.serviceSid,
this._solution.userSid,
this._solution.channelSid
));
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
/* jshint ignore:start */
/**
* Provide a user-friendly representation
*
* @function toJSON
* @memberof Twilio.Chat.V2.ServiceContext.UserContext.UserChannelContext#
*
* @returns Object
*/
/* jshint ignore:end */
UserChannelContext.prototype.toJSON = function toJSON() {
return this._solution;
};
UserChannelContext.prototype[util.inspect.custom] = function inspect(depth,
options) {
return util.inspect(this.toJSON(), options);
};
module.exports = {
UserChannelList: UserChannelList,
UserChannelPage: UserChannelPage,
UserChannelInstance: UserChannelInstance,
UserChannelContext: UserChannelContext
};
|
import { Home } from 'pages'
const routes = [
{
path: '/',
exact: true,
component: Home
}
]
export default routes
|
var ResourceChangedEvents = require('../');
var should = require('should');
var nock = require('nock');
describe('Happy Path', function() {
var mockNock = function(url, path, resp) {
nock(url).get(path).reply(resp.statusCode, resp.data);
};
var doneCalled = false;
var lenientDone = function(done) {
if (!doneCalled) {
done();
doneCalled = true;
}
};
beforeEach(function() {
doneCalled = false
});
describe('init', function() {
beforeEach(function() {
mockNock('http://api.yds.se', '/1', {statusCode: 200, data: 'XXX 1'});
mockNock('http://api.yds.se', '/2', {statusCode: 200, data: 'XXX 2'});
});
var verifyCallComplete = function(url, expected, done) {
var rce = new ResourceChangedEvents({url: url, interval: 100});
rce.on('data', function(data) {
should.exist(data);
data.should.equal(expected);
rce.stop();
lenientDone(done);
});
rce.start();
};
it('RCE instance should retrieve initial data "XXX 1" event for http://api.yds.se/1 on start', function(done) {
verifyCallComplete('http://api.yds.se/1', 'XXX 1', done);
});
it('RCE instance should retrieve initial data "XXX 2" event for http://api.yds.se/2 on start', function(done) {
verifyCallComplete('http://api.yds.se/2', 'XXX 2', done);
});
});
describe('repeat', function() {
var callCount = 0;
beforeEach(function() {
mockNock('http://api.yds.se', '/', {status: 200, data: 'XXX ' + (callCount++)});
});
it('RCE instance should keep calling url even after first invocation', function(done) {
var rce = new ResourceChangedEvents({url: 'http://api.yds.se/', interval: 100});
rce.on('data', function(data) {
should.exist(data);
mockNock('http://api.yds.se', '/', {status: 200, data: 'XXX ' + (callCount++)});
if (callCount > 1) {
rce.stop();
lenientDone(done);
}
});
rce.start();
});
});
});
|
import { MUTATIONS } from '../mutations';
import { GETTERS } from '../getters';
// initial state
const state = {
save_message: {
message: "",
error: false
}
}
// getters
const getters = {
[GETTERS.BANNERS.GET_SAVE_BANNER] (state) {
return state.save_message;
},
};
// actions
const actions = {
saveBanner ({ dispatch, commit }, { message, shouldPop }) {
commit(MUTATIONS.BANNERS.SAVE_BANNER, { message, error: false });
if (shouldPop) {
return new Promise((resolve, reject) => {
setTimeout(() => {
dispatch('saveBanner', { message: '', shouldPop: false });
resolve()
}, 3000)
})
}
},
saveErrorBanner ({ dispatch, commit }, { message, shouldPop }) {
commit(MUTATIONS.BANNERS.SAVE_BANNER, { message, error: true });
if (shouldPop) {
return new Promise((resolve, reject) => {
setTimeout(() => {
dispatch('saveBanner', { message: '', shouldPop: false });
resolve()
}, 3000)
})
}
},
};
// mutations
const mutations = {
[MUTATIONS.BANNERS.SAVE_BANNER] (state, { message, error }) {
state.save_message.message = message;
state.save_message.error = error;
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
};
|
var Icon = require('../icon');
var element = require('magic-virtual-element');
var clone = require('../clone');
exports.render = function render(component) {
var props = clone(component.props);
delete props.children;
return element(
Icon,
props,
element('path', { d: 'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z' })
);
};
|
/*!
* Chart.js
* http://chartjs.org/
* Version: 1.0.1-beta.3
*
* Copyright 2014 Nick Downie
* Released under the MIT license
* https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
*/
(function(){
"use strict";
//Declare root variable - window in the browser, global on the server
var root = this,
previous = root.Chart;
//Occupy the global variable of Chart, and create a simple base class
var Chart = function(context){
var chart = this;
this.canvas = context.canvas;
this.ctx = context;
//Variables global to the chart
var width = this.width = context.canvas.width;
var height = this.height = context.canvas.height;
this.aspectRatio = this.width / this.height;
//High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
helpers.retinaScale(this);
return this;
};
//Globally expose the defaults to allow for user updating/changing
Chart.defaults = {
global: {
// Boolean - Whether to animate the chart
animation: true,
// Number - Number of animation steps
animationSteps: 60,
// String - Animation easing effect
animationEasing: "easeOutQuart",
// Boolean - If we should show the scale at all
showScale: true,
// Boolean - If we want to override with a hard coded scale
scaleOverride: false,
// ** Required if scaleOverride is true **
// Number - The number of steps in a hard coded scale
scaleSteps: null,
// Number - The value jump in the hard coded scale
scaleStepWidth: null,
// Number - The scale starting value
scaleStartValue: null,
// String - Colour of the scale line
scaleLineColor: "rgba(0,0,0,.1)",
// Number - Pixel width of the scale line
scaleLineWidth: 1,
// Boolean - Whether to show labels on the scale
scaleShowLabels: true,
// Interpolated JS string - can access value
scaleLabel: "<%=value%>",
// Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
scaleIntegersOnly: true,
// Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero: false,
// String - Scale label font declaration for the scale label
scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Scale label font size in pixels
scaleFontSize: 12,
// String - Scale label font weight style
scaleFontStyle: "normal",
// String - Scale label font colour
scaleFontColor: "#666",
// Boolean - Whether to use a custom maximum value width (valueMaxWidth must be set).
scaleValueCustomMaxWidth: false,
// Number - Maximum width that a given value can use in the graph.
scaleValueMaxWidth: 60,
// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: false,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
// Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
showTooltips: true,
// Array - Array of string names to attach tooltip events
tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
// String - Tooltip background colour
tooltipFillColor: "rgba(0,0,0,0.8)",
// String - Tooltip label font declaration for the scale label
tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip label font size in pixels
tooltipFontSize: 14,
// String - Tooltip font weight style
tooltipFontStyle: "normal",
// String - Tooltip label font colour
tooltipFontColor: "#fff",
// String - Tooltip title font declaration for the scale label
tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
// Number - Tooltip title font size in pixels
tooltipTitleFontSize: 14,
// String - Tooltip title font weight style
tooltipTitleFontStyle: "bold",
// String - Tooltip title font colour
tooltipTitleFontColor: "#fff",
// Number - pixel width of padding around tooltip text
tooltipYPadding: 6,
// Number - pixel width of padding around tooltip text
tooltipXPadding: 6,
// Number - Size of the caret on the tooltip
tooltipCaretSize: 8,
// Number - Pixel radius of the tooltip border
tooltipCornerRadius: 6,
// Number - Pixel offset from point x to tooltip edge
tooltipXOffset: 10,
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
// String - Template string for single tooltips
multiTooltipTemplate: "<%= value %>",
// String - Colour behind the legend colour block
multiTooltipKeyBackground: '#fff',
// Function - Will fire on animation progression.
onAnimationProgress: function(){},
// Function - Will fire on animation completion.
onAnimationComplete: function(){}
}
};
//Create a dictionary of chart types, to allow for extension of existing types
Chart.types = {};
//Global Chart helpers object for utility methods and classes
var helpers = Chart.helpers = {};
//-- Basic js utility methods
var each = helpers.each = function(loopable,callback,self){
var additionalArgs = Array.prototype.slice.call(arguments, 3);
// Check to see if null or undefined firstly.
if (loopable){
if (loopable.length === +loopable.length){
var i;
for (i=0; i<loopable.length; i++){
callback.apply(self,[loopable[i], i].concat(additionalArgs));
}
}
else{
for (var item in loopable){
callback.apply(self,[loopable[item],item].concat(additionalArgs));
}
}
}
},
clone = helpers.clone = function(obj){
var objClone = {};
each(obj,function(value,key){
if (obj.hasOwnProperty(key)) objClone[key] = value;
});
return objClone;
},
extend = helpers.extend = function(base){
each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
each(extensionObject,function(value,key){
if (extensionObject.hasOwnProperty(key)) base[key] = value;
});
});
return base;
},
merge = helpers.merge = function(base,master){
//Merge properties in left object over to a shallow clone of object right.
var args = Array.prototype.slice.call(arguments,0);
args.unshift({});
return extend.apply(null, args);
},
indexOf = helpers.indexOf = function(arrayToSearch, item){
if (Array.prototype.indexOf) {
return arrayToSearch.indexOf(item);
}
else{
for (var i = 0; i < arrayToSearch.length; i++) {
if (arrayToSearch[i] === item) return i;
}
return -1;
}
},
inherits = helpers.inherits = function(extensions){
//Basic javascript inheritance based on the model created in Backbone.js
var parent = this;
var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
var Surrogate = function(){ this.constructor = ChartElement;};
Surrogate.prototype = parent.prototype;
ChartElement.prototype = new Surrogate();
ChartElement.extend = inherits;
if (extensions) extend(ChartElement.prototype, extensions);
ChartElement.__super__ = parent.prototype;
return ChartElement;
},
noop = helpers.noop = function(){},
uid = helpers.uid = (function(){
var id=0;
return function(){
return "chart-" + id++;
};
})(),
warn = helpers.warn = function(str){
//Method for warning of errors
if (window.console && typeof window.console.warn == "function") console.warn(str);
},
amd = helpers.amd = (typeof root.define == 'function' && root.define.amd),
//-- Math methods
isNumber = helpers.isNumber = function(n){
return !isNaN(parseFloat(n)) && isFinite(n);
},
max = helpers.max = function(array){
return Math.max.apply( Math, array );
},
min = helpers.min = function(array){
return Math.min.apply( Math, array );
},
cap = helpers.cap = function(valueToCap,maxValue,minValue){
if(isNumber(maxValue)) {
if( valueToCap > maxValue ) {
return maxValue;
}
}
else if(isNumber(minValue)){
if ( valueToCap < minValue ){
return minValue;
}
}
return valueToCap;
},
getDecimalPlaces = helpers.getDecimalPlaces = function(num){
if (num%1!==0 && isNumber(num)){
return num.toString().split(".")[1].length;
}
else {
return 0;
}
},
toRadians = helpers.radians = function(degrees){
return degrees * (Math.PI/180);
},
// Gets the angle from vertical upright to the point about a centre.
getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
var distanceFromXCenter = anglePoint.x - centrePoint.x,
distanceFromYCenter = anglePoint.y - centrePoint.y,
radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
//If the segment is in the top left quadrant, we need to add another rotation to the angle
if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
angle += Math.PI*2;
}
return {
angle: angle,
distance: radialDistanceFromCenter
};
},
aliasPixel = helpers.aliasPixel = function(pixelWidth){
return (pixelWidth % 2 === 0) ? 0 : 0.5;
},
splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
//Props to Rob Spencer at scaled innovation for his post on splining between points
//http://scaledinnovation.com/analytics/splines/aboutSplines.html
var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
fa=t*d01/(d01+d12),// scaling factor for triangle Ta
fb=t*d12/(d01+d12);
return {
inner : {
x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
},
outer : {
x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
}
};
},
calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
return Math.floor(Math.log(val) / Math.LN10);
},
calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
//Set a minimum step of two - a point at the top of the graph, and a point at the base
var minSteps = 2,
maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
skipFitting = (minSteps >= maxSteps);
var maxValue = max(valuesArray),
minValue = min(valuesArray);
// We need some degree of seperation here to calculate the scales if all the values are the same
// Adding/minusing 0.5 will give us a range of 1.
if (maxValue === minValue){
maxValue += 0.5;
// So we don't end up with a graph with a negative start value if we've said always start from zero
if (minValue >= 0.5 && !startFromZero){
minValue -= 0.5;
}
else{
// Make up a whole number above the values
maxValue += 0.5;
}
}
var valueRange = Math.abs(maxValue - minValue),
rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
graphRange = graphMax - graphMin,
stepValue = Math.pow(10, rangeOrderOfMagnitude),
numberOfSteps = Math.round(graphRange / stepValue);
//If we have more space on the graph we'll use it to give more definition to the data
while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
if(numberOfSteps > maxSteps){
stepValue *=2;
numberOfSteps = Math.round(graphRange/stepValue);
// Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
if (numberOfSteps % 1 !== 0){
skipFitting = true;
}
}
//We can fit in double the amount of scale points on the scale
else{
//If user has declared ints only, and the step value isn't a decimal
if (integersOnly && rangeOrderOfMagnitude >= 0){
//If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
if(stepValue/2 % 1 === 0){
stepValue /=2;
numberOfSteps = Math.round(graphRange/stepValue);
}
//If it would make it a float break out of the loop
else{
break;
}
}
//If the scale doesn't have to be an int, make the scale more granular anyway.
else{
stepValue /=2;
numberOfSteps = Math.round(graphRange/stepValue);
}
}
}
if (skipFitting){
numberOfSteps = minSteps;
stepValue = graphRange / numberOfSteps;
}
return {
steps : numberOfSteps,
stepValue : stepValue,
min : graphMin,
max : graphMin + (numberOfSteps * stepValue)
};
},
/* jshint ignore:start */
// Blows up jshint errors based on the new Function constructor
//Templating methods
//Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
template = helpers.template = function(templateString, valuesObject){
// If templateString is function rather than string-template - call the function for valuesObject
if(templateString instanceof Function)
{
return templateString(valuesObject);
}
var cache = {};
function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'") +
"');}return p.join('');"
);
// Provide some basic currying to the user
return data ? fn( data ) : fn;
}
return tmpl(templateString,valuesObject);
},
/* jshint ignore:end */
generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
var labelsArray = new Array(numberOfSteps);
if (labelTemplateString){
each(labelsArray,function(val,index){
labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
});
}
return labelsArray;
},
//--Animation methods
//Easing functions adapted from Robert Penner's easing equations
//http://www.robertpenner.com/easing/
easingEffects = helpers.easingEffects = {
linear: function (t) {
return t;
},
easeInQuad: function (t) {
return t * t;
},
easeOutQuad: function (t) {
return -1 * t * (t - 2);
},
easeInOutQuad: function (t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t;
return -1 / 2 * ((--t) * (t - 2) - 1);
},
easeInCubic: function (t) {
return t * t * t;
},
easeOutCubic: function (t) {
return 1 * ((t = t / 1 - 1) * t * t + 1);
},
easeInOutCubic: function (t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t;
return 1 / 2 * ((t -= 2) * t * t + 2);
},
easeInQuart: function (t) {
return t * t * t * t;
},
easeOutQuart: function (t) {
return -1 * ((t = t / 1 - 1) * t * t * t - 1);
},
easeInOutQuart: function (t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t;
return -1 / 2 * ((t -= 2) * t * t * t - 2);
},
easeInQuint: function (t) {
return 1 * (t /= 1) * t * t * t * t;
},
easeOutQuint: function (t) {
return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
},
easeInOutQuint: function (t) {
if ((t /= 1 / 2) < 1) return 1 / 2 * t * t * t * t * t;
return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
},
easeInSine: function (t) {
return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
},
easeOutSine: function (t) {
return 1 * Math.sin(t / 1 * (Math.PI / 2));
},
easeInOutSine: function (t) {
return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
},
easeInExpo: function (t) {
return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
},
easeOutExpo: function (t) {
return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
},
easeInOutExpo: function (t) {
if (t === 0) return 0;
if (t === 1) return 1;
if ((t /= 1 / 2) < 1) return 1 / 2 * Math.pow(2, 10 * (t - 1));
return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
},
easeInCirc: function (t) {
if (t >= 1) return t;
return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
},
easeOutCirc: function (t) {
return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
},
easeInOutCirc: function (t) {
if ((t /= 1 / 2) < 1) return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
},
easeInElastic: function (t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) return 0;
if ((t /= 1) == 1) return 1;
if (!p) p = 1 * 0.3;
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
},
easeOutElastic: function (t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) return 0;
if ((t /= 1) == 1) return 1;
if (!p) p = 1 * 0.3;
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
},
easeInOutElastic: function (t) {
var s = 1.70158;
var p = 0;
var a = 1;
if (t === 0) return 0;
if ((t /= 1 / 2) == 2) return 1;
if (!p) p = 1 * (0.3 * 1.5);
if (a < Math.abs(1)) {
a = 1;
s = p / 4;
} else s = p / (2 * Math.PI) * Math.asin(1 / a);
if (t < 1) return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
},
easeInBack: function (t) {
var s = 1.70158;
return 1 * (t /= 1) * t * ((s + 1) * t - s);
},
easeOutBack: function (t) {
var s = 1.70158;
return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
},
easeInOutBack: function (t) {
var s = 1.70158;
if ((t /= 1 / 2) < 1) return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
},
easeInBounce: function (t) {
return 1 - easingEffects.easeOutBounce(1 - t);
},
easeOutBounce: function (t) {
if ((t /= 1) < (1 / 2.75)) {
return 1 * (7.5625 * t * t);
} else if (t < (2 / 2.75)) {
return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
} else if (t < (2.5 / 2.75)) {
return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
} else {
return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
}
},
easeInOutBounce: function (t) {
if (t < 1 / 2) return easingEffects.easeInBounce(t * 2) * 0.5;
return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
}
},
//Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
requestAnimFrame = helpers.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
return window.setTimeout(callback, 1000 / 60);
};
})(),
cancelAnimFrame = helpers.cancelAnimFrame = (function(){
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
window.msCancelAnimationFrame ||
function(callback) {
return window.clearTimeout(callback, 1000 / 60);
};
})(),
animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
var currentStep = 0,
easingFunction = easingEffects[easingString] || easingEffects.linear;
var animationFrame = function(){
currentStep++;
var stepDecimal = currentStep/totalSteps;
var easeDecimal = easingFunction(stepDecimal);
callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
onProgress.call(chartInstance,easeDecimal,stepDecimal);
if (currentStep < totalSteps){
chartInstance.animationFrame = requestAnimFrame(animationFrame);
} else{
onComplete.apply(chartInstance);
}
};
requestAnimFrame(animationFrame);
},
//-- DOM methods
getRelativePosition = helpers.getRelativePosition = function(evt){
var mouseX, mouseY;
var e = evt.originalEvent || evt,
canvas = evt.currentTarget || evt.srcElement,
boundingRect = canvas.getBoundingClientRect();
if (e.touches){
mouseX = e.touches[0].clientX - boundingRect.left;
mouseY = e.touches[0].clientY - boundingRect.top;
}
else{
mouseX = e.clientX - boundingRect.left;
mouseY = e.clientY - boundingRect.top;
}
return {
x : mouseX,
y : mouseY
};
},
addEvent = helpers.addEvent = function(node,eventType,method){
if (node.addEventListener){
node.addEventListener(eventType,method);
} else if (node.attachEvent){
node.attachEvent("on"+eventType, method);
} else {
node["on"+eventType] = method;
}
},
removeEvent = helpers.removeEvent = function(node, eventType, handler){
if (node.removeEventListener){
node.removeEventListener(eventType, handler, false);
} else if (node.detachEvent){
node.detachEvent("on"+eventType,handler);
} else{
node["on" + eventType] = noop;
}
},
bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
// Create the events object if it's not already present
if (!chartInstance.events) chartInstance.events = {};
each(arrayOfEvents,function(eventName){
chartInstance.events[eventName] = function(){
handler.apply(chartInstance, arguments);
};
addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
});
},
unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
each(arrayOfEvents, function(handler,eventName){
removeEvent(chartInstance.chart.canvas, eventName, handler);
});
},
getMaximumWidth = helpers.getMaximumWidth = function(domNode){
var container = domNode.parentNode;
// TODO = check cross browser stuff with this.
return container.clientWidth;
},
getMaximumHeight = helpers.getMaximumHeight = function(domNode){
var container = domNode.parentNode;
// TODO = check cross browser stuff with this.
return container.clientHeight;
},
getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
retinaScale = helpers.retinaScale = function(chart){
var ctx = chart.ctx,
width = chart.canvas.width,
height = chart.canvas.height;
//console.log(width + " x " + height);
if (window.devicePixelRatio) {
ctx.canvas.style.width = width + "px";
ctx.canvas.style.height = height + "px";
ctx.canvas.height = height * window.devicePixelRatio;
ctx.canvas.width = width * window.devicePixelRatio;
ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
}
},
//-- Canvas methods
clear = helpers.clear = function(chart){
chart.ctx.clearRect(0,0,chart.width,chart.height);
},
fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
return fontStyle + " " + pixelSize+"px " + fontFamily;
},
longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
ctx.font = font;
var longest = 0;
each(arrayOfStrings,function(string){
var textWidth = ctx.measureText(string).width;
longest = (textWidth > longest) ? textWidth : longest;
});
return longest;
},
drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
};
//Store a reference to each instance - allowing us to globally resize chart instances on window resize.
//Destroy method on the chart will remove the instance of the chart from this reference.
Chart.instances = {};
Chart.Type = function(data,options,chart){
this.options = options;
this.chart = chart;
this.id = uid();
//Add the chart instance to the global namespace
Chart.instances[this.id] = this;
// Initialize is always called when a chart type is created
// By default it is a no op, but it should be extended
if (options.responsive){
this.resize();
}
this.initialize.call(this,data);
};
//Core methods that'll be a part of every chart type
extend(Chart.Type.prototype,{
initialize : function(){return this;},
clear : function(){
clear(this.chart);
return this;
},
stop : function(){
// Stops any current animation loop occuring
helpers.cancelAnimFrame.call(root, this.animationFrame);
return this;
},
resize : function(callback){
this.stop();
var canvas = this.chart.canvas,
newWidth = getMaximumWidth(this.chart.canvas),
newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
canvas.width = this.chart.width = newWidth;
canvas.height = this.chart.height = newHeight;
retinaScale(this.chart);
if (typeof callback === "function"){
callback.apply(this, Array.prototype.slice.call(arguments, 1));
}
return this;
},
reflow : noop,
render : function(reflow){
if (reflow){
this.reflow();
}
if (this.options.animation && !reflow){
helpers.animationLoop(
this.draw,
this.options.animationSteps,
this.options.animationEasing,
this.options.onAnimationProgress,
this.options.onAnimationComplete,
this
);
}
else{
this.draw();
this.options.onAnimationComplete.call(this);
}
return this;
},
generateLegend : function(){
return template(this.options.legendTemplate,this);
},
destroy : function(){
this.clear();
unbindEvents(this, this.events);
delete Chart.instances[this.id];
},
showTooltip : function(ChartElements, forceRedraw){
// Only redraw the chart if we've actually changed what we're hovering on.
if (typeof this.activeElements === 'undefined') this.activeElements = [];
var isChanged = (function(Elements){
var changed = false;
if (Elements.length !== this.activeElements.length){
changed = true;
return changed;
}
each(Elements, function(element, index){
if (element !== this.activeElements[index]){
changed = true;
}
}, this);
return changed;
}).call(this, ChartElements);
if (!isChanged && !forceRedraw){
return;
}
else{
this.activeElements = ChartElements;
}
this.draw();
if (ChartElements.length > 0){
// If we have multiple datasets, show a MultiTooltip for all of the data points at that index
if (this.datasets && this.datasets.length > 1) {
var dataArray,
dataIndex;
for (var i = this.datasets.length - 1; i >= 0; i--) {
dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
dataIndex = indexOf(dataArray, ChartElements[0]);
if (dataIndex !== -1){
break;
}
}
var tooltipLabels = [],
tooltipColors = [],
medianPosition = (function(index) {
// Get all the points at that particular index
var Elements = [],
dataCollection,
xPositions = [],
yPositions = [],
xMax,
yMax,
xMin,
yMin;
helpers.each(this.datasets, function(dataset){
dataCollection = dataset.points || dataset.bars || dataset.segments;
if (dataCollection[dataIndex]){
Elements.push(dataCollection[dataIndex]);
}
});
helpers.each(Elements, function(element) {
xPositions.push(element.x);
yPositions.push(element.y);
//Include any colour information about the element
tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
tooltipColors.push({
fill: element._saved.fillColor || element.fillColor,
stroke: element._saved.strokeColor || element.strokeColor
});
}, this);
yMin = min(yPositions);
yMax = max(yPositions);
xMin = min(xPositions);
xMax = max(xPositions);
return {
x: (xMin > this.chart.width/2) ? xMin : xMax,
y: (yMin + yMax)/2
};
}).call(this, dataIndex);
new Chart.MultiTooltip({
x: medianPosition.x,
y: medianPosition.y,
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
xOffset: this.options.tooltipXOffset,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
titleTextColor: this.options.tooltipTitleFontColor,
titleFontFamily: this.options.tooltipTitleFontFamily,
titleFontStyle: this.options.tooltipTitleFontStyle,
titleFontSize: this.options.tooltipTitleFontSize,
cornerRadius: this.options.tooltipCornerRadius,
labels: tooltipLabels,
legendColors: tooltipColors,
legendColorBackground : this.options.multiTooltipKeyBackground,
title: ChartElements[0].label,
chart: this.chart,
ctx: this.chart.ctx
}).draw();
} else {
each(ChartElements, function(Element) {
var tooltipPosition = Element.tooltipPosition();
new Chart.Tooltip({
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
caretHeight: this.options.tooltipCaretSize,
cornerRadius: this.options.tooltipCornerRadius,
text: template(this.options.tooltipTemplate, Element),
chart: this.chart
}).draw();
}, this);
}
}
return this;
},
toBase64Image : function(){
return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
}
});
Chart.Type.extend = function(extensions){
var parent = this;
var ChartType = function(){
return parent.apply(this,arguments);
};
//Copy the prototype object of the this class
ChartType.prototype = clone(parent.prototype);
//Now overwrite some of the properties in the base class with the new extensions
extend(ChartType.prototype, extensions);
ChartType.extend = Chart.Type.extend;
if (extensions.name || parent.prototype.name){
var chartName = extensions.name || parent.prototype.name;
//Assign any potential default values of the new chart type
//If none are defined, we'll use a clone of the chart type this is being extended from.
//I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
//doesn't define some defaults of their own.
var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
Chart.types[chartName] = ChartType;
//Register this new chart type in the Chart prototype
Chart.prototype[chartName] = function(data,options){
var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
return new ChartType(data,config,this);
};
} else{
warn("Name not provided for this chart, so it hasn't been registered");
}
return parent;
};
Chart.Element = function(configuration){
extend(this,configuration);
this.initialize.apply(this,arguments);
this.save();
};
extend(Chart.Element.prototype,{
initialize : function(){},
restore : function(props){
if (!props){
extend(this,this._saved);
} else {
each(props,function(key){
this[key] = this._saved[key];
},this);
}
return this;
},
save : function(){
this._saved = clone(this);
delete this._saved._saved;
return this;
},
update : function(newProps){
each(newProps,function(value,key){
this._saved[key] = this[key];
this[key] = value;
},this);
return this;
},
transition : function(props,ease){
each(props,function(value,key){
this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
},this);
return this;
},
tooltipPosition : function(){
return {
x : this.x,
y : this.y
};
}
});
Chart.Element.extend = inherits;
Chart.Point = Chart.Element.extend({
display: true,
inRange: function(chartX,chartY){
var hitDetectionRange = this.hitDetectionRadius + this.radius;
return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
},
draw : function(){
if (this.display){
var ctx = this.ctx;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
ctx.closePath();
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
ctx.fillStyle = this.fillColor;
ctx.fill();
ctx.stroke();
}
//Quick debug for bezier curve splining
//Highlights control points and the line between them.
//Handy for dev - stripped in the min version.
// ctx.save();
// ctx.fillStyle = "black";
// ctx.strokeStyle = "black"
// ctx.beginPath();
// ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
// ctx.fill();
// ctx.beginPath();
// ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
// ctx.fill();
// ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
// ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
// ctx.stroke();
// ctx.restore();
}
});
Chart.Arc = Chart.Element.extend({
inRange : function(chartX,chartY){
var pointRelativePosition = helpers.getAngleFromPoint(this, {
x: chartX,
y: chartY
});
//Check if within the range of the open/close angle
var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle),
withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
return (betweenAngles && withinRadius);
//Ensure within the outside of the arc centre, but inside arc outer
},
tooltipPosition : function(){
var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
return {
x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
};
},
draw : function(animationPercent){
var easingDecimal = animationPercent || 1;
var ctx = this.ctx;
ctx.beginPath();
ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle);
ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true);
ctx.closePath();
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
ctx.fillStyle = this.fillColor;
ctx.fill();
ctx.lineJoin = 'bevel';
if (this.showStroke){
ctx.stroke();
}
}
});
Chart.Rectangle = Chart.Element.extend({
draw : function(){
var ctx = this.ctx,
halfWidth = this.width/2,
leftX = this.x - halfWidth,
rightX = this.x + halfWidth,
top = this.base - (this.base - this.y),
halfStroke = this.strokeWidth / 2;
// Canvas doesn't allow us to stroke inside the width so we can
// adjust the sizes to fit if we're setting a stroke on the line
if (this.showStroke){
leftX += halfStroke;
rightX -= halfStroke;
top += halfStroke;
}
ctx.beginPath();
ctx.fillStyle = this.fillColor;
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
// It'd be nice to keep this class totally generic to any rectangle
// and simply specify which border to miss out.
ctx.moveTo(leftX, this.base);
ctx.lineTo(leftX, top);
ctx.lineTo(rightX, top);
ctx.lineTo(rightX, this.base);
ctx.fill();
if (this.showStroke){
ctx.stroke();
}
},
height : function(){
return this.base - this.y;
},
inRange : function(chartX,chartY){
return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
}
});
Chart.Tooltip = Chart.Element.extend({
draw : function(){
var ctx = this.chart.ctx;
ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
this.xAlign = "center";
this.yAlign = "above";
//Distance between the actual element.y position and the start of the tooltip caret
var caretPadding = 2;
var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
tooltipRectHeight = this.fontSize + 2*this.yPadding,
tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
if (this.x + tooltipWidth/2 >this.chart.width){
this.xAlign = "left";
} else if (this.x - tooltipWidth/2 < 0){
this.xAlign = "right";
}
if (this.y - tooltipHeight < 0){
this.yAlign = "below";
}
var tooltipX = this.x - tooltipWidth/2,
tooltipY = this.y - tooltipHeight;
ctx.fillStyle = this.fillColor;
switch(this.yAlign)
{
case "above":
//Draw a caret above the x/y
ctx.beginPath();
ctx.moveTo(this.x,this.y - caretPadding);
ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
ctx.closePath();
ctx.fill();
break;
case "below":
tooltipY = this.y + caretPadding + this.caretHeight;
//Draw a caret below the x/y
ctx.beginPath();
ctx.moveTo(this.x, this.y + caretPadding);
ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
ctx.closePath();
ctx.fill();
break;
}
switch(this.xAlign)
{
case "left":
tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
break;
case "right":
tooltipX = this.x - (this.cornerRadius + this.caretHeight);
break;
}
drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
ctx.fill();
ctx.fillStyle = this.textColor;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
}
});
Chart.MultiTooltip = Chart.Element.extend({
initialize : function(){
this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5;
this.ctx.font = this.titleFont;
var titleWidth = this.ctx.measureText(this.title).width,
//Label has a legend square as well so account for this.
labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
longestTextWidth = max([labelWidth,titleWidth]);
this.width = longestTextWidth + (this.xPadding*2);
var halfHeight = this.height/2;
//Check to ensure the height will fit on the canvas
//The three is to buffer form the very
if (this.y - halfHeight < 0 ){
this.y = halfHeight;
} else if (this.y + halfHeight > this.chart.height){
this.y = this.chart.height - halfHeight;
}
//Decide whether to align left or right based on position on canvas
if (this.x > this.chart.width/2){
this.x -= this.xOffset + this.width;
} else {
this.x += this.xOffset;
}
},
getLineHeight : function(index){
var baseLineHeight = this.y - (this.height/2) + this.yPadding,
afterTitleIndex = index-1;
//If the index is zero, we're getting the title
if (index === 0){
return baseLineHeight + this.titleFontSize/2;
} else{
return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5;
}
},
draw : function(){
drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
var ctx = this.ctx;
ctx.fillStyle = this.fillColor;
ctx.fill();
ctx.closePath();
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillStyle = this.titleTextColor;
ctx.font = this.titleFont;
ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
ctx.font = this.font;
helpers.each(this.labels,function(label,index){
ctx.fillStyle = this.textColor;
ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
//A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
//ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
//Instead we'll make a white filled block to put the legendColour palette over.
ctx.fillStyle = this.legendColorBackground;
ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
ctx.fillStyle = this.legendColors[index].fill;
ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
},this);
}
});
Chart.Scale = Chart.Element.extend({
initialize : function(){
this.fit();
},
buildYLabels : function(){
this.yLabels = [];
var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
for (var i=0; i<=this.steps; i++){
this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
}
this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) : 0;
this.yLabelWidth += 40;
},
addXLabel : function(label){
this.xLabels.push(label);
this.valuesCount++;
this.fit();
},
removeXLabel : function(){
this.xLabels.shift();
this.valuesCount--;
this.fit();
},
// Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
fit: function(){
// First we need the width of the yLabels, assuming the xLabels aren't rotated
// To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
this.startPoint = (this.display) ? this.fontSize : 0;
this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
// Apply padding settings to the start and end point.
this.startPoint += this.padding;
this.endPoint -= this.padding;
// Cache the starting height, so can determine if we need to recalculate the scale yAxis
var cachedHeight = this.endPoint - this.startPoint,
cachedYLabelWidth;
// Build the current yLabels so we have an idea of what size they'll be to start
/*
* This sets what is returned from calculateScaleRange as static properties of this class:
*
this.steps;
this.stepValue;
this.min;
this.max;
*
*/
this.calculateYRange(cachedHeight);
// With these properties set we can now build the array of yLabels
// and also the width of the largest yLabel
this.buildYLabels();
this.calculateXLabelRotation();
while((cachedHeight > this.endPoint - this.startPoint)){
cachedHeight = this.endPoint - this.startPoint;
cachedYLabelWidth = this.yLabelWidth;
this.calculateYRange(cachedHeight);
this.buildYLabels();
// Only go through the xLabel loop again if the yLabel width has changed
if (cachedYLabelWidth < this.yLabelWidth){
this.calculateXLabelRotation();
}
}
},
calculateXLabelRotation : function(){
//Get the width of each grid by calculating the difference
//between x offsets between 0 and 1.
this.ctx.font = this.font;
var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
firstRotated,
lastRotated;
this.xScalePaddingRight = lastWidth/2 + 3;
this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth + 10) ? firstWidth/2 : this.yLabelWidth + 10;
this.xLabelRotation = 0;
if (this.display){
var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
cosRotation,
firstRotatedWidth;
this.xLabelWidth = originalLabelWidth;
//Allow 3 pixels x2 padding either side for label readability
var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
//Max label rotate should be 90 - also act as a loop counter
while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
cosRotation = Math.cos(toRadians(this.xLabelRotation));
firstRotated = cosRotation * firstWidth;
lastRotated = cosRotation * lastWidth;
// We're right aligning the text now.
if (firstRotated + this.fontSize / 2 > this.yLabelWidth + 8){
this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
}
this.xScalePaddingRight = this.fontSize/2;
this.xLabelRotation++;
this.xLabelWidth = cosRotation * originalLabelWidth;
}
if (this.xLabelRotation > 0){
this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
}
this.endPoint -= 40; // for x axis label
}
else{
this.xLabelWidth = 0;
this.xScalePaddingRight = this.padding;
this.xScalePaddingLeft = this.padding;
}
},
// Needs to be overidden in each Chart type
// Otherwise we need to pass all the data into the scale class
calculateYRange: noop,
drawingArea: function(){
return this.startPoint - this.endPoint;
},
calculateY : function(value){
var scalingFactor = this.drawingArea() / (this.min - this.max);
return this.endPoint - (scalingFactor * (value - this.min));
},
calculateX : function(index){
var isRotated = (this.xLabelRotation > 0),
// innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
valueCalculatedWidth = innerWidth/(this.valuesCount - ((this.offsetGridLines) ? 0 : 1)),
valueWidth = this.valueCustomMaxWidth ? Math.min(this.valueMaxWidth, valueCalculatedWidth) : valueCalculatedWidth,
valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
if (this.offsetGridLines){
valueOffset += (valueWidth/2);
}
return Math.round(valueOffset);
},
update : function(newProps){
helpers.extend(this, newProps);
this.fit();
},
draw : function(){
var ctx = this.ctx,
yLabelGap = (this.endPoint - this.startPoint) / this.steps,
xStart = Math.round(this.xScalePaddingLeft);
if (this.display){
ctx.fillStyle = this.textColor;
ctx.font = this.font;
each(this.yLabels,function(labelString,index){
var yLabelCenter = this.endPoint - (yLabelGap * index),
linePositionY = Math.round(yLabelCenter);
ctx.textAlign = "right";
ctx.textBaseline = "middle";
if (this.showLabels){
ctx.fillText(labelString,xStart - 10,yLabelCenter);
}
ctx.beginPath();
if (index > 0){
// This is a grid line in the centre, so drop that
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
} else {
// This is the first line on the scale
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
}
linePositionY += helpers.aliasPixel(ctx.lineWidth);
ctx.moveTo(xStart, linePositionY);
ctx.lineTo(this.width, linePositionY);
ctx.stroke();
ctx.closePath();
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
ctx.beginPath();
ctx.moveTo(xStart - 5, linePositionY);
ctx.lineTo(xStart, linePositionY);
ctx.stroke();
ctx.closePath();
},this);
each(this.xLabels,function(label,index){
var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
// Check to see if line/bar here and decide where to place the line
linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
isRotated = (this.xLabelRotation > 0);
ctx.beginPath();
if (index > 0){
// This is a grid line in the centre, so drop that
ctx.lineWidth = this.gridLineWidth;
ctx.strokeStyle = this.gridLineColor;
} else {
// This is the first line on the scale
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
}
ctx.moveTo(linePos,this.endPoint);
ctx.lineTo(linePos,this.startPoint - 3);
ctx.stroke();
ctx.closePath();
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.lineColor;
// Small lines at the bottom of the base grid line
ctx.beginPath();
ctx.moveTo(linePos,this.endPoint);
ctx.lineTo(linePos,this.endPoint + 5);
ctx.stroke();
ctx.closePath();
ctx.save();
ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
ctx.rotate(toRadians(this.xLabelRotation)*-1);
ctx.font = this.font;
ctx.textAlign = (isRotated) ? "right" : "center";
ctx.textBaseline = (isRotated) ? "middle" : "top";
ctx.fillText(label, 0, 0);
ctx.restore();
},this);
// Print X axis
if (this.xAxisLabel) {
ctx.save();
var yPos = this.endPoint + 40;
ctx.font = this.font;
ctx.textAlign = "center";
ctx.textBaseline = "top";
ctx.translate(this.xScalePaddingLeft + ((this.width - this.xScalePaddingLeft) / 2), yPos);
ctx.fillText(this.xAxisLabel, 0, 0);
ctx.restore();
}
// Print Y axis
if (this.yAxisLabel) {
ctx.save();
ctx.font = this.font;
ctx.textAlign = "center";
ctx.textBaseline = "top";
ctx.translate(0, this.height / 2);
ctx.rotate(toRadians(90)*-1);
ctx.fillText(this.yAxisLabel, 0, 0);
ctx.restore();
}
}
}
});
Chart.RadialScale = Chart.Element.extend({
initialize: function(){
this.size = min([this.height, this.width]);
this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
},
calculateCenterOffset: function(value){
// Take into account half font size + the yPadding of the top value
var scalingFactor = this.drawingArea / (this.max - this.min);
return (value - this.min) * scalingFactor;
},
update : function(){
if (!this.lineArc){
this.setScaleSize();
} else {
this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
}
this.buildYLabels();
},
buildYLabels: function(){
this.yLabels = [];
var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
for (var i=0; i<=this.steps; i++){
this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
}
},
getCircumference : function(){
return ((Math.PI*2) / this.valuesCount);
},
setScaleSize: function(){
/*
* Right, this is really confusing and there is a lot of maths going on here
* The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
*
* Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
*
* Solution:
*
* We assume the radius of the polygon is half the size of the canvas at first
* at each index we check if the text overlaps.
*
* Where it does, we store that angle and that index.
*
* After finding the largest index and angle we calculate how much we need to remove
* from the shape radius to move the point inwards by that x.
*
* We average the left and right distances to get the maximum shape radius that can fit in the box
* along with labels.
*
* Once we have that, we can find the centre point for the chart, by taking the x text protrusion
* on each side, removing that from the size, halving it and adding the left x protrusion width.
*
* This will mean we have a shape fitted to the canvas, as large as it can be with the labels
* and position it in the most space efficient manner
*
* https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
*/
// Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
// Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 10), this.width/2]),
pointPosition,
i,
textWidth,
halfTextWidth,
furthestRight = this.width,
furthestRightIndex,
furthestRightAngle,
furthestLeft = 0,
furthestLeftIndex,
furthestLeftAngle,
xProtrusionLeft,
xProtrusionRight,
radiusReductionRight,
radiusReductionLeft,
maxWidthRadius;
this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
for (i=0;i<this.valuesCount;i++){
// 5px to space the text slightly out - similar to what we do in the draw function.
pointPosition = this.getPointPosition(i, largestPossibleRadius);
textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
if (i === 0 || i === this.valuesCount/2){
// If we're at index zero, or exactly the middle, we're at exactly the top/bottom
// of the radar chart, so text will be aligned centrally, so we'll half it and compare
// w/left and right text sizes
halfTextWidth = textWidth/2;
if (pointPosition.x + halfTextWidth > furthestRight) {
furthestRight = pointPosition.x + halfTextWidth;
furthestRightIndex = i;
}
if (pointPosition.x - halfTextWidth < furthestLeft) {
furthestLeft = pointPosition.x - halfTextWidth;
furthestLeftIndex = i;
}
}
else if (i < this.valuesCount/2) {
// Less than half the values means we'll left align the text
if (pointPosition.x + textWidth > furthestRight) {
furthestRight = pointPosition.x + textWidth;
furthestRightIndex = i;
}
}
else if (i > this.valuesCount/2){
// More than half the values means we'll right align the text
if (pointPosition.x - textWidth < furthestLeft) {
furthestLeft = pointPosition.x - textWidth;
furthestLeftIndex = i;
}
}
}
xProtrusionLeft = furthestLeft;
xProtrusionRight = Math.ceil(furthestRight - this.width);
furthestRightAngle = this.getIndexAngle(furthestRightIndex);
furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
// Ensure we actually need to reduce the size of the chart
radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
//this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
},
setCenterPoint: function(leftMovement, rightMovement){
var maxRight = this.width - rightMovement - this.drawingArea,
maxLeft = leftMovement + this.drawingArea;
this.xCenter = (maxLeft + maxRight)/2;
// Always vertically in the centre as the text height doesn't change
this.yCenter = (this.height/2);
},
getIndexAngle : function(index){
var angleMultiplier = (Math.PI * 2) / this.valuesCount;
// Start from the top instead of right, so remove a quarter of the circle
return index * angleMultiplier - (Math.PI/2);
},
getPointPosition : function(index, distanceFromCenter){
var thisAngle = this.getIndexAngle(index);
return {
x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
};
},
draw: function(){
if (this.display){
var ctx = this.ctx;
each(this.yLabels, function(label, index){
// Don't draw a centre value
if (index > 0){
var yCenterOffset = index * (this.drawingArea/this.steps),
yHeight = this.yCenter - yCenterOffset,
pointPosition;
// Draw circular lines around the scale
if (this.lineWidth > 0){
ctx.strokeStyle = this.lineColor;
ctx.lineWidth = this.lineWidth;
if(this.lineArc){
ctx.beginPath();
ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
ctx.closePath();
ctx.stroke();
} else{
ctx.beginPath();
for (var i=0;i<this.valuesCount;i++)
{
pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
if (i === 0){
ctx.moveTo(pointPosition.x, pointPosition.y);
} else {
ctx.lineTo(pointPosition.x, pointPosition.y);
}
}
ctx.closePath();
ctx.stroke();
}
}
if(this.showLabels){
ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
if (this.showLabelBackdrop){
var labelWidth = ctx.measureText(label).width;
ctx.fillStyle = this.backdropColor;
ctx.fillRect(
this.xCenter - labelWidth/2 - this.backdropPaddingX,
yHeight - this.fontSize/2 - this.backdropPaddingY,
labelWidth + this.backdropPaddingX*2,
this.fontSize + this.backdropPaddingY*2
);
}
ctx.textAlign = 'center';
ctx.textBaseline = "middle";
ctx.fillStyle = this.fontColor;
ctx.fillText(label, this.xCenter, yHeight);
}
}
}, this);
if (!this.lineArc){
ctx.lineWidth = this.angleLineWidth;
ctx.strokeStyle = this.angleLineColor;
for (var i = this.valuesCount - 1; i >= 0; i--) {
if (this.angleLineWidth > 0){
var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max));
ctx.beginPath();
ctx.moveTo(this.xCenter, this.yCenter);
ctx.lineTo(outerPosition.x, outerPosition.y);
ctx.stroke();
ctx.closePath();
}
// Extra 3px out for some label spacing
var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
ctx.fillStyle = this.pointLabelFontColor;
var labelsCount = this.labels.length,
halfLabelsCount = this.labels.length/2,
quarterLabelsCount = halfLabelsCount/2,
upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
if (i === 0){
ctx.textAlign = 'center';
} else if(i === halfLabelsCount){
ctx.textAlign = 'center';
} else if (i < halfLabelsCount){
ctx.textAlign = 'left';
} else {
ctx.textAlign = 'right';
}
// Set the correct text baseline based on outer positioning
if (exactQuarter){
ctx.textBaseline = 'middle';
} else if (upperHalf){
ctx.textBaseline = 'bottom';
} else {
ctx.textBaseline = 'top';
}
ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
}
}
}
}
});
// Attach global event to resize each chart instance when the browser resizes
helpers.addEvent(window, "resize", (function(){
// Basic debounce of resize function so it doesn't hurt performance when resizing browser.
var timeout;
return function(){
clearTimeout(timeout);
timeout = setTimeout(function(){
each(Chart.instances,function(instance){
// If the responsive flag is set in the chart instance config
// Cascade the resize event down to the chart.
if (instance.options.responsive){
instance.resize(instance.render, true);
}
});
}, 50);
};
})());
if (amd) {
define(function(){
return Chart;
});
} else if (typeof module === 'object' && module.exports) {
module.exports = Chart;
}
root.Chart = Chart;
Chart.noConflict = function(){
root.Chart = previous;
return Chart;
};
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
helpers = Chart.helpers;
var defaultConfig = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
};
Chart.Type.extend({
name: "Bar",
defaults : defaultConfig,
initialize: function(data){
//Expose options as a scope variable here so we can access it in the ScaleClass
var options = this.options;
// Labels
this.options.xAxisLabel = data.xAxisLabel || false;
this.options.yAxisLabel = data.yAxisLabel || false;
this.ScaleClass = Chart.Scale.extend({
offsetGridLines : true,
calculateBarX : function(datasetCount, datasetIndex, barIndex){
//Reusable method for calculating the xPosition of a given bar based on datasetIndex & width of the bar
var xWidth = this.calculateBaseWidth(),
xAbsolute = this.calculateX(barIndex) - (xWidth/2),
barWidth = this.calculateBarWidth(datasetCount);
return xAbsolute + (barWidth * datasetIndex) + (datasetIndex * options.barDatasetSpacing) + barWidth/2;
},
calculateBaseWidth : function(){
return (this.calculateX(1) - this.calculateX(0)) - (2*options.barValueSpacing);
},
calculateBarWidth : function(datasetCount){
//The padding between datasets is to the right of each bar, providing that there are more than 1 dataset
var baseWidth = this.calculateBaseWidth() - ((datasetCount - 1) * options.barDatasetSpacing);
return (baseWidth / datasetCount);
}
});
this.datasets = [];
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activeBars = (evt.type !== 'mouseout') ? this.getBarsAtEvent(evt) : [];
this.eachBars(function(bar){
bar.restore(['fillColor', 'strokeColor']);
});
helpers.each(activeBars, function(activeBar){
activeBar.fillColor = activeBar.highlightFill;
activeBar.strokeColor = activeBar.highlightStroke;
});
this.showTooltip(activeBars);
});
}
//Declare the extension of the default point, to cater for the options passed in to the constructor
this.BarClass = Chart.Rectangle.extend({
strokeWidth : this.options.barStrokeWidth,
showStroke : this.options.barShowStroke,
ctx : this.chart.ctx
});
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets,function(dataset,datasetIndex){
var datasetObject = {
label : dataset.label || null,
fillColor : dataset.fillColor,
strokeColor : dataset.strokeColor,
bars : []
};
datasetObject._custom = dataset._custom || {};
this.datasets.push(datasetObject);
helpers.each(dataset.data,function(dataPoint,index){
if (helpers.isNumber(dataPoint)){
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.bars.push(new this.BarClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.strokeColor,
fillColor : dataset.fillColor,
highlightFill : dataset.highlightFill || dataset.fillColor,
highlightStroke : dataset.highlightStroke || dataset.strokeColor
}));
}
},this);
},this);
this.buildScale(data.labels);
this.BarClass.prototype.base = this.scale.endPoint;
this.eachBars(function(bar, index, datasetIndex){
helpers.extend(bar, {
width : this.scale.calculateBarWidth(this.datasets.length),
x: this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
y: this.scale.endPoint
});
bar.save();
}, this);
this.render();
},
update : function(){
this.scale.update();
// Reset any highlight colours before updating.
helpers.each(this.activeElements, function(activeElement){
activeElement.restore(['fillColor', 'strokeColor']);
});
this.eachBars(function(bar){
bar.save();
});
this.render();
},
eachBars : function(callback){
helpers.each(this.datasets,function(dataset, datasetIndex){
helpers.each(dataset.bars, callback, this, datasetIndex);
},this);
},
getBarsAtEvent : function(e){
var barsArray = [],
eventPosition = helpers.getRelativePosition(e),
datasetIterator = function(dataset){
barsArray.push(dataset.bars[barIndex]);
},
barIndex;
for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
helpers.each(this.datasets, datasetIterator);
return barsArray;
}
}
}
return barsArray;
},
buildScale : function(labels){
var self = this;
var dataTotal = function(){
var values = [];
self.eachBars(function(bar){
values.push(bar.value);
});
return values;
};
var scaleOptions = {
templateString : this.options.scaleLabel,
height : this.chart.height,
width : this.chart.width,
ctx : this.chart.ctx,
textColor : this.options.scaleFontColor,
fontSize : this.options.scaleFontSize,
fontStyle : this.options.scaleFontStyle,
fontFamily : this.options.scaleFontFamily,
valuesCount : labels.length,
beginAtZero : this.options.scaleBeginAtZero,
integersOnly : this.options.scaleIntegersOnly,
calculateYRange: function(currentHeight){
var updatedRanges = helpers.calculateScaleRange(
dataTotal(),
currentHeight,
this.fontSize,
this.beginAtZero,
this.integersOnly
);
helpers.extend(this, updatedRanges);
},
xLabels : labels,
font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
lineWidth : this.options.scaleLineWidth,
lineColor : this.options.scaleLineColor,
gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
padding : (this.options.showScale) ? 0 : (this.options.barShowStroke) ? this.options.barStrokeWidth : 0,
showLabels : this.options.scaleShowLabels,
valueCustomMaxWidth : this.options.scaleValueCustomMaxWidth,
valueMaxWidth : this.options.scaleValueMaxWidth,
display : this.options.showScale,
xAxisLabel: this.options.xAxisLabel,
yAxisLabel: this.options.yAxisLabel
};
if (this.options.scaleOverride){
helpers.extend(scaleOptions, {
calculateYRange: helpers.noop,
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
});
}
this.scale = new this.ScaleClass(scaleOptions);
},
addData : function(valuesArray,label){
//Map the values array for each of the datasets
helpers.each(valuesArray,function(value,datasetIndex){
if (helpers.isNumber(value)){
//Add a new point for each piece of data, passing any required data to draw.
this.datasets[datasetIndex].bars.push(new this.BarClass({
value : value,
label : label,
x: this.scale.calculateBarX(this.datasets.length, datasetIndex, this.scale.valuesCount+1),
y: this.scale.endPoint,
width : this.scale.calculateBarWidth(this.datasets.length),
base : this.scale.endPoint,
strokeColor : this.datasets[datasetIndex].strokeColor,
fillColor : this.datasets[datasetIndex].fillColor
}));
}
},this);
this.scale.addXLabel(label);
//Then re-render the chart.
this.update();
},
removeData : function(){
this.scale.removeXLabel();
//Then re-render the chart.
helpers.each(this.datasets,function(dataset){
dataset.bars.shift();
},this);
this.update();
},
reflow : function(){
helpers.extend(this.BarClass.prototype,{
y: this.scale.endPoint,
base : this.scale.endPoint
});
var newScaleProps = helpers.extend({
height : this.chart.height,
width : this.chart.width
});
this.scale.update(newScaleProps);
},
draw : function(ease){
var easingDecimal = ease || 1;
this.clear();
var ctx = this.chart.ctx;
this.scale.draw(easingDecimal);
//Draw all the bars for each dataset
helpers.each(this.datasets,function(dataset,datasetIndex){
helpers.each(dataset.bars,function(bar,index){
bar.base = this.scale.endPoint;
//Transition then draw
bar.transition({
x : this.scale.calculateBarX(this.datasets.length, datasetIndex, index),
y : this.scale.calculateY(bar.value),
width : this.scale.calculateBarWidth(this.datasets.length)
}, easingDecimal).draw();
},this);
},this);
}
});
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
//Cache a local reference to Chart.helpers
helpers = Chart.helpers;
var defaultConfig = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke : true,
//String - The colour of each segment stroke
segmentStrokeColor : "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth : 2,
//The percentage of the chart that we cut out of the middle.
percentageInnerCutout : 50,
//Number - Amount of animation steps
animationSteps : 100,
//String - Animation easing effect
animationEasing : "easeOutBounce",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate : true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale : false,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
};
Chart.Type.extend({
//Passing in a name registers this chart in the Chart namespace
name: "Doughnut",
//Providing a defaults will also register the deafults in the chart namespace
defaults : defaultConfig,
//Initialize is fired when the chart is initialized - Data is passed in as a parameter
//Config is automatically merged by the core of Chart.js, and is available at this.options
initialize: function(data){
//Declare segments as a static property to prevent inheriting across the Chart type prototype
this.segments = [];
this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
this.SegmentArc = Chart.Arc.extend({
ctx : this.chart.ctx,
x : this.chart.width/2,
y : this.chart.height/2
});
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
helpers.each(this.segments,function(segment){
segment.restore(["fillColor"]);
});
helpers.each(activeSegments,function(activeSegment){
activeSegment.fillColor = activeSegment.highlightColor;
});
this.showTooltip(activeSegments);
});
}
this.calculateTotal(data);
helpers.each(data,function(datapoint, index){
this.addData(datapoint, index, true);
},this);
this.render();
},
getSegmentsAtEvent : function(e){
var segmentsArray = [];
var location = helpers.getRelativePosition(e);
helpers.each(this.segments,function(segment){
if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
},this);
return segmentsArray;
},
addData : function(segment, atIndex, silent){
var index = atIndex || this.segments.length;
this.segments.splice(index, 0, new this.SegmentArc({
value : segment.value,
outerRadius : (this.options.animateScale) ? 0 : this.outerRadius,
innerRadius : (this.options.animateScale) ? 0 : (this.outerRadius/100) * this.options.percentageInnerCutout,
fillColor : segment.color,
highlightColor : segment.highlight || segment.color,
showStroke : this.options.segmentShowStroke,
strokeWidth : this.options.segmentStrokeWidth,
strokeColor : this.options.segmentStrokeColor,
startAngle : Math.PI * 1.5,
circumference : (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
label : segment.label
}));
if (!silent){
this.reflow();
this.update();
}
},
calculateCircumference : function(value){
return (Math.PI*2)*(value / this.total);
},
calculateTotal : function(data){
this.total = 0;
helpers.each(data,function(segment){
this.total += segment.value;
},this);
},
update : function(){
this.calculateTotal(this.segments);
// Reset any highlight colours before updating.
helpers.each(this.activeElements, function(activeElement){
activeElement.restore(['fillColor']);
});
helpers.each(this.segments,function(segment){
segment.save();
});
this.render();
},
removeData: function(atIndex){
var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
this.segments.splice(indexToDelete, 1);
this.reflow();
this.update();
},
reflow : function(){
helpers.extend(this.SegmentArc.prototype,{
x : this.chart.width/2,
y : this.chart.height/2
});
this.outerRadius = (helpers.min([this.chart.width,this.chart.height]) - this.options.segmentStrokeWidth/2)/2;
helpers.each(this.segments, function(segment){
segment.update({
outerRadius : this.outerRadius,
innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
});
}, this);
},
draw : function(easeDecimal){
var animDecimal = (easeDecimal) ? easeDecimal : 1;
this.clear();
helpers.each(this.segments,function(segment,index){
segment.transition({
circumference : this.calculateCircumference(segment.value),
outerRadius : this.outerRadius,
innerRadius : (this.outerRadius/100) * this.options.percentageInnerCutout
},animDecimal);
segment.endAngle = segment.startAngle + segment.circumference;
segment.draw();
if (index === 0){
segment.startAngle = Math.PI * 1.5;
}
//Check to see if it's the last segment, if not get the next and update the start angle
if (index < this.segments.length-1){
this.segments[index+1].startAngle = segment.endAngle;
}
},this);
}
});
Chart.types.Doughnut.extend({
name : "Pie",
defaults : helpers.merge(defaultConfig,{percentageInnerCutout : 0})
});
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
helpers = Chart.helpers;
var defaultConfig = {
///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether the line is curved between points
bezierCurve : true,
//Number - Tension of the bezier curve between points
bezierCurveTension : 0.4,
//Boolean - Whether to show a dot for each point
pointDot : true,
//Number - Radius of each point dot in pixels
pointDotRadius : 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius : 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill : true,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
};
Chart.Type.extend({
name: "Line",
defaults : defaultConfig,
initialize: function(data){
//Declare the extension of the default point, to cater for the options passed in to the constructor
this.PointClass = Chart.Point.extend({
strokeWidth : this.options.pointDotStrokeWidth,
radius : this.options.pointDotRadius,
display: this.options.pointDot,
hitDetectionRadius : this.options.pointHitDetectionRadius,
ctx : this.chart.ctx,
inRange : function(mouseX){
return (Math.pow(mouseX-this.x, 2) < Math.pow(this.radius + this.hitDetectionRadius,2));
}
});
this.datasets = [];
// Labels
this.options.xAxisLabel = data.xAxisLabel || false;
this.options.yAxisLabel = data.yAxisLabel || false;
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activePoints = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
this.eachPoints(function(point){
point.restore(['fillColor', 'strokeColor']);
});
helpers.each(activePoints, function(activePoint){
activePoint.fillColor = activePoint.highlightFill;
activePoint.strokeColor = activePoint.highlightStroke;
});
this.showTooltip(activePoints);
});
}
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets,function(dataset){
var datasetObject = {
label : dataset.label || null,
fillColor : dataset.fillColor,
strokeColor : dataset.strokeColor,
pointColor : dataset.pointColor,
pointStrokeColor : dataset.pointStrokeColor,
points : []
};
datasetObject._custom = dataset._custom || {};
this.datasets.push(datasetObject);
helpers.each(dataset.data,function(dataPoint,index){
//Best way to do this? or in draw sequence...?
if (helpers.isNumber(dataPoint)){
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.points.push(new this.PointClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.pointStrokeColor,
fillColor : dataset.pointColor,
highlightFill : dataset.pointHighlightFill || dataset.pointColor,
highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
}));
}
},this);
this.buildScale(data.labels);
this.eachPoints(function(point, index){
helpers.extend(point, {
x: this.scale.calculateX(index),
y: this.scale.endPoint
});
point.save();
}, this);
},this);
this.render();
},
update : function(){
this.scale.update();
// Reset any highlight colours before updating.
helpers.each(this.activeElements, function(activeElement){
activeElement.restore(['fillColor', 'strokeColor']);
});
this.eachPoints(function(point){
point.save();
});
this.render();
},
eachPoints : function(callback){
helpers.each(this.datasets,function(dataset){
helpers.each(dataset.points,callback,this);
},this);
},
getPointsAtEvent : function(e){
var pointsArray = [],
eventPosition = helpers.getRelativePosition(e);
helpers.each(this.datasets,function(dataset){
helpers.each(dataset.points,function(point){
if (point.inRange(eventPosition.x,eventPosition.y)) pointsArray.push(point);
});
},this);
return pointsArray;
},
buildScale : function(labels){
var self = this;
var dataTotal = function(){
var values = [];
self.eachPoints(function(point){
values.push(point.value);
});
return values;
};
var scaleOptions = {
templateString : this.options.scaleLabel,
height : this.chart.height,
width : this.chart.width,
ctx : this.chart.ctx,
textColor : this.options.scaleFontColor,
fontSize : this.options.scaleFontSize,
fontStyle : this.options.scaleFontStyle,
fontFamily : this.options.scaleFontFamily,
valuesCount : labels.length,
beginAtZero : this.options.scaleBeginAtZero,
integersOnly : this.options.scaleIntegersOnly,
calculateYRange : function(currentHeight){
var updatedRanges = helpers.calculateScaleRange(
dataTotal(),
currentHeight,
this.fontSize,
this.beginAtZero,
this.integersOnly
);
helpers.extend(this, updatedRanges);
},
xLabels : labels,
font : helpers.fontString(this.options.scaleFontSize, this.options.scaleFontStyle, this.options.scaleFontFamily),
lineWidth : this.options.scaleLineWidth,
lineColor : this.options.scaleLineColor,
gridLineWidth : (this.options.scaleShowGridLines) ? this.options.scaleGridLineWidth : 0,
gridLineColor : (this.options.scaleShowGridLines) ? this.options.scaleGridLineColor : "rgba(0,0,0,0)",
padding: (this.options.showScale) ? 0 : this.options.pointDotRadius + this.options.pointDotStrokeWidth,
showLabels : this.options.scaleShowLabels,
valueCustomMaxWidth : this.options.scaleValueCustomMaxWidth,
valueMaxWidth : this.options.scaleValueMaxWidth,
display : this.options.showScale,
xAxisLabel: this.options.xAxisLabel,
yAxisLabel: this.options.yAxisLabel
};
if (this.options.scaleOverride){
helpers.extend(scaleOptions, {
calculateYRange: helpers.noop,
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
});
}
this.scale = new Chart.Scale(scaleOptions);
},
addData : function(valuesArray,label){
//Map the values array for each of the datasets
helpers.each(valuesArray,function(value,datasetIndex){
if (helpers.isNumber(value)){
//Add a new point for each piece of data, passing any required data to draw.
this.datasets[datasetIndex].points.push(new this.PointClass({
value : value,
label : label,
x: this.scale.calculateX(this.scale.valuesCount+1),
y: this.scale.endPoint,
strokeColor : this.datasets[datasetIndex].pointStrokeColor,
fillColor : this.datasets[datasetIndex].pointColor
}));
}
},this);
this.scale.addXLabel(label);
//Then re-render the chart.
this.update();
},
removeData : function(){
this.scale.removeXLabel();
//Then re-render the chart.
helpers.each(this.datasets,function(dataset){
dataset.points.shift();
},this);
this.update();
},
reflow : function(){
var newScaleProps = helpers.extend({
height : this.chart.height,
width : this.chart.width
});
this.scale.update(newScaleProps);
},
draw : function(ease){
var easingDecimal = ease || 1;
this.clear();
var ctx = this.chart.ctx;
this.scale.draw(easingDecimal);
helpers.each(this.datasets,function(dataset){
//Transition each point first so that the line and point drawing isn't out of sync
//We can use this extra loop to calculate the control points of this dataset also in this loop
helpers.each(dataset.points,function(point,index){
point.transition({
y : this.scale.calculateY(point.value),
x : this.scale.calculateX(index)
}, easingDecimal);
},this);
// Control points need to be calculated in a seperate loop, because we need to know the current x/y of the point
// This would cause issues when there is no animation, because the y of the next point would be 0, so beziers would be skewed
if (this.options.bezierCurve){
helpers.each(dataset.points,function(point,index){
//If we're at the start or end, we don't have a previous/next point
//By setting the tension to 0 here, the curve will transition to straight at the end
if (index === 0){
point.controlPoints = helpers.splineCurve(point,point,dataset.points[index+1],0);
}
else if (index >= dataset.points.length-1){
point.controlPoints = helpers.splineCurve(dataset.points[index-1],point,point,0);
}
else{
point.controlPoints = helpers.splineCurve(dataset.points[index-1],point,dataset.points[index+1],this.options.bezierCurveTension);
}
},this);
}
//Draw the line between all the points
ctx.lineWidth = this.options.datasetStrokeWidth;
ctx.strokeStyle = dataset.strokeColor;
ctx.beginPath();
helpers.each(dataset.points,function(point,index){
if (index>0){
if(this.options.bezierCurve){
ctx.bezierCurveTo(
dataset.points[index-1].controlPoints.outer.x,
dataset.points[index-1].controlPoints.outer.y,
point.controlPoints.inner.x,
point.controlPoints.inner.y,
point.x,
point.y
);
}
else{
ctx.lineTo(point.x,point.y);
}
}
else{
ctx.moveTo(point.x,point.y);
}
},this);
ctx.stroke();
if (this.options.datasetFill){
//Round off the line by going to the base of the chart, back to the start, then fill.
ctx.lineTo(dataset.points[dataset.points.length-1].x, this.scale.endPoint);
ctx.lineTo(this.scale.calculateX(0), this.scale.endPoint);
ctx.fillStyle = dataset.fillColor;
ctx.closePath();
ctx.fill();
}
//Now draw the points over the line
//A little inefficient double looping, but better than the line
//lagging behind the point positions
helpers.each(dataset.points,function(point){
point.draw();
});
},this);
}
});
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
//Cache a local reference to Chart.helpers
helpers = Chart.helpers;
var defaultConfig = {
//Boolean - Show a backdrop to the scale label
scaleShowLabelBackdrop : true,
//String - The colour of the label backdrop
scaleBackdropColor : "rgba(255,255,255,0.75)",
// Boolean - Whether the scale should begin at zero
scaleBeginAtZero : true,
//Number - The backdrop padding above & below the label in pixels
scaleBackdropPaddingY : 2,
//Number - The backdrop padding to the side of the label in pixels
scaleBackdropPaddingX : 2,
//Boolean - Show line for each value in the scale
scaleShowLine : true,
//Boolean - Stroke a line around each segment in the chart
segmentShowStroke : true,
//String - The colour of the stroke on each segement.
segmentStrokeColor : "#fff",
//Number - The width of the stroke value in pixels
segmentStrokeWidth : 2,
//Number - Amount of animation steps
animationSteps : 100,
//String - Animation easing effect.
animationEasing : "easeOutBounce",
//Boolean - Whether to animate the rotation of the chart
animateRotate : true,
//Boolean - Whether to animate scaling the chart from the centre
animateScale : false,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
};
Chart.Type.extend({
//Passing in a name registers this chart in the Chart namespace
name: "PolarArea",
//Providing a defaults will also register the deafults in the chart namespace
defaults : defaultConfig,
//Initialize is fired when the chart is initialized - Data is passed in as a parameter
//Config is automatically merged by the core of Chart.js, and is available at this.options
initialize: function(data){
this.segments = [];
//Declare segment class as a chart instance specific class, so it can share props for this instance
this.SegmentArc = Chart.Arc.extend({
showStroke : this.options.segmentShowStroke,
strokeWidth : this.options.segmentStrokeWidth,
strokeColor : this.options.segmentStrokeColor,
ctx : this.chart.ctx,
innerRadius : 0,
x : this.chart.width/2,
y : this.chart.height/2
});
this.scale = new Chart.RadialScale({
display: this.options.showScale,
fontStyle: this.options.scaleFontStyle,
fontSize: this.options.scaleFontSize,
fontFamily: this.options.scaleFontFamily,
fontColor: this.options.scaleFontColor,
showLabels: this.options.scaleShowLabels,
showLabelBackdrop: this.options.scaleShowLabelBackdrop,
backdropColor: this.options.scaleBackdropColor,
backdropPaddingY : this.options.scaleBackdropPaddingY,
backdropPaddingX: this.options.scaleBackdropPaddingX,
lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
lineColor: this.options.scaleLineColor,
lineArc: true,
width: this.chart.width,
height: this.chart.height,
xCenter: this.chart.width/2,
yCenter: this.chart.height/2,
ctx : this.chart.ctx,
templateString: this.options.scaleLabel,
valuesCount: data.length
});
this.updateScaleRange(data);
this.scale.update();
helpers.each(data,function(segment,index){
this.addData(segment,index,true);
},this);
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];
helpers.each(this.segments,function(segment){
segment.restore(["fillColor"]);
});
helpers.each(activeSegments,function(activeSegment){
activeSegment.fillColor = activeSegment.highlightColor;
});
this.showTooltip(activeSegments);
});
}
this.render();
},
getSegmentsAtEvent : function(e){
var segmentsArray = [];
var location = helpers.getRelativePosition(e);
helpers.each(this.segments,function(segment){
if (segment.inRange(location.x,location.y)) segmentsArray.push(segment);
},this);
return segmentsArray;
},
addData : function(segment, atIndex, silent){
var index = atIndex || this.segments.length;
this.segments.splice(index, 0, new this.SegmentArc({
fillColor: segment.color,
highlightColor: segment.highlight || segment.color,
label: segment.label,
value: segment.value,
outerRadius: (this.options.animateScale) ? 0 : this.scale.calculateCenterOffset(segment.value),
circumference: (this.options.animateRotate) ? 0 : this.scale.getCircumference(),
startAngle: Math.PI * 1.5
}));
if (!silent){
this.reflow();
this.update();
}
},
removeData: function(atIndex){
var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length-1;
this.segments.splice(indexToDelete, 1);
this.reflow();
this.update();
},
calculateTotal: function(data){
this.total = 0;
helpers.each(data,function(segment){
this.total += segment.value;
},this);
this.scale.valuesCount = this.segments.length;
},
updateScaleRange: function(datapoints){
var valuesArray = [];
helpers.each(datapoints,function(segment){
valuesArray.push(segment.value);
});
var scaleSizes = (this.options.scaleOverride) ?
{
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
} :
helpers.calculateScaleRange(
valuesArray,
helpers.min([this.chart.width, this.chart.height])/2,
this.options.scaleFontSize,
this.options.scaleBeginAtZero,
this.options.scaleIntegersOnly
);
helpers.extend(
this.scale,
scaleSizes,
{
size: helpers.min([this.chart.width, this.chart.height]),
xCenter: this.chart.width/2,
yCenter: this.chart.height/2
}
);
},
update : function(){
this.calculateTotal(this.segments);
helpers.each(this.segments,function(segment){
segment.save();
});
this.render();
},
reflow : function(){
helpers.extend(this.SegmentArc.prototype,{
x : this.chart.width/2,
y : this.chart.height/2
});
this.updateScaleRange(this.segments);
this.scale.update();
helpers.extend(this.scale,{
xCenter: this.chart.width/2,
yCenter: this.chart.height/2
});
helpers.each(this.segments, function(segment){
segment.update({
outerRadius : this.scale.calculateCenterOffset(segment.value)
});
}, this);
},
draw : function(ease){
var easingDecimal = ease || 1;
//Clear & draw the canvas
this.clear();
helpers.each(this.segments,function(segment, index){
segment.transition({
circumference : this.scale.getCircumference(),
outerRadius : this.scale.calculateCenterOffset(segment.value)
},easingDecimal);
segment.endAngle = segment.startAngle + segment.circumference;
// If we've removed the first segment we need to set the first one to
// start at the top.
if (index === 0){
segment.startAngle = Math.PI * 1.5;
}
//Check to see if it's the last segment, if not get the next and update the start angle
if (index < this.segments.length - 1){
this.segments[index+1].startAngle = segment.endAngle;
}
segment.draw();
}, this);
this.scale.draw();
}
});
}).call(this);
(function(){
"use strict";
var root = this,
Chart = root.Chart,
helpers = Chart.helpers;
Chart.Type.extend({
name: "Radar",
defaults:{
//Boolean - Whether to show lines for each scale point
scaleShowLine : true,
//Boolean - Whether we show the angle lines out of the radar
angleShowLineOut : true,
//Boolean - Whether to show labels on the scale
scaleShowLabels : false,
// Boolean - Whether the scale should begin at zero
scaleBeginAtZero : true,
//String - Colour of the angle line
angleLineColor : "rgba(0,0,0,.1)",
//Number - Pixel width of the angle line
angleLineWidth : 1,
//String - Point label font declaration
pointLabelFontFamily : "'Arial'",
//String - Point label font weight
pointLabelFontStyle : "normal",
//Number - Point label font size in pixels
pointLabelFontSize : 10,
//String - Point label font colour
pointLabelFontColor : "#666",
//Boolean - Whether to show a dot for each point
pointDot : true,
//Number - Radius of each point dot in pixels
pointDotRadius : 3,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius : 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke : true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,
//Boolean - Whether to fill the dataset with a colour
datasetFill : true,
//String - A legend template
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].strokeColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
},
initialize: function(data){
this.PointClass = Chart.Point.extend({
strokeWidth : this.options.pointDotStrokeWidth,
radius : this.options.pointDotRadius,
display: this.options.pointDot,
hitDetectionRadius : this.options.pointHitDetectionRadius,
ctx : this.chart.ctx
});
this.datasets = [];
this.buildScale(data);
//Set up tooltip events on the chart
if (this.options.showTooltips){
helpers.bindEvents(this, this.options.tooltipEvents, function(evt){
var activePointsCollection = (evt.type !== 'mouseout') ? this.getPointsAtEvent(evt) : [];
this.eachPoints(function(point){
point.restore(['fillColor', 'strokeColor']);
});
helpers.each(activePointsCollection, function(activePoint){
activePoint.fillColor = activePoint.highlightFill;
activePoint.strokeColor = activePoint.highlightStroke;
});
this.showTooltip(activePointsCollection);
});
}
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets,function(dataset){
var datasetObject = {
label: dataset.label || null,
fillColor : dataset.fillColor,
strokeColor : dataset.strokeColor,
pointColor : dataset.pointColor,
pointStrokeColor : dataset.pointStrokeColor,
points : []
};
datasetObject._custom = dataset._custom || {};
this.datasets.push(datasetObject);
helpers.each(dataset.data,function(dataPoint,index){
//Best way to do this? or in draw sequence...?
if (helpers.isNumber(dataPoint)){
//Add a new point for each piece of data, passing any required data to draw.
var pointPosition;
if (!this.scale.animation){
pointPosition = this.scale.getPointPosition(index, this.scale.calculateCenterOffset(dataPoint));
}
datasetObject.points.push(new this.PointClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
x: (this.options.animation) ? this.scale.xCenter : pointPosition.x,
y: (this.options.animation) ? this.scale.yCenter : pointPosition.y,
strokeColor : dataset.pointStrokeColor,
fillColor : dataset.pointColor,
highlightFill : dataset.pointHighlightFill || dataset.pointColor,
highlightStroke : dataset.pointHighlightStroke || dataset.pointStrokeColor
}));
}
},this);
},this);
this.render();
},
eachPoints : function(callback){
helpers.each(this.datasets,function(dataset){
helpers.each(dataset.points,callback,this);
},this);
},
getPointsAtEvent : function(evt){
var mousePosition = helpers.getRelativePosition(evt),
fromCenter = helpers.getAngleFromPoint({
x: this.scale.xCenter,
y: this.scale.yCenter
}, mousePosition);
var anglePerIndex = (Math.PI * 2) /this.scale.valuesCount,
pointIndex = Math.round((fromCenter.angle - Math.PI * 1.5) / anglePerIndex),
activePointsCollection = [];
// If we're at the top, make the pointIndex 0 to get the first of the array.
if (pointIndex >= this.scale.valuesCount || pointIndex < 0){
pointIndex = 0;
}
//if (fromCenter.distance <= this.scale.drawingArea){
helpers.each(this.datasets, function(dataset){
activePointsCollection.push(dataset.points[pointIndex]);
});
//}
return activePointsCollection;
},
buildScale : function(data){
this.scale = new Chart.RadialScale({
display: this.options.showScale,
fontStyle: this.options.scaleFontStyle,
fontSize: this.options.scaleFontSize,
fontFamily: this.options.scaleFontFamily,
fontColor: this.options.scaleFontColor,
showLabels: this.options.scaleShowLabels,
showLabelBackdrop: this.options.scaleShowLabelBackdrop,
backdropColor: this.options.scaleBackdropColor,
backdropPaddingY : this.options.scaleBackdropPaddingY,
backdropPaddingX: this.options.scaleBackdropPaddingX,
lineWidth: (this.options.scaleShowLine) ? this.options.scaleLineWidth : 0,
lineColor: this.options.scaleLineColor,
angleLineColor : this.options.angleLineColor,
angleLineWidth : (this.options.angleShowLineOut) ? this.options.angleLineWidth : 0,
// Point labels at the edge of each line
pointLabelFontColor : this.options.pointLabelFontColor,
pointLabelFontSize : this.options.pointLabelFontSize,
pointLabelFontFamily : this.options.pointLabelFontFamily,
pointLabelFontStyle : this.options.pointLabelFontStyle,
height : this.chart.height,
width: this.chart.width,
xCenter: this.chart.width/2,
yCenter: this.chart.height/2,
ctx : this.chart.ctx,
templateString: this.options.scaleLabel,
labels: data.labels,
valuesCount: data.datasets[0].data.length
});
this.scale.setScaleSize();
this.updateScaleRange(data.datasets);
this.scale.buildYLabels();
},
updateScaleRange: function(datasets){
var valuesArray = (function(){
var totalDataArray = [];
helpers.each(datasets,function(dataset){
if (dataset.data){
totalDataArray = totalDataArray.concat(dataset.data);
}
else {
helpers.each(dataset.points, function(point){
totalDataArray.push(point.value);
});
}
});
return totalDataArray;
})();
var scaleSizes = (this.options.scaleOverride) ?
{
steps: this.options.scaleSteps,
stepValue: this.options.scaleStepWidth,
min: this.options.scaleStartValue,
max: this.options.scaleStartValue + (this.options.scaleSteps * this.options.scaleStepWidth)
} :
helpers.calculateScaleRange(
valuesArray,
helpers.min([this.chart.width, this.chart.height])/2,
this.options.scaleFontSize,
this.options.scaleBeginAtZero,
this.options.scaleIntegersOnly
);
helpers.extend(
this.scale,
scaleSizes
);
},
addData : function(valuesArray,label){
//Map the values array for each of the datasets
this.scale.valuesCount++;
helpers.each(valuesArray,function(value,datasetIndex){
if (helpers.isNumber(value)){
var pointPosition = this.scale.getPointPosition(this.scale.valuesCount, this.scale.calculateCenterOffset(value));
this.datasets[datasetIndex].points.push(new this.PointClass({
value : value,
label : label,
x: pointPosition.x,
y: pointPosition.y,
strokeColor : this.datasets[datasetIndex].pointStrokeColor,
fillColor : this.datasets[datasetIndex].pointColor
}));
}
},this);
this.scale.labels.push(label);
this.reflow();
this.update();
},
removeData : function(){
this.scale.valuesCount--;
this.scale.labels.shift();
helpers.each(this.datasets,function(dataset){
dataset.points.shift();
},this);
this.reflow();
this.update();
},
update : function(){
this.eachPoints(function(point){
point.save();
});
this.reflow();
this.render();
},
reflow: function(){
helpers.extend(this.scale, {
width : this.chart.width,
height: this.chart.height,
size : helpers.min([this.chart.width, this.chart.height]),
xCenter: this.chart.width/2,
yCenter: this.chart.height/2
});
this.updateScaleRange(this.datasets);
this.scale.setScaleSize();
this.scale.buildYLabels();
},
draw : function(ease){
var easeDecimal = ease || 1,
ctx = this.chart.ctx;
this.clear();
this.scale.draw();
helpers.each(this.datasets,function(dataset){
//Transition each point first so that the line and point drawing isn't out of sync
helpers.each(dataset.points,function(point,index){
point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
},this);
//Draw the line between all the points
ctx.lineWidth = this.options.datasetStrokeWidth;
ctx.strokeStyle = dataset.strokeColor;
ctx.beginPath();
helpers.each(dataset.points,function(point,index){
if (index === 0){
ctx.moveTo(point.x,point.y);
}
else{
ctx.lineTo(point.x,point.y);
}
},this);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = dataset.fillColor;
ctx.fill();
//Now draw the points over the line
//A little inefficient double looping, but better than the line
//lagging behind the point positions
helpers.each(dataset.points,function(point){
point.draw();
});
},this);
}
});
}).call(this);
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define("require exports ../Point ../Polygon ../Polyline ../SpatialReference".split(" "),function(H,v,D,E,F,G){function y(a,p,e,g){var n=1/298.257223563,t=Math.sin(e);e=Math.cos(e);var b=(1-n)*Math.tan(a);a=1/Math.sqrt(1+b*b);for(var f=b*a,h=Math.atan2(b,e),b=a*t*a*t,c=1-b,d=2.7233160610754688E11*c/4.040829998466145E13,k=1+d/16384*(4096+d*(-768+d*(320-175*d))),u=d/1024*(256+d*(-128+d*(74-47*d))),d=g/(6356752.31424518*k),r=2*Math.PI,m,l,q,v;1E-12<Math.abs(d-r);)q=Math.cos(2*h+d),m=Math.sin(d),l=Math.cos(d),
v=u*m*(q+u/4*(l*(-1+2*q*q)-u/6*q*(-3+4*m*m)*(-3+4*q*q))),r=d,d=g/(6356752.31424518*k)+v;g=f*m-a*l*e;c=n/16*c*(4+n*(4-3*c));return new D((p+(Math.atan2(m*t,a*l-f*m*e)-(1-c)*n*Math.sqrt(b)*(d+c*m*(q+c*l*(-1+2*q*q)))))/(Math.PI/180),Math.atan2(f*l+a*m*e,(1-n)*Math.sqrt(b+g*g))/(Math.PI/180),new G({wkid:4326}))}function A(a,p,e,g){var n=1/298.257223563,t=g-p,b=Math.atan((1-n)*Math.tan(a)),f=Math.atan((1-n)*Math.tan(e)),h=Math.sin(b),b=Math.cos(b),c=Math.sin(f),f=Math.cos(f),d=1E3,k=t,u,r,m,l,q,v,w,x;
do{l=Math.sin(k);q=Math.cos(k);m=Math.sqrt(f*l*f*l+(b*c-h*f*q)*(b*c-h*f*q));if(0===m)return{geodesicDistance:0};q=h*c+b*f*q;v=Math.atan2(m,q);w=b*f*l/m;r=1-w*w;l=q-2*h*c/r;isNaN(l)&&(l=0);x=n/16*r*(4+n*(4-3*r));u=k;k=t+(1-x)*n*w*(v+x*m*(l+x*q*(-1+2*l*l)))}while(1E-12<Math.abs(k-u)&&0<--d);if(0===d)return h=g-p,{geodesicDistance:6371009*Math.acos(Math.sin(a)*Math.sin(e)+Math.cos(a)*Math.cos(e)*Math.cos(g-p)),azimuth:Math.atan2(Math.sin(h)*Math.cos(e),Math.cos(a)*Math.sin(e)-Math.sin(a)*Math.cos(e)*
Math.cos(h))};a=2.7233160610754688E11*r/4.040829998466145E13;p=a/1024*(256+a*(-128+a*(74-47*a)));return{geodesicDistance:6356752.31424518*(1+a/16384*(4096+a*(-768+a*(320-175*a))))*(v-p*m*(l+p/4*(q*(-1+2*l*l)-p/6*l*(-3+4*m*m)*(-3+4*l*l)))),azimuth:Math.atan2(f*Math.sin(k),b*c-h*f*Math.cos(k)),reverseAzimuth:Math.atan2(b*Math.sin(k),b*c*Math.cos(k)-h*f)}}function B(a,p){var e=Math.PI/180;637.100877151506>p&&(p=637.100877151506);if("polyline"!==a.type&&"polygon"!==a.type)throw console.error("_geodesicDensify: the input geometry is neither polyline nor polygon"),
Error("_geodesicDensify: the input geometry is neither polyline nor polygon");for(var g=[],n=0,t="polyline"===a.type?a.paths:a.rings;n<t.length;n++){var b=t[n],f=[];g.push(f);f.push([b[0][0],b[0][1]]);for(var h=b[0][0]*e,c=b[0][1]*e,d=void 0,k=void 0,u=0;u<b.length-1;u++)if(d=b[u+1][0]*e,k=b[u+1][1]*e,h!==d||c!==k){var k=A(c,h,k,d),d=k.azimuth,k=k.geodesicDistance,r=k/p;if(1<r){for(var m=1;m<=r-1;m++){var l=y(c,h,d,m*p);f.push([l.x,l.y])}r=y(c,h,d,(k+Math.floor(r-1)*p)/2);f.push([r.x,r.y])}c=y(c,
h,d,k);f.push([c.x,c.y]);h=c.x*e;c=c.y*e}}return"polyline"===a.type?new F({paths:g,spatialReference:a.spatialReference}):new E({rings:g,spatialReference:a.spatialReference})}function z(a,p){var e=Math.PI/180,g=Math.sin(p[1]*e),g=.9933056200098026*(g/(1-.006694379990197414*g*g)-6.111035746609262*Math.log((1-.0818191908429643*g)/(1+.0818191908429643*g)));a[0]=6378137*p[0]*e;a[1]=3189068.5*g;return a}Object.defineProperty(v,"__esModule",{value:!0});var C={esriMiles:1,esriKilometers:1.609344,esriFeet:5280,
esriMeters:1609.34,esriYards:1760,esriNauticalMiles:.869,esriCentimeters:160934,esriDecimeters:16093.4,esriInches:63360,esriMillimeters:1609340,esriAcres:1,esriAres:40.4685642,esriSquareKilometers:.00404685642,esriSquareMiles:.0015625,esriSquareFeet:43560,esriSquareMeters:4046.85642,esriHectares:.404685642,esriSquareYards:4840,esriSquareInches:6272640,esriSquareMillimeters:4046856420,esriSquareCentimeters:4.04685642E7,esriSquareDecimeters:404685.642};v.directGeodeticSolver=y;v.inverseGeodeticSolver=
A;v.geodesicDensify=B;v.geodesicLengths=function(a,p){for(var e=Math.PI/180,g=[],n=0;n<a.length;n++){for(var t=a[n].paths,b=0,f=0;f<t.length;f++){for(var h=t[f],c=0,d=1;d<h.length;d++){var k=h[d-1][0]*e,u=h[d][0]*e,r=h[d-1][1]*e,m=h[d][1]*e;if(r!==m||k!==u)k=A(r,k,m,u),c+=k.geodesicDistance/1609.344}b+=c}b*=C[p];g.push(b)}return g};var w=[0,0],x=[0,0];v.geodesicAreas=function(a,p){for(var e=[],g=0;g<a.length;g++){var n=B(a[g],1E4);e.push(n)}a=[];for(g=0;g<e.length;g++){for(var n=e[g].rings,t=0,b=
0;b<n.length;b++){var f=n[b];z(w,f[0]);z(x,f[f.length-1]);for(var h=x[0]*w[1]-w[0]*x[1],c=0;c<f.length-1;c++)z(w,f[c+1]),z(x,f[c]),h+=x[0]*w[1]-w[0]*x[1];h/=4046.87;t+=h}t*=C[p];a.push(t/-2)}return a}});
|
'use strict';
/*
CreditCategory model fields:
{
title
}
*/
module.exports = function(sequelize, DataTypes) {
var CreditCategory = sequelize.define('CreditCategory', {
title: {
type: DataTypes.STRING,
allowNull: false,
field: 'title',
unique: true,
validate: {
is: /^[0-9а-яА-ЯёЁa-z,.'-]+$/i
}
}
}, {
tableName: 'credit_categories',
underscored: true,
timestamps: true,
paranoid: false,
classMethods: {
associate: function(models) {
CreditCategory.hasMany(models.CreditType);
}
}
});
return CreditCategory;
};
|
var fs = require('fs');
var os = require('os');
var blessed = require('blessed');
var multiline = require('multiline');
if (os.platform() === 'win32') {
console.log('**************************************************************');
console.log('Hackathon Starter Generator has been disabled on Windows until');
console.log('https://github.com/chjj/blessed fixes the issue #179.');
console.log('**************************************************************');
process.exit();
}
var screen = blessed.screen({
autoPadding: true
});
screen.key('q', function() {
process.exit(0);
});
var home = blessed.list({
parent: screen,
padding: { top: 2 },
mouse: true,
keys: true,
fg: 'white',
bg: 'blue',
selectedFg: 'blue',
selectedBg: 'white',
items: [
'» CHANGE EMAIL SERVICE',
'» ADD NODE.JS CLUSTER SUPPORT',
'» EXIT'
]
});
var homeTitle = blessed.text({
parent: screen,
align: 'center',
fg: 'blue',
bg: 'white',
content: 'Hackathon Starter (c) 2014'
});
var footer = blessed.text({
parent: screen,
bottom: 0,
fg: 'white',
bg: 'blue',
tags: true,
content: ' {cyan-fg}<Up/Down>{/cyan-fg} moves | {cyan-fg}<Enter>{/cyan-fg} selects | {cyan-fg}<q>{/cyan-fg} exits'
});
var inner = blessed.form({
top: 'center',
left: 'center',
mouse: true,
keys: true,
width: 33,
height: 10,
border: {
type: 'line',
fg: 'white',
bg: 'red'
},
fg: 'white',
bg: 'red'
});
var success = blessed.box({
top: 'center',
left: 'center',
mouse: true,
keys: true,
tags: true,
width: '50%',
height: '40%',
border: {
type: 'line',
fg: 'white',
bg: 'green'
},
fg: 'white',
bg: 'green',
padding: 1
});
success.on('keypress', function() {
home.focus();
home.remove(success);
});
var clusterText = blessed.text({
top: 'top',
bg: 'red',
fg: 'white',
tags: true,
content: 'Take advantage of multi-core systems using built-in {underline}cluster{/underline} module.'
});
var enable = blessed.button({
parent: inner,
bottom: 0,
mouse: true,
shrink: true,
name: 'enable',
content: ' ENABLE ',
border: {
type: 'line',
fg: 'white',
bg: 'red'
},
style: {
fg: 'white',
bg: 'red',
focus: {
fg: 'red',
bg: 'white'
}
}
});
var disable = blessed.button({
parent: inner,
bottom: 0,
left: 10,
mouse: true,
shrink: true,
name: 'disable',
content: ' DISABLE ',
border: {
type: 'line',
fg: 'white',
bg: 'red'
},
style: {
fg: 'white',
bg: 'red',
focus: {
fg: 'red',
bg: 'white'
}
}
});
var cancel = blessed.button({
parent: inner,
bottom: 0,
left: 21,
mouse: true,
shrink: true,
name: 'cancel',
content: ' CANCEL ',
border: {
type: 'line',
fg: 'white',
bg: 'red'
},
style: {
fg: 'white',
bg: 'red',
focus: {
fg: 'red',
bg: 'white'
}
}
});
cancel.on('press', function() {
home.focus();
home.remove(inner);
screen.render();
});
var emailForm = blessed.form({
mouse: true,
keys: true,
fg: 'white',
bg: 'blue',
padding: { left: 1, right: 1 }
});
emailForm.on('submit', function() {
var contactCtrl = fs.readFileSync('controllers/contact.js').toString().split(os.EOL);
var userCtrl = fs.readFileSync('controllers/user.js').toString().split(os.EOL);
var choice = null;
if (sendgridRadio.checked) {
choice = 'SendGrid';
} else if (mailgunRadio.checked) {
choice = 'Mailgun';
} else if (mandrillRadio.checked) {
choice = 'Mandrill';
}
var index = contactCtrl.indexOf('var transporter = nodemailer.createTransport({');
contactCtrl.splice(index + 1, 1, " service: '" + choice + "',");
contactCtrl.splice(index + 3, 1, ' user: secrets.' + choice.toLowerCase() +'.user,');
contactCtrl.splice(index + 4, 1, ' pass: secrets.' + choice.toLowerCase() + '.password');
fs.writeFileSync('controllers/contact.js', contactCtrl.join(os.EOL));
index = userCtrl.indexOf(' var transporter = nodemailer.createTransport({');
userCtrl.splice(index + 1, 1, " service: '" + choice + "',");
userCtrl.splice(index + 3, 1, ' user: secrets.' + choice.toLowerCase() + '.user,');
userCtrl.splice(index + 4, 1, ' pass: secrets.' + choice.toLowerCase() + '.password');
index = userCtrl.indexOf(' var transporter = nodemailer.createTransport({', (index + 1));
userCtrl.splice(index + 1, 1, " service: '" + choice + "',");
userCtrl.splice(index + 3, 1, ' user: secrets.' + choice.toLowerCase() + '.user,');
userCtrl.splice(index + 4, 1, ' pass: secrets.' + choice.toLowerCase() + '.password');
fs.writeFileSync('controllers/user.js', userCtrl.join(os.EOL));
home.remove(emailForm);
home.append(success);
success.setContent('Email Service has been switched to ' + choice);
success.focus();
screen.render();
});
var emailText = blessed.text({
parent: emailForm,
content: 'Select one of the following email service providers for {underline}contact form{/underline} and {underline}password reset{/underline}.',
padding: 1,
bg: 'red',
fg: 'white',
tags: true
});
var sendgridRadio = blessed.radiobutton({
parent: emailForm,
top: 5,
checked: true,
mouse: true,
fg: 'white',
bg: 'blue',
content: 'SendGrid'
});
var mailgunRadio = blessed.radiobutton({
parent: emailForm,
top: 6,
mouse: true,
fg: 'white',
bg: 'blue',
content: 'Mailgun'
});
var mandrillRadio = blessed.radiobutton({
parent: emailForm,
top: 7,
mouse: true,
fg: 'white',
bg: 'blue',
content: 'Mandrill'
});
var emailSubmit = blessed.button({
parent: emailForm,
top: 9,
mouse: true,
shrink: true,
name: 'submit',
content: ' SUBMIT ',
style: {
fg: 'blue',
bg: 'white',
focus: {
fg: 'white',
bg: 'red'
}
}
});
emailSubmit.on('press', function() {
emailForm.submit();
});
var emailCancel = blessed.button({
parent: emailForm,
top: 9,
left: 9,
mouse: true,
shrink: true,
name: 'cancel',
content: ' CANCEL ',
style: {
fg: 'blue',
bg: 'white',
focus: {
fg: 'white',
bg: 'red'
}
}
});
emailCancel.on('press', function() {
home.focus();
home.remove(emailForm);
screen.render();
});
home.on('select', function(child, index) {
switch (index) {
case 0:
home.append(emailForm);
emailForm.focus();
break;
case 1:
addClusterSupport();
home.append(success);
success.setContent('New file {underline}cluster_app.js{/underline} has been created. Your app is now able to use more than 1 CPU by running {underline}node cluster_app.js{/underline}, which in turn spawns multiple instances of {underline}app.js{/underline}');
success.focus();
screen.render();
break;
default:
process.exit(0);
}
});
screen.render();
function addClusterSupport() {
var fileContents = multiline(function() {
/*
var os = require('os');
var cluster = require('cluster');
cluster.setupMaster({
exec: 'app.js'
});
cluster.on('exit', function(worker) {
console.log('worker ' + worker.id + ' died');
cluster.fork();
});
for (var i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
*/
});
fs.writeFileSync('cluster_app.js', fileContents);
}
|
// Encode.js v3.4.1
//---------------------------------------------------------------------------
// ★Encodeクラス URLのエンコード/デコードを扱う
//---------------------------------------------------------------------------
// URLエンコード/デコード
// Encodeクラス
pzpr.classmgr.makeCommon({
//---------------------------------------------------------
Encode:{
pflag : "",
outpflag : '',
outcols : null,
outrows : null,
outbstr : '',
fio : null,
//---------------------------------------------------------------------------
// enc.checkpflag() pflagに指定した文字列が含まれているか調べる
//---------------------------------------------------------------------------
// ぱずぷれApplet->v3でURLの仕様が変わったパズル:
// creek, gokigen, lits (Applet+c===v3, Applet===v3+d)
// 何回かURL形式を変更したパズル:
// icebarn (v3, Applet+c, Applet), slalom (v3+p, v3+d, v3/Applet)
// v3になって以降pidを分離したパズルのうち元パズルのURL形式を変更して短くしたパズル:
// bonsan, kramma (cを付加)
// URL形式は同じで表示形式の情報をもたせているパズル:
// bosanowa, pipelink, yajilin
checkpflag : function(ca){ return (this.pflag.indexOf(ca)>=0);},
//---------------------------------------------------------------------------
// enc.decodeURL() parseURL()を行い、各種各パズルのdecode関数を呼び出す
// enc.encodeURL() 各種各パズルのencode関数を呼び出し、URLを出力する
//
// enc.decodePzpr() 各パズルのURL入力用(オーバーライド用)
// enc.encodePzpr() 各パズルのURL出力用(オーバーライド用)
//---------------------------------------------------------------------------
decodeURL : function(url){
var pzl = pzpr.parser.parseURL(url), puzzle = this.puzzle, bd = puzzle.board;
bd.initBoardSize(pzl.cols, pzl.rows);
if(!!pzl.body){
this.pflag = pzl.pflag;
this.outbstr = pzl.body;
switch(pzl.type){
case pzl.URL_PZPRV3: case pzl.URL_KANPENP:
this.decodePzpr(pzl.URL_PZPRV3);
break;
case pzl.URL_PZPRAPP:
this.decodePzpr(pzl.URL_PZPRAPP);
break;
case pzl.URL_KANPEN:
this.fio = new puzzle.klass.FileIO();
this.fio.dataarray = this.outbstr.replace(/_/g, " ").split("/");
this.decodeKanpen();
this.fio = null;
break;
case pzl.URL_HEYAAPP:
this.decodeHeyaApp();
break;
}
}
bd.rebuildInfo();
},
encodeURL : function(type){
var puzzle = this.puzzle, pid = puzzle.pid, bd = puzzle.board;
var pzl = new pzpr.parser.URLData('');
type = type || pzl.URL_PZPRV3; /* type===pzl.URL_AUTO(0)もまとめて変換する */
if(type===pzl.URL_KANPEN && pid==='lits'){ type = pzl.URL_KANPENP;}
this.outpflag = null;
this.outcols = bd.cols;
this.outrows = bd.rows;
this.outbstr = '';
switch(type){
case pzl.URL_PZPRV3:
this.encodePzpr(pzl.URL_PZPRV3);
break;
case pzl.URL_PZPRAPP:
throw "no Implemention";
case pzl.URL_KANPENP:
if(!puzzle.info.exists.kanpen){ throw "no Implemention";}
this.encodePzpr(pzl.URL_PZPRAPP);
this.outpflag = this.outpflag || "";
break;
case pzl.URL_KANPEN:
this.fio = new puzzle.klass.FileIO();
this.encodeKanpen();
this.outbstr = this.fio.datastr.replace(/\r?\n/g,"/").replace(/ /g, "_");
this.fio = null;
break;
case pzl.URL_HEYAAPP:
this.encodeHeyaApp();
break;
default:
throw "invalid URL Type";
}
pzl.pid = pid;
pzl.type = type;
pzl.pflag = this.outpflag;
pzl.cols = this.outcols;
pzl.rows = this.outrows;
pzl.body = this.outbstr;
return pzl.generate();
},
// オーバーライド用
decodePzpr : function(type){ throw "no Implemention";},
encodePzpr : function(type){ throw "no Implemention";},
decodeKanpen : function(){ throw "no Implemention";},
encodeKanpen : function(){ throw "no Implemention";},
decodeHeyaApp : function(){ throw "no Implemention";},
encodeHeyaApp : function(){ throw "no Implemention";}
}
});
|
/// BCRYPT
var bcrypt = NpmModuleBcrypt;
var bcryptHash = Meteor.wrapAsync(bcrypt.hash);
var bcryptCompare = Meteor.wrapAsync(bcrypt.compare);
// User records have a 'services.password.bcrypt' field on them to hold
// their hashed passwords (unless they have a 'services.password.srp'
// field, in which case they will be upgraded to bcrypt the next time
// they log in).
//
// When the client sends a password to the server, it can either be a
// string (the plaintext password) or an object with keys 'digest' and
// 'algorithm' (must be "sha-256" for now). The Meteor client always sends
// password objects { digest: *, algorithm: "sha-256" }, but DDP clients
// that don't have access to SHA can just send plaintext passwords as
// strings.
//
// When the server receives a plaintext password as a string, it always
// hashes it with SHA256 before passing it into bcrypt. When the server
// receives a password as an object, it asserts that the algorithm is
// "sha-256" and then passes the digest to bcrypt.
Accounts._bcryptRounds = 10;
// Given a 'password' from the client, extract the string that we should
// bcrypt. 'password' can be one of:
// - String (the plaintext password)
// - Object with 'digest' and 'algorithm' keys. 'algorithm' must be "sha-256".
//
var getPasswordString = function (password) {
if (typeof password === "string") {
password = SHA256(password);
} else { // 'password' is an object
if (password.algorithm !== "sha-256") {
throw new Error("Invalid password hash algorithm. " +
"Only 'sha-256' is allowed.");
}
password = password.digest;
}
return password;
};
// Use bcrypt to hash the password for storage in the database.
// `password` can be a string (in which case it will be run through
// SHA256 before bcrypt) or an object with properties `digest` and
// `algorithm` (in which case we bcrypt `password.digest`).
//
var hashPassword = function (password) {
password = getPasswordString(password);
return bcryptHash(password, Accounts._bcryptRounds);
};
// Check whether the provided password matches the bcrypt'ed password in
// the database user record. `password` can be a string (in which case
// it will be run through SHA256 before bcrypt) or an object with
// properties `digest` and `algorithm` (in which case we bcrypt
// `password.digest`).
//
Accounts._checkPassword = function (user, password) {
var result = {
userId: user._id
};
password = getPasswordString(password);
if (! bcryptCompare(password, user.services.password.bcrypt)) {
result.error = new Meteor.Error(403, "Incorrect password");
}
return result;
};
var checkPassword = Accounts._checkPassword;
///
/// LOGIN
///
Accounts._findUserByQuery = function (query) {
var user = null;
if (query.id) {
user = Meteor.users.findOne({ _id: query.id });
} else {
var fieldName;
var fieldValue;
if (query.username) {
fieldName = 'username';
fieldValue = query.username;
} else if (query.email) {
fieldName = 'emails.address';
fieldValue = query.email;
} else {
throw new Error("shouldn't happen (validation missed something)");
}
var selector = {};
selector[fieldName] = fieldValue;
user = Meteor.users.findOne(selector);
// If user is not found, try a case insensitive lookup
if (!user) {
selector = selectorForFastCaseInsensitiveLookup(fieldName, fieldValue);
var candidateUsers = Meteor.users.find(selector).fetch();
// No match if multiple candidates are found
if (candidateUsers.length === 1) {
user = candidateUsers[0];
}
}
}
return user;
};
/**
* @summary Finds the user with the specified username.
* First tries to match username case sensitively; if that fails, it
* tries case insensitively; but if more than one user matches the case
* insensitive search, it returns null.
* @locus Server
* @param {String} username The username to look for
* @returns {Object} A user if found, else null
* @importFromPackage accounts-base
*/
Accounts.findUserByUsername = function (username) {
return Accounts._findUserByQuery({
username: username
});
};
/**
* @summary Finds the user with the specified email.
* First tries to match email case sensitively; if that fails, it
* tries case insensitively; but if more than one user matches the case
* insensitive search, it returns null.
* @locus Server
* @param {String} email The email address to look for
* @returns {Object} A user if found, else null
* @importFromPackage accounts-base
*/
Accounts.findUserByEmail = function (email) {
return Accounts._findUserByQuery({
email: email
});
};
// Generates a MongoDB selector that can be used to perform a fast case
// insensitive lookup for the given fieldName and string. Since MongoDB does
// not support case insensitive indexes, and case insensitive regex queries
// are slow, we construct a set of prefix selectors for all permutations of
// the first 4 characters ourselves. We first attempt to matching against
// these, and because 'prefix expression' regex queries do use indexes (see
// http://docs.mongodb.org/v2.6/reference/operator/query/regex/#index-use),
// this has been found to greatly improve performance (from 1200ms to 5ms in a
// test with 1.000.000 users).
var selectorForFastCaseInsensitiveLookup = function (fieldName, string) {
// Performance seems to improve up to 4 prefix characters
var prefix = string.substring(0, Math.min(string.length, 4));
var orClause = _.map(generateCasePermutationsForString(prefix),
function (prefixPermutation) {
var selector = {};
selector[fieldName] =
new RegExp('^' + Meteor._escapeRegExp(prefixPermutation));
return selector;
});
var caseInsensitiveClause = {};
caseInsensitiveClause[fieldName] =
new RegExp('^' + Meteor._escapeRegExp(string) + '$', 'i')
return {$and: [{$or: orClause}, caseInsensitiveClause]};
}
// Generates permutations of all case variations of a given string.
var generateCasePermutationsForString = function (string) {
var permutations = [''];
for (var i = 0; i < string.length; i++) {
var ch = string.charAt(i);
permutations = _.flatten(_.map(permutations, function (prefix) {
var lowerCaseChar = ch.toLowerCase();
var upperCaseChar = ch.toUpperCase();
// Don't add unneccesary permutations when ch is not a letter
if (lowerCaseChar === upperCaseChar) {
return [prefix + ch];
} else {
return [prefix + lowerCaseChar, prefix + upperCaseChar];
}
}));
}
return permutations;
}
var checkForCaseInsensitiveDuplicates = function (fieldName, displayName, fieldValue, ownUserId) {
// Some tests need the ability to add users with the same case insensitive
// value, hence the _skipCaseInsensitiveChecksForTest check
var skipCheck = _.has(Accounts._skipCaseInsensitiveChecksForTest, fieldValue);
if (fieldValue && !skipCheck) {
var matchedUsers = Meteor.users.find(
selectorForFastCaseInsensitiveLookup(fieldName, fieldValue)).fetch();
if (matchedUsers.length > 0 &&
// If we don't have a userId yet, any match we find is a duplicate
(!ownUserId ||
// Otherwise, check to see if there are multiple matches or a match
// that is not us
(matchedUsers.length > 1 || matchedUsers[0]._id !== ownUserId))) {
throw new Meteor.Error(403, displayName + " already exists.");
}
}
};
// XXX maybe this belongs in the check package
var NonEmptyString = Match.Where(function (x) {
check(x, String);
return x.length > 0;
});
var userQueryValidator = Match.Where(function (user) {
check(user, {
id: Match.Optional(NonEmptyString),
username: Match.Optional(NonEmptyString),
email: Match.Optional(NonEmptyString)
});
if (_.keys(user).length !== 1)
throw new Match.Error("User property must have exactly one field");
return true;
});
var passwordValidator = Match.OneOf(
String,
{ digest: String, algorithm: String }
);
// Handler to login with a password.
//
// The Meteor client sets options.password to an object with keys
// 'digest' (set to SHA256(password)) and 'algorithm' ("sha-256").
//
// For other DDP clients which don't have access to SHA, the handler
// also accepts the plaintext password in options.password as a string.
//
// (It might be nice if servers could turn the plaintext password
// option off. Or maybe it should be opt-in, not opt-out?
// Accounts.config option?)
//
// Note that neither password option is secure without SSL.
//
Accounts.registerLoginHandler("password", function (options) {
if (! options.password || options.srp)
return undefined; // don't handle
check(options, {
user: userQueryValidator,
password: passwordValidator
});
var user = Accounts._findUserByQuery(options.user);
if (!user)
throw new Meteor.Error(403, "User not found");
if (!user.services || !user.services.password ||
!(user.services.password.bcrypt || user.services.password.srp))
throw new Meteor.Error(403, "User has no password set");
if (!user.services.password.bcrypt) {
if (typeof options.password === "string") {
// The client has presented a plaintext password, and the user is
// not upgraded to bcrypt yet. We don't attempt to tell the client
// to upgrade to bcrypt, because it might be a standalone DDP
// client doesn't know how to do such a thing.
var verifier = user.services.password.srp;
var newVerifier = SRP.generateVerifier(options.password, {
identity: verifier.identity, salt: verifier.salt});
if (verifier.verifier !== newVerifier.verifier) {
return {
userId: user._id,
error: new Meteor.Error(403, "Incorrect password")
};
}
return {userId: user._id};
} else {
// Tell the client to use the SRP upgrade process.
throw new Meteor.Error(400, "old password format", EJSON.stringify({
format: 'srp',
identity: user.services.password.srp.identity
}));
}
}
return checkPassword(
user,
options.password
);
});
// Handler to login using the SRP upgrade path. To use this login
// handler, the client must provide:
// - srp: H(identity + ":" + password)
// - password: a string or an object with properties 'digest' and 'algorithm'
//
// We use `options.srp` to verify that the client knows the correct
// password without doing a full SRP flow. Once we've checked that, we
// upgrade the user to bcrypt and remove the SRP information from the
// user document.
//
// The client ends up using this login handler after trying the normal
// login handler (above), which throws an error telling the client to
// try the SRP upgrade path.
//
// XXX COMPAT WITH 0.8.1.3
Accounts.registerLoginHandler("password", function (options) {
if (!options.srp || !options.password)
return undefined; // don't handle
check(options, {
user: userQueryValidator,
srp: String,
password: passwordValidator
});
var user = Accounts._findUserByQuery(options.user);
if (!user)
throw new Meteor.Error(403, "User not found");
// Check to see if another simultaneous login has already upgraded
// the user record to bcrypt.
if (user.services && user.services.password && user.services.password.bcrypt)
return checkPassword(user, options.password);
if (!(user.services && user.services.password && user.services.password.srp))
throw new Meteor.Error(403, "User has no password set");
var v1 = user.services.password.srp.verifier;
var v2 = SRP.generateVerifier(
null,
{
hashedIdentityAndPassword: options.srp,
salt: user.services.password.srp.salt
}
).verifier;
if (v1 !== v2)
return {
userId: user._id,
error: new Meteor.Error(403, "Incorrect password")
};
// Upgrade to bcrypt on successful login.
var salted = hashPassword(options.password);
Meteor.users.update(
user._id,
{
$unset: { 'services.password.srp': 1 },
$set: { 'services.password.bcrypt': salted }
}
);
return {userId: user._id};
});
///
/// CHANGING
///
/**
* @summary Change a user's username. Use this instead of updating the
* database directly. The operation will fail if there is an existing user
* with a username only differing in case.
* @locus Server
* @param {String} userId The ID of the user to update.
* @param {String} newUsername A new username for the user.
* @importFromPackage accounts-base
*/
Accounts.setUsername = function (userId, newUsername) {
check(userId, NonEmptyString);
check(newUsername, NonEmptyString);
var user = Meteor.users.findOne(userId);
if (!user)
throw new Meteor.Error(403, "User not found");
var oldUsername = user.username;
// Perform a case insensitive check for duplicates before update
checkForCaseInsensitiveDuplicates('username', 'Username', newUsername, user._id);
Meteor.users.update({_id: user._id}, {$set: {username: newUsername}});
// Perform another check after update, in case a matching user has been
// inserted in the meantime
try {
checkForCaseInsensitiveDuplicates('username', 'Username', newUsername, user._id);
} catch (ex) {
// Undo update if the check fails
Meteor.users.update({_id: user._id}, {$set: {username: oldUsername}});
throw ex;
}
};
// Let the user change their own password if they know the old
// password. `oldPassword` and `newPassword` should be objects with keys
// `digest` and `algorithm` (representing the SHA256 of the password).
//
// XXX COMPAT WITH 0.8.1.3
// Like the login method, if the user hasn't been upgraded from SRP to
// bcrypt yet, then this method will throw an 'old password format'
// error. The client should call the SRP upgrade login handler and then
// retry this method again.
//
// UNLIKE the login method, there is no way to avoid getting SRP upgrade
// errors thrown. The reasoning for this is that clients using this
// method directly will need to be updated anyway because we no longer
// support the SRP flow that they would have been doing to use this
// method previously.
Meteor.methods({changePassword: function (oldPassword, newPassword) {
check(oldPassword, passwordValidator);
check(newPassword, passwordValidator);
if (!this.userId)
throw new Meteor.Error(401, "Must be logged in");
var user = Meteor.users.findOne(this.userId);
if (!user)
throw new Meteor.Error(403, "User not found");
if (!user.services || !user.services.password ||
(!user.services.password.bcrypt && !user.services.password.srp))
throw new Meteor.Error(403, "User has no password set");
if (! user.services.password.bcrypt) {
throw new Meteor.Error(400, "old password format", EJSON.stringify({
format: 'srp',
identity: user.services.password.srp.identity
}));
}
var result = checkPassword(user, oldPassword);
if (result.error)
throw result.error;
var hashed = hashPassword(newPassword);
// It would be better if this removed ALL existing tokens and replaced
// the token for the current connection with a new one, but that would
// be tricky, so we'll settle for just replacing all tokens other than
// the one for the current connection.
var currentToken = Accounts._getLoginToken(this.connection.id);
Meteor.users.update(
{ _id: this.userId },
{
$set: { 'services.password.bcrypt': hashed },
$pull: {
'services.resume.loginTokens': { hashedToken: { $ne: currentToken } }
},
$unset: { 'services.password.reset': 1 }
}
);
return {passwordChanged: true};
}});
// Force change the users password.
/**
* @summary Forcibly change the password for a user.
* @locus Server
* @param {String} userId The id of the user to update.
* @param {String} newPassword A new password for the user.
* @param {Object} [options]
* @param {Object} options.logout Logout all current connections with this userId (default: true)
* @importFromPackage accounts-base
*/
Accounts.setPassword = function (userId, newPlaintextPassword, options) {
options = _.extend({logout: true}, options);
var user = Meteor.users.findOne(userId);
if (!user)
throw new Meteor.Error(403, "User not found");
var update = {
$unset: {
'services.password.srp': 1, // XXX COMPAT WITH 0.8.1.3
'services.password.reset': 1
},
$set: {'services.password.bcrypt': hashPassword(newPlaintextPassword)}
};
if (options.logout) {
update.$unset['services.resume.loginTokens'] = 1;
}
Meteor.users.update({_id: user._id}, update);
};
///
/// RESETTING VIA EMAIL
///
// Method called by a user to request a password reset email. This is
// the start of the reset process.
Meteor.methods({forgotPassword: function (options) {
check(options, {email: String});
var user = Accounts.findUserByEmail(options.email);
if (!user)
throw new Meteor.Error(403, "User not found");
const emails = _.pluck(user.emails || [], 'address');
const caseSensitiveEmail = _.find(emails, email => {
return email.toLowerCase() === options.email.toLowerCase();
});
Accounts.sendResetPasswordEmail(user._id, caseSensitiveEmail);
}});
// send the user an email with a link that when opened allows the user
// to set a new password, without the old password.
/**
* @summary Send an email with a link the user can use to reset their password.
* @locus Server
* @param {String} userId The id of the user to send email to.
* @param {String} [email] Optional. Which address of the user's to send the email to. This address must be in the user's `emails` list. Defaults to the first email in the list.
* @importFromPackage accounts-base
*/
Accounts.sendResetPasswordEmail = function (userId, email) {
// Make sure the user exists, and email is one of their addresses.
var user = Meteor.users.findOne(userId);
if (!user)
throw new Error("Can't find user");
// pick the first email if we weren't passed an email.
if (!email && user.emails && user.emails[0])
email = user.emails[0].address;
// make sure we have a valid email
if (!email || !_.contains(_.pluck(user.emails || [], 'address'), email))
throw new Error("No such email for user.");
var token = Random.secret();
var when = new Date();
var tokenRecord = {
token: token,
email: email,
when: when,
reason: 'reset'
};
Meteor.users.update(userId, {$set: {
"services.password.reset": tokenRecord
}});
// before passing to template, update user object with new token
Meteor._ensure(user, 'services', 'password').reset = tokenRecord;
var resetPasswordUrl = Accounts.urls.resetPassword(token);
var options = {
to: email,
from: Accounts.emailTemplates.resetPassword.from
? Accounts.emailTemplates.resetPassword.from(user)
: Accounts.emailTemplates.from,
subject: Accounts.emailTemplates.resetPassword.subject(user)
};
if (typeof Accounts.emailTemplates.resetPassword.text === 'function') {
options.text =
Accounts.emailTemplates.resetPassword.text(user, resetPasswordUrl);
}
if (typeof Accounts.emailTemplates.resetPassword.html === 'function')
options.html =
Accounts.emailTemplates.resetPassword.html(user, resetPasswordUrl);
if (typeof Accounts.emailTemplates.headers === 'object') {
options.headers = Accounts.emailTemplates.headers;
}
Email.send(options);
};
// send the user an email informing them that their account was created, with
// a link that when opened both marks their email as verified and forces them
// to choose their password. The email must be one of the addresses in the
// user's emails field, or undefined to pick the first email automatically.
//
// This is not called automatically. It must be called manually if you
// want to use enrollment emails.
/**
* @summary Send an email with a link the user can use to set their initial password.
* @locus Server
* @param {String} userId The id of the user to send email to.
* @param {String} [email] Optional. Which address of the user's to send the email to. This address must be in the user's `emails` list. Defaults to the first email in the list.
* @importFromPackage accounts-base
*/
Accounts.sendEnrollmentEmail = function (userId, email) {
// XXX refactor! This is basically identical to sendResetPasswordEmail.
// Make sure the user exists, and email is in their addresses.
var user = Meteor.users.findOne(userId);
if (!user)
throw new Error("Can't find user");
// pick the first email if we weren't passed an email.
if (!email && user.emails && user.emails[0])
email = user.emails[0].address;
// make sure we have a valid email
if (!email || !_.contains(_.pluck(user.emails || [], 'address'), email))
throw new Error("No such email for user.");
var token = Random.secret();
var when = new Date();
var tokenRecord = {
token: token,
email: email,
when: when,
reason: 'enroll'
};
Meteor.users.update(userId, {$set: {
"services.password.reset": tokenRecord
}});
// before passing to template, update user object with new token
Meteor._ensure(user, 'services', 'password').reset = tokenRecord;
var enrollAccountUrl = Accounts.urls.enrollAccount(token);
var options = {
to: email,
from: Accounts.emailTemplates.enrollAccount.from
? Accounts.emailTemplates.enrollAccount.from(user)
: Accounts.emailTemplates.from,
subject: Accounts.emailTemplates.enrollAccount.subject(user)
};
if (typeof Accounts.emailTemplates.enrollAccount.text === 'function') {
options.text =
Accounts.emailTemplates.enrollAccount.text(user, enrollAccountUrl);
}
if (typeof Accounts.emailTemplates.enrollAccount.html === 'function')
options.html =
Accounts.emailTemplates.enrollAccount.html(user, enrollAccountUrl);
if (typeof Accounts.emailTemplates.headers === 'object') {
options.headers = Accounts.emailTemplates.headers;
}
Email.send(options);
};
// Take token from sendResetPasswordEmail or sendEnrollmentEmail, change
// the users password, and log them in.
Meteor.methods({resetPassword: function (token, newPassword) {
var self = this;
return Accounts._loginMethod(
self,
"resetPassword",
arguments,
"password",
function () {
check(token, String);
check(newPassword, passwordValidator);
var user = Meteor.users.findOne({
"services.password.reset.token": token});
if (!user)
throw new Meteor.Error(403, "Token expired");
var when = user.services.password.reset.when;
var reason = user.services.password.reset.reason;
var tokenLifetimeMs = Accounts._getPasswordResetTokenLifetimeMs();
if (reason === "enroll") {
tokenLifetimeMs = Accounts._getPasswordEnrollTokenLifetimeMs();
}
var currentTimeMs = Date.now();
if ((currentTimeMs - when) > tokenLifetimeMs)
throw new Meteor.Error(403, "Token expired");
var email = user.services.password.reset.email;
if (!_.include(_.pluck(user.emails || [], 'address'), email))
return {
userId: user._id,
error: new Meteor.Error(403, "Token has invalid email address")
};
var hashed = hashPassword(newPassword);
// NOTE: We're about to invalidate tokens on the user, who we might be
// logged in as. Make sure to avoid logging ourselves out if this
// happens. But also make sure not to leave the connection in a state
// of having a bad token set if things fail.
var oldToken = Accounts._getLoginToken(self.connection.id);
Accounts._setLoginToken(user._id, self.connection, null);
var resetToOldToken = function () {
Accounts._setLoginToken(user._id, self.connection, oldToken);
};
try {
// Update the user record by:
// - Changing the password to the new one
// - Forgetting about the reset token that was just used
// - Verifying their email, since they got the password reset via email.
var affectedRecords = Meteor.users.update(
{
_id: user._id,
'emails.address': email,
'services.password.reset.token': token
},
{$set: {'services.password.bcrypt': hashed,
'emails.$.verified': true},
$unset: {'services.password.reset': 1,
'services.password.srp': 1}});
if (affectedRecords !== 1)
return {
userId: user._id,
error: new Meteor.Error(403, "Invalid email")
};
} catch (err) {
resetToOldToken();
throw err;
}
// Replace all valid login tokens with new ones (changing
// password should invalidate existing sessions).
Accounts._clearAllLoginTokens(user._id);
return {userId: user._id};
}
);
}});
///
/// EMAIL VERIFICATION
///
// send the user an email with a link that when opened marks that
// address as verified
/**
* @summary Send an email with a link the user can use verify their email address.
* @locus Server
* @param {String} userId The id of the user to send email to.
* @param {String} [email] Optional. Which address of the user's to send the email to. This address must be in the user's `emails` list. Defaults to the first unverified email in the list.
* @importFromPackage accounts-base
*/
Accounts.sendVerificationEmail = function (userId, address) {
// XXX Also generate a link using which someone can delete this
// account if they own said address but weren't those who created
// this account.
// Make sure the user exists, and address is one of their addresses.
var user = Meteor.users.findOne(userId);
if (!user)
throw new Error("Can't find user");
// pick the first unverified address if we weren't passed an address.
if (!address) {
var email = _.find(user.emails || [],
function (e) { return !e.verified; });
address = (email || {}).address;
if (!address) {
throw new Error("That user has no unverified email addresses.");
}
}
// make sure we have a valid address
if (!address || !_.contains(_.pluck(user.emails || [], 'address'), address))
throw new Error("No such email address for user.");
var tokenRecord = {
token: Random.secret(),
address: address,
when: new Date()};
Meteor.users.update(
{_id: userId},
{$push: {'services.email.verificationTokens': tokenRecord}});
// before passing to template, update user object with new token
Meteor._ensure(user, 'services', 'email');
if (!user.services.email.verificationTokens) {
user.services.email.verificationTokens = [];
}
user.services.email.verificationTokens.push(tokenRecord);
var verifyEmailUrl = Accounts.urls.verifyEmail(tokenRecord.token);
var options = {
to: address,
from: Accounts.emailTemplates.verifyEmail.from
? Accounts.emailTemplates.verifyEmail.from(user)
: Accounts.emailTemplates.from,
subject: Accounts.emailTemplates.verifyEmail.subject(user)
};
if (typeof Accounts.emailTemplates.verifyEmail.text === 'function') {
options.text =
Accounts.emailTemplates.verifyEmail.text(user, verifyEmailUrl);
}
if (typeof Accounts.emailTemplates.verifyEmail.html === 'function')
options.html =
Accounts.emailTemplates.verifyEmail.html(user, verifyEmailUrl);
if (typeof Accounts.emailTemplates.headers === 'object') {
options.headers = Accounts.emailTemplates.headers;
}
Email.send(options);
};
// Take token from sendVerificationEmail, mark the email as verified,
// and log them in.
Meteor.methods({verifyEmail: function (token) {
var self = this;
return Accounts._loginMethod(
self,
"verifyEmail",
arguments,
"password",
function () {
check(token, String);
var user = Meteor.users.findOne(
{'services.email.verificationTokens.token': token});
if (!user)
throw new Meteor.Error(403, "Verify email link expired");
var tokenRecord = _.find(user.services.email.verificationTokens,
function (t) {
return t.token == token;
});
if (!tokenRecord)
return {
userId: user._id,
error: new Meteor.Error(403, "Verify email link expired")
};
var emailsRecord = _.find(user.emails, function (e) {
return e.address == tokenRecord.address;
});
if (!emailsRecord)
return {
userId: user._id,
error: new Meteor.Error(403, "Verify email link is for unknown address")
};
// By including the address in the query, we can use 'emails.$' in the
// modifier to get a reference to the specific object in the emails
// array. See
// http://www.mongodb.org/display/DOCS/Updating/#Updating-The%24positionaloperator)
// http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull
Meteor.users.update(
{_id: user._id,
'emails.address': tokenRecord.address},
{$set: {'emails.$.verified': true},
$pull: {'services.email.verificationTokens': {address: tokenRecord.address}}});
return {userId: user._id};
}
);
}});
/**
* @summary Add an email address for a user. Use this instead of directly
* updating the database. The operation will fail if there is a different user
* with an email only differing in case. If the specified user has an existing
* email only differing in case however, we replace it.
* @locus Server
* @param {String} userId The ID of the user to update.
* @param {String} newEmail A new email address for the user.
* @param {Boolean} [verified] Optional - whether the new email address should
* be marked as verified. Defaults to false.
* @importFromPackage accounts-base
*/
Accounts.addEmail = function (userId, newEmail, verified) {
check(userId, NonEmptyString);
check(newEmail, NonEmptyString);
check(verified, Match.Optional(Boolean));
if (_.isUndefined(verified)) {
verified = false;
}
var user = Meteor.users.findOne(userId);
if (!user)
throw new Meteor.Error(403, "User not found");
// Allow users to change their own email to a version with a different case
// We don't have to call checkForCaseInsensitiveDuplicates to do a case
// insensitive check across all emails in the database here because: (1) if
// there is no case-insensitive duplicate between this user and other users,
// then we are OK and (2) if this would create a conflict with other users
// then there would already be a case-insensitive duplicate and we can't fix
// that in this code anyway.
var caseInsensitiveRegExp =
new RegExp('^' + Meteor._escapeRegExp(newEmail) + '$', 'i');
var didUpdateOwnEmail = _.any(user.emails, function(email, index) {
if (caseInsensitiveRegExp.test(email.address)) {
Meteor.users.update({
_id: user._id,
'emails.address': email.address
}, {$set: {
'emails.$.address': newEmail,
'emails.$.verified': verified
}});
return true;
}
return false;
});
// In the other updates below, we have to do another call to
// checkForCaseInsensitiveDuplicates to make sure that no conflicting values
// were added to the database in the meantime. We don't have to do this for
// the case where the user is updating their email address to one that is the
// same as before, but only different because of capitalization. Read the
// big comment above to understand why.
if (didUpdateOwnEmail) {
return;
}
// Perform a case insensitive check for duplicates before update
checkForCaseInsensitiveDuplicates('emails.address', 'Email', newEmail, user._id);
Meteor.users.update({
_id: user._id
}, {
$addToSet: {
emails: {
address: newEmail,
verified: verified
}
}
});
// Perform another check after update, in case a matching user has been
// inserted in the meantime
try {
checkForCaseInsensitiveDuplicates('emails.address', 'Email', newEmail, user._id);
} catch (ex) {
// Undo update if the check fails
Meteor.users.update({_id: user._id},
{$pull: {emails: {address: newEmail}}});
throw ex;
}
}
/**
* @summary Remove an email address for a user. Use this instead of updating
* the database directly.
* @locus Server
* @param {String} userId The ID of the user to update.
* @param {String} email The email address to remove.
* @importFromPackage accounts-base
*/
Accounts.removeEmail = function (userId, email) {
check(userId, NonEmptyString);
check(email, NonEmptyString);
var user = Meteor.users.findOne(userId);
if (!user)
throw new Meteor.Error(403, "User not found");
Meteor.users.update({_id: user._id},
{$pull: {emails: {address: email}}});
}
///
/// CREATING USERS
///
// Shared createUser function called from the createUser method, both
// if originates in client or server code. Calls user provided hooks,
// does the actual user insertion.
//
// returns the user id
var createUser = function (options) {
// Unknown keys allowed, because a onCreateUserHook can take arbitrary
// options.
check(options, Match.ObjectIncluding({
username: Match.Optional(String),
email: Match.Optional(String),
password: Match.Optional(passwordValidator)
}));
var username = options.username;
var email = options.email;
if (!username && !email)
throw new Meteor.Error(400, "Need to set a username or email");
var user = {services: {}};
if (options.password) {
var hashed = hashPassword(options.password);
user.services.password = { bcrypt: hashed };
}
if (username)
user.username = username;
if (email)
user.emails = [{address: email, verified: false}];
// Perform a case insensitive check before insert
checkForCaseInsensitiveDuplicates('username', 'Username', username);
checkForCaseInsensitiveDuplicates('emails.address', 'Email', email);
var userId = Accounts.insertUserDoc(options, user);
// Perform another check after insert, in case a matching user has been
// inserted in the meantime
try {
checkForCaseInsensitiveDuplicates('username', 'Username', username, userId);
checkForCaseInsensitiveDuplicates('emails.address', 'Email', email, userId);
} catch (ex) {
// Remove inserted user if the check fails
Meteor.users.remove(userId);
throw ex;
}
return userId;
};
// method for create user. Requests come from the client.
Meteor.methods({createUser: function (options) {
var self = this;
return Accounts._loginMethod(
self,
"createUser",
arguments,
"password",
function () {
// createUser() above does more checking.
check(options, Object);
if (Accounts._options.forbidClientAccountCreation)
return {
error: new Meteor.Error(403, "Signups forbidden")
};
// Create user. result contains id and token.
var userId = createUser(options);
// safety belt. createUser is supposed to throw on error. send 500 error
// instead of sending a verification email with empty userid.
if (! userId)
throw new Error("createUser failed to insert new user");
// If `Accounts._options.sendVerificationEmail` is set, register
// a token to verify the user's primary email, and send it to
// that address.
if (options.email && Accounts._options.sendVerificationEmail)
Accounts.sendVerificationEmail(userId, options.email);
// client gets logged in as the new user afterwards.
return {userId: userId};
}
);
}});
// Create user directly on the server.
//
// Unlike the client version, this does not log you in as this user
// after creation.
//
// returns userId or throws an error if it can't create
//
// XXX add another argument ("server options") that gets sent to onCreateUser,
// which is always empty when called from the createUser method? eg, "admin:
// true", which we want to prevent the client from setting, but which a custom
// method calling Accounts.createUser could set?
//
Accounts.createUser = function (options, callback) {
options = _.clone(options);
// XXX allow an optional callback?
if (callback) {
throw new Error("Accounts.createUser with callback not supported on the server yet.");
}
return createUser(options);
};
///
/// PASSWORD-SPECIFIC INDEXES ON USERS
///
Meteor.users._ensureIndex('services.email.verificationTokens.token',
{unique: 1, sparse: 1});
Meteor.users._ensureIndex('services.password.reset.token',
{unique: 1, sparse: 1});
Meteor.users._ensureIndex('services.password.reset.when',
{sparse: 1});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M19 23h-1.5v-9H19v9zM7.53 14H6l-2 9h1.53l2-9zm5.97-8.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM9.8 8.9L7 23h2.1l1.8-8 2.1 2v6h2v-7.5l-2.1-2 .6-3C14.8 12 16.8 13 19 13v-2c-1.9 0-3.5-1-4.3-2.4l-1-1.6c-.56-.89-1.68-1.25-2.65-.84L6 8.3V13h2V9.6l1.8-.7z" />
, 'NordicWalking');
|
var _ = require('lodash');
var Handlebars = require('handlebars');
var HandlebarsCompiler = function () {
// TODO register helpers here?
};
HandlebarsCompiler.prototype.compileAll = function (templates, callback) {
var templateFns = {};
_.each(templates, function (content, name) {
try {
// if the template name starts with an underscore, register it as a partial
if (_.last(name.split('/')).indexOf('_') === 0) {
Handlebars.registerPartial(name, content);
}
else {
templateFns[name] = Handlebars.compile(content);
}
}
catch (error) {
callback(error);
}
});
callback(null, templateFns);
};
module.exports = HandlebarsCompiler;
|
module.exports = function (grunt) {
// load plugins
[
'grunt-cafe-mocha',
'grunt-contrib-jshint',
'grunt-exec'
].forEach(function (task) {
grunt.loadNpmTasks(task)
})
// configure plugins
grunt.initConfig({
cafemocha: {
all: {src: 'qa/tests-*.js', options: {ui: 'tdd'}}
},
jshint: {
app: ['meadowlark.js', 'public/js/**/*.js', 'lib/**/*.js'],
qa: ['Gruntfile.js', 'public/qa/**/*.js', 'qa/**/*.js']
},
exec: {
linkchecker: {cmd: 'linkchecker http://localhost:3000'}
}
})
// register tasks
grunt.registerTask('default', ['cafemocha', 'jshint', 'exec'])
}
|
import React from 'react/addons'
export default React.createClass({
displayName: 'Number',
mixins: [React.addons.PureRenderMixin],
render() {
return <span {...this.props}>{this.props.value}</span>
}
})
|
/**
* @license AngularJS v1.5.6
* (c) 2010-2016 Google, Inc. http://angularjs.org
* License: MIT
*/
(function (window, angular) {
'use strict';
/**
* @ngdoc module
* @name ngRoute
* @description
*
* # ngRoute
*
* The `ngRoute` module provides routing and deeplinking services and directives for angular apps.
*
* ## Example
* See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
*
*
* <div doc-module-components="ngRoute"></div>
*/
/* global -ngRouteModule */
var ngRouteModule = angular.module('ngRoute', ['ng']).
provider('$route', $RouteProvider),
$routeMinErr = angular.$$minErr('ngRoute');
/**
* @ngdoc provider
* @name $routeProvider
*
* @description
*
* Used for configuring routes.
*
* ## Example
* See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
*
* ## Dependencies
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*/
function $RouteProvider() {
function inherit(parent, extra) {
return angular.extend(Object.create(parent), extra);
}
var routes = {};
/**
* @ngdoc method
* @name $routeProvider#when
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exactly match the
* route definition.
*
* * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
* to the next slash are matched and stored in `$routeParams` under the given `name`
* when the route matches.
* * `path` can contain named groups starting with a colon and ending with a star:
* e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
* when the route matches.
* * `path` can contain optional named groups with a question mark: e.g.`:name?`.
*
* For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
* `/color/brown/largecode/code/with/slashes/edit` and extract:
*
* * `color: brown`
* * `largecode: code/with/slashes`.
*
*
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{(string|function()=}` – Controller fn that should be associated with
* newly created scope or the name of a {@link angular.Module#controller registered
* controller} if passed as a string.
* - `controllerAs` – `{string=}` – An identifier name for a reference to the controller.
* If present, the controller will be published to scope under the `controllerAs` name.
* - `template` – `{string=|function()=}` – html template as a string or a function that
* returns an html template as a string which should be used by {@link
* ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
* This property takes precedence over `templateUrl`.
*
* If `template` is a function, it will be called with the following parameters:
*
* - `{Array.<Object>}` - route parameters extracted from the current
* `$location.path()` by applying the current route
*
* - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
* template that should be used by {@link ngRoute.directive:ngView ngView}.
*
* If `templateUrl` is a function, it will be called with the following parameters:
*
* - `{Array.<Object>}` - route parameters extracted from the current
* `$location.path()` by applying the current route
*
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, the router
* will wait for them all to be resolved or one to be rejected before the controller is
* instantiated.
* If all the promises are resolved successfully, the values of the resolved promises are
* injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is
* fired. If any of the promises are rejected the
* {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired.
* For easier access to the resolved dependencies from the template, the `resolve` map will
* be available on the scope of the route, under `$resolve` (by default) or a custom name
* specified by the `resolveAs` property (see below). This can be particularly useful, when
* working with {@link angular.Module#component components} as route templates.<br />
* <div class="alert alert-warning">
* **Note:** If your scope already contains a property with this name, it will be hidden
* or overwritten. Make sure, you specify an appropriate name for this property, that
* does not collide with other properties on the scope.
* </div>
* The map object is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link auto.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is
* resolved before its value is injected into the controller. Be aware that
* `ngRoute.$routeParams` will still refer to the previous route within these resolve
* functions. Use `$route.current.params` to access the new route parameters, instead.
*
* - `resolveAs` - `{string=}` - The name under which the `resolve` map will be available on
* the scope of the route. If omitted, defaults to `$resolve`.
*
* - `redirectTo` – `{(string|function())=}` – value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - `{boolean=}` - reload route when only `$location.search()`
* or `$location.hash()` changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* - `[caseInsensitiveMatch=false]` - `{boolean=}` - match routes without being case sensitive
*
* If the option is set to `true`, then the particular route can be matched without being
* case sensitive
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function (path, route) {
//copy original route object to preserve params inherited from proto chain
var routeCopy = angular.copy(route);
if (angular.isUndefined(routeCopy.reloadOnSearch)) {
routeCopy.reloadOnSearch = true;
}
if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) {
routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch;
}
routes[path] = angular.extend(
routeCopy,
path && pathRegExp(path, routeCopy)
);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length - 1] == '/')
? path.substr(0, path.length - 1)
: path + '/';
routes[redirectPath] = angular.extend(
{redirectTo: path},
pathRegExp(redirectPath, routeCopy)
);
}
return this;
};
/**
* @ngdoc property
* @name $routeProvider#caseInsensitiveMatch
* @description
*
* A boolean property indicating if routes defined
* using this provider should be matched using a case insensitive
* algorithm. Defaults to `false`.
*/
this.caseInsensitiveMatch = false;
/**
* @param path {string} path
* @param opts {Object} options
* @return {?Object}
*
* @description
* Normalizes the given path, returning a regular expression
* and the original path.
*
* Inspired by pathRexp in visionmedia/express/lib/utils.js.
*/
function pathRegExp(path, opts) {
var insensitive = opts.caseInsensitiveMatch,
ret = {
originalPath: path,
regexp: path
},
keys = ret.keys = [];
path = path
.replace(/([().])/g, '\\$1')
.replace(/(\/)?:(\w+)(\*\?|[\?\*])?/g, function (_, slash, key, option) {
var optional = (option === '?' || option === '*?') ? '?' : null;
var star = (option === '*' || option === '*?') ? '*' : null;
keys.push({name: key, optional: !!optional});
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (star && '(.+?)' || '([^/]+)')
+ (optional || '')
+ ')'
+ (optional || '');
})
.replace(/([\/$\*])/g, '\\$1');
ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
return ret;
}
/**
* @ngdoc method
* @name $routeProvider#otherwise
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object|string} params Mapping information to be assigned to `$route.current`.
* If called with a string, the value maps to `redirectTo`.
* @returns {Object} self
*/
this.otherwise = function (params) {
if (typeof params === 'string') {
params = {redirectTo: params};
}
this.when(null, params);
return this;
};
this.$get = ['$rootScope',
'$location',
'$routeParams',
'$q',
'$injector',
'$templateRequest',
'$sce',
function ($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce) {
/**
* @ngdoc service
* @name $route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as defined in the route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* The `locals` will be assigned to the route scope's `$resolve` property. You can override
* the property name, using `resolveAs` in the route definition. See
* {@link ngRoute.$routeProvider $routeProvider} for more info.
*
* @property {Object} routes Object with all route configuration Objects as its properties.
*
* @description
* `$route` is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*
* You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with the
* {@link ngRoute.directive:ngView `ngView`} directive and the
* {@link ngRoute.$routeParams `$routeParams`} service.
*
* @example
* This example shows how changing the URL hash causes the `$route` to match a route against the
* URL, and the `ngView` pulls in the partial.
*
* <example name="$route-service" module="ngRouteExample"
* deps="angular-route.js" fixBase="true">
* <file name="index.html">
* <div ng-controller="MainController">
* Choose:
* <a href="Book/Moby">Moby</a> |
* <a href="Book/Moby/ch/1">Moby: Ch1</a> |
* <a href="Book/Gatsby">Gatsby</a> |
* <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
* <a href="Book/Scarlet">Scarlet Letter</a><br/>
*
* <div ng-view></div>
*
* <hr />
*
* <pre>$location.path() = {{$location.path()}}</pre>
* <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
* <pre>$route.current.params = {{$route.current.params}}</pre>
* <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
* <pre>$routeParams = {{$routeParams}}</pre>
* </div>
* </file>
*
* <file name="book.html">
* controller: {{name}}<br />
* Book Id: {{params.bookId}}<br />
* </file>
*
* <file name="chapter.html">
* controller: {{name}}<br />
* Book Id: {{params.bookId}}<br />
* Chapter Id: {{params.chapterId}}
* </file>
*
* <file name="script.js">
* angular.module('ngRouteExample', ['ngRoute'])
*
* .controller('MainController', function($scope, $route, $routeParams, $location) {
* $scope.$route = $route;
* $scope.$location = $location;
* $scope.$routeParams = $routeParams;
* })
*
* .controller('BookController', function($scope, $routeParams) {
* $scope.name = "BookController";
* $scope.params = $routeParams;
* })
*
* .controller('ChapterController', function($scope, $routeParams) {
* $scope.name = "ChapterController";
* $scope.params = $routeParams;
* })
*
* .config(function($routeProvider, $locationProvider) {
* $routeProvider
* .when('/Book/:bookId', {
* templateUrl: 'book.html',
* controller: 'BookController',
* resolve: {
* // I will cause a 1 second delay
* delay: function($q, $timeout) {
* var delay = $q.defer();
* $timeout(delay.resolve, 1000);
* return delay.promise;
* }
* }
* })
* .when('/Book/:bookId/ch/:chapterId', {
* templateUrl: 'chapter.html',
* controller: 'ChapterController'
* });
*
* // configure html5 to get links working on jsfiddle
* $locationProvider.html5Mode(true);
* });
*
* </file>
*
* <file name="protractor.js" type="protractor">
* it('should load and compile correct template', function() {
* element(by.linkText('Moby: Ch1')).click();
* var content = element(by.css('[ng-view]')).getText();
* expect(content).toMatch(/controller\: ChapterController/);
* expect(content).toMatch(/Book Id\: Moby/);
* expect(content).toMatch(/Chapter Id\: 1/);
*
* element(by.partialLinkText('Scarlet')).click();
*
* content = element(by.css('[ng-view]')).getText();
* expect(content).toMatch(/controller\: BookController/);
* expect(content).toMatch(/Book Id\: Scarlet/);
* });
* </file>
* </example>
*/
/**
* @ngdoc event
* @name $route#$routeChangeStart
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occur.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* The route change (and the `$location` change that triggered it) can be prevented
* by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on}
* for more details about event object.
*
* @param {Object} angularEvent Synthetic event object.
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name $route#$routeChangeSuccess
* @eventType broadcast on root scope
* @description
* Broadcasted after a route change has happened successfully.
* The `resolve` dependencies are now available in the `current.locals` property.
*
* {@link ngRoute.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Object} angularEvent Synthetic event object.
* @param {Route} current Current route information.
* @param {Route|Undefined} previous Previous route information, or undefined if current is
* first route entered.
*/
/**
* @ngdoc event
* @name $route#$routeChangeError
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Object} angularEvent Synthetic event object
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
*/
/**
* @ngdoc event
* @name $route#$routeUpdate
* @eventType broadcast on root scope
* @description
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*
* @param {Object} angularEvent Synthetic event object
* @param {Route} current Current/previous route information.
*/
var forceReload = false,
preparedRoute,
preparedRouteIsUpdateOnly,
$route = {
routes: routes,
/**
* @ngdoc method
* @name $route#reload
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ngRoute.directive:ngView ngView}
* creates new scope and reinstantiates the controller.
*/
reload: function () {
forceReload = true;
var fakeLocationEvent = {
defaultPrevented: false,
preventDefault: function fakePreventDefault() {
this.defaultPrevented = true;
forceReload = false;
}
};
$rootScope.$evalAsync(function () {
prepareRoute(fakeLocationEvent);
if (!fakeLocationEvent.defaultPrevented) commitRoute();
});
},
/**
* @ngdoc method
* @name $route#updateParams
*
* @description
* Causes `$route` service to update the current URL, replacing
* current route parameters with those specified in `newParams`.
* Provided property names that match the route's path segment
* definitions will be interpolated into the location's path, while
* remaining properties will be treated as query params.
*
* @param {!Object<string, string>} newParams mapping of URL parameter names to values
*/
updateParams: function (newParams) {
if (this.current && this.current.$$route) {
newParams = angular.extend({}, this.current.params, newParams);
$location.path(interpolate(this.current.$$route.originalPath, newParams));
// interpolate modifies newParams, only query params are left
$location.search(newParams);
} else {
throw $routeMinErr('norout', 'Tried updating route when with no current route');
}
}
};
$rootScope.$on('$locationChangeStart', prepareRoute);
$rootScope.$on('$locationChangeSuccess', commitRoute);
return $route;
/////////////////////////////////////////////////////
/**
* @param on {string} current url
* @param route {Object} route regexp to match the url against
* @return {?Object}
*
* @description
* Check if the route matches the current url.
*
* Inspired by match in
* visionmedia/express/lib/router/router.js.
*/
function switchRouteMatcher(on, route) {
var keys = route.keys,
params = {};
if (!route.regexp) return null;
var m = route.regexp.exec(on);
if (!m) return null;
for (var i = 1, len = m.length; i < len; ++i) {
var key = keys[i - 1];
var val = m[i];
if (key && val) {
params[key.name] = val;
}
}
return params;
}
function prepareRoute($locationEvent) {
var lastRoute = $route.current;
preparedRoute = parseRoute();
preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route
&& angular.equals(preparedRoute.pathParams, lastRoute.pathParams)
&& !preparedRoute.reloadOnSearch && !forceReload;
if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) {
if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) {
if ($locationEvent) {
$locationEvent.preventDefault();
}
}
}
}
function commitRoute() {
var lastRoute = $route.current;
var nextRoute = preparedRoute;
if (preparedRouteIsUpdateOnly) {
lastRoute.params = nextRoute.params;
angular.copy(lastRoute.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', lastRoute);
} else if (nextRoute || lastRoute) {
forceReload = false;
$route.current = nextRoute;
if (nextRoute) {
if (nextRoute.redirectTo) {
if (angular.isString(nextRoute.redirectTo)) {
$location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params)
.replace();
} else {
$location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search()))
.replace();
}
}
}
$q.when(nextRoute).
then(resolveLocals).
then(function (locals) {
// after route change
if (nextRoute == $route.current) {
if (nextRoute) {
nextRoute.locals = locals;
angular.copy(nextRoute.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
}
}, function (error) {
if (nextRoute == $route.current) {
$rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
}
});
}
}
function resolveLocals(route) {
if (route) {
var locals = angular.extend({}, route.resolve);
angular.forEach(locals, function (value, key) {
locals[key] = angular.isString(value) ?
$injector.get(value) :
$injector.invoke(value, null, null, key);
});
var template = getTemplateFor(route);
if (angular.isDefined(template)) {
locals['$template'] = template;
}
return $q.all(locals);
}
}
function getTemplateFor(route) {
var template, templateUrl;
if (angular.isDefined(template = route.template)) {
if (angular.isFunction(template)) {
template = template(route.params);
}
} else if (angular.isDefined(templateUrl = route.templateUrl)) {
if (angular.isFunction(templateUrl)) {
templateUrl = templateUrl(route.params);
}
if (angular.isDefined(templateUrl)) {
route.loadedTemplateUrl = $sce.valueOf(templateUrl);
template = $templateRequest(templateUrl);
}
}
return template;
}
/**
* @returns {Object} the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
angular.forEach(routes, function (route, path) {
if (!match && (params = switchRouteMatcher($location.path(), route))) {
match = inherit(route, {
params: angular.extend({}, $location.search(), params),
pathParams: params
});
match.$$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams: {}});
}
/**
* @returns {string} interpolation of the redirect path with the parameters
*/
function interpolate(string, params) {
var result = [];
angular.forEach((string || '').split(':'), function (segment, i) {
if (i === 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
ngRouteModule.provider('$routeParams', $RouteParamsProvider);
/**
* @ngdoc service
* @name $routeParams
* @requires $route
*
* @description
* The `$routeParams` service allows you to retrieve the current set of route parameters.
*
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*
* The route parameters are a combination of {@link ng.$location `$location`}'s
* {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
* The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* Note that the `$routeParams` are only updated *after* a route change completes successfully.
* This means that you cannot rely on `$routeParams` being correct in route resolve functions.
* Instead you can use `$route.current.params` to access the new route's parameters.
*
* @example
* ```js
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
* ```
*/
function $RouteParamsProvider() {
this.$get = function () {
return {};
};
}
ngRouteModule.directive('ngView', ngViewFactory);
ngRouteModule.directive('ngView', ngViewFillContentFactory);
/**
* @ngdoc directive
* @name ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*
* @animations
* | Animation | Occurs |
* |----------------------------------|-------------------------------------|
* | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM |
* | {@link ng.$animate#leave leave} | when the old element is removed from to the DOM |
*
* The enter and leave animation occur concurrently.
*
* @knownIssue If `ngView` is contained in an asynchronously loaded template (e.g. in another
* directive's templateUrl or in a template loaded using `ngInclude`), then you need to
* make sure that `$route` is instantiated in time to capture the initial
* `$locationChangeStart` event and load the appropriate view. One way to achieve this
* is to have it as a dependency in a `.run` block:
* `myModule.run(['$route', function() {}]);`
*
* @scope
* @priority 400
* @param {string=} onload Expression to evaluate whenever the view updates.
*
* @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the view is updated.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
* as an expression yields a truthy value.
* @example
<example name="ngView-directive" module="ngViewExample"
deps="angular-route.js;angular-animate.js"
animations="true" fixBase="true">
<file name="index.html">
<div ng-controller="MainCtrl as main">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div class="view-animate-container">
<div ng-view class="view-animate"></div>
</div>
<hr />
<pre>$location.path() = {{main.$location.path()}}</pre>
<pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{main.$route.current.params}}</pre>
<pre>$routeParams = {{main.$routeParams}}</pre>
</div>
</file>
<file name="book.html">
<div>
controller: {{book.name}}<br />
Book Id: {{book.params.bookId}}<br />
</div>
</file>
<file name="chapter.html">
<div>
controller: {{chapter.name}}<br />
Book Id: {{chapter.params.bookId}}<br />
Chapter Id: {{chapter.params.chapterId}}
</div>
</file>
<file name="animations.css">
.view-animate-container {
position:relative;
height:100px!important;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.view-animate {
padding:10px;
}
.view-animate.ng-enter, .view-animate.ng-leave {
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
display:block;
width:100%;
border-left:1px solid black;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
padding:10px;
}
.view-animate.ng-enter {
left:100%;
}
.view-animate.ng-enter.ng-enter-active {
left:0;
}
.view-animate.ng-leave.ng-leave-active {
left:-100%;
}
</file>
<file name="script.js">
angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookCtrl',
controllerAs: 'book'
})
.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: 'ChapterCtrl',
controllerAs: 'chapter'
});
$locationProvider.html5Mode(true);
}])
.controller('MainCtrl', ['$route', '$routeParams', '$location',
function($route, $routeParams, $location) {
this.$route = $route;
this.$location = $location;
this.$routeParams = $routeParams;
}])
.controller('BookCtrl', ['$routeParams', function($routeParams) {
this.name = "BookCtrl";
this.params = $routeParams;
}])
.controller('ChapterCtrl', ['$routeParams', function($routeParams) {
this.name = "ChapterCtrl";
this.params = $routeParams;
}]);
</file>
<file name="protractor.js" type="protractor">
it('should load and compile correct template', function() {
element(by.linkText('Moby: Ch1')).click();
var content = element(by.css('[ng-view]')).getText();
expect(content).toMatch(/controller\: ChapterCtrl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element(by.partialLinkText('Scarlet')).click();
content = element(by.css('[ng-view]')).getText();
expect(content).toMatch(/controller\: BookCtrl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ngView#$viewContentLoaded
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
function ngViewFactory($route, $anchorScroll, $animate) {
return {
restrict: 'ECA',
terminal: true,
priority: 400,
transclude: 'element',
link: function (scope, $element, attr, ctrl, $transclude) {
var currentScope,
currentElement,
previousLeaveAnimation,
autoScrollExp = attr.autoscroll,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function cleanupLastView() {
if (previousLeaveAnimation) {
$animate.cancel(previousLeaveAnimation);
previousLeaveAnimation = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
previousLeaveAnimation = $animate.leave(currentElement);
previousLeaveAnimation.then(function () {
previousLeaveAnimation = null;
});
currentElement = null;
}
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (angular.isDefined(template)) {
var newScope = scope.$new();
var current = $route.current;
// Note: This will also link all children of ng-view that were contained in the original
// html. If that content contains controllers, ... they could pollute/change the scope.
// However, using ng-view on an element with additional content does not make sense...
// Note: We can't remove them in the cloneAttchFn of $transclude as that
// function is called before linking the content, which would apply child
// directives to non existing elements.
var clone = $transclude(newScope, function (clone) {
$animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() {
if (angular.isDefined(autoScrollExp)
&& (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
});
cleanupLastView();
});
currentElement = clone;
currentScope = current.scope = newScope;
currentScope.$emit('$viewContentLoaded');
currentScope.$eval(onloadExp);
} else {
cleanupLastView();
}
}
}
};
}
// This directive is called during the $transclude call of the first `ngView` directive.
// It will replace and compile the content of the element with the loaded template.
// We need this directive so that the element content is already filled when
// the link function of another directive on the same element as ngView
// is called.
ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
function ngViewFillContentFactory($compile, $controller, $route) {
return {
restrict: 'ECA',
priority: -400,
link: function (scope, $element) {
var current = $route.current,
locals = current.locals;
$element.html(locals.$template);
var link = $compile($element.contents());
if (current.controller) {
locals.$scope = scope;
var controller = $controller(current.controller, locals);
if (current.controllerAs) {
scope[current.controllerAs] = controller;
}
$element.data('$ngControllerController', controller);
$element.children().data('$ngControllerController', controller);
}
scope[current.resolveAs || '$resolve'] = locals;
link(scope);
}
};
}
})(window, window.angular);
|
/**
* @file Main file of Yeoman generator for React web
* @author Karol Altamirano <karlos.altamirano@gmail.com>
* @copyright 2016 - 2017 Karol Altamirano
* @license MIT
*/
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');
const _ = require('lodash');
module.exports = class extends Generator {
prompting() {
this.log(yosay(`Welcome to the ${chalk.green('React Web')} Generator!`));
const prompts = [
{
type: 'input',
name: 'name',
message: 'Your project name (use kebab-case)',
default: _.kebabCase(this.appname),
},
];
return this.prompt(prompts).then((props) => {
this.props = props;
});
}
writing() {
// copy all files except .gitignore and package.json
this.fs.copy(
this.templatePath('**/!(.gitignore|.npmignore|package.json)'),
this.destinationPath(), { globOptions: { dot: true } }
);
// copy .gitignore
if (this.fs.exists(this.templatePath('.npmignore'))) {
this.fs.copy(
this.templatePath('.npmignore'),
this.destinationPath('.gitignore')
);
} else {
this.fs.copy(
this.templatePath('.gitignore'),
this.destinationPath('.gitignore')
);
}
// copy package.json
this.fs.copyTpl(
this.templatePath('package.json'),
this.destinationPath('package.json'),
{ name: _.kebabCase(this.props.name) }
);
}
install() {
this.yarnInstall(null, null, () => {
this.spawnCommandSync('flow-typed', ['install']);
});
}
};
|
module.exports = function (grunt, data) {
return {
options: {
livereload: true
},
setups: {
files: ['<%= _PATH.setup %>/<%= _FILE.config %>'],
tasks: [
'json_generator:bowerrc',
'json_generator:bower',
'shell:bowerRemove',
'shell:bowerCacheClean',
'shell:bowerUpdate',
'less:vendors',
'less:vendorsRTL',
'concat:vendors',
'googlefonts',
'embedfont',
'open'
]
},
styles: {
files: ['<%= _PATH.src_styles %>/<%= _FILE.styles_less %>', '<%= _PATH.src_styles %>/**/<%= _FILE.styles_less %>'],
tasks: ['less:custom', 'less:customRTL']
},
sprites: {
files: ['<%= _PATH.src_images %>/**/<%= _DIR.sprite %>/<%= _FILE.images_raster %>', '!<%= _PATH.src_images_svg_sprite %>/**'],
tasks: ['sprite']
},
svgsprites: {
files: ['<%= _PATH.src_images_svg_sprite %>/<%= _FILE.images_svg %>'],
tasks: ['svg_sprite']
},
images: {
files: ['<%= _PATH.src_images %>/**/<%= _FILE.images_all %>', '!<%= _PATH.src_images %>/**/<%= _DIR.sprite %>/**'],
tasks: ['newer:copy:images']
},
scripts: {
files: ['<%= _PATH.src_scripts %>/<%= _FILE.scripts_js %>', '<%= _PATH.src_scripts %>/**/<%= _FILE.scripts_js %>'],
tasks: ['concat:custom']
},
templates: {
files: ['<%= _PATH.templates %>/<%= _FILE.templates_all %>', '<%= _PATH.templates %>/**/<%= _FILE.templates_all %>']
}
}
};
|
import React from 'react';
import { createRendererWithUniDriver, cleanup } from '../../../test/utils/unit';
import Timeline from '../Timeline';
import { timelinePrivateDriverFactory } from './Timeline.private.uni.driver';
describe(Timeline.displayName, () => {
const render = createRendererWithUniDriver(timelinePrivateDriverFactory);
afterEach(() => {
cleanup();
});
it('should render', async () => {
const { driver } = render(<Timeline items={[]} />);
expect(await driver.exists()).toBe(true);
});
it('should render timeline with basic item', async () => {
const items = [
{
label: 'timeline item number 1',
},
];
const { driver } = render(<Timeline items={items} />);
expect(await driver.getLabelText(0)).toEqual(items[0].label);
});
it('should render the provided `label` node', async () => {
const items = [
{
label: <div data-hook="label-node">timeline item number 1</div>,
},
];
const { driver } = render(<Timeline items={items} />);
expect(
!!(await driver.element()).querySelector('[data-hook="label-node"]'),
).toBe(true);
});
it('should render timeline with text suffix', async () => {
const items = [
{
label: 'timeline item number 1',
suffix: 'suffix text',
},
];
const { driver } = render(<Timeline items={items} />);
expect(await driver.getSuffixText(0)).toEqual(items[0].suffix);
});
it('should render timeline with suffix element', async () => {
const items = [
{
label: 'timeline item number 1',
suffix: <div>suffix node</div>,
},
];
const { driver } = render(<Timeline items={items} />);
expect(await driver.getSuffixElement(0).text()).toEqual('suffix node');
});
it('should render timeline with label action element', async () => {
const items = [
{
label: 'timeline item number 1',
labelAction: <div>label node</div>,
},
];
const { driver } = render(<Timeline items={items} />);
expect(await driver.getLabelActionElement(0).text()).toEqual('label node');
});
it('should render timeline with custom prefix element', async () => {
const items = [
{
label: 'timeline item number 1',
customPrefix: <div>custom prefix node</div>,
},
];
const { driver } = render(<Timeline items={items} />);
expect(await driver.getBulletIndicatorElement(0).text()).toEqual(
'custom prefix node',
);
});
});
|
import {Observable} from 'rx'
import {div, input, label} from '@cycle/dom'
function renderInputField(value) {
return input('.number-input .mdl-textfield__input',
{
type: 'tel',
attributes: {inputmode: "numeric"},
value: value,
pattern: "-?[0-9]*(\.[0-9]+)?"
}
)
}
function renderLabel(labelText) {
return label('.number-input-label .mdl-textfield__label', labelText)
}
function renderNumberInput(props, value) {
return div('.number-input-container', [
div('.mdl-textfield .mdl-js-textfield .mdl-textfield--floating-label',
[renderInputField(value), renderLabel(props.label)]
)]
)
}
function view(props$, value$) {
return Observable.combineLatest(props$, value$, renderNumberInput);
}
export default view;
|
define([
'./directives/index.js'
], function () {
console.log("[OK] - Loading shared modules");
});
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("path", {
d: "M4 8.25l7.51 1-7.5-3.22zm.01 9.72l7.5-3.22-7.51 1z",
opacity: ".3"
}), h("path", {
d: "M2.01 3L2 10l15 2-15 2 .01 7L23 12 2.01 3zM4 8.25V6.03l7.51 3.22-7.51-1zm.01 9.72v-2.22l7.51-1-7.51 3.22z"
})), 'SendTwoTone');
|
/**
* Created by Administrator on 2017/4/19 0019.
*/
var app = require('app');
app.registerController('TreeCtrl', TreeCtrl);
/*@ngInject*/
function TreeCtrl($scope) {
var vm = $scope;
vm.node = null;
var names = ['Homer', 'Marge', 'Bart', 'Lisa', 'Mo'];
function createSubTree(level, width, prefix) {
if (level > 0) {
var res = [];
for (var i = 1; i <= width; i++)
res.push({
"label": "Node " + prefix + i,
"id": "id" + prefix + i,
"i": i,
"children": createSubTree(level - 1, width, prefix + i + "."),
"name": names[i % names.length]
});
return res;
} else
return [];
}
vm.treedata = createSubTree(3, 4, "")
vm.showSelected = function(sel) {
console.log(sel)
vm.selectedNode = sel;
vm.node = sel;
};
vm.expandedNodes = [$scope.treedata[1],
$scope.treedata[3],
$scope.treedata[3].children[2],
$scope.treedata[3].children[2].children[1]
];
vm.getColor = function(node) {
return ["#a40", "#04a", "#990", "#0a4"][node.i % 4];
};
}
|
/**
* Scapegoat
* https://github.com/brentertz/scapegoat
*
* Copyright (c) 2014 Brent Ertz
* Licensed under the MIT license.
*/
var chars = {
'&': '&',
'"': '"',
''': '\'',
'<': '<',
'>': '>'
};
/**
* Escape special characters in the given string of html.
*
* @param {String} html
* @return {String}
*/
module.exports = {
escape: function(html) {
if (!html) {
return '';
}
var values = Object.keys(chars).map(function(key) { return chars[key]; });
var re = new RegExp('(' + values.join('|') + ')', 'g');
return String(html).replace(re, function(match) {
for (var key in chars) {
if (chars.hasOwnProperty(key) && chars[key] === match) {
return key;
}
}
});
},
/**
* Unescape special characters in the given string of html.
*
* @param {String} html
* @return {String}
*/
unescape: function(html) {
if (!html) {
return '';
}
var re = new RegExp('(' + Object.keys(chars).join('|') + ')', 'g');
return String(html).replace(re, function(match) {
return chars[match];
});
}
};
|
_globals.core.__videoBackends.jsmpeg = function() { return _globals.video.jsmpeg.backend }
|
// Generated on 2014-11-04 using generator-ionic 0.6.1
'use strict';
var _ = require('lodash');
var path = require('path');
var cordovaCli = require('cordova');
//var spawn = require('child_process').spawn;
var spawn = require('win-spawn');
var exec = require('child_process').exec;
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
pkg: grunt.file.readJSON('package.json'),
yeoman: {
// configurable paths
app: 'app',
scripts: 'js',
styles: 'css',
images: 'img'
},
// Environment Variables for Angular App
// This creates an Angular Module that can be injected via ENV
// Add any desired constants to the ENV objects below.
// https://github.com/diegonetto/generator-ionic#environment-specific-configuration
ngconstant: {
options: {
space: ' ',
wrap: '"use strict";\n\n {%= __ngModule %}',
name: 'cnodejs.config',
dest: '<%= yeoman.app %>/<%= yeoman.scripts %>/config.js',
constants: {
'$ionicLoadingConfig': {
template: '请求中...'
}
}
},
development: {
constants: {
ENV: {
version: '<%= pkg.version %>',
name: 'development',
debug: true,
// Test user access token
accessToken: '7c8c8a48-bf32-4021-8a91-f4c1e59eaadb',
api: 'http://dev.cnodejs.org/api/v1'
}
}
},
production: {
constants: {
ENV: {
version: '<%= pkg.version %>',
name: 'production',
debug: false,
api: 'https://cnodejs.org/api/v1'
}
}
}
},
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep', 'newer:copy:app']
},
html: {
files: ['<%= yeoman.app %>/**/*.html'],
tasks: ['newer:copy:app']
},
js: {
files: ['<%= yeoman.app %>/<%= yeoman.scripts %>/**/*.js'],
tasks: ['newer:copy:app', 'newer:jshint:all']
},
compass: {
files: ['<%= yeoman.app %>/<%= yeoman.styles %>/**/*.{scss,sass}'],
tasks: ['compass:server', 'autoprefixer', 'newer:copy:tmp']
},
gruntfile: {
files: ['Gruntfile.js'],
tasks: ['ngconstant:development', 'newer:copy:app']
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost'
},
dist: {
options: {
base: 'www'
}
},
coverage: {
options: {
port: 9002,
open: true,
base: ['coverage']
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'Gruntfile.js',
'<%= yeoman.app %>/<%= yeoman.scripts %>/**/*.js'
],
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/unit/**/*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'www/*',
'!www/.git*'
]
}]
},
server: '.tmp'
},
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/<%= yeoman.styles %>/',
src: '{,*/}*.css',
dest: '.tmp/<%= yeoman.styles %>/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//,
overrides: {
'moment': {
'main': 'min/moment-with-locales.js'
}
}
},
sass: {
src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
ignorePath: /(\.\.\/){1,2}lib\//
}
},
// Compiles Sass to CSS and generates necessary files if requested
compass: {
options: {
sassDir: '<%= yeoman.app %>/<%= yeoman.styles %>',
cssDir: '.tmp/<%= yeoman.styles %>',
generatedImagesDir: '.tmp/<%= yeoman.images %>/generated',
imagesDir: '<%= yeoman.app %>/<%= yeoman.images %>',
javascriptsDir: '<%= yeoman.app %>/<%= yeoman.scripts %>',
fontsDir: '<%= yeoman.app %>/<%= yeoman.styles %>/fonts',
importPath: '<%= yeoman.app %>/lib',
httpImagesPath: '/<%= yeoman.images %>',
httpGeneratedImagesPath: '/<%= yeoman.images %>/generated',
httpFontsPath: '/<%= yeoman.styles %>/fonts',
relativeAssets: false,
assetCacheBuster: false,
raw: 'Sass::Script::Number.precision = 10\n'
},
dist: {
options: {
generatedImagesDir: 'www/<%= yeoman.images %>/generated'
}
},
server: {
options: {
debugInfo: true
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: 'www',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on the useminPrepare configuration
usemin: {
html: ['www/**/*.html'],
css: ['www/<%= yeoman.styles %>/**/*.css'],
options: {
assetsDirs: ['www']
}
},
// The following *-min tasks produce minified files in the dist folder
cssmin: {
options: {
root: '<%= yeoman.app %>',
noRebase: true
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: 'www',
src: ['*.html', 'templates/**/*.html'],
dest: 'www'
}]
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: 'www',
src: [
'<%= yeoman.images %>/**/*.{png,jpg,jpeg,gif,webp,svg}',
'*.html',
'templates/**/*.html',
'fonts/*'
]
}, {
expand: true,
cwd: '.tmp/<%= yeoman.images %>',
dest: 'www/<%= yeoman.images %>',
src: ['generated/*']
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/<%= yeoman.styles %>',
dest: '.tmp/<%= yeoman.styles %>/',
src: '{,*/}*.css'
},
fonts: {
expand: true,
cwd: 'app/lib/ionic/release/fonts/',
dest: '<%= yeoman.app %>/fonts/',
src: '*'
},
vendor: {
expand: true,
cwd: '<%= yeoman.app %>/vendor',
dest: '.tmp/<%= yeoman.styles %>/',
src: '{,*/}*.css'
},
app: {
expand: true,
cwd: '<%= yeoman.app %>',
dest: 'www/',
src: [
'**/*',
'!**/*.(scss,sass,css)',
]
},
tmp: {
expand: true,
cwd: '.tmp',
dest: 'www/',
src: '**/*'
}
},
concurrent: {
ionic: {
tasks: [],
options: {
logConcurrentOutput: true
}
},
server: [
'compass:server',
'copy:styles',
'copy:vendor',
'copy:fonts'
],
test: [
'compass',
'copy:styles',
'copy:vendor',
'copy:fonts'
],
dist: [
'compass:dist',
'copy:styles',
'copy:vendor',
'copy:fonts'
]
},
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// 'www/<%= yeoman.styles %>/main.css': [
// '.tmp/<%= yeoman.styles %>/**/*.css',
// '<%= yeoman.app %>/<%= yeoman.styles %>/**/*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// 'www/<%= yeoman.scripts %>/scripts.js': [
// 'www/<%= yeoman.scripts %>/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Test settings
// These will override any config options in karma.conf.js if you create it.
karma: {
options: {
basePath: '',
frameworks: ['mocha', 'chai'],
files: [
'<%= yeoman.app %>/lib/angular/angular.js',
'<%= yeoman.app %>/lib/angular-animate/angular-animate.js',
'<%= yeoman.app %>/lib/angular-sanitize/angular-sanitize.js',
'<%= yeoman.app %>/lib/angular-ui-router/release/angular-ui-router.js',
'<%= yeoman.app %>/lib/ionic/release/js/ionic.js',
'<%= yeoman.app %>/lib/ionic/release/js/ionic-angular.js',
'<%= yeoman.app %>/lib/angular-mocks/angular-mocks.js',
'<%= yeoman.app %>/<%= yeoman.scripts %>/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
autoWatch: false,
reporters: ['dots', 'coverage'],
port: 8080,
singleRun: false,
preprocessors: {
// Update this if you change the yeoman config path
'app/js/**/*.js': ['coverage']
},
coverageReporter: {
reporters: [
{ type: 'html', dir: 'coverage/' },
{ type: 'text-summary' }
]
}
},
unit: {
// Change this to 'Chrome', 'Firefox', etc. Note that you will need
// to install a karma launcher plugin for browsers other than Chrome.
browsers: ['PhantomJS'],
background: true
},
continuous: {
browsers: ['PhantomJS'],
singleRun: true,
}
},
// ngAnnotate tries to make the code safe for minification automatically by
// using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/<%= yeoman.scripts %>',
src: '*.js',
dest: '.tmp/concat/<%= yeoman.scripts %>'
}]
}
}
});
// Register tasks for all Cordova commands
_.functions(cordovaCli).forEach(function (name) {
grunt.registerTask(name, function () {
this.args.unshift(name.replace('cordova:', ''));
// Handle URL's being split up by Grunt because of `:` characters
if (_.contains(this.args, 'http') || _.contains(this.args, 'https')) {
this.args = this.args.slice(0, -2).concat(_.last(this.args, 2).join(':'));
}
var done = this.async();
var exec = process.platform === 'win32' ? 'cordova.cmd' : 'cordova';
var cmd = path.resolve('./node_modules/cordova/bin', exec);
var flags = process.argv.splice(3);
var child = spawn(cmd, this.args.concat(flags));
child.stdout.on('data', function (data) {
grunt.log.writeln(data);
});
child.stderr.on('data', function (data) {
grunt.log.error(data);
});
child.on('close', function (code) {
code = code ? false : true;
done(code);
});
});
});
// Since Apache Ripple serves assets directly out of their respective platform
// directories, we watch all registered files and then copy all un-built assets
// over to www/. Last step is running cordova prepare so we can refresh the ripple
// browser tab to see the changes. Technically ripple runs `cordova prepare` on browser
// refreshes, but at this time you would need to re-run the emulator to see changes.
grunt.registerTask('ripple', ['wiredep', 'newer:copy:app', 'ripple-emulator']);
grunt.registerTask('ripple-emulator', function () {
grunt.config.set('watch', {
all: {
files: _.flatten(_.pluck(grunt.config.get('watch'), 'files')),
tasks: ['newer:copy:app', 'prepare']
}
});
var cmd = path.resolve('./node_modules/ripple-emulator/bin', 'ripple');
var child = spawn(cmd, ['emulate']);
child.stdout.on('data', function (data) {
grunt.log.writeln(data);
});
child.stderr.on('data', function (data) {
grunt.log.error(data);
});
process.on('exit', function (code) {
child.kill('SIGINT');
process.exit(code);
});
return grunt.task.run(['watch']);
});
// Dynamically configure `karma` target of `watch` task so that
// we don't have to run the karma test server as part of `grunt serve`
grunt.registerTask('watch:karma', function () {
var karma = {
files: ['<%= yeoman.app %>/<%= yeoman.scripts %>/**/*.js', 'test/spec/**/*.js'],
tasks: ['newer:jshint:test', 'karma:unit:run']
};
grunt.config.set('watch', karma);
return grunt.task.run(['watch']);
});
// Wrap ionic-cli commands
grunt.registerTask('ionic', function() {
var done = this.async();
var script = path.resolve('./node_modules/ionic/bin/', 'ionic');
var flags = process.argv.splice(3);
var child = spawn(script, this.args.concat(flags), { stdio: 'inherit' });
child.on('close', function (code) {
code = code ? false : true;
done(code);
});
});
grunt.registerTask('test', [
'clean',
'concurrent:test',
'autoprefixer',
'karma:unit:start',
'watch:karma'
]);
grunt.registerTask('serve', function (target) {
if (target === 'compress') {
return grunt.task.run(['compress', 'ionic:serve']);
}
grunt.config('concurrent.ionic.tasks', ['ionic:serve', 'watch']);
grunt.task.run(['init', 'concurrent:ionic']);
});
grunt.registerTask('emulate', function() {
grunt.config('concurrent.ionic.tasks', ['ionic:emulate:' + this.args.join(), 'watch']);
return grunt.task.run(['init', 'concurrent:ionic']);
});
grunt.registerTask('run', function() {
grunt.config('concurrent.ionic.tasks', ['ionic:run:' + this.args.join(), 'watch']);
return grunt.task.run(['init', 'concurrent:ionic']);
});
grunt.registerTask('build', function() {
return grunt.task.run(['compress', 'ionic:build:' + this.args.join()]);
});
// Bumping bundle version
grunt.registerTask('bumpingBundleVersion', function() {
var done = this.async();
exec('git rev-list HEAD | wc -l | awk \'{print $1}\'', function(error, stdout, stderr) {
if (error === null) {
var config = grunt.file.read('config.xml');
config = config.replace(/CFBundleVersion="(\S+)"/gi, 'CFBundleVersion="' + stdout.trim() + '"')
.replace(/versionCode="(\S+)"/gi, 'versionCode="' + stdout.trim() + '"');
grunt.file.write('config.xml', config);
done();
}
});
});
grunt.registerTask('init', [
'clean',
'ngconstant:development',
'wiredep',
'concurrent:server',
'autoprefixer',
'newer:copy:app',
'newer:copy:tmp'
]);
grunt.registerTask('compress', [
'clean',
'ngconstant:production',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngAnnotate',
'copy:dist',
'cssmin',
'uglify',
'usemin',
'htmlmin'
]);
grunt.registerTask('coverage', ['karma:continuous', 'connect:coverage:keepalive']);
grunt.registerTask('default', [
'newer:jshint',
'karma:continuous',
'compress'
]);
};
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require lodash
//= require backbone
//= require moment
//= require wikitest
//= require_tree ../templates
//= require_tree ./models
//= require_tree ./collections
//= require_tree ./views
//= require_tree ./routers
//= require_tree .
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _defineProperty2 = require('babel-runtime/helpers/defineProperty');
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createReactClass = require('create-react-class');
var _createReactClass2 = _interopRequireDefault(_createReactClass);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _mixin = require('./mixin');
var _mixin2 = _interopRequireDefault(_mixin);
var _InputHandler = require('./InputHandler');
var _InputHandler2 = _interopRequireDefault(_InputHandler);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function noop() {}
function preventDefault(e) {
e.preventDefault();
}
var InputNumber = (0, _createReactClass2['default'])({
propTypes: {
focusOnUpDown: _propTypes2['default'].bool,
onChange: _propTypes2['default'].func,
onKeyDown: _propTypes2['default'].func,
onKeyUp: _propTypes2['default'].func,
prefixCls: _propTypes2['default'].string,
disabled: _propTypes2['default'].bool,
onFocus: _propTypes2['default'].func,
onBlur: _propTypes2['default'].func,
readOnly: _propTypes2['default'].bool,
max: _propTypes2['default'].number,
min: _propTypes2['default'].number,
step: _propTypes2['default'].oneOfType([_propTypes2['default'].number, _propTypes2['default'].string]),
upHandler: _propTypes2['default'].node,
downHandler: _propTypes2['default'].node,
useTouch: _propTypes2['default'].bool,
formatter: _propTypes2['default'].func,
parser: _propTypes2['default'].func,
onMouseEnter: _propTypes2['default'].func,
onMouseLeave: _propTypes2['default'].func,
onMouseOver: _propTypes2['default'].func,
onMouseOut: _propTypes2['default'].func
},
mixins: [_mixin2['default']],
getDefaultProps: function getDefaultProps() {
return {
focusOnUpDown: true,
useTouch: false,
prefixCls: 'rc-input-number'
};
},
componentDidMount: function componentDidMount() {
this.componentDidUpdate();
},
componentWillUpdate: function componentWillUpdate() {
try {
this.start = this.refs.input.selectionStart;
this.end = this.refs.input.selectionEnd;
} catch (e) {
// Fix error in Chrome:
// Failed to read the 'selectionStart' property from 'HTMLInputElement'
// http://stackoverflow.com/q/21177489/3040605
}
},
componentDidUpdate: function componentDidUpdate() {
if (this.props.focusOnUpDown && this.state.focused) {
var selectionRange = this.refs.input.setSelectionRange;
if (selectionRange && typeof selectionRange === 'function' && this.start !== undefined && this.end !== undefined && this.start !== this.end) {
this.refs.input.setSelectionRange(this.start, this.end);
} else {
this.focus();
}
}
},
onKeyDown: function onKeyDown(e) {
if (e.keyCode === 38) {
var ratio = this.getRatio(e);
this.up(e, ratio);
this.stop();
} else if (e.keyCode === 40) {
var _ratio = this.getRatio(e);
this.down(e, _ratio);
this.stop();
}
var onKeyDown = this.props.onKeyDown;
if (onKeyDown) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
onKeyDown.apply(undefined, [e].concat(args));
}
},
onKeyUp: function onKeyUp(e) {
this.stop();
var onKeyUp = this.props.onKeyUp;
if (onKeyUp) {
for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
onKeyUp.apply(undefined, [e].concat(args));
}
},
getRatio: function getRatio(e) {
var ratio = 1;
if (e.metaKey || e.ctrlKey) {
ratio = 0.1;
} else if (e.shiftKey) {
ratio = 10;
}
return ratio;
},
getValueFromEvent: function getValueFromEvent(e) {
return e.target.value;
},
focus: function focus() {
this.refs.input.focus();
},
formatWrapper: function formatWrapper(num) {
if (this.props.formatter) {
return this.props.formatter(num);
}
return num;
},
render: function render() {
var _classNames;
var props = (0, _extends3['default'])({}, this.props);
var prefixCls = props.prefixCls,
disabled = props.disabled,
readOnly = props.readOnly,
useTouch = props.useTouch;
var classes = (0, _classnames2['default'])((_classNames = {}, (0, _defineProperty3['default'])(_classNames, prefixCls, true), (0, _defineProperty3['default'])(_classNames, props.className, !!props.className), (0, _defineProperty3['default'])(_classNames, prefixCls + '-disabled', disabled), (0, _defineProperty3['default'])(_classNames, prefixCls + '-focused', this.state.focused), _classNames));
var upDisabledClass = '';
var downDisabledClass = '';
var value = this.state.value;
if (value) {
if (!isNaN(value)) {
var val = Number(value);
if (val >= props.max) {
upDisabledClass = prefixCls + '-handler-up-disabled';
}
if (val <= props.min) {
downDisabledClass = prefixCls + '-handler-down-disabled';
}
} else {
upDisabledClass = prefixCls + '-handler-up-disabled';
downDisabledClass = prefixCls + '-handler-down-disabled';
}
}
var editable = !props.readOnly && !props.disabled;
// focus state, show input value
// unfocus state, show valid value
var inputDisplayValue = void 0;
if (this.state.focused) {
inputDisplayValue = this.state.inputValue;
} else {
inputDisplayValue = this.toPrecisionAsStep(this.state.value);
}
if (inputDisplayValue === undefined || inputDisplayValue === null) {
inputDisplayValue = '';
}
var upEvents = void 0;
var downEvents = void 0;
if (useTouch) {
upEvents = {
onTouchStart: editable && !upDisabledClass ? this.up : noop,
onTouchEnd: this.stop
};
downEvents = {
onTouchStart: editable && !downDisabledClass ? this.down : noop,
onTouchEnd: this.stop
};
} else {
upEvents = {
onMouseDown: editable && !upDisabledClass ? this.up : noop,
onMouseUp: this.stop,
onMouseLeave: this.stop
};
downEvents = {
onMouseDown: editable && !downDisabledClass ? this.down : noop,
onMouseUp: this.stop,
onMouseLeave: this.stop
};
}
var inputDisplayValueFormat = this.formatWrapper(inputDisplayValue);
var isUpDisabled = !!upDisabledClass || disabled || readOnly;
var isDownDisabled = !!downDisabledClass || disabled || readOnly;
// ref for test
return _react2['default'].createElement(
'div',
{
className: classes,
style: props.style,
onMouseEnter: props.onMouseEnter,
onMouseLeave: props.onMouseLeave,
onMouseOver: props.onMouseOver,
onMouseOut: props.onMouseOut
},
_react2['default'].createElement(
'div',
{ className: prefixCls + '-handler-wrap' },
_react2['default'].createElement(
_InputHandler2['default'],
(0, _extends3['default'])({
ref: 'up',
disabled: isUpDisabled,
prefixCls: prefixCls,
unselectable: 'unselectable'
}, upEvents, {
role: 'button',
'aria-label': 'Increase Value',
'aria-disabled': !!isUpDisabled,
className: prefixCls + '-handler ' + prefixCls + '-handler-up ' + upDisabledClass
}),
this.props.upHandler || _react2['default'].createElement('span', {
unselectable: 'unselectable',
className: prefixCls + '-handler-up-inner',
onClick: preventDefault
})
),
_react2['default'].createElement(
_InputHandler2['default'],
(0, _extends3['default'])({
ref: 'down',
disabled: isDownDisabled,
prefixCls: prefixCls,
unselectable: 'unselectable'
}, downEvents, {
role: 'button',
'aria-label': 'Decrease Value',
'aria-disabled': !!isDownDisabled,
className: prefixCls + '-handler ' + prefixCls + '-handler-down ' + downDisabledClass
}),
this.props.downHandler || _react2['default'].createElement('span', {
unselectable: 'unselectable',
className: prefixCls + '-handler-down-inner',
onClick: preventDefault
})
)
),
_react2['default'].createElement(
'div',
{
className: prefixCls + '-input-wrap',
role: 'spinbutton',
'aria-valuemin': props.min,
'aria-valuemax': props.max,
'aria-valuenow': value
},
_react2['default'].createElement('input', {
type: props.type,
placeholder: props.placeholder,
onClick: props.onClick,
className: prefixCls + '-input',
autoComplete: 'off',
onFocus: this.onFocus,
onBlur: this.onBlur,
onKeyDown: editable ? this.onKeyDown : noop,
onKeyUp: editable ? this.onKeyUp : noop,
autoFocus: props.autoFocus,
maxLength: props.maxLength,
readOnly: props.readOnly,
disabled: props.disabled,
max: props.max,
min: props.min,
name: props.name,
onChange: this.onChange,
ref: 'input',
value: inputDisplayValueFormat
})
)
);
}
});
exports['default'] = InputNumber;
module.exports = exports['default'];
|
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function (root) {
if (root === null) return [];
const stack = [root], result = [];
while (stack.length > 0) {
const node = stack.pop();
if (typeof node === 'object') {
if (node.right) stack.push(node.right);
stack.push(node.val);
if (node.left) stack.push(node.left);
} else {
result.push(node);
}
}
return result;
};
|
/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/
/**
* Constructor
* DataSourceHandler
*
* @see
* @since: 2015.07.15
* @author: hw.shim
*/
// @formatter:off
define([
'dojo/topic',
'external/eventEmitter/EventEmitter',
'plugins/workbench/plugin', //TODO : refactor
'webida-lib/util/genetic',
'webida-lib/util/logger/logger-client'
], function(
topic,
EventEmitter,
workbench,
genetic,
Logger
) {
'use strict';
// @formatter:on
/**
* @typedef {Object} DataSource
*/
var logger = new Logger();
//logger.setConfig('level', Logger.LEVELS.log);
//logger.off();
var singleton = null;
function DataSourceHandler() {
logger.info('new DataSourceHandler()');
/** @type {Object} */
this.subscribed = [];
/** @type {Array.<Array>} */
this.deletedNodesSet = [];
this._subscribe();
}
/**
* @return {LifecycleManager}
*/
DataSourceHandler.getInstance = function() {
if (singleton === null) {
singleton = new this();
}
return singleton;
}
genetic.inherits(DataSourceHandler, EventEmitter, {
/**
* subscribe to topic
* @private
*/
_subscribe: function() {
//on deleted
this.subscribed.push(topic.subscribe('workspace.nodes.deleting', this._onNodesDeleted.bind(this)));
this.subscribed.push(topic.subscribe('fs.cache.node.deleted', this._checkCase.bind(this)));
//on content changed
this.subscribed.push(topic.subscribe('data-source/content-change', this._onContentChange.bind(this)));
},
/**
* unsubscribe topics
* @private
*/
_unsubscribe: function() {
this.subscribed.forEach(function(subscribed) {
subscribed.remove();
});
},
/**
* @private
*/
_isMultiDelete: function(path) {
var result = false;
this.deletedNodesSet.forEach(function(deletedNodes) {
deletedNodes.forEach(function(node) {
if (node === path) {
result = true;
}
});
});
return result;
},
/**
* @private
*/
_checkCase: function(fsUrl, dir, name, type, movedPath) {
logger.info('_checkCase(' + JSON.stringify(arguments) + ')');
var path = dir + name;
if (type === 'file') {
if (movedPath) {
this._onNodeMoved(path, movedPath);
} else {
this._onNodeDeleted(path);
}
} else if (type === 'dir') {
path += '/';
movedPath += '/';
if (movedPath) {
this._onDirMoved(path, movedPath);
} else {
this._onDirDeleted(path);
}
}
},
// ************* On Moved ************* //
/**
* @private
*/
_onNodeMoved: function(sourcePath, targetPath) {
logger.info('_onNodeMoved(' + sourcePath + ', ' + targetPath + ')');
var dsRegistry = workbench.getDataSourceRegistry();
var dataSource = dsRegistry.getDataSourceById(sourcePath);
if (dataSource) {
dataSource.setId(targetPath);
}
},
/**
* @private
*/
_onDirMoved: function(sourceDir, targetDir) {
logger.info('_onDirMoved(' + sourceDir + ', ' + targetDir + ')');
var dataSource, persistence, dsId;
var registry = this._getPartRegistry();
var editorParts = registry.getEditorParts();
editorParts.forEach(function(editorPart) {
dataSource = editorPart.getDataSource();
persistence = dataSource.getPersistence();
dsId = dataSource.getId();
if (dsId.indexOf(sourceDir) >= 0) {
dataSource.setId(targetDir + persistence.getName());
}
});
},
// ************* On Deleted ************* //
/**
* @private
*/
_onDirDeleted: function(dirPath) {
logger.info('_onDirDeleted(' + dirPath + ')');
var dsId;
var shouldBeClosedParts = [];
var registry = this._getPartRegistry();
var editorParts = registry.getEditorParts();
editorParts.forEach(function(editorPart) {
dsId = editorPart.getDataSource().getId();
if (dsId.indexOf(dirPath) >= 0) {
shouldBeClosedParts.push(editorPart);
}
});
shouldBeClosedParts.forEach(function(part) {
_askClose(part.getDataSource());
});
},
/**
* @private
* TODO : Support Close All (or Remain All)
* But, This feature is required indeed? :(
*/
_onNodesDeleted: function(nodes) {
logger.info('_onNodesDeleted(' + nodes + ')');
this.deletedNodesSet.push(nodes);
},
/**
* @private
*/
_onNodeDeleted: function(dataSourceId) {
logger.info('_onNodeDeleted(' + dataSourceId + ')');
var registry = this._getPartRegistry();
var dsRegistry = workbench.getDataSourceRegistry();
var dataSource = dsRegistry.getDataSourceById(dataSourceId);
var parts = registry.getPartsByDataSource(dataSource);
if (parts.length > 0) {
_askClose(dataSource);
}
},
// ************* On Content Changed ************* //
_onContentChange: function(dataSourceId) {
var dsRegistry = workbench.getDataSourceRegistry();
var dataSource = dsRegistry.getDataSourceById(dataSourceId);
_askReload(dataSource);
},
/**
* @private
*/
_getPartRegistry: function() {
var page = workbench.getCurrentPage();
return page.getPartRegistry();
}
});
function _askClose(dataSource) {
var dataSourceId = dataSource.getId();
var persistence = dataSource.getPersistence();
require(['popup-dialog'], function(PopupDialog) {
// @formatter:off
PopupDialog.yesno({
title: "Close '" + persistence.getName() + "'?",
message: "'" + persistence.getPath() + "' has been deleted. "
+ 'Close the editor for the resource?'
}).then(function() {
topic.publish('editor/close/data-source-id', dataSourceId, {
force: true
});
}, function() {
});
// @formatter:on
});
}
function _askReload(dataSource) {
var dataSourceId = dataSource.getId();
var persistence = dataSource.getPersistence();
require(['popup-dialog'], function(PopupDialog) {
// @formatter:off
PopupDialog.yesno({
title: "Reload '" + persistence.getName() + "'?",
message: "'" + persistence.getPath() + "' has been changed. "
+ 'Reload the editor(s) for the resource?',
type: 'warning'
}).then(function() {
var page = workbench.getCurrentPage();
var registry = page.getPartRegistry();
var parts = registry.getPartsByDataSource(dataSource);
parts.forEach(function(part) {
part.resetModel();
});
}, function() {
});
// @formatter:on
});
}
return DataSourceHandler;
});
|
import GeometryDescriptorBase from './GeometryDescriptorBase';
class BufferGeometryDescriptorBase extends GeometryDescriptorBase {
updateCacheAndReplace = (propName, threeObject, newValue) => {
threeObject.userData._propsCache[propName] = newValue;
threeObject.userData._wantPropertyOverwrite = true;
};
beginPropertyUpdates(threeObject) {
super.beginPropertyUpdates(threeObject);
threeObject.userData._wantPropertyOverwrite = false;
}
completePropertyUpdates(threeObject) {
super.completePropertyUpdates(threeObject);
if (threeObject.userData._wantPropertyOverwrite) {
threeObject.userData._wantPropertyOverwrite = false;
threeObject.copy(this.construct(threeObject.userData._propsCache));
}
}
applyInitialProps(threeObject, props) {
super.applyInitialProps(threeObject, props);
threeObject.userData._propsCache = {
...props,
};
}
}
module.exports = BufferGeometryDescriptorBase;
|
/**
* cbpAnimatedHeader.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2013, Codrops
* http://www.codrops.com
*/
var cbpAnimatedHeader = (function() {
var docElem = document.documentElement,
header = document.querySelector( '.navbar-default' ),
didScroll = false,
changeHeaderOn = 400;
function init() {
window.addEventListener( 'scroll', function( event ) {
if( !didScroll ) {
didScroll = true;
setTimeout( scrollPage, 100 );
}
}, false );
}
function scrollPage() {
var sy = scrollY();
if ( sy >= changeHeaderOn ) {
classie.add( header, 'navbar-shrink' );
}
else {
classie.remove( header, 'navbar-shrink' );
}
didScroll = false;
}
function scrollY() {
return window.pageYOffset || docElem.scrollTop;
}
init();
})();
|
App.info({
id: 'de.lespace.kurentometeor',
name: 'helloWorld',
description: 'a simple Kurento WebRTC Example',
author: 'Nico Krause',
email: 'nico@le-space.de',
website: 'http://www.le-space.de'
});
// Set up resources such as icons and launch screens.
// App.icons({
// 'iphone': 'icons/icon-60.png',
// 'iphone_2x': 'icons/icon-60@2x.png',
// // ... more screen sizes and platforms ...
// });
// App.launchScreens({
// 'iphone': 'splash/Default~iphone.png',
// 'iphone_2x': 'splash/Default@2x~iphone.png',
// // ... more screen sizes and platforms ...
// });
// Set PhoneGap/Cordova preferences
// App.setPreference('BackgroundColor', '0xff0000ff');
App.accessRule('http://*');
App.accessRule('https://*');
App.accessRule('*');
App.accessRule('*://test.remote.yoga:*');
App.accessRule('*://173.194.71.127:*');
App.accessRule('*5.9.154.226:*');
App.accessRule('*://localhost:*');
App.accessRule('*://192.168.192.251:*');
|
angular.module('house_app', [])
.controller('house_controller',
['$scope', '$attrs', function($scope, $attrs)
{
$scope.ajax_call = function(function_name, kwargs, callback, next_callback)
{
ajax_call(
$attrs.apiurl, function_name, kwargs,
scope_apply_callback($scope, function(api_result) {
var callback_result = run_possible_callback(
callback, api_result);
run_possible_callback(next_callback, callback_result);
})
);
}
$scope.press_remote_button = function (device, button)
{
$scope.ajax_call(
"press_remote", {"device": device, "button": button});
}
$scope.press_remote_buttons = function (devices_and_buttons_and_timeouts)
{
$scope.ajax_call(
"press_remote_buttons",
{"devices_and_buttons_and_timeouts":
devices_and_buttons_and_timeouts});
}
$scope.on_remote_button_down = function (device, button)
{
$scope.pressed_device_and_button = [device, button];
function send_signal()
{
$scope.ajax_call(
"press_remote",
{"device": device, "button": button},
function () {
if ($scope.pressed_device_and_button[0] == device &&
$scope.pressed_device_and_button[1] == button)
send_signal();
}
);
}
send_signal();
}
$scope.on_remote_button_up = function ()
{
$scope.pressed_device_and_button = [null, null];
}
$scope.set_light_scene = function (scene_name)
{
$scope.ajax_call("set_light_scene", {"scene_name": scene_name});
}
$scope.turn_on_switch = function (switch_name)
{
$scope.ajax_call("turn_on_switch", {"switch_name": switch_name});
}
$scope.turn_off_switch = function (switch_name)
{
$scope.ajax_call("turn_off_switch", {"switch_name": switch_name});
}
init = function() {
$scope.pressed_device_and_button = [null, null];
}
init();
}]).directive("ngTouchstart", [function() {
return function (scope, element, attr) {
element.on("touchstart mousedown", function(event) {
scope.$apply(function() { scope.$eval(attr.ngTouchstart); });
});
};
}]).directive("ngTouchend", [function() {
return function (scope, element, attr) {
element.on("touchend mouseup", function(event) {
scope.$apply(function() { scope.$eval(attr.ngTouchend); });
});
};
}]);
|
/*! angular-facebook-insight - v0.6.1 - 2014-07-13
* Copyright (c) 2014 ; Licensed */
'use strict';
angular.module("angular-s3-upload-tpls", ["templates/angular-s3-upload-button.html"]);
|
/*!
* Aloha Editor
* Author & Copyright (c) 2010 Gentics Software GmbH
* aloha-sales@gentics.com
* Licensed unter the terms of http://www.aloha-editor.com/license.html
*/
define(
['aloha',
'aloha/plugin',
'aloha/jquery',
'aloha/floatingmenu',
'i18n!toc/nls/i18n',
'i18n!aloha/nls/i18n',
'aloha/console'],
function( Aloha, Plugin, jQuery, FloatingMenu, i18n, i18nCore, console ) {
"use strict";
var
GENTICS = window.GENTICS,
namespace = 'toc',
$containers = null,
allTocs = [];
/* helper functions */
function last(a) { return a[a.length - 1]; }
function head(a) { return a[0]; }
function tail(a) { return a.slice(1); }
function indexOf(a, item) {
return detect(a, function(cmp){
return cmp === item;
});
}
function detect(a, f) {
for (var i = 0; i < a.length; i++) {
if (f(a[i])) {
return a[i];
}
}
return null;
}
function map(a, f) {
var result = [];
for (var i = 0; i < a.length; i++) {
result.push(f(a[i]));
}
return result;
}
function each(a, f) {
map(a, f);
}
/**
* register the plugin with unique name
*/
return Plugin.create(namespace, {
languages: ['en', 'de'],
minEntries: 0,
updateInterval: 5000,
config: ['toc'],
init: function () {
var that = this;
if ( typeof this.settings.minEntries === 'undefined' ) {
this.settings.minEntries = this.minEntries;
}
if ( typeof this.settings.updateInterval === 'undefined' ) {
this.settings.updateInterval = this.updateInterval;
}
Aloha.bind( 'aloha-editable-activated', function ( event, rangeObject ) {
if (Aloha.activeEditable) {
that.cfg = that.getEditableConfig( Aloha.activeEditable.obj );
if ( jQuery.inArray( 'toc', that.cfg ) != -1 ) {
that.insertTocButton.show();
} else {
that.insertTocButton.hide();
return;
}
}
});
this.initButtons();
jQuery(document).ready(function(){
that.spawn();
});
},
initButtons: function () {
var scope = 'Aloha.continuoustext',
that = this;
this.insertTocButton = new Aloha.ui.Button({
'iconClass' : 'aloha-button aloha-button-ol',
'size' : 'small',
'onclick' : function () { that.insertAtSelection($containers); },
'tooltip' : i18n.t('button.addtoc.tooltip'),
'toggle' : false
});
FloatingMenu.addButton(
scope,
this.insertTocButton,
i18nCore.t('floatingmenu.tab.insert'),
1
);
},
register: function ($c) {
$containers = $c;
},
/**
* inserts a new TOC at the current selection
*/
insertAtSelection: function($containers){
$containers = $containers || editableContainers();
var id = generateId('toc');
// we start out with an empty ordered list
var $tocElement = jQuery("<ol class='toc_root'></ol>").
attr('id', id).attr('contentEditable', 'false');
var range = Aloha.Selection.getRangeObject();
var tocEditable = Aloha.activeEditable;
var $tocContainer = jQuery(document.getElementById(tocEditable.getId()));
GENTICS.Utils.Dom.insertIntoDOM($tocElement, range, $tocContainer);
this.create(id).register($containers).update().tickTock();
},
/**
* Spawn containers for all ols with the toc_root class.
*/
spawn: function ($ctx, $containers) {
$ctx = $ctx || jQuery('body');
$containers = $containers || editableContainers();
$ctx.find('ol.toc_root').each(function(){
var id = jQuery(this).attr('id');
if (!id) {
id = generateId('toc');
jQuery(this).attr('id', id);
}
that.create(id).register($containers).tickTock();
});
},
create: function (id) {
allTocs.push(this);
return {
'id': id,
'$containers': jQuery(),
'settings': this.settings,
/**
* find the TOC root element for this instance
*/
root: function(){
return jQuery(document.getElementById(this.id));
},
/**
* registers the given containers with the TOC. a
* container is an element that may begin or contain
* sections. Note: use .live on all [contenteditable=true]
* to catch dynamically added editables.
* the same containers can be passed in multiple times. they will
* be registered only once.
*/
register: function ($containers){
var self = this;
// the .add() method ensures that the $containers will be in
// document order (required for correct TOC order)
self.$containers = self.$containers.add($containers);
self.$containers.filter(function(){
return !jQuery(this).data(namespace + '.' + self.id + '.listening');
}).each(function(){
var $container = jQuery(this);
$container.data(namespace + '.' + self.id + '.listening', true);
$container.bind('blur', function(){
self.cleanupIds($container.get(0));
self.update($container);
});
});
return self;
},
tickTock: function (interval) {
var self = this;
interval = interval || this.settings.updateInterval;
if (!interval) {
return;
}
window.setInterval(function(){
self.register(editableContainers());
// TODO: use the active editable instead of rebuilding
// the entire TOC
self.update();
}, interval);
return self;
},
/**
* there are various ways which can cause duplicate ids on targets
* (e.g. pressing enter in a heading and writing in a new line, or
* copy&pasting). Passing a ctx updates only those elements
* either inside or equal to it.
* TODO: to be correct this should do
* a $.contains(documentElement...
*/
cleanupIds: function (ctx) {
var ids = [],
that = this;
this.headings(this.$containers).each(function(){
var id = jQuery(this).attr('id');
if ( (id && -1 != jQuery.inArray(id, ids))
|| ( ctx
&& (jQuery.contains(ctx, this) || ctx === this)))
{
jQuery(this).attr('id', generateId(this));
}
ids.push(id);
});
return this;
},
/**
* Updates the TOC from the sections in the given context, or in
* all containers that have been registered with this TOC, if no
* context is given.
*/
update: function ($ctx) {
var self = this;
$ctx = $ctx || self.$containers;
var outline = this.outline(self.$containers);
var ancestors = [self.root()];
var prevSiblings = [];
//TODO: handle TOC rebuilding more intelligently. currently,
//the TOC is always rebuilt from scratch.
last(ancestors).empty();
(function descend(outline) {
var prevSiblings = [];
each(outline, function (node) {
var $section = head(node);
var $entry = self.linkSection($section, ancestors, prevSiblings);
ancestors.push($entry);
descend(tail(node));
ancestors.pop();
prevSiblings.push($entry);
});
})(tail(outline));
// count number of li's in the TOC, if less than minEntries, hide the TOC
var minEntries = self.root().attr('data-TOC-minEntries') || this.settings.minEntries;
if (self.root().find('li').length >= minEntries) {
self.root().show();
} else {
self.root().hide();
}
return this;
},
/**
* updates or creates an entry in the TOC for the given section.
*/
linkSection: function ($section, ancestors, prevSiblings) {
var linkId = $section.eq(0).attr('id');
if (!linkId) {
linkId = generateId($section.get(0));
$section.eq(0).attr('id', linkId);
}
var $root = this.root();
var $entry = anchorFromLinkId($root, linkId);
if (!$entry.length) {
$entry = jQuery('<li><a/></li>');
}
$entry.find('a').
attr('href', '#' + linkId).
text($section.eq(0).text());
if (last(prevSiblings)) {
last(prevSiblings).after($entry);
}
else {
if (last(ancestors).get(0) == $root.get(0)) {
$root.append($entry);
}
else {
var $subToc = jQuery('<ol/>').append($entry);
last(ancestors).append($subToc);
}
}
return $entry;
},
/**
* returns a tree of sections in the given context. if the context
* element(s) begin a section, they will be included. First element
* of each branch in the tree is a $(section) or $() for the
* root node.
* TODO: http://www.w3.org/TR/html5/sections.html#outline
*/
outline: function (ctx) {
var rootNode = [jQuery()];
var potentialParents = [rootNode];
this.headings(ctx).each(function(){
var $heading = jQuery(this);
var nodeName = this.nodeName.toLowerCase();
var hLevels = ['h6', 'h5', 'h4', 'h3', 'h2', 'h1'];
var currLevel = jQuery.inArray(nodeName, hLevels);
var higherEq = hLevels.slice(currLevel).join(',');
var $section = $heading.nextUntil(higherEq).andSelf();
var node = [$section];
var parent = detect(potentialParents, function (parent) {
var parentSection = parent[0];
return !parentSection.length || //top-level contains everything
detect(parentSection, function (sectionElem) {
return $heading.get(0) === sectionElem ||
jQuery.contains(sectionElem, $heading.get(0));
});
});
parent.push(node);
potentialParents.splice(0, indexOf(potentialParents, parent), node);
});
return rootNode;
},
headings: function ($ctx) {
return $ctx.find(':header').add($ctx.filter(':header'));
}
}
}
});
//-------------- module methods -----------------
function editableContainers () {
return jQuery(map(Aloha.editables, function (editable) {
return document.getElementById(editable.getId());
}));
}
function anchorFromLinkId ($ctx, linkId) {
return linkId ? $ctx.find('a[href $= "#' + linkId + '"]') : jQuery();
}
function linkIdFromAnchor ($anchor){
var href = $anchor.attr('href');
return href ? href.match(/#(.*?)$/)[1] : null;
}
function generateId (elemOrText) {
var validId;
if (typeof elemOrText == "object") {
validId = jQuery(elemOrText).text().
replace(/[^a-zA-Z-]+/g, '-').
replace(/^[^a-zA-Z]+/, '');
} else if (elemOrText) {
validId = elemOrText;
}
for (var uniquifier = 0;; uniquifier++) {
var uniqueId = validId;
if (uniquifier) {
uniqueId += '-' + uniquifier;
}
var conflict = document.getElementById(uniqueId);
if ( !conflict
|| ( typeof elemOrText == "object"
&& conflict === elemOrText))
{
return uniqueId;
}
}
//unreachable
}
});
|
import map from './map';
export default function listen() {
window.addEventListener('attribute.load.cmd', function(e){
var loader = map(e.detail);
loader.call(e.target);
});
}
|
import SectionManager from '../SectionManager';
export default function calculateSizeAndPositionData({
cellCount,
cellSizeAndPositionGetter,
sectionSize,
}) {
const cellMetadata = [];
const sectionManager = new SectionManager(sectionSize);
let height = 0;
let width = 0;
for (let index = 0; index < cellCount; index++) {
const cellMetadatum = cellSizeAndPositionGetter({index});
if (
cellMetadatum.height == null ||
isNaN(cellMetadatum.height) ||
cellMetadatum.width == null ||
isNaN(cellMetadatum.width) ||
cellMetadatum.x == null ||
isNaN(cellMetadatum.x) ||
cellMetadatum.y == null ||
isNaN(cellMetadatum.y)
) {
throw Error(
`Invalid metadata returned for cell ${index}:
x:${cellMetadatum.x}, y:${cellMetadatum.y}, width:${cellMetadatum.width}, height:${cellMetadatum.height}`,
);
}
height = Math.max(height, cellMetadatum.y + cellMetadatum.height);
width = Math.max(width, cellMetadatum.x + cellMetadatum.width);
cellMetadata[index] = cellMetadatum;
sectionManager.registerCell({
cellMetadatum,
index,
});
}
return {
cellMetadata,
height,
sectionManager,
width,
};
}
|
/* global Flatdoc */
/* global bowlineApp */
'use strict';
/**
* @ngdoc function
* @name bowlineApp.controller:AboutCtrl
* @description
* # AboutCtrl
* Controller of the bowlineApp
*/
bowlineApp.controller('docsController', ['$scope', '$location', '$http', '$routeParams', 'loginModule', 'ENV', function($scope,$location,$http,$routeParams,login,ENV) {
var REPO = 'dougbtv/bowline';
$scope.mode = "started";
var markdown = {
"started": 'docs/GettingStarted.md',
"runninglocal": 'docs/RunningLocally.md',
"usinghooks": 'docs/UsingGitHooks.md',
};
if ($routeParams.specificdoc) {
$scope.mode = $routeParams.specificdoc;
}
var readme_full_url = "https://raw.githubusercontent.com/dougbtv/bowline/master/" + markdown[$scope.mode];
$http.get(readme_full_url)
.success(function(data) {
// console.log("!trace readme ajax data: ",data);
var md = new Remarkable();
$scope.rendered_markdown = md.render(data);
}.bind(this))
.error(function(data) {
// Couldn't reach the readme, seems.
}.bind(this));
/*
Flatdoc.run({
fetcher: Flatdoc.github(REPO, markdown[$scope.mode])
});
*/
// This just sets the location, and we let that do the magic, since it will re-instantiate this mother.
$scope.clickDocs = function(mode) {
$location.path("/docs/" + mode);
};
$scope.docsTab = function(mode) {
if (mode === $scope.mode) {
return "active";
} else {
return "";
}
};
}]);
|
// const urlParser = document.createElement('a');
// export function domain(url) {
// urlParser.href = url;
// return urlParser.hostname;
// }
// compatible for ssr, no global DOM ?
export function host(url) {
const host = url.replace(/^https?:\/\//, '').replace(/\/.*$/, '');
const parts = host.split('.').splice(-3);
if (parts[0] === 'www') parts.shift();
return parts.join('.');
}
export function timeAgo(time) {
const diff = Date.now() / 1000 - Number(time);
if (diff < 3600) {
return pluralize(~~(diff / 60), 'minute');
} else if (diff < 3600 * 24) {
return pluralize(~~(diff / 3600), 'hour');
} else {
return pluralize(~~(diff / 3600 / 24), 'day');
}
}
/**
* pluralize labels for text
* @param {Number} time
* @param {String} label
* @returns
*/
function pluralize(time, label) {
if (time === 1) {
return time + label;
} else {
return time + label + 's';
}
}
|
var string = require('../../utils/string');
var parser = require('./parser');
/**
* var updateSelectorParent - get a Selector that just got modified
* and make sure to modify it's parents Selectors as well accordingly
*
* @param {Selector} selector
*/
var updateSelectorParent = function(selector) {
while (selector['_parent']) {
selector['_parent']['_raw'] = selector['_parent'].stringify();
selector = selector['_parent'];
}
};
/**
* var addToSelector - add provided selector type to Selector
*
* @param {Selector} selector
* @param {string} type
* @param {string/object} val
*/
var addToSelector = function(selector, type, val) {
if (selector[type].includes(val)) {
return;
}
selector[type].push(val);
selector['_raw'] = selector.stringify();
updateSelectorParent(selector);
};
/**
* var removeFromSelector - remove provided selector type from Selector
*
* @param {Selector} selector
* @param {string} type
* @param {string/object} val
*/
var removeFromSelector = function(selector, type, val) {
selector[type] = selector[type].filter(function(curVal) {
return curVal !== val && (!curVal['_raw'] || !val['_raw'] || curVal['_raw'] !== val['_raw']);
});
selector['_raw'] = selector.stringify();
updateSelectorParent(selector);
};
/**
* var isContainedInSelector - tell whether provided selector type is contained in selector
*
* @param {Selector} selector
* @param {string} type
* @param {string/object} val
* @returns {bool}
*/
var isContainedInSelector = function(selector, type, val) {
return selector[type].filter(function(curVal) {
return curVal === val || (curVal['_raw'] && val['_raw'] && curVal['_raw'] === val['_raw']);
}).length !== 0;
};
/**
* class SelectorUnit
* representation of a selector unit.
* example for a valid SelectorUnit: 'A#id1'
*
* @param {string} str string representation of a selectorUnit
* @param {function} newSelector callback that gets a string representation of a
* Selector and returns a Selector instance
*/
class SelectorUnit {
constructor(str, newSelector) {
var obj = parse(str, newSelector);
for (var prop in obj) {
this[prop] = obj[prop];
}
}
stringify() {
return stringify(this);
}
isTagEquals(tag) {
return tag === this['tag'];
}
contains(prop, val) {
if (!prop || !val) {
return;
}
switch (prop) {
case 'id':
return isContainedInSelector(this, 'ids', val);
break;
case 'class':
return isContainedInSelector(this, 'classes', val);
break;
case 'pseudoClass':
return isContainedInSelector(this, 'pseudoClasses', val);
break;
case 'pseudoElement':
return isContainedInSelector(this, 'pseudoElements', val);
break;
case 'attribute':
// in case of attribute setting, variables and their order change
var operator = arguments[2];
prop = val;
val = arguments[3];
var raw = prop; // TODO: make it possible to pass 'contains' instead of '*='
if ('' !== operator) {
raw += operator + val;
}
return isContainedInSelector(this, 'attributes', {
'property' : prop,
'value' : val,
'behaviour' : parser.ATTRIBUTES_OPERATORS[operator],
'operator' : operator,
'_raw' : raw
});
break;
case 'not':
return isContainedInSelector(this, 'nots', val);
}
}
set(prop, val) {
if (!prop || !val) {
return;
}
switch (prop) {
case 'tag':
this['tag'] = val || '*';
var prevTag = parser.getTag(this['_raw']);
if (!prevTag) {
this['_raw'] = val + this['_raw'];
} else {
this['_raw'] = this['_raw'].replace(prevTag, val);
}
updateSelectorParent(this);
break;
case 'id':
addToSelector(this, 'ids', val);
break;
case 'class':
addToSelector(this, 'classes', val);
break;
case 'pseudoClass':
addToSelector(this, 'pseudoClasses', val);
break;
case 'pseudoElement':
addToSelector(this, 'pseudoElements', val);
break;
case 'attribute':
// in case of attribute setting, variables and their order change
var operator = arguments[2];
prop = val;
val = arguments[3];
var raw = prop; // TODO: make it possible to pass 'contains' instead of '*='
if ('' !== operator) {
raw += operator + val;
}
for (var i in this['attributes']) {
if (raw === this['attributes'][i]['_raw']) {
return;
}
}
addToSelector(this, 'attributes', {
'property' : prop,
'value' : val,
'behaviour' : parser.ATTRIBUTES_OPERATORS[operator],
'operator' : operator,
'_raw' : raw
});
break;
case 'not':
val['_parent'] = this; // link new not to it's parent
addToSelector(this, 'nots', val);
}
}
remove(prop, val) {
if (!prop || !val) {
return;
}
switch (prop) {
case 'tag':
this['set']('tag', '*');
break;
case 'id':
removeFromSelector(this, 'ids', val);
break;
case 'class':
removeFromSelector(this, 'classes', val);
break;
case 'pseudoClass':
removeFromSelector(this, 'pseudoClasses', val);
break;
case 'pseudoElement':
removeFromSelector(this, 'pseudoElements', val);
break;
case 'attribute':
// in case of attribute setting, variables and their order change
var operator = arguments[2];
prop = val;
val = arguments[3];
var raw = prop; // TODO: make it possible to pass 'contains' instead of '*='
if ('' !== operator) {
raw += operator + val;
}
removeFromSelector(this, 'attributes', {
'property' : prop,
'value' : val,
'behaviour' : parser.ATTRIBUTES_OPERATORS[operator],
'operator' : operator,
'_raw' : raw
});
break;
case 'not':
delete val['_parent'];
removeFromSelector(this, 'nots', val);
}
}
}
/**
* var parse - convert selector string into the selector's representation as an array
*
* @param {string} str
* @param {function} newSelector callback that gets a string representation of a
* Selector and returns a Selector instance
* @returns {array} array of Selectors
*/
var parse = function(selector,newSelector) {
var obj = {};
selector = string.trim(selector);
obj['_raw'] = parser.getRaw(selector);
obj['tag'] = parser.getTag(selector) || '*';
var ret = parser.splitByHierarchy(selector);
if (ret) {
var bfrSelector = ret[0];
var hierarchyKind = ret[1];
var afrSelector = ret[2];
obj[hierarchyKind] = newSelector(afrSelector)[0]; // parse the next hierarchy component
// only the selector of before the operator occurence should be extracted for information
selector = bfrSelector;
}
obj['ids'] = parser.getIds(selector);
obj['classes'] = parser.getClasses(selector);
obj['pseudoElements'] = parser.getPseudoElements(selector);
obj['pseudoClasses'] = parser.getPseudoClasses(selector);
obj['nots'] = [];
var nots = parser.getNots(obj['_raw']);
for (var j in nots) {
obj['nots'][j] = parse(nots[j], newSelector); // every :not includes another selector
}
obj['attributes'] = parser.getAttributes(selector);
// make sure every selector is linked to it's parent selector (if one exists)
for (var j in obj['nots']) {
obj['nots'][j]['_parent'] = obj;
}
for (var j in parser.HIERARCHY_OPERATORS) {
if (obj[parser.HIERARCHY_OPERATORS[j]]) {
obj[parser.HIERARCHY_OPERATORS[j]]['_parent'] = obj;
}
}
return obj;
};
/**
* var stringify - convert selector's representation as an array into the raw selector as a string
*
* @param {array} arr - array of Selectors
* @returns {string}
*/
var stringify = function(unit) {
var constructRawSelector = function(selector) {
var str = '';
str += parser.getTag(selector['_raw']) || '';
for (var i in selector['ids']) {
str += '#' + selector['ids'][i];
}
for (var i in selector['classes']) {
str += '.' + selector['classes'][i];
}
for (var i in selector['pseudoClasses']) {
str += ':' + selector['pseudoClasses'][i];
}
for (var i in selector['pseudoElements']) {
str += '::' + selector['pseudoElements'][i];
}
for (var i in selector['attributes']) {
str += '[' + selector['attributes'][i]['_raw'] + ']';
}
for (var i in selector['nots']) {
if (!selector['nots'][i]['_parent']) {
// in case a not was removed using API but this selector does not know it yet
delete selector['nots'][i];
continue;
}
str += ':not(' + constructRawSelector(selector['nots'][i]) + ')';
}
return str;
};
var stringifyRecursive = function(selector) {
var str = '';
str += constructRawSelector(selector);
for (var operator in parser.HIERARCHY_OPERATORS) {
var hir = parser.HIERARCHY_OPERATORS[operator];
if (selector[hir]) {
str += (' ' + operator + ' ').replace(' ', ' '); // in case operator is whitespace
str += stringify([selector[hir]]);
}
}
return str;
};
var str = stringifyRecursive(unit);
return str;
};
module.exports = SelectorUnit;
|
'use strict';
module.exports = angular.module('sm.molecules.carousel', [
require('ux_patterns/_helpers/angular/transition').name
])
.controller('CarouselController', require('./controllers/carousel_controller'))
.directive('carousel', require('./directives/carousel_directive'))
.directive('slide', require('./directives/carousel_slide_directive'))
;
|
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./signup.component'));
__export(require('./signup.routes'));
//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImFwcC9zaWdudXAvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7OztBQUdBLGlCQUFjLG9CQUFvQixDQUFDLEVBQUE7QUFDbkMsaUJBQWMsaUJBQWlCLENBQUMsRUFBQSIsImZpbGUiOiJhcHAvc2lnbnVwL2luZGV4LmpzIiwic291cmNlc0NvbnRlbnQiOlsiLyoqXG4qXHRUaGlzIGJhcnJlbCBmaWxlIHByb3ZpZGVzIHRoZSBleHBvcnQgZm9yIHRoZSBsYXp5IGxvYWRlZCBTaWdudXBDb21wb25lbnQuXG4qL1xuZXhwb3J0ICogZnJvbSAnLi9zaWdudXAuY29tcG9uZW50JztcbmV4cG9ydCAqIGZyb20gJy4vc2lnbnVwLnJvdXRlcyc7XG4iXX0=
|
const express = require('express')
const {verifyAuthorization} = require('../handlers/auth')
const {verifyPermission} = require('../handlers/permissions')
const resourcesController = require('./controller')
// eslint-disable-next-line new-cap
const router = express.Router()
const verifyRoles = verifyPermission('resources')
router.get('/', [
verifyAuthorization,
verifyRoles('read'),
resourcesController.list
])
module.exports = router
|
const event = require('./event');
const fourOhFour = require('./404');
const home = require('./home');
const login = require('./login');
const logout = require('./logout');
const register = require('./register');
module.exports = {
event,
fourOhFour,
home,
logout,
login,
register
};
|
require.config({
paths: {
"backbone": "vendor/components/backbone/index"
,"$": "vendor/components/jquery/index"
,"json": "vendor/components/json/index"
,"marionette": "vendor/components/marionette/index"
,"_": "vendor/components/lodash/index"
,"requirejs": "vendor/components/requirejs/index"
,"talent" : 'vendor/components/talent/index'
},
shim: {
'$': {
exports: '$'
}
,'_': {
exports: '_'
}
,'backbone': {
deps: ['json', '_', '$'],
exports: 'Backbone'
}
,'marionette': {
deps: ['backbone'],
exports: 'Marionette'
}
,'talent': {
deps: ['marionette'],
exports: 'Talent'
}
}
});
|
/**
* Created by alucas on 25/11/16.
*/
// # styles
require('./stories.scss');
import './draft-js-plugins/stories';
import './react-draft-wysiwyg/stories';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.