<commit_before>var through = require('through2');
var falafel = require('falafel');

var bpb = function () {
	//var file = typeof arguments[0] == 'string' ? arguments[0] : null; // not currently used
	var options = typeof arguments[0] == 'string' ? arguments[1] : arguments[0];
	var chunks = [];
	return through(function (buffer, encoding, next) {
		chunks.push(buffer.toString('utf8'));
		next();
	}, function (next) {
		this.push(transform(chunks.join(''), options));
		next()
	});
};

function transform(source, options){
	options = options || {};

	var occurrences = [];

	var f = falafel(source, options, function(node){
		if (isOccurrence(node)){
			occurrences.push(node);
		}
		if (isDeclarationOverride(node)){
			getScope(node).$overridden = true;
		}
		if (isFunctionOverride(node)){
			node.$overridden = true;
		}
	});

	occurrences.forEach(function(occurrence){
		for (var scope = getScope(occurrence); scope; scope = getScope(scope)){
			if (scope.$overridden){
				return;
			}
		}
		occurrence.update('true');
	});

	return String(f);
}

function isOccurrence(node){
	return (node.type == 'MemberExpression') && !node.computed
		&& (node.object.type == 'Identifier') && (node.object.name == 'process')
		&& (node.property.type == 'Identifier') && (node.property.name == 'browser');
}

function getScope(node){
	do {node = node.parent;}
	while (node && (node.type != 'FunctionDeclaration') && (node.type != 'FunctionExpression') && (node.type != 'Program'));
	return node;
}

function isDeclarationOverride(node){
	return ((node.type == 'VariableDeclarator') && (node.id.type == 'Identifier') && (node.id.name == 'process'))
		|| ((node.type == 'FunctionDeclaration') && (node.id.type == 'Identifier') && (node.id.name == 'process'));
}

function isFunctionOverride(node){
	if ((node.type == 'FunctionDeclaration') || (node.type == 'FunctionExpression')){
		if (node.id && (node.id.type == 'Identifier') && (node.id.name == 'process')){
			return true;
		}
		for (var i = 0; i < node.params.length; i++){
			if ((node.params[i].type == 'Identifier') && (node.params[i].name == 'process')){
				return true;
			}
		}
	}
	return false;
}

module.exports = bpb;<commit_msg>implement es6 support<commit_after>var through = require('through2');
var falafel = require('falafel');

var bpb = function () {
	//var file = typeof arguments[0] == 'string' ? arguments[0] : null; // not currently needed
	var options = typeof arguments[0] == 'string' ? arguments[1] : arguments[0];
	var chunks = [];
	return through(function (buffer, encoding, next) {
		chunks.push(buffer.toString('utf8'));
		next();
	}, function (next) {
		this.push(transform(chunks.join(''), options));
		next()
	});
};

bpb.sync = transform;

function transform(source, options){
	options = options || {};
	options.ecmaVersion = options.ecmaVersion || 5;
	var emca_6 = options.ecmaVersion == 6;
	var occurrences = [];

	var f = falafel(source, options, function(node){
		if (isOccurrence(node)){
			occurrences.push(node);
		}
		if (isVarDecOverride(node)){
			getFunctionScope(node).$overridden = true;
		}
		if (emca_6 && isLetOrConstDecOverride(node)){
			if (((node.parent.type == 'ForStatement') && (node.parent.init == node))
					|| ((node.parent.type == 'ForInStatement') && (node.parent.left == node))){
				node.parent.body.$overridden = true;
			} else {
				getBlockScope(node).$overridden = true;
			}
		}
		if (isFuncDecOverride(node)){
			(emca_6 ? getBlockScope : getFunctionScope)(node).$overridden = true;
		}
		if (isFunctionOverride(node) || isBlockOverride(node)){
			node.$overridden = true;
		}
	});

	occurrences.forEach(function(occurrence){
		for (var scope = occurrence.parent; scope; scope = scope.parent){
			if (scope.$overridden){
				return;
			}
		}
		occurrence.update('true');
	});

	return String(f);
}

function isOccurrence(node){
	return (node.type == 'MemberExpression') && !node.computed
		&& (node.object.type == 'Identifier') && (node.object.name == 'process')
		&& (node.property.type == 'Identifier') && (node.property.name == 'browser');
}

function getFunctionScope(node){
	do {node = node.parent;}
	while (node && (node.type != 'FunctionDeclaration') && (node.type != 'FunctionExpression') && (node.type != 'Program'));
	return node;
}

function getBlockScope(node){
	do {node = node.parent;}
	while (node && (node.type != 'BlockStatement') && (node.type != 'Program'));
	return node;
}

function isVarDecOverride(node){
	if ((node.type == 'VariableDeclaration') && (node.kind == 'var')){
		for (var i = 0; i < node.declarations.length; i++){
			if (node.declarations[i].id.name == 'process'){
				return true;
			}
		}
	}
	return false;
}

function isLetOrConstDecOverride(node){
	if ((node.type == 'VariableDeclaration') && ((node.kind == 'let') || (node.kind == 'const'))){
		for (var i = 0; i < node.declarations.length; i++){
			if (node.declarations[i].id.name == 'process'){
				return true;
			}
		}
	}
	return false;
}

function isFuncDecOverride(node){
	return ((node.type == 'FunctionDeclaration') && (node.id.name == 'process'));
}

function isFunctionOverride(node){
	if ((node.type == 'FunctionDeclaration') || (node.type == 'FunctionExpression')){
		if (node.id && (node.id.name == 'process')){
			return true;
		}
		for (var i = 0; i < node.params.length; i++){
			if (node.params[i].name == 'process'){
				return true;
			}
		}
	}
	return false;
}

function isBlockOverride(node){
	return (node.type == 'BlockStatement') && (node.parent.type == 'CatchClause') && (node.parent.param.name == 'process');
}

module.exports = bpb;<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var defaults = require('defaults');
var integration = require('analytics.js-integration');

/**
 * Expose `Simplereach` integration.
 */

var Simplereach = module.exports = integration('Simplereach')
  .global('__reach_config')
  .global('SPR')
  .option('pid', '000000000000000000000000')
  .tag('<script src="//d8rk54i4mohrb.cloudfront.net/js/reach.js">');

/**
 * Initialize.
 * http://www.simplereach.com/docs/#standardImplementation
 * Some adjustments made to standard implementation
 *
 * @api public
 */

Simplereach.prototype.initialize = function() {
  window.__reach_config = window.__reach_config || {};
  defaults(window.__reach_config, {
    pid: this.options.pid,
    reach_tracking: false
  });
  this.load(this.ready);
};

/**
 * Loaded?
 *
 * @api private
 * @return {boolean}
 */

Simplereach.prototype.loaded = function() {
  return !!window.SPR;
};

/**
 * Page.
 *
 * http://www.simplereach.com/docs/ajax/
 *
 * @api public
 */

Simplereach.prototype.page = function() {
  window.SPR.collect(window.__reach_config);
};
<commit_msg>update integration name<commit_after>/**
 * Module dependencies.
 */

var defaults = require('defaults');
var integration = require('analytics.js-integration');

/**
 * Expose `Simplereach` integration.
 */

var SimpleReach = module.exports = integration('SimpleReach')
  .global('__reach_config')
  .global('SPR')
  .option('pid', '')
  .tag('<script src="//d8rk54i4mohrb.cloudfront.net/js/reach.js">');

/**
 * Initialize.
 * http://www.simplereach.com/docs/#standardImplementation
 * Some adjustments made to standard implementation
 *
 * @api public
 */

SimpleReach.prototype.initialize = function() {
  window.__reach_config = window.__reach_config || {};
  defaults(window.__reach_config, {
    pid: this.options.pid,
    reach_tracking: false
  });
  this.load(this.ready);
};

/**
 * Loaded?
 *
 * @api private
 * @return {boolean}
 */

SimpleReach.prototype.loaded = function() {
  return !!window.SPR;
};

/**
 * Page.
 *
 * http://www.simplereach.com/docs/ajax/
 *
 * @api public
 */

SimpleReach.prototype.page = function() {
  window.SPR.collect(window.__reach_config);
};
<|endoftext|>


<commit_before>module.exports = {
    type: 'assertion',
    files: [
        require.resolve('qunitjs'),
        __dirname + '/adapter.js'
    ]
};
<commit_msg>added plugin name property<commit_after>module.exports = {
    name : 'qunit',
    type: 'assertion',
    files: [
        require.resolve('qunitjs'),
        __dirname + '/adapter.js'
    ]
};
<|endoftext|>


<commit_before>/*jshint laxcomma: true, smarttabs: true, node:true, mocha: true*/
'use strict';
/**
 * index.js
 * @module index.js
 * @author Eric Satterwhite
 * @since 1.0.0
 * @requires util
 * @requires async
 * @requires flat
 * @requires node-etcd
 * @requires mout/objec/merge
 * @requires nconf-etcd/lib/common
 */

var util      = require('util')
  , Etcd      = require('node-etcd')
  , merge     = require('mout/object/merge')
  , set       = require('mout/object/set')
  , async     = require('async')
  , flat      = require('flat')
  , common    = require('./common')
  , unflatten = flat.unflatten
  , NOOP      =  new Function()
  , SAVE_KEY  = '/%s/%s'
  , defaults
  ;

try{
	var conf = require('nconf');
	conf.Etcd = Store;
} catch( e ) {}

defaults = {
	hosts:null,
	readOnly:false,
	namespace:'nconf',
	logicalSeparator:':'
};

function rebuild( d , root ){
	var x, len;
	root = root || {};
	if(!d.dir){
		set( root, d.key.replace(/^\//,'').replace(/\//g,'.'), d.value);
		return root;
	}
	for(x=0,len = d.nodes.length; x<len; x++){
		rebuild( d.nodes[x], root );
	}
	return root;
}

function Store( options ){
	options               = merge({},defaults, options);
	this.options          = options;
	this.store            = {};
	this.readOnly         = options.readOnly;
	this.type             = 'etcd';
	this.namespace        = options.namespace;
	this.logicalSeparator = options.logicalSeparator ;
	this.client           = new Etcd(options.hosts||['127.0.0.1:4001'] );
}

/**
 * Get a value from the internal store
 * @method module:nconf-etcd2#get
 * @param {String} key Key to retrieve for this instance.
 * @return {String|Object} value
 **/
Store.prototype.get = function get(key){
	var target = this.store
	  , path   = common.path(key, this.logicalSeparator)
	  ;

	while (path.length > 0) {
		key = path.shift();
		if (target && target.hasOwnProperty(key)) {
			target = target[key];
			continue;
		}
		return undefined;
	}

	return target;
};

/**
 * Sets a value or nested values at a given key
 * This method does not save to etcd. use the {@link module:nconf-etcd2#save|save}
 * @method module:nconf-etcd2#set
 * @param {String} key The key at which to set a value
 * @param {String|Object} value the value to set.
 * @return {String|Object}
 **/
Store.prototype.set = function set(key, value){
	if (this.readOnly) {
	  return false;
	}

	var target = this.store,
		path   = common.path(key, this.logicalSeparator);

	if (path.length === 0) {
	  if (!value || typeof value !== 'object') {
		return false;
	  }
	  else {
		this.reset();
		this.store = value;
		return true;
	  }
	}

	while (path.length > 1) {
	  key = path.shift();
	  if (!target[key] || typeof target[key] !== 'object') {
		target[key] = {};
	  }

	  target = target[key];
	}

	// Set the specified value in the nested JSON structure
	key = path.shift();
	target[key] = value;
	return true;
};

/**
 * DESCRIPTION
 * @method module:nconf-etcd2#clear
 * @param {String} key deletes a specific key from the structure
 **/
Store.prototype.clear = function clear(key){
	if (this.readOnly) {
	  return false;
	}

	var target = this.store,
		value  = target,
		path   = common.path(key, this.logicalSeparator);

	//
	// Scope into the object to get the appropriate nested context
	//
	for (var i = 0; i < path.length - 1; i++) {
	  key = path[i];
	  value = target[key];
	  if (typeof value !== 'function' && typeof value !== 'object') {
		return false;
	  }
	  target = value;
	}

	// Delete the key from the nested JSON structure
	key = path[i];
	delete target[key];
	return true;
};

/**
 * Clears the internal store
 * @method module:nconf-etcd2#reset
 * @return {Boolean} success
 **/
Store.prototype.reset = function reset(){
	if (this.readOnly) {
	  return false;
	}

	this.store  = {};
	return true;
};

/**
 * Loads data from the namespace in ectd and caches it locally
 * @method module:nconf-etcd2#load
 * @param {Function} callback node style callback. passed the result of the data load if succeeds
 **/
Store.prototype.load = function load( cb ){
	this.client.mkdir('/' + this.namespace,function(){
		this.client.get('/' + this.namespace, {recursive:true}, function(err, data ){
			(cb||NOOP)(err, err ? null : this.store = rebuild( data.node )[this.namespace] );
		}.bind( this ));
	}.bind(this))
};

/**
 * Loads data from the namespace in ectd and caches it locally
 * @method module:nconf-etcd2#load
 * @param {Function} callback node style callback. passed the result of the data load if succeeds
 **/
Store.prototype.loadSync = function load( cb ){
	var response = this.client.getSync('/' + this.namespace, {recursive:true});

	if(response.err){
		if( response.err.errorCode == 100){
			this.client.mkdirSync('/' + this.namespace)
			return this.store = {};
		}
	} else {
		throw response.err.error;
	}
	return this.store = rebuild( response.body.node )[this.namespace];
};

/**
 * Merges the properties in `value` into the existing object value
 * at `key`. If the existing value `key` is not an Object, it will be
 * completely overwritten.
 * @method module:nconf-etcd2#merge
 * @param {String} key the key of the value to to merge
 * @param {Object} value The object to merge into the current value
 * @return {Boolean} success
 **/
Store.prototype.merge = function( key, value ) {
	if (this.readOnly) {
	  return false;
	}

	//
	// If the key is not an `Object` or is an `Array`,
	// then simply set it. Merging is for Objects.
	//
	if (typeof value !== 'object' || Array.isArray(value) || value === null) {
	  return this.set(key, value);
	}

	var self    = this,
		target  = this.store,
		path    = common.path(key, this.logicalSeparator),
		fullKey = key;

	//
	// Scope into the object to get the appropriate nested context
	//
	while (path.length > 1) {
	  key = path.shift();
	  if (!target[key]) {
		target[key] = {};
	  }

	  target = target[key];
	}

	// Set the specified value in the nested JSON structure
	key = path.shift();

	//
	// If the current value at the key target is not an `Object`,
	// or is an `Array` then simply override it because the new value
	// is an Object.
	//
	if (typeof target[key] !== 'object' || Array.isArray(target[key])) {
	  target[key] = value;
	  return true;
	}

	return Object.keys(value).every(function (nested) {
	  return self.merge(common.keyed(self.logicalSeparator, fullKey, nested), value[nested]);
	});
};
/**
 * Saves the current data cache to the etcd backend
 * error 102 dir -> value
 * error 104 value -> dir
 * @method module:nconf-etcd2#save
 * @param {Function} callback node style callback
 **/
Store.prototype.save = function save( cb ){
	var tmp = flat( this.store, {delimiter:'/'});
	async.each(
		Object.keys( tmp ).sort()
		,function( key, callback ){
			var fullkey = util.format(SAVE_KEY, this.namespace, key);
			this.client.set(
				fullkey
				, tmp[key]
				, function( err ){
					var code = err ? err.errorCode : 0;
					switch(code){
						case 102:
							dirToValue.call(this,fullkey,tmp[key],callback);
							break;
						case 104:
							valueToDir.call(this,err.error.cause,fullkey,tmp[key],callback);
							break;
						default:
							callback( err );
					}
				}.bind( this )
			);
		}.bind( this )
		,(cb || NOOP)
	);
};

/**
 * Saves the current data cache to the etcd backend
 * @method module:nconf-etcd2#saveSync
 * @param {Function} callback node style callback
 **/
Store.prototype.saveSync = function save( cb ){
	var tmp = flat( this.store, {delimiter:'/'})
	  , keys = Object.keys( tmp ).sort()
	  , fullkey
	  , response
	  , code
	  , key
	  ;

	for(var idx=0, len=keys.length; idx<len; idx++ ){
		key      = keys[idx];
		fullkey  = util.format(SAVE_KEY, this.namespace, key);
		response = this.client.setSync( fullkey, tmp[key]);
		code     = response.err ? response.err.error.errorCode : 0;

		switch(code){
			case 102:
				this.client.rmdirSync( fullkey, {recursive:true} );
				this.client.setSync(fullkey, tmp[key]);
				break;
			case 104:
				this.client.delSync(response.err.error.cause);
				this.client.setSync(fullkey, tmp[key]);
				break;
			default:
				return;
		}

	}
	// cleanup;
	tmp = keys = response = code = null;
	return this.store;
};

function dirToValue( key, value, callback ){
	this.client.rmdir(
		  key
		, {recursive:true}
		, function( ){
			this.client.set(key, value, callback);
		}.bind( this )
	)
};
function valueToDir(dir, key, value, callback ){
	this.client.del(
		  dir
		, function( ){
			this.client.set(key, value, callback);
		}.bind( this )
	)
};

module.exports = Store;
<commit_msg>fix bad error catch<commit_after>/*jshint laxcomma: true, smarttabs: true, node:true, mocha: true*/
'use strict';
/**
 * index.js
 * @module index.js
 * @author Eric Satterwhite
 * @since 1.0.0
 * @requires util
 * @requires async
 * @requires flat
 * @requires node-etcd
 * @requires mout/objec/merge
 * @requires nconf-etcd/lib/common
 */

var util      = require('util')
  , Etcd      = require('node-etcd')
  , merge     = require('mout/object/merge')
  , set       = require('mout/object/set')
  , async     = require('async')
  , flat      = require('flat')
  , common    = require('./common')
  , unflatten = flat.unflatten
  , NOOP      =  new Function()
  , SAVE_KEY  = '/%s/%s'
  , defaults
  ;

try{
	var conf = require('nconf');
	conf.Etcd = Store;
} catch( e ) {}

defaults = {
	hosts:null,
	readOnly:false,
	namespace:'nconf',
	logicalSeparator:':'
};

function rebuild( d , root ){
	var x, len;
	root = root || {};
	if(!d.dir){
		set( root, d.key.replace(/^\//,'').replace(/\//g,'.'), d.value);
		return root;
	}
	for(x=0,len = d.nodes.length; x<len; x++){
		rebuild( d.nodes[x], root );
	}
	return root;
}

function Store( options ){
	options               = merge({},defaults, options);
	this.options          = options;
	this.store            = {};
	this.readOnly         = options.readOnly;
	this.type             = 'etcd';
	this.namespace        = options.namespace;
	this.logicalSeparator = options.logicalSeparator ;
	this.client           = new Etcd(options.hosts||['127.0.0.1:4001'] );
}

/**
 * Get a value from the internal store
 * @method module:nconf-etcd2#get
 * @param {String} key Key to retrieve for this instance.
 * @return {String|Object} value
 **/
Store.prototype.get = function get(key){
	var target = this.store
	  , path   = common.path(key, this.logicalSeparator)
	  ;

	while (path.length > 0) {
		key = path.shift();
		if (target && target.hasOwnProperty(key)) {
			target = target[key];
			continue;
		}
		return undefined;
	}

	return target;
};

/**
 * Sets a value or nested values at a given key
 * This method does not save to etcd. use the {@link module:nconf-etcd2#save|save}
 * @method module:nconf-etcd2#set
 * @param {String} key The key at which to set a value
 * @param {String|Object} value the value to set.
 * @return {String|Object}
 **/
Store.prototype.set = function set(key, value){
	if (this.readOnly) {
	  return false;
	}

	var target = this.store,
		path   = common.path(key, this.logicalSeparator);

	if (path.length === 0) {
	  if (!value || typeof value !== 'object') {
		return false;
	  }
	  else {
		this.reset();
		this.store = value;
		return true;
	  }
	}

	while (path.length > 1) {
	  key = path.shift();
	  if (!target[key] || typeof target[key] !== 'object') {
		target[key] = {};
	  }

	  target = target[key];
	}

	// Set the specified value in the nested JSON structure
	key = path.shift();
	target[key] = value;
	return true;
};

/**
 * DESCRIPTION
 * @method module:nconf-etcd2#clear
 * @param {String} key deletes a specific key from the structure
 **/
Store.prototype.clear = function clear(key){
	if (this.readOnly) {
	  return false;
	}

	var target = this.store,
		value  = target,
		path   = common.path(key, this.logicalSeparator);

	//
	// Scope into the object to get the appropriate nested context
	//
	for (var i = 0; i < path.length - 1; i++) {
	  key = path[i];
	  value = target[key];
	  if (typeof value !== 'function' && typeof value !== 'object') {
		return false;
	  }
	  target = value;
	}

	// Delete the key from the nested JSON structure
	key = path[i];
	delete target[key];
	return true;
};

/**
 * Clears the internal store
 * @method module:nconf-etcd2#reset
 * @return {Boolean} success
 **/
Store.prototype.reset = function reset(){
	if (this.readOnly) {
	  return false;
	}

	this.store  = {};
	return true;
};

/**
 * Loads data from the namespace in ectd and caches it locally
 * @method module:nconf-etcd2#load
 * @param {Function} callback node style callback. passed the result of the data load if succeeds
 **/
Store.prototype.load = function load( cb ){
	this.client.mkdir('/' + this.namespace,function(){
		this.client.get('/' + this.namespace, {recursive:true}, function(err, data ){
			(cb||NOOP)(err, err ? null : this.store = rebuild( data.node )[this.namespace] );
		}.bind( this ));
	}.bind(this))
};

/**
 * Loads data from the namespace in ectd and caches it locally
 * @method module:nconf-etcd2#load
 * @param {Function} callback node style callback. passed the result of the data load if succeeds
 **/
Store.prototype.loadSync = function load( cb ){
	var response = this.client.getSync('/' + this.namespace, {recursive:true});

	if(response.err){
		if( response.err.errorCode == 100){
			this.client.mkdirSync('/' + this.namespace)
			return this.store = {};
		} else {
			throw response.err.error;
		}
	}
	return this.store = rebuild( response.body.node )[this.namespace];
};

/**
 * Merges the properties in `value` into the existing object value
 * at `key`. If the existing value `key` is not an Object, it will be
 * completely overwritten.
 * @method module:nconf-etcd2#merge
 * @param {String} key the key of the value to to merge
 * @param {Object} value The object to merge into the current value
 * @return {Boolean} success
 **/
Store.prototype.merge = function( key, value ) {
	if (this.readOnly) {
	  return false;
	}

	//
	// If the key is not an `Object` or is an `Array`,
	// then simply set it. Merging is for Objects.
	//
	if (typeof value !== 'object' || Array.isArray(value) || value === null) {
	  return this.set(key, value);
	}

	var self    = this,
		target  = this.store,
		path    = common.path(key, this.logicalSeparator),
		fullKey = key;

	//
	// Scope into the object to get the appropriate nested context
	//
	while (path.length > 1) {
	  key = path.shift();
	  if (!target[key]) {
		target[key] = {};
	  }

	  target = target[key];
	}

	// Set the specified value in the nested JSON structure
	key = path.shift();

	//
	// If the current value at the key target is not an `Object`,
	// or is an `Array` then simply override it because the new value
	// is an Object.
	//
	if (typeof target[key] !== 'object' || Array.isArray(target[key])) {
	  target[key] = value;
	  return true;
	}

	return Object.keys(value).every(function (nested) {
	  return self.merge(common.keyed(self.logicalSeparator, fullKey, nested), value[nested]);
	});
};
/**
 * Saves the current data cache to the etcd backend
 * error 102 dir -> value
 * error 104 value -> dir
 * @method module:nconf-etcd2#save
 * @param {Function} callback node style callback
 **/
Store.prototype.save = function save( cb ){
	var tmp = flat( this.store, {delimiter:'/'});
	async.each(
		Object.keys( tmp ).sort()
		,function( key, callback ){
			var fullkey = util.format(SAVE_KEY, this.namespace, key);
			this.client.set(
				fullkey
				, tmp[key]
				, function( err ){
					var code = err ? err.errorCode : 0;
					switch(code){
						case 102:
							dirToValue.call(this,fullkey,tmp[key],callback);
							break;
						case 104:
							valueToDir.call(this,err.error.cause,fullkey,tmp[key],callback);
							break;
						default:
							callback( err );
					}
				}.bind( this )
			);
		}.bind( this )
		,(cb || NOOP)
	);
};

/**
 * Saves the current data cache to the etcd backend
 * @method module:nconf-etcd2#saveSync
 * @param {Function} callback node style callback
 **/
Store.prototype.saveSync = function save( cb ){
	var tmp = flat( this.store, {delimiter:'/'})
	  , keys = Object.keys( tmp ).sort()
	  , fullkey
	  , response
	  , code
	  , key
	  ;

	for(var idx=0, len=keys.length; idx<len; idx++ ){
		key      = keys[idx];
		fullkey  = util.format(SAVE_KEY, this.namespace, key);
		response = this.client.setSync( fullkey, tmp[key]);
		code     = response.err ? response.err.error.errorCode : 0;

		switch(code){
			case 102:
				this.client.rmdirSync( fullkey, {recursive:true} );
				this.client.setSync(fullkey, tmp[key]);
				break;
			case 104:
				this.client.delSync(response.err.error.cause);
				this.client.setSync(fullkey, tmp[key]);
				break;
			default:
				return;
		}

	}
	// cleanup;
	tmp = keys = response = code = null;
	return this.store;
};

function dirToValue( key, value, callback ){
	this.client.rmdir(
		  key
		, {recursive:true}
		, function( ){
			this.client.set(key, value, callback);
		}.bind( this )
	)
};
function valueToDir(dir, key, value, callback ){
	this.client.del(
		  dir
		, function( ){
			this.client.set(key, value, callback);
		}.bind( this )
	)
};

module.exports = Store;
<|endoftext|>


<commit_before>var tmp = require('tmp');
tmp.setGracefulCleanup();

var request = require('./request');
var download = require('./download');
var extract = require('./extract');
var utils = require('./utils');

/**
 * Factory function for resolver
 * It is called only one time by Bower, to instantiate resolver.
 * You can instantiate here any caches or create helper functions.
 */
module.exports = function resolver (bower) {

  function getFragments(source) {
      return {
          registryUrl: utils.getRegistryUrl(bower.config),
          repositoryName: utils.getRepositoryName(source)
      }
  };

  // Resolver factory returns an instance of resolver
  return {

    // Match method tells whether resolver supports given source
    // It can return either boolean or promise of boolean
    // source = angular-ui-router (bower install angular-ui-router)
    match: function (source) {
      return source.indexOf(utils.NEXUS_PREFIX) === 0;
    },

    releases: function (source) {
      var fragments = getFragments(source);
      var requestUrl = utils.getNexusRegistry(bower.config) + fragments.repositoryName.split('/')[1];
      return request(requestUrl, bower.config).then(function (response) {
          return utils.extractReleases(response);
      });
    },

    // It downloads package and extracts it to temporary directory
    // You can use npm's "tmp" package to tmp directories
    // See the "Resolver API" section for details on this method
    // endpoint is the value returned by releases()
    fetch: function (endpoint, cached) {
      // If cached package is semver, reuse it
      if (cached.version) return;

      var fragments = getFragments(endpoint.source);
      var pkgFragment = fragments.repositoryName.split('/').join('/-/');
      var downloadUrl = utils.getNexusRegistry(bower.config) + pkgFragment + '-' + endpoint.target + '.tgz';
      var downloadPath = tmp.dirSync();

      return download(downloadUrl, downloadPath.name, bower.config).then(function (archivePatch) {
          var extractPath = tmp.dirSync();

          return extract(archivePatch, extractPath.name).then(function () {
              downloadPath.removeCallback();

              return {
                  tempPath: extractPath.name,
                  removeIgnores: true
              };
          });
      });
    }
  }
}<commit_msg>fix bug : set the right value bower.config for 3rd argument of download method<commit_after>var tmp = require('tmp');
tmp.setGracefulCleanup();

var request = require('./request');
var download = require('./download');
var extract = require('./extract');
var utils = require('./utils');

/**
 * Factory function for resolver
 * It is called only one time by Bower, to instantiate resolver.
 * You can instantiate here any caches or create helper functions.
 */
module.exports = function resolver (bower) {

  function getFragments(source) {
      return {
          registryUrl: utils.getRegistryUrl(bower.config),
          repositoryName: utils.getRepositoryName(source)
      }
  };

  // Resolver factory returns an instance of resolver
  return {

    // Match method tells whether resolver supports given source
    // It can return either boolean or promise of boolean
    // source = angular-ui-router (bower install angular-ui-router)
    match: function (source) {
      return source.indexOf(utils.NEXUS_PREFIX) === 0;
    },

    releases: function (source) {
      var fragments = getFragments(source);
      var requestUrl = utils.getNexusRegistry(bower.config) + fragments.repositoryName.split('/')[1];
      return request(requestUrl, bower.config).then(function (response) {
          return utils.extractReleases(response);
      });
    },

    // It downloads package and extracts it to temporary directory
    // You can use npm's "tmp" package to tmp directories
    // See the "Resolver API" section for details on this method
    // endpoint is the value returned by releases()
    fetch: function (endpoint, cached) {
      // If cached package is semver, reuse it
      if (cached.version) return;

      var fragments = getFragments(endpoint.source);
      var pkgFragment = fragments.repositoryName.split('/').join('/-/');
      var downloadUrl = utils.getNexusRegistry(bower.config) + pkgFragment + '-' + endpoint.target + '.tgz';
      var downloadPath = tmp.dirSync();

      return download(downloadUrl, downloadPath.name, bower.config).then(function (archivePatch) {
          var extractPath = tmp.dirSync();
          return extract(archivePatch, extractPath.name).then(function () {
              downloadPath.removeCallback();

              return {
                  tempPath: extractPath.name,
                  removeIgnores: true
              };
          });
      });
    }
  }
}<|endoftext|>


<commit_before>const Proto = require('uberproto');
const errors = require('@feathersjs/errors');
const cloneDeep = require('clone-deep');

const { sorter, select, filterQuery, _ } = require('@feathersjs/commons');

const sift = require('sift');

const _select = (...args) => {
  const base = select(...args);

  return function (result) {
    return base(cloneDeep(result));
  };
};

class Service {
  constructor (options = {}) {
    this.paginate = options.paginate || {};
    this._id = this.id = options.idField || options.id || 'id';
    this._uId = options.startId || 0;
    this.store = options.store || {};
    this.events = options.events || [];
    this._matcher = options.matcher;
    this._sorter = options.sorter || sorter;
  }

  extend (obj) {
    return Proto.extend(obj, this);
  }

  // Find without hooks and mixins that can be used internally and always returns
  // a pagination object
  _find (params, getFilter = filterQuery) {
    const { query, filters } = getFilter(params.query || {});
    const map = _select(params);
    let values = _.values(this.store);

    if (this._matcher) {
      values = values.filter(this._matcher(query));
    } else {
      values = sift(query, values);
    }

    const total = values.length;

    if (filters.$sort) {
      values.sort(this._sorter(filters.$sort));
    }

    if (filters.$skip) {
      values = values.slice(filters.$skip);
    }

    if (typeof filters.$limit !== 'undefined') {
      values = values.slice(0, filters.$limit);
    }

    return Promise.resolve({
      total,
      limit: filters.$limit,
      skip: filters.$skip || 0,
      data: map(values)
    });
  }

  find (params) {
    const paginate = typeof params.paginate !== 'undefined' ? params.paginate : this.paginate;
    // Call the internal find with query parameter that include pagination
    const result = this._find(params, query => filterQuery(query, paginate));

    if (!(paginate && paginate.default)) {
      return result.then(page => page.data);
    }

    return result;
  }

  get (id, params) {
    if (id in this.store) {
      return Promise.resolve(this.store[id])
        .then(_select(params, this.id));
    }

    return Promise.reject(
      new errors.NotFound(`No record found for id '${id}'`)
    );
  }

  // Create without hooks and mixins that can be used internally
  _create (data, params) {
    let id = data[this._id] || this._uId++;
    let current = _.extend({}, data, { [this._id]: id });

    return Promise.resolve((this.store[id] = current))
      .then(_select(params, this.id));
  }

  create (data, params) {
    if (Array.isArray(data)) {
      return Promise.all(data.map(current => this._create(current)));
    }

    return this._create(data, params);
  }

  // Update without hooks and mixins that can be used internally
  _update (id, data, params) {
    if (id in this.store) {
      // We don't want our id to change type if it can be coerced
      const oldId = this.store[id][this._id];

      id = oldId == id ? oldId : id; // eslint-disable-line

      data = _.extend({}, data, { [this._id]: id });
      this.store[id] = data;

      return Promise.resolve(this.store[id])
        .then(_select(params, this.id));
    }

    return Promise.reject(
      new errors.NotFound(`No record found for id '${id}'`)
    );
  }

  update (id, data, params) {
    if (id === null || Array.isArray(data)) {
      return Promise.reject(new errors.BadRequest(
        `You can not replace multiple instances. Did you mean 'patch'?`
      ));
    }

    return this._update(id, data, params);
  }

  // Patch without hooks and mixins that can be used internally
  _patch (id, data, params) {
    if (id in this.store) {
      _.extend(this.store[id], _.omit(data, this._id));

      return Promise.resolve(this.store[id])
        .then(_select(params, this.id));
    }

    return Promise.reject(
      new errors.NotFound(`No record found for id '${id}'`)
    );
  }

  patch (id, data, params) {
    if (id === null) {
      return this._find(params).then(page => {
        return Promise.all(page.data.map(
          current => this._patch(current[this._id], data, params))
        );
      });
    }

    return this._patch(id, data, params);
  }

  // Remove without hooks and mixins that can be used internally
  _remove (id, params) {
    if (id in this.store) {
      const deleted = this.store[id];
      delete this.store[id];

      return Promise.resolve(deleted)
        .then(_select(params, this.id));
    }

    return Promise.reject(
      new errors.NotFound(`No record found for id '${id}'`)
    );
  }

  remove (id, params) {
    if (id === null) {
      return this._find(params).then(page =>
        Promise.all(page.data.map(current =>
          this._remove(current[this._id], params
        )
      )));
    }

    return this._remove(id, params);
  }
}

module.exports = function init (options) {
  return new Service(options);
};

module.exports.Service = Service;
<commit_msg>Fix cloning of instances (#79)<commit_after>const Proto = require('uberproto');
const errors = require('@feathersjs/errors');
const cloneDeep = require('clone-deep');

const { sorter, select, filterQuery, _ } = require('@feathersjs/commons');

const sift = require('sift');

const _select = (...args) => {
  const base = select(...args);

  return function (result) {
    return base(cloneDeep(result, (obj) => JSON.parse(JSON.stringify(obj))));
  };
};

class Service {
  constructor (options = {}) {
    this.paginate = options.paginate || {};
    this._id = this.id = options.idField || options.id || 'id';
    this._uId = options.startId || 0;
    this.store = options.store || {};
    this.events = options.events || [];
    this._matcher = options.matcher;
    this._sorter = options.sorter || sorter;
  }

  extend (obj) {
    return Proto.extend(obj, this);
  }

  // Find without hooks and mixins that can be used internally and always returns
  // a pagination object
  _find (params, getFilter = filterQuery) {
    const { query, filters } = getFilter(params.query || {});
    const map = _select(params);
    let values = _.values(this.store);

    if (this._matcher) {
      values = values.filter(this._matcher(query));
    } else {
      values = sift(query, values);
    }

    const total = values.length;

    if (filters.$sort) {
      values.sort(this._sorter(filters.$sort));
    }

    if (filters.$skip) {
      values = values.slice(filters.$skip);
    }

    if (typeof filters.$limit !== 'undefined') {
      values = values.slice(0, filters.$limit);
    }

    return Promise.resolve({
      total,
      limit: filters.$limit,
      skip: filters.$skip || 0,
      data: map(values)
    });
  }

  find (params) {
    const paginate = typeof params.paginate !== 'undefined' ? params.paginate : this.paginate;
    // Call the internal find with query parameter that include pagination
    const result = this._find(params, query => filterQuery(query, paginate));

    if (!(paginate && paginate.default)) {
      return result.then(page => page.data);
    }

    return result;
  }

  get (id, params) {
    if (id in this.store) {
      return Promise.resolve(this.store[id])
        .then(_select(params, this.id));
    }

    return Promise.reject(
      new errors.NotFound(`No record found for id '${id}'`)
    );
  }

  // Create without hooks and mixins that can be used internally
  _create (data, params) {
    let id = data[this._id] || this._uId++;
    let current = _.extend({}, data, { [this._id]: id });

    return Promise.resolve((this.store[id] = current))
      .then(_select(params, this.id));
  }

  create (data, params) {
    if (Array.isArray(data)) {
      return Promise.all(data.map(current => this._create(current)));
    }

    return this._create(data, params);
  }

  // Update without hooks and mixins that can be used internally
  _update (id, data, params) {
    if (id in this.store) {
      // We don't want our id to change type if it can be coerced
      const oldId = this.store[id][this._id];

      id = oldId == id ? oldId : id; // eslint-disable-line

      data = _.extend({}, data, { [this._id]: id });
      this.store[id] = data;

      return Promise.resolve(this.store[id])
        .then(_select(params, this.id));
    }

    return Promise.reject(
      new errors.NotFound(`No record found for id '${id}'`)
    );
  }

  update (id, data, params) {
    if (id === null || Array.isArray(data)) {
      return Promise.reject(new errors.BadRequest(
        `You can not replace multiple instances. Did you mean 'patch'?`
      ));
    }

    return this._update(id, data, params);
  }

  // Patch without hooks and mixins that can be used internally
  _patch (id, data, params) {
    if (id in this.store) {
      _.extend(this.store[id], _.omit(data, this._id));

      return Promise.resolve(this.store[id])
        .then(_select(params, this.id));
    }

    return Promise.reject(
      new errors.NotFound(`No record found for id '${id}'`)
    );
  }

  patch (id, data, params) {
    if (id === null) {
      return this._find(params).then(page => {
        return Promise.all(page.data.map(
          current => this._patch(current[this._id], data, params))
        );
      });
    }

    return this._patch(id, data, params);
  }

  // Remove without hooks and mixins that can be used internally
  _remove (id, params) {
    if (id in this.store) {
      const deleted = this.store[id];
      delete this.store[id];

      return Promise.resolve(deleted)
        .then(_select(params, this.id));
    }

    return Promise.reject(
      new errors.NotFound(`No record found for id '${id}'`)
    );
  }

  remove (id, params) {
    if (id === null) {
      return this._find(params).then(page =>
        Promise.all(page.data.map(current =>
          this._remove(current[this._id], params
        )
      )));
    }

    return this._remove(id, params);
  }
}

module.exports = function init (options) {
  return new Service(options);
};

module.exports.Service = Service;
<|endoftext|>


<commit_before>// dependencies
var Marked = require("marked")
  , QueryString = require ("querystring")
  , fileCache = {
        dummyPath: {
            ttl: setTimeout (function () {
                delete fileCache["dummyPath"];
            }, Config.gitSite.cache.ttl)
          , content: "Dummy"
        }
    };

/**
 *  This function reads a file from hard disk or from cache
 *  deleting it after the ttl timeout expires.
 *
 */
function readFile (path, callback) {

    // try to get the file from cache
    var fromCache = fileCache[path];
    if (fromCache) {

        // reset timeout
        fromCache.ttl = setTimeout (function () {
            console.log("Deleting " + path);
            delete fileCache[path]
        }, Config.gitSite.cache.ttl);

        // callback content
        return callback (null, fromCache.content);
    }

    // read file using statique
    Statique.readFile (path, function (err, content) {

        if (err) {
            return callback (err);
        }

        fileCache[path] = {
            ttl: setTimeout (function () {
                console.log("Deleting " + path);
                delete fileCache[path];
            }, Config.gitSite.cache.ttl)
          , content: content
        };

        callback (null, content.toString());
    });
}

/**
 *  Get form data for POST requests
 *
 */
function getFormData (req, callback) {

    var formData = ""
      , error = ""
      ;

    req.on ("data", function (data) {
        formData += data;
    });

    req.on ("error", function (data) {
        error += data;
    });

    req.on ("end", function (data) {

        if (error) {
            return callback (error);
        }

        callback (null, QueryString.parse (formData));
    });
}

/**
 *  Handle GET requests
 *
 */
module.exports["handlePage:GET"] = function (req, res, pathName, route) {

    // build the route
    route = SITE_CONFIG.paths.roots.pages + route;

    // read file
    readFile (route, function (err, fileContent) {

        if (err) {
            console.error (err);
            return Statique.sendRes (res, 500, "html", "Internal server error");
        }

        // success response
        Statique.sendRes (res, 200, "text/html",
            SITE_CONFIG.parsed.roots.template.page.replace (
                "{{PAGE_CONTENT}}"
              , Marked (fileContent)
            ).replace(
                "{{TITLE}}"
              , SITE_CONFIG.title
            )
        );
    });
};

/**
 *  Handle POST requests
 *
 */
module.exports["handlePage:POST"] = function (req, res, pathName, route) {

    // get form data
    getFormData (req, function (err, formData) {

        if (err) {
            console.error (err);
            return res.end ("Internal server error");
        }

        console.log(formData);
    });
};
<commit_msg>Generate pages dynamically<commit_after>// dependencies
var Marked = require("marked")
  , QueryString = require ("querystring")
  , fileCache = {
        dummyPath: {
            ttl: setTimeout (function () {
                delete fileCache["dummyPath"];
            }, Config.gitSite.cache.ttl)
          , content: "Dummy"
        }
    };

/**
 *  This function reads a file from hard disk or from cache
 *  deleting it after the ttl timeout expires.
 *
 */
function readFile (path, callback) {

    // try to get the file from cache
    var fromCache = fileCache[path];
    if (fromCache) {

        // reset timeout
        fromCache.ttl = setTimeout (function () {
            console.log("Deleting " + path);
            delete fileCache[path]
        }, Config.gitSite.cache.ttl);

        // callback content
        return callback (null, fromCache.content);
    }

    // read file using statique
    Statique.readFile (path, function (err, content) {

        if (err) {
            return callback (err);
        }

        fileCache[path] = {
            ttl: setTimeout (function () {
                console.log("Deleting " + path);
                delete fileCache[path];
            }, Config.gitSite.cache.ttl)
          , content: content
        };

        callback (null, content.toString());
    });
}

/**
 *  Get form data for POST requests
 *
 */
function getFormData (req, callback) {

    var formData = ""
      , error = ""
      ;

    req.on ("data", function (data) {
        formData += data;
    });

    req.on ("error", function (data) {
        error += data;
    });

    req.on ("end", function (data) {

        if (error) {
            return callback (error);
        }

        callback (null, QueryString.parse (formData));
    });
}

/**
 *  Handle GET requests
 *
 */
module.exports["handlePage:GET"] = function (req, res, pathName, route) {

    // build the route
    route = SITE_CONFIG.paths.roots.pages + route;

    // read file
    readFile (route, function (err, fileContent) {

        if (err) {
            console.error (err);
            return Statique.sendRes (res, 500, "html", "Internal server error");
        }

        // convert page object to array
        var pageArray = []
          , pages = SITE_CONFIG.parsed.roots.pages
          , pageHtml = "";
          ;

        for (var url in pages) {
            var cPage = JSON.parse(JSON.stringify(pages[url]));
            cPage.url = url;
            pageArray.push (cPage);
        }

        pageArray.sort (function (a, b) {
            return a.order > b.order;
        });

        for (var i = 0; i < pageArray.length; ++i) {
            var cPageObj = pageArray[i];
            pageHtml +=
                "
\n"
              + "    " + cPageObj.label + "\n"
              + "
\n";
        }

        // success response
        Statique.sendRes (res, 200, "text/html",
            SITE_CONFIG.parsed.roots.template.page.replace (
                "{{PAGE_CONTENT}}"
              , Marked (fileContent)
            ).replace(
                "{{TITLE}}"
              , SITE_CONFIG.title
            ).replace(
                "{{PAGES}}"
              , pageHtml
            )
        );
    });
};

/**
 *  Handle POST requests
 *
 */
module.exports["handlePage:POST"] = function (req, res, pathName, route) {

    // get form data
    getFormData (req, function (err, formData) {

        if (err) {
            console.error (err);
            return res.end ("Internal server error");
        }

        console.log(formData);
    });
};
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

sap.ui.define(['jquery.sap.global', 'sap/ui/core/Renderer', './InputBaseRenderer'],
	function(jQuery, Renderer, InputBaseRenderer) {
	"use strict";

	/**
	 * Input renderer.
	 * @namespace
	 *
	 * InputRenderer extends the InputBaseRenderer
	 */
	var InputRenderer = Renderer.extend(InputBaseRenderer);

	/**
	 * Adds control specific class
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addOuterClasses = function(oRm, oControl) {
		oRm.addClass("sapMInput");
		if (oControl.getShowValueHelp() && oControl.getEnabled() && oControl.getEditable()) {
			oRm.addClass("sapMInputVH");
			if (oControl.getValueHelpOnly()) {
				oRm.addClass("sapMInputVHO");
			}
		}
		if (oControl.getDescription()) {
				oRm.addClass("sapMInputDescription");
		}
	};

	/**
	 * Add extra styles for input container
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addOuterStyles = function(oRm, oControl) {
	};

	/**
	 * add extra attributes to Input
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.writeInnerAttributes = function(oRm, oControl) {
		oRm.writeAttribute("type", oControl.getType().toLowerCase());
		if (oControl.getType() == sap.m.InputType.Number && sap.ui.getCore().getConfiguration().getRTL()) {
			oRm.writeAttribute("dir", "ltr");
			oRm.addStyle("text-align", "right");
		}

		if ((!oControl.getEnabled() && oControl.getType() == "Password")
				|| (oControl.getShowSuggestion() && oControl._bUseDialog)
				|| (oControl.getValueHelpOnly() && oControl.getEnabled() && oControl.getEditable() && oControl.getShowValueHelp())) {
			// required for JAWS reader on password fields on desktop and in other cases:
			oRm.writeAttribute("readonly", "readonly");
		}
	};

	/**
	 * Adds inner css classes to the input field
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addInnerClasses = function(oRm, oControl) {
	};

	/**
	 * Add inner styles to the input field
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addInnerStyles = function(oRm, oControl) {

		if (oControl.getDescription()) {
			oRm.addStyle("width", oControl.getFieldWidth() || "50%");
		}
	};

	/**
	 * add extra content to Input
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.writeInnerContent = function(oRm, oControl) {

		var id = oControl.getId(),
			description = oControl.getDescription();

		if (!description) {
			this.writeValueHelpIcon(oRm, oControl);
		} else {
			oRm.write("");
			this.writeValueHelpIcon(oRm, oControl);
			oRm.writeEscaped(description);
			oRm.write("");
		}

		if (sap.ui.getCore().getConfiguration().getAccessibility()) {
			if (oControl.getShowSuggestion() && oControl.getEnabled() && oControl.getEditable()) {
				oRm.write("");
			}
		}

	};

	InputRenderer.writeValueHelpIcon = function(oRm, oControl) {

		if (oControl.getShowValueHelp() && oControl.getEnabled() && oControl.getEditable()) {
			// Set tabindex to -1 to prevent the focus from going to the underlying list row,
			// in case when the input is placed inside of a list/table.
			oRm.write('
');
			oRm.renderControl(oControl._getValueHelpIcon());
			oRm.write("
");
		}

	};

	/**
	 * Add inner styles to the placeholder
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addPlaceholderStyles = function(oRm, oControl) {

		if (oControl.getDescription()) {
			oRm.addStyle("width", oControl.getFieldWidth() || "50%");
		}

	};

	InputRenderer.getAriaLabelledBy = function(oControl) {
		var ariaLabels = InputBaseRenderer.getAriaLabelledBy.call(this, oControl) || "";
		if (oControl.getDescription()) {
			ariaLabels = ariaLabels + " " + oControl.getId() + "-Descr";
		}
		return ariaLabels;
	};

	InputRenderer.getAriaDescribedBy = function(oControl) {

		var sAriaDescribedBy = InputBaseRenderer.getAriaDescribedBy.apply(this, arguments);

		if (oControl.getShowValueHelp() && oControl.getEnabled() && oControl.getEditable()) {
			if (sAriaDescribedBy) {
				sAriaDescribedBy = sAriaDescribedBy + " " + oControl._sAriaValueHelpLabelId;
			} else {
				sAriaDescribedBy = oControl._sAriaValueHelpLabelId;
			}
			if (oControl.getValueHelpOnly()) {
				sAriaDescribedBy = sAriaDescribedBy + " " + oControl._sAriaInputDisabledLabelId;
			}
		}

		if (oControl.getShowSuggestion() && oControl.getEnabled() && oControl.getEditable()) {
			if (sAriaDescribedBy) {
				sAriaDescribedBy = sAriaDescribedBy + " " + oControl.getId() + "-SuggDescr";
			} else {
				sAriaDescribedBy = oControl.getId() + "-SuggDescr";
			}
		}

		return sAriaDescribedBy;

	};

	/**
	 * Returns aria accessibility role for the control.
	 * Hook for the subclasses.
	 *
	 * @param {sap.ui.core.Control} oControl an object representation of the control
	 * @returns {String}
	 */
	InputRenderer.getAriaRole = function(oControl) {
		return "";
	};

	InputRenderer.getAccessibilityState = function(oControl) {

		var mAccessibilityState = InputBaseRenderer.getAccessibilityState.apply(this, arguments);

		if (oControl.getShowSuggestion() && oControl.getEnabled() && oControl.getEditable()) {
			mAccessibilityState.autocomplete = "list";
		}

		return mAccessibilityState;

	};

	return InputRenderer;

}, /* bExport= */ true);
<commit_msg>[FIX] sap.m.Input: Acc issue in Input fixed<commit_after>/*!
 * ${copyright}
 */

sap.ui.define(['jquery.sap.global', 'sap/ui/core/Renderer', './InputBaseRenderer'],
	function(jQuery, Renderer, InputBaseRenderer) {
	"use strict";

	/**
	 * Input renderer.
	 * @namespace
	 *
	 * InputRenderer extends the InputBaseRenderer
	 */
	var InputRenderer = Renderer.extend(InputBaseRenderer);

	/**
	 * Adds control specific class
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addOuterClasses = function(oRm, oControl) {
		oRm.addClass("sapMInput");
		if (oControl.getShowValueHelp() && oControl.getEnabled() && oControl.getEditable()) {
			oRm.addClass("sapMInputVH");
			if (oControl.getValueHelpOnly()) {
				oRm.addClass("sapMInputVHO");
			}
		}
		if (oControl.getDescription()) {
				oRm.addClass("sapMInputDescription");
		}
	};

	/**
	 * Add extra styles for input container
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addOuterStyles = function(oRm, oControl) {
	};

	/**
	 * add extra attributes to Input
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.writeInnerAttributes = function(oRm, oControl) {
		oRm.writeAttribute("type", oControl.getType().toLowerCase());
		if (oControl.getType() == sap.m.InputType.Number && sap.ui.getCore().getConfiguration().getRTL()) {
			oRm.writeAttribute("dir", "ltr");
			oRm.addStyle("text-align", "right");
		}

		if ((!oControl.getEnabled() && oControl.getType() == "Password")
				|| (oControl.getShowSuggestion() && oControl._bUseDialog)
				|| (oControl.getValueHelpOnly() && oControl.getEnabled() && oControl.getEditable() && oControl.getShowValueHelp())) {
			// required for JAWS reader on password fields on desktop and in other cases:
			oRm.writeAttribute("readonly", "readonly");
		}
	};

	/**
	 * Adds inner css classes to the input field
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addInnerClasses = function(oRm, oControl) {
	};

	/**
	 * Add inner styles to the input field
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addInnerStyles = function(oRm, oControl) {

		if (oControl.getDescription()) {
			oRm.addStyle("width", oControl.getFieldWidth() || "50%");
		}
	};

	/**
	 * add extra content to Input
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.writeInnerContent = function(oRm, oControl) {

		var id = oControl.getId(),
			description = oControl.getDescription();

		if (!description) {
			this.writeValueHelpIcon(oRm, oControl);
		} else {
			oRm.write("");
			this.writeValueHelpIcon(oRm, oControl);
			oRm.writeEscaped(description);
			oRm.write("");
		}

		if (sap.ui.getCore().getConfiguration().getAccessibility()) {
			if (oControl.getShowSuggestion() && oControl.getEnabled() && oControl.getEditable()) {
				oRm.write("");
			}
		}

	};

	InputRenderer.writeValueHelpIcon = function(oRm, oControl) {

		if (oControl.getShowValueHelp() && oControl.getEnabled() && oControl.getEditable()) {
			// Set tabindex to -1 to prevent the focus from going to the underlying list row,
			// in case when the input is placed inside of a list/table.
			oRm.write('
');
			oRm.renderControl(oControl._getValueHelpIcon());
			oRm.write("
");
		}

	};

	/**
	 * Add inner styles to the placeholder
	 *
	 * @param {sap.ui.core.RenderManager} oRm the RenderManager that can be used for writing to the render output buffer
	 * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered
	 */
	InputRenderer.addPlaceholderStyles = function(oRm, oControl) {

		if (oControl.getDescription()) {
			oRm.addStyle("width", oControl.getFieldWidth() || "50%");
		}

	};

	InputRenderer.getAriaLabelledBy = function(oControl) {
		var ariaLabels = InputBaseRenderer.getAriaLabelledBy.call(this, oControl) || "";
		if (oControl.getDescription()) {
			ariaLabels = ariaLabels + " " + oControl.getId() + "-Descr";
		}
		return ariaLabels;
	};

	InputRenderer.getAriaDescribedBy = function(oControl) {

		var sAriaDescribedBy = InputBaseRenderer.getAriaDescribedBy.apply(this, arguments);

		if (oControl.getShowValueHelp() && oControl.getEnabled() && oControl.getEditable()) {
			if (sAriaDescribedBy) {
				sAriaDescribedBy = sAriaDescribedBy + " " + oControl._sAriaValueHelpLabelId;
			} else {
				sAriaDescribedBy = oControl._sAriaValueHelpLabelId;
			}
			if (oControl.getValueHelpOnly()) {
				sAriaDescribedBy = sAriaDescribedBy + " " + oControl._sAriaInputDisabledLabelId;
			}
		}

		if (oControl.getShowSuggestion() && oControl.getEnabled() && oControl.getEditable()) {
			if (sAriaDescribedBy) {
				sAriaDescribedBy = sAriaDescribedBy + " " + oControl.getId() + "-SuggDescr";
			} else {
				sAriaDescribedBy = oControl.getId() + "-SuggDescr";
			}
		}

		return sAriaDescribedBy;

	};

	/**
	 * Returns aria accessibility role for the control.
	 * Hook for the subclasses.
	 *
	 * @param {sap.ui.core.Control} oControl an object representation of the control
	 * @returns {String}
	 */
	InputRenderer.getAriaRole = function(oControl) {
		return "";
	};

	InputRenderer.getAccessibilityState = function(oControl) {

		var mAccessibilityState = InputBaseRenderer.getAccessibilityState.apply(this, arguments);

		if (oControl.getShowSuggestion() && oControl.getEnabled() && oControl.getEditable()) {
			mAccessibilityState.autocomplete = "list";
		}

		return mAccessibilityState;

	};

	return InputRenderer;

}, /* bExport= */ true);
<|endoftext|>


<commit_before>import {map, baseLayerDict, dragElement, overlay_list} from '../util.js';
import {displayedColorbar, syncImageLoad, currentDomain, current_display, current_timestamp, currentSimulation, rasters, raster_base, sorted_timestamps, organization} from './Controller.js';

/**
 * Component that handles adding and removing layers to the map. Provides user with a window
 * to choose different layers available to add.
 */
export class LayerController extends HTMLElement {
    constructor() {
        super();
        this.innerHTML = `
            <link rel="stylesheet" href="css/layerController.css"/>

                    Base Maps

                    Rasters

                    Overlays

        `;
        this.mapType = 'OSM';
        this.currentSimulation = '';
        this.overlayDict = {};
        this.rasterDict = {};
        this.imgCanvas = null;
        this.clrBarCanvas = null;
        this.clrBarMaps = {};
        this.markerIcon = L.icon({iconUrl: 'icons/square_icon_filled.png', iconSize: [5,5]});
        this.markers = [];
        this.overlayOrder = [];
    }

    /** Disable map events from within the layer selection window to prevent unwanted zooming
     * and panning. */
    connectedCallback() {
        const layerController = this.querySelector('#layer-controller-container');
        dragElement(layerController, '');
        L.DomEvent.disableClickPropagation(layerController);
        L.DomEvent.disableScrollPropagation(layerController);

        currentDomain.subscribe(() => this.domainSwitch());
        current_timestamp.subscribe(() => this.updateTime());
        this.buildMapBase();
        // syncImageLoad.subscribe(() => {
        //     if (displayedColorbar.getValue()) {
        //         const rasterColorbar = document.querySelector('#raster-colorbar');
        //         var layerImage = null;
        //         if (displayedColorbar.getValue() in overlay_list) {
        //             layerImage = this.overlayDict[displayedColorbar.getValue()]._image;
        //         } else {
        //             layerImage = this.rasterDict[displayedColorbar.getValue()]._image;
        //         }
        //         this.clrBarCanvas = this.drawCanvas(rasterColorbar);
        //         this.imgCanvas = this.drawCanvas(layerImage);
        //         this.updateMarkers();
        //     }
        // });
    }

    updateTime() {
        var rasters_now = rasters.getValue()[currentDomain.getValue()][current_timestamp.getValue()];
        for (var layer_name in current_display.getValue()) {
            var layer = current_display.getValue()[layer_name];
            var raster_info = rasters_now[layer_name];
            var cs = raster_info.coords;
            layer.setUrl(raster_base.getValue() + raster_info.raster,
                        [ [cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]] ],
                        { attribution: organization.getValue(), opacity: 0.5 });
            if (layer_name == displayedColorbar.getValue()) {
                const rasterColorbar = document.querySelector('#raster-colorbar');
                rasterColorbar.src = raster_base.getValue() + raster_info.colorbar;
            }
        }
    }

    /** Called when a new domain is selected or a new simulation is selected. */
    domainSwitch() {
        for(var layerName in current_display.getValue()) {
            this.handleOverlayRemove(layerName, current_display.getValue()[layerName]);
        }
        var prevDisplay = current_display.getValue();
        if (this.currentSimulation != currentSimulation.getValue()) {
            prevDisplay = {};
            this.currentSimulation = currentSimulation.getValue();
            this.querySelector('#layer-controller-container').style.display = 'block';
        }
        current_display.setValue({});
        var first_rasters = rasters.getValue()[currentDomain.getValue()][sorted_timestamps.getValue()[0]];
        var vars = Object.keys(first_rasters);
        var cs = first_rasters[vars[0]].coords;
        map.fitBounds([ [cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]] ]);

        // build the layer groups
        this.rasterDict = {};
        this.overlayDict = {};
        Object.entries(first_rasters).map(entry => {
            var r = entry[0];
            var raster_info = first_rasters[r];
            var cs = raster_info.coords;
            var layer = L.imageOverlay(raster_base.getValue() + raster_info.raster,
                                        [[cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]]],
                                        {
                                            attribution: organization.getValue(),
                                            opacity: 0.5,
                                            interactive: true
                                        });
            if(r in prevDisplay) current_display.getValue()[r] = layer;
            if(overlay_list.indexOf(r) >= 0) {
                this.overlayDict[r] = layer;
            } else {
                this.rasterDict[r] = layer;
            }
        });
        this.buildLayerBoxes();
    }

    /** Called when a layer is selected. */
    handleOverlayadd(name, layer) {
        // register in currently displayed layers and bring to front if it's an overlay
        console.log('name ' + name + ' layer ' + layer);
        layer.addTo(map);
        current_display.getValue()[name] = layer;
        if(overlay_list.indexOf(name) >= 0) {
            layer.bringToFront();
        } else {
            layer.bringToBack();
        }

        // if the overlay being added now has a colorbar and there is none displayed, show it
        var rasters_now = rasters.getValue()[currentDomain.getValue()][current_timestamp.getValue()];
        var raster_info = rasters_now[name];
        var cs = raster_info.coords;
        layer.setUrl(raster_base.getValue() + raster_info.raster,
                    [ [cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]] ],
                    { attribution: organization.getValue(), opacity: 0.5 });
        if('colorbar' in raster_info) {
            var cb_url = raster_base.getValue() + raster_info.colorbar;
            const rasterColorbar = document.querySelector('#raster-colorbar');
            rasterColorbar.src = cb_url;
            rasterColorbar.style.display = 'block';
            displayedColorbar.setValue(name);
            // var img = layer._image;
            // img.ondblclick = (e) => {
            //     var latLon = map.mouseEventToLatLng(e);
            //     e.stopPropagation();
            //     var popUp = L.popup({closeOnClick: false, autoClose: false, autoPan: false}).setLatLng([latLon.lat, latLon.lng]).openOn(map);
            //     popUp.imageCoords = {layerX: e.layerX /img.width, layerY: e.layerY / img.height};
            //     this.updateMarker(popUp);
            //     this.markers.push(popUp);
            // }
            // img.onload = () => syncImageLoad.increment();
            // rasterColorbar.onload = () => syncImageLoad.increment();
            // map.on('zoomend', () => this.imgCanvas = this.drawCanvas(img));
            // this.imgCanvas = this.drawCanvas(img);
            // this.clrBarCanvas = this.drawCanvas(rasterColorbar);
            // this.updateMarkers();
        }
        this.overlayOrder.push(name);
    }

    /** Called when a layer is de-selected. */
    handleOverlayRemove(name, layer) {
        layer.remove(map);
        this.overlayOrder.splice(this.overlayOrder.indexOf(name), 1);
        const rasterColorbar = document.querySelector('#raster-colorbar');
        var rasters_now = rasters.getValue()[currentDomain.getValue()][current_timestamp.getValue()];
        var img = null;
        var mostRecentColorbar = null;
        var colorbarSrc = '';
        var colorbarDisplay = 'none';
        for (var i = this.overlayOrder.length - 1; i >= 0; i--) {
            if ('colorbar' in rasters_now[this.overlayOrder[i]]) {
                mostRecentColorbar = this.overlayOrder[i];
                colorbarSrc = raster_base.getValue() + rasters_now[this.overlayOrder[i]].colorbar;
                colorbarDisplay = 'block';
                img = this.getLayer(this.overlayOrder[i])._image;
                break;
            }
        }
        displayedColorbar.setValue(mostRecentColorbar);
        rasterColorbar.src = colorbarSrc;
        rasterColorbar.style.display = colorbarDisplay;
        this.imgCanvas = this.drawCanvas(img);
        this.clrBarCanvas = this.drawCanvas(rasterColorbar);
        this.updateMarkers();
    }

    getLayer(name) {
        if (name in overlay_list) return this.overlayDict[name];
        return this.rasterDict[name];
    }

    drawCanvas(img) {
        var canvas = null;
        if (img != null) {
            canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
        }
        return canvas;
    }

    updateMarkers() {
        this.markers.map(marker => {
            this.updateMarker(marker);
        });
    }

    updateMarker(marker) {
        var popupContent = "No layer bar with colobar to show values of";
        if (this.imgCanvas) {
            var imageCoords = marker.imageCoords;
            var xCoord = Math.floor(imageCoords.layerX * this.imgCanvas.width);
            var yCoord = Math.floor(imageCoords.layerY * this.imgCanvas.height);
            var pixelData = this.imgCanvas.getContext('2d').getImageData(xCoord, yCoord, 1, 1).data;
            popupContent = this.matchToColorBar(pixelData);
        }
        marker.setContent(popupContent);
    }

    matchToColorBar(pixelData) {
        // if (this.clrBarCanvas) {
        //     for (var i = 0; i < this.clrBarCanvas.width; i++) {
        //         for (var j = 0; j < this.clrBarCanvas.height; j++) {
        //             var colorBarData = this.clrBarCanvas.getContext('2d').getImageData(i, j, 1, 1).data;
        //             if (colorBarData[0] == pixelData[0] && colorBarData[1] == pixelData[1] && colorBarData[2] == pixelData[2]) {
        //                 console.log(i, j);
        //             }
        //         }
        //     }
        // }
        return `<p style="color: rgb(${pixelData[0]}, ${pixelData[1]}, ${pixelData[2]})">R:${pixelData[0]} G:${pixelData[1]} B:${pixelData[2]}</p>`;
    }

    buildColorMap(layerName) {

    }

    /** Called when a new domain is selected or a new simulation is selected. */
    domainSwitch() {
        for(var layerName in current_display.getValue()) {
            this.handleOverlayRemove(layerName, current_display.getValue()[layerName]);
        }
        var prevDisplay = current_display.getValue();
        if (this.currentSimulation != currentSimulation.getValue()) {
            prevDisplay = {};
            this.currentSimulation = currentSimulation.getValue();
            this.querySelector('#layer-controller-container').style.display = 'block';
        }
        current_display.setValue({});
        var first_rasters = rasters.getValue()[currentDomain.getValue()][current_timestamp.getValue()];
        var vars = Object.keys(first_rasters);
        var cs = first_rasters[vars[0]].coords;
        map.fitBounds([ [cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]] ]);

        // build the layer groups
        this.rasterDict = {};
        this.overlayDict = {};
        Object.entries(first_rasters).map(entry => {
            var r = entry[0];
            var raster_info = first_rasters[r];
            var cs = raster_info.coords;
            var layer = L.imageOverlay(raster_base.getValue() + raster_info.raster,
                                        [[cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]]],
                                        {
                                            attribution: organization.getValue(),
                                            opacity: 0.5,
                                            interactive: true
                                        });
            if(r in prevDisplay) current_display.getValue()[r] = layer;
            if(overlay_list.indexOf(r) >= 0) {
                this.overlayDict[r] = layer;
            } else {
                this.rasterDict[r] = layer;
            }
        });
        this.buildLayerBoxes();
    }

    /** Adds checkboxes for the different available map types. Should only be called once after
     * the map has been initialized. */
    buildMapBase() {
        const baseMapDiv = this.querySelector('#map-checkboxes');
        for (const [name, layer] of Object.entries(baseLayerDict)) {
            let mapCheckBox = this.buildMapCheckBox(name, layer);
            baseMapDiv.appendChild(mapCheckBox);
        }
    }

    /** Builds a checkbox for each raster layer and overlay layer */
    buildLayerBoxes() {
        const rasterRegion = this.querySelector('#raster-layers');
        rasterRegion.style.display = 'block';
        if (Object.keys(this.rasterDict).length == 0) rasterRegion.style.display = 'none';

        const overlayRegion = this.querySelector('#overlay-layers');
        overlayRegion.style.display = 'block';
        if (Object.keys(this.overlayDict).length == 0) overlayRegion.style.display = 'none';

        const rasterDiv = this.querySelector('#raster-checkboxes');
        rasterDiv.innerHTML = '';
        const overlayDiv = this.querySelector('#overlay-checkboxes');
        overlayDiv.innerHTML = '';

        [[rasterDiv, this.rasterDict], [overlayDiv, this.overlayDict]].map(([layerDiv, layerDict]) => {
            for (const [name, layer] of Object.entries(layerDict)) {
                let layerBox = this.buildLayerBox(name, layer);
                layerDiv.appendChild(layerBox);
            }
        });
    }

    /** Builds a radio box for each map base that can be chosen */
    buildMapCheckBox(name, layer) {
        let [div, input] = this.buildCheckBox(name);
        input.type = 'radio';
        input.name = 'base';
        input.checked = name == this.mapType;
        input.onclick = () => {
            if (input.checked) {
                layer.addTo(map);
                this.mapType = name;
                layer.bringToFront();
            } else {
                layer.remove(map);
            }
        }
        return div;
    }

    /** Creates the checkbox for a layer. Displays name and when clicked adds layer to the map. base is
     * a boolean that indicates whether creating a checkbox for a map type or a layer.*/
    buildLayerBox(name, layer) {
        let [div, input] = this.buildCheckBox(name, layer);
        input.type = 'checkbox';
        input.name = 'layers';
        input.checked = name in current_display.getValue();
        if (name in current_display.getValue()) {
            this.handleOverlayadd(name, layer);
        }
        input.onclick = () => {
            if (input.checked) this.handleOverlayadd(name, layer);
            else {
                this.handleOverlayRemove(name, layer);
                delete current_display.getValue()[name];
            }
        }
        return div;
    }

    buildCheckBox(name) {
        var div = document.createElement('div');
        div.className = 'layer-checkbox';
        const input = document.createElement('input');
        input.id = name;
        var label = document.createElement('label');
        label.for = name;
        label.innerText = name;
        div.appendChild(input);
        div.appendChild(label);
        return [div, input];
    }

}

window.customElements.define('layer-controller', LayerController);<commit_msg>Adds back in ability to create markers<commit_after>import {map, baseLayerDict, dragElement, overlay_list} from '../util.js';
import {displayedColorbar, syncImageLoad, currentDomain, current_display, current_timestamp, currentSimulation, rasters, raster_base, sorted_timestamps, organization} from './Controller.js';

/**
 * Component that handles adding and removing layers to the map. Provides user with a window
 * to choose different layers available to add.
 */
export class LayerController extends HTMLElement {
    constructor() {
        super();
        this.innerHTML = `
            <link rel="stylesheet" href="css/layerController.css"/>

                    Base Maps

                    Rasters

                    Overlays

        `;
        this.mapType = 'OSM';
        this.currentSimulation = '';
        this.overlayDict = {};
        this.rasterDict = {};
        this.imgCanvas = null;
        this.clrBarCanvas = null;
        this.clrBarMaps = {};
        this.markerIcon = L.icon({iconUrl: 'icons/square_icon_filled.png', iconSize: [5,5]});
        this.markers = [];
        this.overlayOrder = [];
    }

    /** Disable map events from within the layer selection window to prevent unwanted zooming
     * and panning. */
    connectedCallback() {
        const layerController = this.querySelector('#layer-controller-container');
        dragElement(layerController, '');
        L.DomEvent.disableClickPropagation(layerController);
        L.DomEvent.disableScrollPropagation(layerController);

        currentDomain.subscribe(() => this.domainSwitch());
        current_timestamp.subscribe(() => this.updateTime());
        this.buildMapBase();
        syncImageLoad.subscribe(() => {
            if (displayedColorbar.getValue()) {
                const rasterColorbar = document.querySelector('#raster-colorbar');
                var layerImage = this.getLayer(displayedColorbar.getValue())._image;
                this.clrBarCanvas = this.drawCanvas(rasterColorbar);
                this.imgCanvas = this.drawCanvas(layerImage);
                this.updateMarkers();
            }
        });
    }

    updateTime() {
        var rasters_now = rasters.getValue()[currentDomain.getValue()][current_timestamp.getValue()];
        for (var layer_name in current_display.getValue()) {
            var layer = current_display.getValue()[layer_name];
            var raster_info = rasters_now[layer_name];
            var cs = raster_info.coords;
            layer.setUrl(raster_base.getValue() + raster_info.raster,
                        [ [cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]] ],
                        { attribution: organization.getValue(), opacity: 0.5 });
            if (layer_name == displayedColorbar.getValue()) {
                const rasterColorbar = document.querySelector('#raster-colorbar');
                rasterColorbar.src = raster_base.getValue() + raster_info.colorbar;
            }
        }
    }

    /** Called when a new domain is selected or a new simulation is selected. */
    domainSwitch() {
        for(var layerName in current_display.getValue()) {
            this.handleOverlayRemove(layerName, current_display.getValue()[layerName]);
        }
        var prevDisplay = current_display.getValue();
        if (this.currentSimulation != currentSimulation.getValue()) {
            prevDisplay = {};
            this.currentSimulation = currentSimulation.getValue();
            this.querySelector('#layer-controller-container').style.display = 'block';
        }
        current_display.setValue({});
        var first_rasters = rasters.getValue()[currentDomain.getValue()][sorted_timestamps.getValue()[0]];
        var vars = Object.keys(first_rasters);
        var cs = first_rasters[vars[0]].coords;
        map.fitBounds([ [cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]] ]);

        // build the layer groups
        this.rasterDict = {};
        this.overlayDict = {};
        Object.entries(first_rasters).map(entry => {
            var r = entry[0];
            var raster_info = first_rasters[r];
            var cs = raster_info.coords;
            var layer = L.imageOverlay(raster_base.getValue() + raster_info.raster,
                                        [[cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]]],
                                        {
                                            attribution: organization.getValue(),
                                            opacity: 0.5,
                                            interactive: true
                                        });
            if(r in prevDisplay) current_display.getValue()[r] = layer;
            if(overlay_list.indexOf(r) >= 0) {
                this.overlayDict[r] = layer;
            } else {
                this.rasterDict[r] = layer;
            }
        });
        this.buildLayerBoxes();
    }

    /** Called when a layer is selected. */
    handleOverlayadd(name, layer) {
        // register in currently displayed layers and bring to front if it's an overlay
        console.log('name ' + name + ' layer ' + layer);
        layer.addTo(map);
        current_display.getValue()[name] = layer;
        this.overlayOrder.push(name);
        if(overlay_list.indexOf(name) >= 0) {
            layer.bringToFront();
        } else {
            layer.bringToBack();
        }

        // if the overlay being added now has a colorbar and there is none displayed, show it
        var rasters_now = rasters.getValue()[currentDomain.getValue()][current_timestamp.getValue()];
        var raster_info = rasters_now[name];
        var cs = raster_info.coords;
        layer.setUrl(raster_base.getValue() + raster_info.raster,
                    [ [cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]] ],
                    { attribution: organization.getValue(), opacity: 0.5 });
        if('colorbar' in raster_info) {
            var cb_url = raster_base.getValue() + raster_info.colorbar;
            const rasterColorbar = document.querySelector('#raster-colorbar');
            rasterColorbar.src = cb_url;
            rasterColorbar.style.display = 'block';
            displayedColorbar.setValue(name);
            var img = layer._image;
            img.ondblclick = (e) => {
                var latLon = map.mouseEventToLatLng(e);
                e.stopPropagation();
                var popUp = L.popup({closeOnClick: false, autoClose: false, autoPan: false}).setLatLng([latLon.lat, latLon.lng]).openOn(map);
                popUp.imageCoords = {layerX: e.layerX /img.width, layerY: e.layerY / img.height};
                this.updateMarker(popUp);
                this.markers.push(popUp);
            }
            img.onload = () => syncImageLoad.increment();
            rasterColorbar.onload = () => syncImageLoad.increment();
            map.on('zoomend', () => this.imgCanvas = this.drawCanvas(img));
            this.imgCanvas = this.drawCanvas(img);
            this.clrBarCanvas = this.drawCanvas(rasterColorbar);
            this.updateMarkers();
        }
    }

    /** Called when a layer is de-selected. */
    handleOverlayRemove(name, layer) {
        layer.remove(map);
        this.overlayOrder.splice(this.overlayOrder.indexOf(name), 1);
        const rasterColorbar = document.querySelector('#raster-colorbar');
        var rasters_now = rasters.getValue()[currentDomain.getValue()][current_timestamp.getValue()];
        var img = null;
        var mostRecentColorbar = null;
        var colorbarSrc = '';
        var colorbarDisplay = 'none';
        for (var i = this.overlayOrder.length - 1; i >= 0; i--) {
            if ('colorbar' in rasters_now[this.overlayOrder[i]]) {
                mostRecentColorbar = this.overlayOrder[i];
                colorbarSrc = raster_base.getValue() + rasters_now[this.overlayOrder[i]].colorbar;
                colorbarDisplay = 'block';
                img = this.getLayer(this.overlayOrder[i])._image;
                break;
            }
        }
        displayedColorbar.setValue(mostRecentColorbar);
        rasterColorbar.src = colorbarSrc;
        rasterColorbar.style.display = colorbarDisplay;
        this.imgCanvas = this.drawCanvas(img);
        this.clrBarCanvas = this.drawCanvas(rasterColorbar);
        this.updateMarkers();
    }

    getLayer(name) {
        if (name in overlay_list) return this.overlayDict[name];
        return this.rasterDict[name];
    }

    drawCanvas(img) {
        var canvas = null;
        if (img != null) {
            canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
        }
        return canvas;
    }

    updateMarkers() {
        this.markers.map(marker => {
            this.updateMarker(marker);
        });
    }

    updateMarker(marker) {
        var popupContent = "No layer bar with colobar to show values of";
        if (this.imgCanvas) {
            var imageCoords = marker.imageCoords;
            var xCoord = Math.floor(imageCoords.layerX * this.imgCanvas.width);
            var yCoord = Math.floor(imageCoords.layerY * this.imgCanvas.height);
            var pixelData = this.imgCanvas.getContext('2d').getImageData(xCoord, yCoord, 1, 1).data;
            popupContent = this.matchToColorBar(pixelData);
        }
        marker.setContent(popupContent);
    }

    matchToColorBar(pixelData) {
        // if (this.clrBarCanvas) {
        //     for (var i = 0; i < this.clrBarCanvas.width; i++) {
        //         for (var j = 0; j < this.clrBarCanvas.height; j++) {
        //             var colorBarData = this.clrBarCanvas.getContext('2d').getImageData(i, j, 1, 1).data;
        //             if (colorBarData[0] == pixelData[0] && colorBarData[1] == pixelData[1] && colorBarData[2] == pixelData[2]) {
        //                 console.log(i, j);
        //             }
        //         }
        //     }
        // }
        return `<p style="color: rgb(${pixelData[0]}, ${pixelData[1]}, ${pixelData[2]})">R:${pixelData[0]} G:${pixelData[1]} B:${pixelData[2]}</p>`;
    }

    buildColorMap(layerName) {

    }

    /** Called when a new domain is selected or a new simulation is selected. */
    domainSwitch() {
        for(var layerName in current_display.getValue()) {
            this.handleOverlayRemove(layerName, current_display.getValue()[layerName]);
        }
        var prevDisplay = current_display.getValue();
        if (this.currentSimulation != currentSimulation.getValue()) {
            prevDisplay = {};
            this.currentSimulation = currentSimulation.getValue();
            this.querySelector('#layer-controller-container').style.display = 'block';
        }
        current_display.setValue({});
        var first_rasters = rasters.getValue()[currentDomain.getValue()][current_timestamp.getValue()];
        var vars = Object.keys(first_rasters);
        var cs = first_rasters[vars[0]].coords;
        map.fitBounds([ [cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]] ]);

        // build the layer groups
        this.rasterDict = {};
        this.overlayDict = {};
        Object.entries(first_rasters).map(entry => {
            var r = entry[0];
            var raster_info = first_rasters[r];
            var cs = raster_info.coords;
            var layer = L.imageOverlay(raster_base.getValue() + raster_info.raster,
                                        [[cs[0][1], cs[0][0]], [cs[2][1], cs[2][0]]],
                                        {
                                            attribution: organization.getValue(),
                                            opacity: 0.5,
                                            interactive: true
                                        });
            if(r in prevDisplay) current_display.getValue()[r] = layer;
            if(overlay_list.indexOf(r) >= 0) {
                this.overlayDict[r] = layer;
            } else {
                this.rasterDict[r] = layer;
            }
        });
        this.buildLayerBoxes();
    }

    /** Adds checkboxes for the different available map types. Should only be called once after
     * the map has been initialized. */
    buildMapBase() {
        const baseMapDiv = this.querySelector('#map-checkboxes');
        for (const [name, layer] of Object.entries(baseLayerDict)) {
            let mapCheckBox = this.buildMapCheckBox(name, layer);
            baseMapDiv.appendChild(mapCheckBox);
        }
    }

    /** Builds a checkbox for each raster layer and overlay layer */
    buildLayerBoxes() {
        const rasterRegion = this.querySelector('#raster-layers');
        rasterRegion.style.display = 'block';
        if (Object.keys(this.rasterDict).length == 0) rasterRegion.style.display = 'none';

        const overlayRegion = this.querySelector('#overlay-layers');
        overlayRegion.style.display = 'block';
        if (Object.keys(this.overlayDict).length == 0) overlayRegion.style.display = 'none';

        const rasterDiv = this.querySelector('#raster-checkboxes');
        rasterDiv.innerHTML = '';
        const overlayDiv = this.querySelector('#overlay-checkboxes');
        overlayDiv.innerHTML = '';

        [[rasterDiv, this.rasterDict], [overlayDiv, this.overlayDict]].map(([layerDiv, layerDict]) => {
            for (const [name, layer] of Object.entries(layerDict)) {
                let layerBox = this.buildLayerBox(name, layer);
                layerDiv.appendChild(layerBox);
            }
        });
    }

    /** Builds a radio box for each map base that can be chosen */
    buildMapCheckBox(name, layer) {
        let [div, input] = this.buildCheckBox(name);
        input.type = 'radio';
        input.name = 'base';
        input.checked = name == this.mapType;
        input.onclick = () => {
            if (input.checked) {
                layer.addTo(map);
                this.mapType = name;
                layer.bringToFront();
            } else {
                layer.remove(map);
            }
        }
        return div;
    }

    /** Creates the checkbox for a layer. Displays name and when clicked adds layer to the map. base is
     * a boolean that indicates whether creating a checkbox for a map type or a layer.*/
    buildLayerBox(name, layer) {
        let [div, input] = this.buildCheckBox(name, layer);
        input.type = 'checkbox';
        input.name = 'layers';
        input.checked = name in current_display.getValue();
        if (name in current_display.getValue()) {
            this.handleOverlayadd(name, layer);
        }
        input.onclick = () => {
            if (input.checked) this.handleOverlayadd(name, layer);
            else {
                this.handleOverlayRemove(name, layer);
                delete current_display.getValue()[name];
            }
        }
        return div;
    }

    buildCheckBox(name) {
        var div = document.createElement('div');
        div.className = 'layer-checkbox';
        const input = document.createElement('input');
        input.id = name;
        var label = document.createElement('label');
        label.for = name;
        label.innerText = name;
        div.appendChild(input);
        div.appendChild(label);
        return [div, input];
    }

}

window.customElements.define('layer-controller', LayerController);<|endoftext|>


<commit_before>// User service
// Users API resources
// author @sauliuz

var util = require('util');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var request = require('request');

function userRoutes() {

  var userRouter = new express.Router();
  userRouter.use(cors());
  userRouter.use(bodyParser());

  // API resource to get all users.
  // should only acceesible for administrative users (via admin user tokens).
  userRouter.get('/', function(req, res) {

    // approach
    // 1. validate that the token submited in the request is still in the cache (if not ask for relogin)
    // 2. validate if the user attached to the token has admin priviledges (403 unauthorised if they dont)
    // 3. return the list of users if requesting user is admin.

    // response
    res.json({
      users: 'get all users',
      message: 'this resource is currentlly not implemented'
    });

  });

  // API resource for user login.
  userRouter.post('/login', function(req, res) {

    // approach
    // 1. get the username and password from the JSON payload
    // 2. validate the payloads with regex (username should be email, password - no weird stuff)
    // 3. request to user database (403 if not found)
    // 4. for found users, generate the token, store in the cashe. send back the username, token and TTL

    // response
    res.json({
      users: 'post user login',
      message: 'this resource is currentlly not implemented'
    });

  });

  // API resource for user login.
  userRouter.post('/logout', function(req, res) {

    // approach
    // 1. get the token from JSON
    // 2. delete the token key from cache (200 ok upon success)

    // response
    res.json({
      users: 'post user logout',
      message: 'this resource is currentlly not implemented'
    });

  });

  // API resource to create new user registration.
  userRouter.post('/register', function(req, res) {

    // approach
    // 1. get the username and password from the JSON payload
    // 2. validate the payloads with regex ()
    // 3. add user to the database, make them low level user by default (admin users cannot be created by mobile client)
    // 4. if create is success, generate the token, store in the cashe. send back the username, token and TTL

    // response
    res.json({
      activities: 'post user registration',
      message: 'this resource is currentlly not implemented'
    });
  });

  // end of users resources
  // any new resources shuld go here

  return userRouter;
};

module.exports = userRoutes;

// the end
<commit_msg>testing fh mongo<commit_after>// User service
// Users API resources
// author @sauliuz

var util = require('util');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var request = require('request');
var fh = require('fh-mbaas-api');

function userRoutes() {

  var userRouter = new express.Router();
  userRouter.use(cors());
  userRouter.use(bodyParser());

  // API resource to get all users.
  // should only acceesible for administrative users (via admin user tokens).
  userRouter.get('/', function(req, res) {

    // approach
    // 1. validate that the token submited in the request is still in the cache (if not ask for relogin)
    // 2. validate if the user attached to the token has admin priviledges (403 unauthorised if they dont)
    // 3. return the list of users if requesting user is admin.

    // Read a single entry
    var options = {
      "act": "read",
      "type": "myFirstEntity", // Entity/Collection name
      "guid": "4e563ea44fe8e7fc19000002" // Row/Entry ID
    };

    //
    $fh.db(options, function (err, data) {
      if (err) {
        console.error("Error " + err);

        res.json({
          mongoerror: err
        });

      } else {
        console.log(JSON.stringify(data));
        /* Sample output
          {
            "fields": {
              "address1": "22 Blogger Lane",
              "address2": "Bloggsville",
              "country": "Bloggland",
              "fistName": "Joe",
              "lastName": "Bloggs",
              "phone": "555-123456"
            },
            "guid": "4e563ea44fe8e7fc19000002",
            "type": "myFirstEntity"
          }
        */
        res.json({
          mongosuccess: data
        });

      }
});

    // // response
    // res.json({
    //   users: 'get all users',
    //   message: 'this resource is currentlly not implemented'
    // });

  });

  // API resource for user login.
  userRouter.post('/login', function(req, res) {

    // approach
    // 1. get the username and password from the JSON payload
    // 2. validate the payloads with regex (username should be email, password - no weird stuff)
    // 3. request to user database (403 if not found)
    // 4. for found users, generate the token, store in the cashe. send back the username, token and TTL

    // response
    res.json({
      users: 'post user login',
      message: 'this resource is currentlly not implemented'
    });

  });

  // API resource for user login.
  userRouter.post('/logout', function(req, res) {

    // approach
    // 1. get the token from JSON
    // 2. delete the token key from cache (200 ok upon success)

    // response
    res.json({
      users: 'post user logout',
      message: 'this resource is currentlly not implemented'
    });

  });

  // API resource to create new user registration.
  userRouter.post('/register', function(req, res) {

    // approach
    // 1. get the username and password from the JSON payload
    // 2. validate the payloads with regex ()
    // 3. add user to the database, make them low level user by default (admin users cannot be created by mobile client)
    // 4. if create is success, generate the token, store in the cashe. send back the username, token and TTL

    // response
    res.json({
      activities: 'post user registration',
      message: 'this resource is currentlly not implemented'
    });
  });

  // end of users resources
  // any new resources shuld go here

  return userRouter;
};

module.exports = userRoutes;

// the end
<|endoftext|>