<commit_before>dojo.provide("dojox.lang.oo.declare");

dojo.experimental("dojox.lang.oo.declare");

// a drop-in replacement for dojo.declare() with fixed bugs and enhancements

(function(){
	var d = dojo, oo = dojox.lang.oo, op = Object.prototype,
		cname = "constructor", has = "hasOwnProperty", dname = "declaredClass",
		isF = d.isFunction, each = d.forEach, xtor = function(){}, counter = 0;

	function err(msg){ throw new Error("declare: " + msg); }

	// C3 Method Resolution Order (see http://www.python.org/download/releases/2.3/mro/)
	function c3mro(bases){
		var result = [0], l = bases.length, classes = new Array(l),
			i = 0, j, m, m2, c, cls, lin, clsNum = 0;

		// initialize
		each(bases, function(c, i){
			if(!c) err("mixin #" + i + " is null");
			lin = c._meta && c._meta.bases || [c];
			clsNum += lin.length;
			m = {};
			each(lin, function(c){
				var proto = c.prototype, name = proto[has](dname) && proto[dname];
				if(!name) name = proto[dname] = "dojoUniqClassName_" + (counter++);
				m[name] = c;
			});
			classes[i] = {
				idx: 0,
				map: m,
				lin: d.map(lin, function(c){ return c.prototype[dname]; })
			};
		});

		// C3 MRO algorithm
		while(clsNum){
			for(i = l; i--;){
				m = classes[i];
				c = m.lin[m.idx];
				if(c){
					// check if it is in the tail of any classes
					for(j = l; j--;){
						m2 = classes[j];
						if(i != j && (c in m2.map) && c != m2.lin[m2.idx]) break;
					}
					if(j < 0){
						result.push(m.map[c]);
						// remove c from all heads
						for(j = l; j--;){
							m = classes[j];
							if(c == m.lin[m.idx]){
								++m.idx;
								--clsNum
							}
						}
						break;
					}
				}
			}
			if(i < 0) err("can't build consistent linearization");
		}

		return result;
	}

	oo.makeDeclare = function(ctorSpecial, chains){
		chains = chains || {};

		function buildMethodList(bases, name){
			var methods = [], i = 0, l = bases.length, h, b;
			for(;i < l; ++i){
				b = bases[i];
				// the assignment on the next line is intentional
				if(h = b._meta) (h = h.hidden)[has](name) && methods.push(h[name]);
				else
					// the assignment on the next line is intentional
					(name == cname) && methods.push(b) ||
						(h = b.prototype[name]) && h !== op[name] && methods.push(h);
			}
			name != cname && (h = op[name]) && methods.push(h);
			return chains[name] === "after" ? methods.reverse() : methods;
		}

		function inherited(args, a, b){
			var c = this.constructor, m = c._meta, cache = c._cache,
				caller, i, l, f, n, ch, x, name;

			// crack arguments
			if(typeof args == "string"){
				name = args;
				args = a;
				a = b;
			}

			caller = inherited.caller;
			n = caller.nom;
			if(n && name && n !== name) err("calling inherited() with a different name: " + name);
			name = name || n;
			ch = cache[has](name) && cache[name];

			// get the cached method list
			if(!ch){
				if(!name) err("can't deduce a name to call inherited()");
				if(name == cname && ctorSpecial) err("calling constructor as inherited");
				if(chains[has](name)) err("calling chained method as inherited: " + name);
				ch = cache[name] = buildMethodList(m.bases, name);
			}

			// alternative (simpler) caching
			x = this._inherited;
			if(!x || x.name !== name || ch[x.pos] !== caller || caller.caller !== inherited){
				// find the caller
				for(i = 0, l = ch.length; i < l && ch[i] !== caller; ++i);
				// the assignment on the next line is intentional
				if(i == l) this[name] === caller && (i = -1) || err("can't find the caller for inherited()");
				// the assignment on the next line is intentional
				this._inherited = x = {name: name, pos: i};
			}
			f = ch[++x.pos];
			return f ? f.apply(this, a || args) : undefined;
		}

		return function(className, superclass, props){
			var mixins, proto, i, l, t, ctor, ctorChain, name, bases;

			// crack parameters
			if(typeof className != "string"){
				props = superclass;
				superclass = className;
				className = "";
			}
			props = props || {};

			// build a prototype
			if(superclass){
				// multiple inheritance (potentially)
				bases = d.isArray(superclass) ? c3mro(superclass) :
					[0].concat((t = superclass._meta) && t.bases || [superclass]);
				// the assignment on the next line is intentional
				superclass = bases[l = bases.length - 1];
				for(i = l - 1;;){
					t = bases[i--];
					// delegation
					xtor.prototype = superclass.prototype;
					proto = new xtor;
					if(!t) break;
					d._mixin(proto, t.prototype);
					(ctor = function(){}).superclass = superclass;
					ctor.prototype = proto;
					superclass = proto.constructor = ctor;
				}
				xtor.prototype = 0;	// cleanup
			}else{
				bases = [0];
				proto = {};
			}

			// add metadata for incoming functions
			for(name in props) (t = props[name]) !== op[name] && isF(t) && (t.nom = name);
			each(d._extraNames, function(name, t){ (t = props[name]) !== op[name] && isF(t) && (t.nom = name); });

			// add props
			d._mixin(proto, props);

			// build ctor
			if(ctorSpecial){
				// compatibility mode with the legacy dojo.declare()
				ctor = function(){
					var a = arguments, args = a, a0, f, i, l, h, preArgs;
					this._inherited = 0;
					// perform the shaman's rituals of the original dojo.declare()
					// 1) call two types of the preamble
					if((a0 = a[0]) && a0.preamble || this.preamble){
						// full blown ritual
						preArgs = new Array(bases.length);
						// prepare parameters
						preArgs[0] = a;
						for(i = 0, l = bases.length - 1; i < l;){
							// the assignment on the next line is intentional
							a = (a0 = a[0]) && (f = a0.preamble) && f.apply(this, a) || a;
							// the assignment on the next line is intentional
							a = (f = bases[i]._meta.hidden.preamble) && f.apply(this, a) || a;
							preArgs[++i] = a;
						}
						// call all constructors
						for(; i >= 0; --i){
							h = bases[i]._meta.hidden;
							h[has](cname) && h.constructor.apply(this, preArgs[i]);
						}
					}else{
						// reduced ritual
						// 2) call the constructor with the same parameters
						for(i = ctorChain.length - 1; i >= 0; ctorChain[i--].apply(this, a));
					}
					// 3) continue the original ritual: call the postscript
					// the assignment on the next line is intentional
					(f = this.postscript) && f.apply(this, args);
				};
			}else{
				if(chains[has](cname)){
					// chained constructor
					ctor = function(){
						var a = arguments, f, i, l;
						this._inherited = 0;
						// perform the shaman's rituals of the original dojo.declare()
						// 1) do not call the preamble
						// 2) call the constructor with the same parameters
						for(i = 0, l = ctorChain.length; i < l; ctorChain[i++].apply(this, a));
						// 3) call the postscript
						// the assignment on the next line is intentional
						(f = this.postscript) && f.apply(this, a);
					};
				}else{
					// plain vanilla constructor
					ctor = function(){
						var a = arguments, f;
						this._inherited = 0;
						// perform the shaman's rituals of the original dojo.declare()
						// 1) do not call the preamble
						// 2) call our original constructor
						// the assignment on the next line is intentional
						(f = ctorChain[0]) && f.apply(this, a);
						// 3) call the postscript
						// the assignment on the next line is intentional
						(f = this.postscript) && f.apply(this, a);
					};
				}
			}

			// build metadata on the constructor
			bases[0] = ctor;
			ctor._meta  = {bases: bases, hidden: props};
			ctor._cache = {};
			ctor.superclass = superclass && superclass.prototype;

			proto.constructor = ctor;
			ctor.prototype = proto;

			// add "standard" methods to the ptototype
			proto.inherited = inherited;
			proto.isInstanceOf = function(cls){
				for(var i = 0, l = bases.length; i < l; ++i){
					if(bases[i] === cls) return true;
				}
				return this instanceof cls;
			};

			// the assignment on the next line is intentional
			className && d.setObject(proto[dname] = className, ctor);

			// build chains and add them to the prototype
			function bindChain(name){
				if(typeof chains[name] == "string")
					(proto[name] = function(){
						var t = buildMethodList(bases, name), l = t.length,
							f = function(){ for(var i = 0; i < l; ++i){ t[i].apply(this, arguments); } };
						f.nom = name;
						// memoization
						// the assignment on the next line is intentional
						(ctor.prototype[name] = f).apply(this, arguments);
					}).nom = name;
			}
			for(name in chains){ bindChain(name); }
			//each(d._extraNames, bindChain); // no need to chain functions
			ctorChain = buildMethodList(bases, cname);

			return ctor;	// Function
		};
	};

	oo.declare = oo.makeDeclare(true);

	/*=====
	//	summary:
	//		Create a feature-rich constructor from compact notation
	//	className: String?:
	//		The optional name of the constructor (loosely, a "class")
	//		stored in the "declaredClass" property in the created prototype
	//	superclass: Function|Function[]:
	//		May be null, a Function, or an Array of Functions. If an array,
	//		the first element is used as the prototypical ancestor and
	//		any following Functions become mixin ancestors.
	//	props: Object:
	//		An object whose properties are copied to the created prototype.
	//		Add an instance-initialization function by making it a property
	//		named "constructor".
	//	description:
	//		Create a constructor using a compact notation for inheritance and
	//		prototype extension.
	//
	//		Mixin ancestors provide a type of multiple inheritance. Prototypes of mixin
	//		ancestors are copied to the new class: changes to mixin prototypes will
	//		not affect classes to which they have been mixed in.
	//
	//		"className" is cached in "declaredClass" property of the new class.
	//
	//	example:
	//	|	dojox.lang.oo.declare("my.classes.bar", my.classes.foo, {
	//	|		// properties to be added to the class prototype
	//	|		someValue: 2,
	//	|		// initialization function
	//	|		constructor: function(){
	//	|			this.myComplicatedObject = new ReallyComplicatedObject();
	//	|		},
	//	|		// other functions
	//	|		someMethod: function(){
	//	|			doStuff();
	//	|		}
	//	|	});
	=====*/
})();
<commit_msg>lang.oo: minor performance tweak, !strict.<commit_after>dojo.provide("dojox.lang.oo.declare");

dojo.experimental("dojox.lang.oo.declare");

// a drop-in replacement for dojo.declare() with fixed bugs and enhancements

(function(){
	var d = dojo, oo = dojox.lang.oo, op = Object.prototype,
		cname = "constructor", has = "hasOwnProperty", dname = "declaredClass",
		isF = d.isFunction, each = d.forEach, xtor = function(){}, counter = 0;

	function err(msg){ throw new Error("declare: " + msg); }

	// C3 Method Resolution Order (see http://www.python.org/download/releases/2.3/mro/)
	function c3mro(bases){
		var result = [0], l = bases.length, classes = new Array(l),
			i = 0, j, m, m2, c, cls, lin, proto, name, clsNum = 0;

		// initialize
		for(; i < l; ++i){
			c = bases[i];
			if(!c) err("mixin #" + i + " is null");
			lin = c._meta && c._meta.bases || [c];
			clsNum += lin.length;
			m = {};
			for(j = 0, m2 = lin.length; j < m2; ++j){
				// the assignment on the next line is intentional
				proto = (cls = lin[j]).prototype;
				name = proto[has](dname) && proto[dname];
				if(!name) name = proto[dname] = "dojoUniqClassName_" + (counter++);
				m[name] = cls;
			}
			classes[i] = {
				idx: 0,
				map: m,
				lin: d.map(lin, function(c){ return c.prototype[dname]; })
			};
		}

		// C3 MRO algorithm
		while(clsNum){
			for(i = l; i--;){
				m = classes[i];
				c = m.lin[m.idx];
				if(c){
					// check if it is in the tail of any classes
					for(j = l; j--;){
						m2 = classes[j];
						if(i != j && (c in m2.map) && c != m2.lin[m2.idx]) break;
					}
					if(j < 0){
						result.push(m.map[c]);
						// remove c from all heads
						for(j = l; j--;){
							m = classes[j];
							if(c == m.lin[m.idx]){
								++m.idx;
								--clsNum
							}
						}
						break;
					}
				}
			}
			if(i < 0) err("can't build consistent linearization");
		}

		return result;
	}

	oo.makeDeclare = function(ctorSpecial, chains){
		chains = chains || {};

		function buildMethodList(bases, name){
			var methods = [], i = 0, l = bases.length, h, b;
			for(;i < l; ++i){
				b = bases[i];
				// the assignment on the next line is intentional
				if(h = b._meta) (h = h.hidden)[has](name) && methods.push(h[name]);
				else
					// the assignment on the next line is intentional
					(name == cname) && methods.push(b) ||
						(h = b.prototype[name]) && h !== op[name] && methods.push(h);
			}
			name != cname && (h = op[name]) && methods.push(h);
			return chains[name] === "after" ? methods.reverse() : methods;
		}

		function inherited(args, a, b){
			var c = this.constructor, m = c._meta, cache = c._cache,
				caller, i, l, f, n, ch, x, name;

			// crack arguments
			if(typeof args == "string"){
				name = args;
				args = a;
				a = b;
			}

			caller = inherited.caller;
			n = caller.nom;
			if(n && name && n !== name) err("calling inherited() with a different name: " + name);
			name = name || n;
			ch = cache[has](name) && cache[name];

			// get the cached method list
			if(!ch){
				if(!name) err("can't deduce a name to call inherited()");
				if(name == cname && ctorSpecial) err("calling constructor as inherited");
				if(chains[has](name)) err("calling chained method as inherited: " + name);
				ch = cache[name] = buildMethodList(m.bases, name);
			}

			// alternative (simpler) caching
			x = this._inherited;
			if(!x || x.name !== name || ch[x.pos] !== caller || caller.caller !== inherited){
				// find the caller
				for(i = 0, l = ch.length; i < l && ch[i] !== caller; ++i);
				// the assignment on the next line is intentional
				if(i == l) this[name] === caller && (i = -1) || err("can't find the caller for inherited()");
				// the assignment on the next line is intentional
				this._inherited = x = {name: name, pos: i};
			}
			f = ch[++x.pos];
			return f ? f.apply(this, a || args) : undefined;
		}

		return function(className, superclass, props){
			var mixins, proto, i, l, t, ctor, ctorChain, name, bases;

			// crack parameters
			if(typeof className != "string"){
				props = superclass;
				superclass = className;
				className = "";
			}
			props = props || {};

			// build a prototype
			if(superclass){
				// multiple inheritance (potentially)
				bases = d.isArray(superclass) ? c3mro(superclass) :
					[0].concat((t = superclass._meta) && t.bases || [superclass]);
				// the assignment on the next line is intentional
				superclass = bases[l = bases.length - 1];
				for(i = l - 1;;){
					t = bases[i--];
					// delegation
					xtor.prototype = superclass.prototype;
					proto = new xtor;
					if(!t) break;
					d._mixin(proto, t.prototype);
					(ctor = function(){}).superclass = superclass;
					ctor.prototype = proto;
					superclass = proto.constructor = ctor;
				}
				xtor.prototype = 0;	// cleanup
			}else{
				bases = [0];
				proto = {};
			}

			// add metadata for incoming functions
			for(name in props) (t = props[name]) !== op[name] && isF(t) && (t.nom = name);
			each(d._extraNames, function(name, t){ (t = props[name]) !== op[name] && isF(t) && (t.nom = name); });

			// add props
			d._mixin(proto, props);

			// build ctor
			if(ctorSpecial){
				// compatibility mode with the legacy dojo.declare()
				ctor = function(){
					var a = arguments, args = a, a0, f, i, l, h, preArgs;
					this._inherited = 0;
					// perform the shaman's rituals of the original dojo.declare()
					// 1) call two types of the preamble
					if((a0 = a[0]) && a0.preamble || this.preamble){
						// full blown ritual
						preArgs = new Array(bases.length);
						// prepare parameters
						preArgs[0] = a;
						for(i = 0, l = bases.length - 1; i < l;){
							// the assignment on the next line is intentional
							a = (a0 = a[0]) && (f = a0.preamble) && f.apply(this, a) || a;
							// the assignment on the next line is intentional
							a = (f = bases[i]._meta.hidden.preamble) && f.apply(this, a) || a;
							preArgs[++i] = a;
						}
						// call all constructors
						for(; i >= 0; --i){
							h = bases[i]._meta.hidden;
							h[has](cname) && h.constructor.apply(this, preArgs[i]);
						}
					}else{
						// reduced ritual
						// 2) call the constructor with the same parameters
						for(i = ctorChain.length - 1; i >= 0; ctorChain[i--].apply(this, a));
					}
					// 3) continue the original ritual: call the postscript
					// the assignment on the next line is intentional
					(f = this.postscript) && f.apply(this, args);
				};
			}else{
				if(chains[has](cname)){
					// chained constructor
					ctor = function(){
						var a = arguments, f, i, l;
						this._inherited = 0;
						// perform the shaman's rituals of the original dojo.declare()
						// 1) do not call the preamble
						// 2) call the constructor with the same parameters
						for(i = 0, l = ctorChain.length; i < l; ctorChain[i++].apply(this, a));
						// 3) call the postscript
						// the assignment on the next line is intentional
						(f = this.postscript) && f.apply(this, a);
					};
				}else{
					// plain vanilla constructor
					ctor = function(){
						var a = arguments, f;
						this._inherited = 0;
						// perform the shaman's rituals of the original dojo.declare()
						// 1) do not call the preamble
						// 2) call our original constructor
						// the assignment on the next line is intentional
						(f = ctorChain[0]) && f.apply(this, a);
						// 3) call the postscript
						// the assignment on the next line is intentional
						(f = this.postscript) && f.apply(this, a);
					};
				}
			}

			// build metadata on the constructor
			bases[0] = ctor;
			ctor._meta  = {bases: bases, hidden: props};
			ctor._cache = {};
			ctor.superclass = superclass && superclass.prototype;

			proto.constructor = ctor;
			ctor.prototype = proto;

			// add "standard" methods to the ptototype
			proto.inherited = inherited;
			proto.isInstanceOf = function(cls){
				for(var i = 0, l = bases.length; i < l; ++i){
					if(bases[i] === cls) return true;
				}
				return this instanceof cls;
			};

			// the assignment on the next line is intentional
			className && d.setObject(proto[dname] = className, ctor);

			// build chains and add them to the prototype
			function bindChain(name){
				if(typeof chains[name] == "string")
					(proto[name] = function(){
						var t = buildMethodList(bases, name), l = t.length,
							f = function(){ for(var i = 0; i < l; ++i){ t[i].apply(this, arguments); } };
						f.nom = name;
						// memoization
						// the assignment on the next line is intentional
						(ctor.prototype[name] = f).apply(this, arguments);
					}).nom = name;
			}
			for(name in chains){ bindChain(name); }
			//each(d._extraNames, bindChain); // no need to chain functions
			ctorChain = buildMethodList(bases, cname);

			return ctor;	// Function
		};
	};

	oo.declare = oo.makeDeclare(true);

	/*=====
	//	summary:
	//		Create a feature-rich constructor from compact notation
	//	className: String?:
	//		The optional name of the constructor (loosely, a "class")
	//		stored in the "declaredClass" property in the created prototype
	//	superclass: Function|Function[]:
	//		May be null, a Function, or an Array of Functions. If an array,
	//		the first element is used as the prototypical ancestor and
	//		any following Functions become mixin ancestors.
	//	props: Object:
	//		An object whose properties are copied to the created prototype.
	//		Add an instance-initialization function by making it a property
	//		named "constructor".
	//	description:
	//		Create a constructor using a compact notation for inheritance and
	//		prototype extension.
	//
	//		Mixin ancestors provide a type of multiple inheritance. Prototypes of mixin
	//		ancestors are copied to the new class: changes to mixin prototypes will
	//		not affect classes to which they have been mixed in.
	//
	//		"className" is cached in "declaredClass" property of the new class.
	//
	//	example:
	//	|	dojox.lang.oo.declare("my.classes.bar", my.classes.foo, {
	//	|		// properties to be added to the class prototype
	//	|		someValue: 2,
	//	|		// initialization function
	//	|		constructor: function(){
	//	|			this.myComplicatedObject = new ReallyComplicatedObject();
	//	|		},
	//	|		// other functions
	//	|		someMethod: function(){
	//	|			doStuff();
	//	|		}
	//	|	});
	=====*/
})();
<|endoftext|>


<commit_before>var builder = require('focus').component.builder;
var React = require('react');
var applicationStore = require('focus').application.builtInStore();
var stylableBehaviour = require('../../mixin/stylable');
var Button = require('../../common/button/action').component;
var SelectButtons = require('../../common/select-action').component;
var contentActionsMixin = {
  mixins: [stylableBehaviour],
  /** @inheriteddoc */
  getInitialState: function getContentActionsInitialState() {
    return this._getStateFromStore();
  },
  /** @inheriteddoc */
  componentWillMount: function ContentActionsWillMount() {
    applicationStore.addActionsChangeListener(this._handleComponentChange);
  },
  /** @inheriteddoc */
  componentWillUnMount: function ContentActionsWillUnMount(){
    applicationStore.removeActionsChangeListener(this._onComponentChange);
  },
  _getStateFromStore: function getContentActionsStateFromStore(){
    return {actions: applicationStore.getActions() || {primary: [], secondary: []}};
  },
  _handleComponentChange: function _handleComponentChange(){
    this.setState(this._getStateFromStore());
  },
  /** @inheriteddoc */
  render: function renderActions() {
    return (

        {this.state.actions.primary.map((primary)=>{
          //<button class="btn btn-fab"></button>
          return <Button shape='fab' style={{className: primary.className}} handleOnClick={primary.action} label={primary.label} type='button' icon={primary.icon}/>;
        })}
        <SelectButtons operationList={this.state.actions.secondary} />

    );
  }
};

module.exports = builder(contentActionsMixin);
<commit_msg>[action] Fix the unmount unlistning action thanks to @sebez<commit_after>var builder = require('focus').component.builder;
var React = require('react');
var applicationStore = require('focus').application.builtInStore();
var stylableBehaviour = require('../../mixin/stylable');
var Button = require('../../common/button/action').component;
var SelectButtons = require('../../common/select-action').component;
var contentActionsMixin = {
  mixins: [stylableBehaviour],
  /** @inheriteddoc */
  getInitialState: function getContentActionsInitialState() {
    return this._getStateFromStore();
  },
  /** @inheriteddoc */
  componentWillMount: function ContentActionsWillMount() {
    applicationStore.addActionsChangeListener(this._handleComponentChange);
  },
  /** @inheriteddoc */
  componentWillUnMount: function ContentActionsWillUnMount(){
    applicationStore.removeActionsChangeListener(this._handleComponentChange);
  },
  _getStateFromStore: function getContentActionsStateFromStore(){
    return {actions: applicationStore.getActions() || {primary: [], secondary: []}};
  },
  _handleComponentChange: function _handleComponentChange(){
    this.setState(this._getStateFromStore());
  },
  /** @inheriteddoc */
  render: function renderActions() {
    return (

        {this.state.actions.primary.map((primary)=>{
          //<button class="btn btn-fab"></button>
          return <Button shape='fab' style={{className: primary.className}} handleOnClick={primary.action} label={primary.label} type='button' icon={primary.icon}/>;
        })}
        <SelectButtons operationList={this.state.actions.secondary} />

    );
  }
};

module.exports = builder(contentActionsMixin);
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const { SyncHook, AsyncSeriesHook } = require("tapable");
const { makeWebpackError } = require("../HookWebpackError");
const WebpackError = require("../WebpackError");
const ArrayQueue = require("./ArrayQueue");

const QUEUED_STATE = 0;
const PROCESSING_STATE = 1;
const DONE_STATE = 2;

let inHandleResult = 0;

/**
 * @template T
 * @callback Callback
 * @param {WebpackError=} err
 * @param {T=} result
 */

/**
 * @template T
 * @template K
 * @template R
 */
class AsyncQueueEntry {
	/**
	 * @param {T} item the item
	 * @param {Callback<R>} callback the callback
	 */
	constructor(item, callback) {
		this.item = item;
		/** @type {typeof QUEUED_STATE | typeof PROCESSING_STATE | typeof DONE_STATE} */
		this.state = QUEUED_STATE;
		this.callback = callback;
		/** @type {Callback<R>[] | undefined} */
		this.callbacks = undefined;
		this.result = undefined;
		/** @type {WebpackError | undefined} */
		this.error = undefined;
	}
}

/**
 * @template T
 * @template K
 * @template R
 */
class AsyncQueue {
	/**
	 * @param {Object} options options object
	 * @param {string=} options.name name of the queue
	 * @param {number=} options.parallelism how many items should be processed at once
	 * @param {AsyncQueue<any, any, any>=} options.parent parent queue, which will have priority over this queue and with shared parallelism
	 * @param {function(T): K=} options.getKey extract key from item
	 * @param {function(T, Callback<R>): void} options.processor async function to process items
	 */
	constructor({ name, parallelism, parent, processor, getKey }) {
		this._name = name;
		this._parallelism = parallelism || 1;
		this._processor = processor;
		this._getKey =
			getKey || /** @type {(T) => K} */ (item => /** @type {any} */ (item));
		/** @type {Map<K, AsyncQueueEntry<T, K, R>>} */
		this._entries = new Map();
		/** @type {ArrayQueue<AsyncQueueEntry<T, K, R>>} */
		this._queued = new ArrayQueue();
		/** @type {AsyncQueue<any, any, any>[]} */
		this._children = undefined;
		this._activeTasks = 0;
		this._willEnsureProcessing = false;
		this._needProcessing = false;
		this._stopped = false;
		this._root = parent ? parent._root : this;
		if (parent) {
			if (this._root._children === undefined) {
				this._root._children = [this];
			} else {
				this._root._children.push(this);
			}
		}

		this.hooks = {
			/** @type {AsyncSeriesHook<[T]>} */
			beforeAdd: new AsyncSeriesHook(["item"]),
			/** @type {SyncHook<[T]>} */
			added: new SyncHook(["item"]),
			/** @type {AsyncSeriesHook<[T]>} */
			beforeStart: new AsyncSeriesHook(["item"]),
			/** @type {SyncHook<[T]>} */
			started: new SyncHook(["item"]),
			/** @type {SyncHook<[T, Error, R]>} */
			result: new SyncHook(["item", "error", "result"])
		};

		this._ensureProcessing = this._ensureProcessing.bind(this);
	}

	/**
	 * @param {T} item an item
	 * @param {Callback<R>} callback callback function
	 * @returns {void}
	 */
	add(item, callback) {
		if (this._stopped) return callback(new WebpackError("Queue was stopped"));
		this.hooks.beforeAdd.callAsync(item, err => {
			if (err) {
				callback(
					makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeAdd`)
				);
				return;
			}
			const key = this._getKey(item);
			const entry = this._entries.get(key);
			if (entry !== undefined) {
				if (entry.state === DONE_STATE) {
					process.nextTick(() => callback(entry.error, entry.result));
				} else if (entry.callbacks === undefined) {
					entry.callbacks = [callback];
				} else {
					entry.callbacks.push(callback);
				}
				return;
			}
			const newEntry = new AsyncQueueEntry(item, callback);
			if (this._stopped) {
				this.hooks.added.call(item);
				this._root._activeTasks++;
				process.nextTick(() =>
					this._handleResult(newEntry, new WebpackError("Queue was stopped"))
				);
			} else {
				this._entries.set(key, newEntry);
				this._queued.enqueue(newEntry);
				const root = this._root;
				root._needProcessing = true;
				if (root._willEnsureProcessing === false) {
					root._willEnsureProcessing = true;
					setImmediate(root._ensureProcessing);
				}
				this.hooks.added.call(item);
			}
		});
	}

	/**
	 * @param {T} item an item
	 * @returns {void}
	 */
	invalidate(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		this._entries.delete(key);
		if (entry.state === QUEUED_STATE) {
			this._queued.delete(entry);
		}
	}

	/**
	 * Waits for an already started item
	 * @param {T} item an item
	 * @param {Callback<R>} callback callback function
	 * @returns {void}
	 */
	waitFor(item, callback) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		if (entry === undefined) {
			return callback(
				new WebpackError(
					"waitFor can only be called for an already started item"
				)
			);
		}
		if (entry.state === DONE_STATE) {
			process.nextTick(() => callback(entry.error, entry.result));
		} else if (entry.callbacks === undefined) {
			entry.callbacks = [callback];
		} else {
			entry.callbacks.push(callback);
		}
	}

	/**
	 * @returns {void}
	 */
	stop() {
		this._stopped = true;
		const queue = this._queued;
		this._queued = new ArrayQueue();
		const root = this._root;
		for (const entry of queue) {
			this._entries.delete(this._getKey(entry.item));
			root._activeTasks++;
			this._handleResult(entry, new WebpackError("Queue was stopped"));
		}
	}

	/**
	 * @returns {void}
	 */
	increaseParallelism() {
		const root = this._root;
		root._parallelism++;
		/* istanbul ignore next */
		if (root._willEnsureProcessing === false && root._needProcessing) {
			root._willEnsureProcessing = true;
			setImmediate(root._ensureProcessing);
		}
	}

	/**
	 * @returns {void}
	 */
	decreaseParallelism() {
		const root = this._root;
		root._parallelism--;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently being processed
	 */
	isProcessing(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === PROCESSING_STATE;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently queued
	 */
	isQueued(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === QUEUED_STATE;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently queued
	 */
	isDone(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === DONE_STATE;
	}

	/**
	 * @returns {void}
	 */
	_ensureProcessing() {
		while (this._activeTasks < this._parallelism) {
			const entry = this._queued.dequeue();
			if (entry === undefined) break;
			this._activeTasks++;
			entry.state = PROCESSING_STATE;
			this._startProcessing(entry);
		}
		this._willEnsureProcessing = false;
		if (this._queued.length > 0) return;
		if (this._children !== undefined) {
			for (const child of this._children) {
				while (this._activeTasks < this._parallelism) {
					const entry = child._queued.dequeue();
					if (entry === undefined) break;
					this._activeTasks++;
					entry.state = PROCESSING_STATE;
					child._startProcessing(entry);
				}
				if (child._queued.length > 0) return;
			}
		}
		if (!this._willEnsureProcessing) this._needProcessing = false;
	}

	/**
	 * @param {AsyncQueueEntry<T, K, R>} entry the entry
	 * @returns {void}
	 */
	_startProcessing(entry) {
		this.hooks.beforeStart.callAsync(entry.item, err => {
			if (err) {
				this._handleResult(
					entry,
					makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeStart`)
				);
				return;
			}
			let inCallback = false;
			try {
				this._processor(entry.item, (e, r) => {
					inCallback = true;
					this._handleResult(entry, e, r);
				});
			} catch (err) {
				if (inCallback) throw err;
				this._handleResult(entry, err, null);
			}
			this.hooks.started.call(entry.item);
		});
	}

	/**
	 * @param {AsyncQueueEntry<T, K, R>} entry the entry
	 * @param {WebpackError=} err error, if any
	 * @param {R=} result result, if any
	 * @returns {void}
	 */
	_handleResult(entry, err, result) {
		this.hooks.result.callAsync(entry.item, err, result, hookError => {
			const error = hookError
				? makeWebpackError(hookError, `AsyncQueue(${this._name}).hooks.result`)
				: err;

			const callback = entry.callback;
			const callbacks = entry.callbacks;
			entry.state = DONE_STATE;
			entry.callback = undefined;
			entry.callbacks = undefined;
			entry.result = result;
			entry.error = error;

			const root = this._root;
			root._activeTasks--;
			if (root._willEnsureProcessing === false && root._needProcessing) {
				root._willEnsureProcessing = true;
				setImmediate(root._ensureProcessing);
			}

			if (inHandleResult++ > 3) {
				process.nextTick(() => {
					callback(error, result);
					if (callbacks !== undefined) {
						for (const callback of callbacks) {
							callback(error, result);
						}
					}
				});
			} else {
				callback(error, result);
				if (callbacks !== undefined) {
					for (const callback of callbacks) {
						callback(error, result);
					}
				}
			}
			inHandleResult--;
		});
	}
}

module.exports = AsyncQueue;
<commit_msg>avoid nextTick when possible<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const { SyncHook, AsyncSeriesHook } = require("tapable");
const { makeWebpackError } = require("../HookWebpackError");
const WebpackError = require("../WebpackError");
const ArrayQueue = require("./ArrayQueue");

const QUEUED_STATE = 0;
const PROCESSING_STATE = 1;
const DONE_STATE = 2;

let inHandleResult = 0;

/**
 * @template T
 * @callback Callback
 * @param {WebpackError=} err
 * @param {T=} result
 */

/**
 * @template T
 * @template K
 * @template R
 */
class AsyncQueueEntry {
	/**
	 * @param {T} item the item
	 * @param {Callback<R>} callback the callback
	 */
	constructor(item, callback) {
		this.item = item;
		/** @type {typeof QUEUED_STATE | typeof PROCESSING_STATE | typeof DONE_STATE} */
		this.state = QUEUED_STATE;
		this.callback = callback;
		/** @type {Callback<R>[] | undefined} */
		this.callbacks = undefined;
		this.result = undefined;
		/** @type {WebpackError | undefined} */
		this.error = undefined;
	}
}

/**
 * @template T
 * @template K
 * @template R
 */
class AsyncQueue {
	/**
	 * @param {Object} options options object
	 * @param {string=} options.name name of the queue
	 * @param {number=} options.parallelism how many items should be processed at once
	 * @param {AsyncQueue<any, any, any>=} options.parent parent queue, which will have priority over this queue and with shared parallelism
	 * @param {function(T): K=} options.getKey extract key from item
	 * @param {function(T, Callback<R>): void} options.processor async function to process items
	 */
	constructor({ name, parallelism, parent, processor, getKey }) {
		this._name = name;
		this._parallelism = parallelism || 1;
		this._processor = processor;
		this._getKey =
			getKey || /** @type {(T) => K} */ (item => /** @type {any} */ (item));
		/** @type {Map<K, AsyncQueueEntry<T, K, R>>} */
		this._entries = new Map();
		/** @type {ArrayQueue<AsyncQueueEntry<T, K, R>>} */
		this._queued = new ArrayQueue();
		/** @type {AsyncQueue<any, any, any>[]} */
		this._children = undefined;
		this._activeTasks = 0;
		this._willEnsureProcessing = false;
		this._needProcessing = false;
		this._stopped = false;
		this._root = parent ? parent._root : this;
		if (parent) {
			if (this._root._children === undefined) {
				this._root._children = [this];
			} else {
				this._root._children.push(this);
			}
		}

		this.hooks = {
			/** @type {AsyncSeriesHook<[T]>} */
			beforeAdd: new AsyncSeriesHook(["item"]),
			/** @type {SyncHook<[T]>} */
			added: new SyncHook(["item"]),
			/** @type {AsyncSeriesHook<[T]>} */
			beforeStart: new AsyncSeriesHook(["item"]),
			/** @type {SyncHook<[T]>} */
			started: new SyncHook(["item"]),
			/** @type {SyncHook<[T, Error, R]>} */
			result: new SyncHook(["item", "error", "result"])
		};

		this._ensureProcessing = this._ensureProcessing.bind(this);
	}

	/**
	 * @param {T} item an item
	 * @param {Callback<R>} callback callback function
	 * @returns {void}
	 */
	add(item, callback) {
		if (this._stopped) return callback(new WebpackError("Queue was stopped"));
		this.hooks.beforeAdd.callAsync(item, err => {
			if (err) {
				callback(
					makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeAdd`)
				);
				return;
			}
			const key = this._getKey(item);
			const entry = this._entries.get(key);
			if (entry !== undefined) {
				if (entry.state === DONE_STATE) {
					if (inHandleResult++ > 3) {
						process.nextTick(() => callback(entry.error, entry.result));
					} else {
						callback(entry.error, entry.result);
					}
					inHandleResult--;
				} else if (entry.callbacks === undefined) {
					entry.callbacks = [callback];
				} else {
					entry.callbacks.push(callback);
				}
				return;
			}
			const newEntry = new AsyncQueueEntry(item, callback);
			if (this._stopped) {
				this.hooks.added.call(item);
				this._root._activeTasks++;
				process.nextTick(() =>
					this._handleResult(newEntry, new WebpackError("Queue was stopped"))
				);
			} else {
				this._entries.set(key, newEntry);
				this._queued.enqueue(newEntry);
				const root = this._root;
				root._needProcessing = true;
				if (root._willEnsureProcessing === false) {
					root._willEnsureProcessing = true;
					setImmediate(root._ensureProcessing);
				}
				this.hooks.added.call(item);
			}
		});
	}

	/**
	 * @param {T} item an item
	 * @returns {void}
	 */
	invalidate(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		this._entries.delete(key);
		if (entry.state === QUEUED_STATE) {
			this._queued.delete(entry);
		}
	}

	/**
	 * Waits for an already started item
	 * @param {T} item an item
	 * @param {Callback<R>} callback callback function
	 * @returns {void}
	 */
	waitFor(item, callback) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		if (entry === undefined) {
			return callback(
				new WebpackError(
					"waitFor can only be called for an already started item"
				)
			);
		}
		if (entry.state === DONE_STATE) {
			process.nextTick(() => callback(entry.error, entry.result));
		} else if (entry.callbacks === undefined) {
			entry.callbacks = [callback];
		} else {
			entry.callbacks.push(callback);
		}
	}

	/**
	 * @returns {void}
	 */
	stop() {
		this._stopped = true;
		const queue = this._queued;
		this._queued = new ArrayQueue();
		const root = this._root;
		for (const entry of queue) {
			this._entries.delete(this._getKey(entry.item));
			root._activeTasks++;
			this._handleResult(entry, new WebpackError("Queue was stopped"));
		}
	}

	/**
	 * @returns {void}
	 */
	increaseParallelism() {
		const root = this._root;
		root._parallelism++;
		/* istanbul ignore next */
		if (root._willEnsureProcessing === false && root._needProcessing) {
			root._willEnsureProcessing = true;
			setImmediate(root._ensureProcessing);
		}
	}

	/**
	 * @returns {void}
	 */
	decreaseParallelism() {
		const root = this._root;
		root._parallelism--;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently being processed
	 */
	isProcessing(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === PROCESSING_STATE;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently queued
	 */
	isQueued(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === QUEUED_STATE;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently queued
	 */
	isDone(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === DONE_STATE;
	}

	/**
	 * @returns {void}
	 */
	_ensureProcessing() {
		while (this._activeTasks < this._parallelism) {
			const entry = this._queued.dequeue();
			if (entry === undefined) break;
			this._activeTasks++;
			entry.state = PROCESSING_STATE;
			this._startProcessing(entry);
		}
		this._willEnsureProcessing = false;
		if (this._queued.length > 0) return;
		if (this._children !== undefined) {
			for (const child of this._children) {
				while (this._activeTasks < this._parallelism) {
					const entry = child._queued.dequeue();
					if (entry === undefined) break;
					this._activeTasks++;
					entry.state = PROCESSING_STATE;
					child._startProcessing(entry);
				}
				if (child._queued.length > 0) return;
			}
		}
		if (!this._willEnsureProcessing) this._needProcessing = false;
	}

	/**
	 * @param {AsyncQueueEntry<T, K, R>} entry the entry
	 * @returns {void}
	 */
	_startProcessing(entry) {
		this.hooks.beforeStart.callAsync(entry.item, err => {
			if (err) {
				this._handleResult(
					entry,
					makeWebpackError(err, `AsyncQueue(${this._name}).hooks.beforeStart`)
				);
				return;
			}
			let inCallback = false;
			try {
				this._processor(entry.item, (e, r) => {
					inCallback = true;
					this._handleResult(entry, e, r);
				});
			} catch (err) {
				if (inCallback) throw err;
				this._handleResult(entry, err, null);
			}
			this.hooks.started.call(entry.item);
		});
	}

	/**
	 * @param {AsyncQueueEntry<T, K, R>} entry the entry
	 * @param {WebpackError=} err error, if any
	 * @param {R=} result result, if any
	 * @returns {void}
	 */
	_handleResult(entry, err, result) {
		this.hooks.result.callAsync(entry.item, err, result, hookError => {
			const error = hookError
				? makeWebpackError(hookError, `AsyncQueue(${this._name}).hooks.result`)
				: err;

			const callback = entry.callback;
			const callbacks = entry.callbacks;
			entry.state = DONE_STATE;
			entry.callback = undefined;
			entry.callbacks = undefined;
			entry.result = result;
			entry.error = error;

			const root = this._root;
			root._activeTasks--;
			if (root._willEnsureProcessing === false && root._needProcessing) {
				root._willEnsureProcessing = true;
				setImmediate(root._ensureProcessing);
			}

			if (inHandleResult++ > 3) {
				process.nextTick(() => {
					callback(error, result);
					if (callbacks !== undefined) {
						for (const callback of callbacks) {
							callback(error, result);
						}
					}
				});
			} else {
				callback(error, result);
				if (callbacks !== undefined) {
					for (const callback of callbacks) {
						callback(error, result);
					}
				}
			}
			inHandleResult--;
		});
	}
}

module.exports = AsyncQueue;
<|endoftext|>


<commit_before>import cx from 'classnames';
import React from 'react';

import ClearButton from './ClearButton.react';
import Loader from './Loader.react';
import Overlay from './Overlay.react';
import TypeaheadInput from './TypeaheadInput.react';
import TypeaheadMenu from './TypeaheadMenu.react';

import typeaheadContainer from './containers/typeaheadContainer';
import {addCustomOption, getOptionLabel, getTruncatedOptions} from './utils/';

class Typeahead extends React.Component {
  componentWillReceiveProps(nextProps) {
    const {
      allowNew,
      onInitialItemChange,
      onResultsChange,
      results,
    } = nextProps;

    // Clear the initial item when there are no results.
    if (!(allowNew || results.length)) {
      onInitialItemChange(null);
    }

    if (results.length !== this.props.results.length) {
      onResultsChange(results);
    }
  }

  render() {
    const {
      allowNew,
      bsSize,
      className,
      disabled,
      dropup,
      emptyLabel,
      isFocused,
      labelKey,
      minLength,
      onInputChange,
      onInputFocus,
      onKeyDown,
      onSelectionAdd,
      onSelectionRemove,
      paginate,
      showMenu,
      shownResults,
      text,
    } = this.props;

    let results = this.props.results.slice();

    // This must come before we truncate.
    const shouldPaginate = paginate && results.length > shownResults;

    // Truncate if necessary.
    results = getTruncatedOptions(results, shownResults);

    // Add the custom option.
    if (allowNew) {
      results = addCustomOption(results, text, labelKey);
    }

    const menuVisible = !!(
      showMenu &&
      text.length >= minLength &&
      (results.length || emptyLabel !== '')
    );

    return (

        <TypeaheadInput
          {...this.props}
          onAdd={onSelectionAdd}
          onChange={onInputChange}
          onKeyDown={(e) => onKeyDown(results, e)}
          onRemove={onSelectionRemove}
          options={results}
          ref={(input) => this._input = input}
        />
        {this._renderAux()}
        {this._renderMenu(results, shouldPaginate, menuVisible)}

          {this._renderAccessibilityStatus(results, menuVisible)}

    );
  }

  getInputNode() {
    return this._input.getInputNode();
  }

  _renderAux = () => {
    const {
      bsSize,
      clearButton,
      disabled,
      isLoading,
      onClear,
      selected,
    } = this.props;

    if (isLoading) {
      return (

          <Loader bsSize={bsSize} />

      );
    }

    if (clearButton && !disabled && selected.length) {
      return (

          <ClearButton
            bsSize={bsSize}
            onClick={onClear}
          />

      );
    }
  }

  _renderMenu = (results, shouldPaginate, menuVisible) => {
    const {
      align,
      bodyContainer,
      className,
      dropup,
      emptyLabel,
      labelKey,
      maxHeight,
      newSelectionPrefix,
      onMenuHide,
      onMenuShow,
      onPaginate,
      paginationText,
      renderMenu,
      renderMenuItemChildren,
      text,
    } = this.props;

    const menuProps = {
      align,
      dropup,
      emptyLabel,
      labelKey,
      maxHeight,
      newSelectionPrefix,
      paginationText,
      onPaginate,
      paginate: shouldPaginate,
      text,
    };

    const menu = typeof renderMenu === 'function' ?
      renderMenu(results, menuProps) :
      <TypeaheadMenu
        {...menuProps}
        options={results}
        renderMenuItemChildren={renderMenuItemChildren}
      />;

    return (
      <Overlay
        align={align}
        className={className}
        container={bodyContainer ? document.body : this}
        dropup={dropup}
        onMenuHide={onMenuHide}
        onMenuShow={onMenuShow}
        show={menuVisible}
        target={this}>
        {menu}
      </Overlay>
    );
  }

  _renderAccessibilityStatus = (results, menuVisible) => {
    const {activeItem, emptyLabel, labelKey, selected} = this.props;

    if (!menuVisible) {
      return selected.length === 1 ?
        '1 selection' :
        `${selected.length} selections`;
    }

    // Let the user know which result is active when keying up and down.
    if (activeItem) {
      return getOptionLabel(activeItem, labelKey);
    }

    // Display info about the number of matches.
    if (results.length === 0) {
      return emptyLabel;
    }

    const resultString = results.length === 1 ?
      '1 result' :
      `${results.length} results`;

    return `${resultString}. Use up and down arrow keys to navigate.`;
  }
}

export default typeaheadContainer(Typeahead);
<commit_msg>Make the clear button keyboard-accessible<commit_after>import cx from 'classnames';
import React from 'react';

import ClearButton from './ClearButton.react';
import Loader from './Loader.react';
import Overlay from './Overlay.react';
import TypeaheadInput from './TypeaheadInput.react';
import TypeaheadMenu from './TypeaheadMenu.react';

import typeaheadContainer from './containers/typeaheadContainer';
import {addCustomOption, getOptionLabel, getTruncatedOptions} from './utils/';

class Typeahead extends React.Component {
  componentWillReceiveProps(nextProps) {
    const {
      allowNew,
      onInitialItemChange,
      onResultsChange,
      results,
    } = nextProps;

    // Clear the initial item when there are no results.
    if (!(allowNew || results.length)) {
      onInitialItemChange(null);
    }

    if (results.length !== this.props.results.length) {
      onResultsChange(results);
    }
  }

  render() {
    const {
      allowNew,
      bsSize,
      className,
      disabled,
      dropup,
      emptyLabel,
      isFocused,
      labelKey,
      minLength,
      onInputChange,
      onInputFocus,
      onKeyDown,
      onSelectionAdd,
      onSelectionRemove,
      paginate,
      showMenu,
      shownResults,
      text,
    } = this.props;

    let results = this.props.results.slice();

    // This must come before we truncate.
    const shouldPaginate = paginate && results.length > shownResults;

    // Truncate if necessary.
    results = getTruncatedOptions(results, shownResults);

    // Add the custom option.
    if (allowNew) {
      results = addCustomOption(results, text, labelKey);
    }

    const menuVisible = !!(
      showMenu &&
      text.length >= minLength &&
      (results.length || emptyLabel !== '')
    );

    return (

        <TypeaheadInput
          {...this.props}
          onAdd={onSelectionAdd}
          onChange={onInputChange}
          onKeyDown={(e) => onKeyDown(results, e)}
          onRemove={onSelectionRemove}
          options={results}
          ref={(input) => this._input = input}
        />
        {this._renderAux()}
        {this._renderMenu(results, shouldPaginate, menuVisible)}

          {this._renderAccessibilityStatus(results, menuVisible)}

    );
  }

  getInputNode() {
    return this._input.getInputNode();
  }

  _renderAux = () => {
    const {
      bsSize,
      clearButton,
      disabled,
      isLoading,
      onClear,
      selected,
    } = this.props;

    if (isLoading) {
      return (

          <Loader bsSize={bsSize} />

      );
    }

    if (clearButton && !disabled && selected.length) {
      return (

          <ClearButton
            bsSize={bsSize}
            onClick={onClear}
            onFocus={(e) => {
              // Prevent the main input from auto-focusing again.
              e.stopPropagation();
            }}
          />

      );
    }
  }

  _renderMenu = (results, shouldPaginate, menuVisible) => {
    const {
      align,
      bodyContainer,
      className,
      dropup,
      emptyLabel,
      labelKey,
      maxHeight,
      newSelectionPrefix,
      onMenuHide,
      onMenuShow,
      onPaginate,
      paginationText,
      renderMenu,
      renderMenuItemChildren,
      text,
    } = this.props;

    const menuProps = {
      align,
      dropup,
      emptyLabel,
      labelKey,
      maxHeight,
      newSelectionPrefix,
      paginationText,
      onPaginate,
      paginate: shouldPaginate,
      text,
    };

    const menu = typeof renderMenu === 'function' ?
      renderMenu(results, menuProps) :
      <TypeaheadMenu
        {...menuProps}
        options={results}
        renderMenuItemChildren={renderMenuItemChildren}
      />;

    return (
      <Overlay
        align={align}
        className={className}
        container={bodyContainer ? document.body : this}
        dropup={dropup}
        onMenuHide={onMenuHide}
        onMenuShow={onMenuShow}
        show={menuVisible}
        target={this}>
        {menu}
      </Overlay>
    );
  }

  _renderAccessibilityStatus = (results, menuVisible) => {
    const {activeItem, emptyLabel, labelKey, selected} = this.props;

    if (!menuVisible) {
      return selected.length === 1 ?
        '1 selection' :
        `${selected.length} selections`;
    }

    // Let the user know which result is active when keying up and down.
    if (activeItem) {
      return getOptionLabel(activeItem, labelKey);
    }

    // Display info about the number of matches.
    if (results.length === 0) {
      return emptyLabel;
    }

    const resultString = results.length === 1 ?
      '1 result' :
      `${results.length} results`;

    return `${resultString}. Use up and down arrow keys to navigate.`;
  }
}

export default typeaheadContainer(Typeahead);
<|endoftext|>


<commit_before>OpenLayers.ProxyHost = "http://vgr.saf.org/gis/proxy?url=";
var map, infoControls;
var plots_gbl;
var bounds = new OpenLayers.Bounds(
		8483476,1154149,
		8484709,1153340
);
var labels = ["Id", "Survey No.", "Subdivision No.", "Rent Roll No.", "Owner",
    "Databank Survey No.", "Databank Rent Roll", "Databank Owner", "Databank Status",
    "Farming", "Lease", "Lessee", "Last Cultivated", "No Consent", "Threat", "Organic",
    "Heirloom seeds", "Fallow Block"];

var labelvars = ["Id", "SurveyNo", "SubDivNo", "RentRoll", "Owner", "DBSvNo", "DBRentRoll", "DBOwner", "DBStatus", "Farming", "Lease", "Lessee", "LastCult", "DenyConsent", "Threat", "Organic", "Heirloom", "FallowBlock"];

function load(plots) {
	map = new OpenLayers.Map('map', {projection: new
	OpenLayers.Projection("EPSG:900913"), numZoomLevels: 28});
	plots_gbl=plots;

	var districts = new OpenLayers.Layer.WMS("Districts",
            "http://188.166.179.117:8080/geoserver-2.5/vayal/wms",
            {'layers': 'vayal:districts', projection: new
            OpenLayers.Projection("EPSG:4326"), transparent: true, format: 'image/gif'},
            {isBaseLayer: false}
	);

	var kannoli = new OpenLayers.Layer.WMS("Kannolichira",
            "http://188.166.179.117:8080/geoserver-2.5/vgr/wms",
            {'layers': 'vgr:plots_modified', projection: new
            OpenLayers.Projection("EPSG:4326"), transparent: true, format:
            'image/gif'},
            {isBaseLayer: false}
	);

	var osm = new OpenLayers.Layer.OSM("OpenStreetMap");

	var ggle = new OpenLayers.Layer.Google(
	    "Google Hybrid",
	    {type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20}
        );

        infoControls = new OpenLayers.Control.WMSGetFeatureInfo({
                url: 'http://188.166.179.117:8080/geoserver-2.5/vgr/wms',
                title: 'Identify features by clicking',
                layers: [kannoli],
                queryVisible: true
            });

	infoControls.infoFormat = 'application/vnd.ogc.gml';
	infoControls.events.register("getfeatureinfo", this, showInfo);

        map.addLayers([osm, ggle, kannoli]);
        map.addControl(infoControls);
        map.addControl(new OpenLayers.Control.LayerSwitcher());
        infoControls.activate();
        map.zoomToExtent(bounds);
}

function showInfo(evt) {
        if (evt.features && evt.features.length) {
          var id = evt.features[0].attributes.id;
          var ind = id-1;
          document.getElementById('responseText').innerHTML = '
\

\
              Id	\
              '+plots_gbl[ind][0]+'	\

\

';

          for (var i=0; i<labelvars.length; i++){
              console.log(plots_gbl[ind][i]);
              document.getElementById(labelvars[i]).value = plots_gbl[ind][i];
          }
          /*
          document.getElementById('Id').value = plots_gbl[ind][0];
          document.getElementById('SurveyNo').value = plots_gbl[ind][1];
          document.getElementById('SubDivNo').value = plots_gbl[ind][2];
          document.getElementById('RentRoll').value = plots_gbl[ind][3];
          document.getElementById('Owner').value = plots_gbl[ind][4];
          document.getElementById('DBSvNo').value = plots_gbl[ind][5];
          document.getElementById('DBRentRoll').value = plots_gbl[ind][6];
          document.getElementById('DBOwner').value = plots_gbl[ind][7];
          document.getElementById('DBStatus').value = plots_gbl[ind][8];
          document.getElementById('Farming').value = plots_gbl[ind][9];
          document.getElementById('Lease').value = plots_gbl[ind][10];
          document.getElementById('Lessee').value = plots_gbl[ind][11];
          document.getElementById('LastCult').value = plots_gbl[ind][12];
          document.getElementById('DenyConsent').value = plots_gbl[ind][13];
          document.getElementById('Threat').value = plots_gbl[ind][14];
          document.getElementById('Organic').value = plots_gbl[ind][15];
          document.getElementById('Heirloom').value = plots_gbl[ind][16];
          document.getElementById('FallowBlock').value = plots_gbl[ind][17];
*/

        }
}

            <commit_msg>Corrected the proxy URL in Kannolichira_edit<commit_after>OpenLayers.ProxyHost = "http://vgr.salimalifoundation.org/gis/proxy?url=";
var map, infoControls;
var plots_gbl;
var bounds = new OpenLayers.Bounds(
		8483476,1154149,
		8484709,1153340
);
var labels = ["Id", "Survey No.", "Subdivision No.", "Rent Roll No.", "Owner",
    "Databank Survey No.", "Databank Rent Roll", "Databank Owner", "Databank Status",
    "Farming", "Lease", "Lessee", "Last Cultivated", "No Consent", "Threat", "Organic",
    "Heirloom seeds", "Fallow Block"];

var labelvars = ["Id", "SurveyNo", "SubDivNo", "RentRoll", "Owner", "DBSvNo", "DBRentRoll", "DBOwner", "DBStatus", "Farming", "Lease", "Lessee", "LastCult", "DenyConsent", "Threat", "Organic", "Heirloom", "FallowBlock"];

function load(plots) {
	map = new OpenLayers.Map('map', {projection: new
	OpenLayers.Projection("EPSG:900913"), numZoomLevels: 28});
	plots_gbl=plots;

	var districts = new OpenLayers.Layer.WMS("Districts",
            "http://188.166.179.117:8080/geoserver-2.5/vayal/wms",
            {'layers': 'vayal:districts', projection: new
            OpenLayers.Projection("EPSG:4326"), transparent: true, format: 'image/gif'},
            {isBaseLayer: false}
	);

	var kannoli = new OpenLayers.Layer.WMS("Kannolichira",
            "http://188.166.179.117:8080/geoserver-2.5/vgr/wms",
            {'layers': 'vgr:plots_modified', projection: new
            OpenLayers.Projection("EPSG:4326"), transparent: true, format:
            'image/gif'},
            {isBaseLayer: false}
	);

	var osm = new OpenLayers.Layer.OSM("OpenStreetMap");

	var ggle = new OpenLayers.Layer.Google(
	    "Google Hybrid",
	    {type: google.maps.MapTypeId.HYBRID, numZoomLevels: 20}
        );

        infoControls = new OpenLayers.Control.WMSGetFeatureInfo({
                url: 'http://188.166.179.117:8080/geoserver-2.5/vgr/wms',
                title: 'Identify features by clicking',
                layers: [kannoli],
                queryVisible: true
            });

	infoControls.infoFormat = 'application/vnd.ogc.gml';
	infoControls.events.register("getfeatureinfo", this, showInfo);

        map.addLayers([osm, ggle, kannoli]);
        map.addControl(infoControls);
        map.addControl(new OpenLayers.Control.LayerSwitcher());
        infoControls.activate();
        map.zoomToExtent(bounds);
}

function showInfo(evt) {
        if (evt.features && evt.features.length) {
          var id = evt.features[0].attributes.id;
          var ind = id-1;
          document.getElementById('responseText').innerHTML = '
\

\
              Id	\
              '+plots_gbl[ind][0]+'	\

\

';

          for (var i=0; i<labelvars.length; i++){
              console.log(plots_gbl[ind][i]);
              document.getElementById(labelvars[i]).value = plots_gbl[ind][i];
          }
          /*
          document.getElementById('Id').value = plots_gbl[ind][0];
          document.getElementById('SurveyNo').value = plots_gbl[ind][1];
          document.getElementById('SubDivNo').value = plots_gbl[ind][2];
          document.getElementById('RentRoll').value = plots_gbl[ind][3];
          document.getElementById('Owner').value = plots_gbl[ind][4];
          document.getElementById('DBSvNo').value = plots_gbl[ind][5];
          document.getElementById('DBRentRoll').value = plots_gbl[ind][6];
          document.getElementById('DBOwner').value = plots_gbl[ind][7];
          document.getElementById('DBStatus').value = plots_gbl[ind][8];
          document.getElementById('Farming').value = plots_gbl[ind][9];
          document.getElementById('Lease').value = plots_gbl[ind][10];
          document.getElementById('Lessee').value = plots_gbl[ind][11];
          document.getElementById('LastCult').value = plots_gbl[ind][12];
          document.getElementById('DenyConsent').value = plots_gbl[ind][13];
          document.getElementById('Threat').value = plots_gbl[ind][14];
          document.getElementById('Organic').value = plots_gbl[ind][15];
          document.getElementById('Heirloom').value = plots_gbl[ind][16];
          document.getElementById('FallowBlock').value = plots_gbl[ind][17];
*/

        }
}

            <|endoftext|>


<commit_before><commit_msg>Update ogario.v4.js<commit_after><|endoftext|>


<commit_before>function exports(sequelize, DataTypes) {
  const Response = sequelize.define('Response', {
    GuestId: DataTypes.UUID,
  }, {
    classMethods: {
      associate(models) {
        // associations can be defined here

        models.Response.belongsTo(models.Guest, { as: 'Response', foreignKey: 'GuestId' });
        models.Response.belongsTo(models.Question, { as: 'Response', foreignKey: 'QuestionId' });
        models.Response.belongsTo(models.Choice, { as: 'Response', foreignKey: 'ChoiceId' });
      },
    },
  });
  return Response;
}

module.exports = exports;
<commit_msg>Remove explicit foreign key declarations.<commit_after>function exports(sequelize, DataTypes) {
  const Response = sequelize.define('Response', {
    GuestId: DataTypes.UUID,
  }, {
    classMethods: {
      associate(models) {
        // associations can be defined here

        models.Response.belongsTo(models.Guest);
        models.Response.belongsTo(models.Question);
        models.Response.belongsTo(models.Choice);
      },
    },
  });
  return Response;
}

module.exports = exports;
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const { SyncHook, AsyncSeriesHook } = require("tapable");

const QUEUED_STATE = 0;
const PROCESSING_STATE = 1;
const DONE_STATE = 2;

/**
 * @template T
 * @callback Callback<T>
 * @param {Error=} err
 * @param {T=} result
 */

/**
 * @template T
 * @template K
 * @template R
 */
class AsyncQueueEntry {
	/**
	 * @param {T} item the item
	 * @param {Callback<R>} callback the callback
	 */
	constructor(item, callback) {
		this.item = item;
		/** @type {typeof QUEUED_STATE | typeof PROCESSING_STATE | typeof DONE_STATE} */
		this.state = QUEUED_STATE;
		this.callback = callback;
		/** @type {Callback<R>[] | undefined} */
		this.callbacks = undefined;
		this.result = undefined;
		this.error = undefined;
	}
}

/**
 * @template T
 * @template K
 * @template R
 */
class AsyncQueue {
	/**
	 * @param {Object} options options object
	 * @param {string=} options.name name of the queue
	 * @param {number} options.parallelism how many items should be processed at once
	 * @param {function(T): K=} options.getKey extract key from item
	 * @param {function(T, Callback<R>): void} options.processor async function to process items
	 */
	constructor({ name, parallelism, processor, getKey }) {
		this._name = name;
		this._parallelism = parallelism;
		this._processor = processor;
		this._getKey =
			getKey || /** @type {(T) => K} */ (item => /** @type {any} */ (item));
		/** @type {Map<K, AsyncQueueEntry<T, K, R>>} */
		this._entries = new Map();
		/** @type {AsyncQueueEntry<T, K, R>[]} */
		this._queued = [];
		this._activeTasks = 0;
		this._willEnsureProcessing = false;
		this._stopped = false;

		this.hooks = {
			/** @type {AsyncSeriesHook<[T]>} */
			beforeAdd: new AsyncSeriesHook(["item"]),
			/** @type {SyncHook<[T]>} */
			added: new SyncHook(["item"]),
			/** @type {AsyncSeriesHook<[T]>} */
			beforeStart: new AsyncSeriesHook(["item"]),
			/** @type {SyncHook<[T]>} */
			started: new SyncHook(["item"]),
			/** @type {SyncHook<[T, Error, R]>} */
			result: new SyncHook(["item", "error", "result"])
		};

		this._ensureProcessing = this._ensureProcessing.bind(this);
	}

	/**
	 * @param {T} item a item
	 * @param {Callback<R>} callback callback function
	 * @returns {void}
	 */
	add(item, callback) {
		if (this._stopped) return callback(new Error("Queue was stopped"));
		this.hooks.beforeAdd.callAsync(item, err => {
			if (err) {
				callback(err);
				return;
			}
			const key = this._getKey(item);
			const entry = this._entries.get(key);
			if (entry !== undefined) {
				if (entry.state === DONE_STATE) {
					process.nextTick(() => callback(entry.error, entry.result));
				} else if (entry.callbacks === undefined) {
					entry.callbacks = [callback];
				} else {
					entry.callbacks.push(callback);
				}
				return;
			}
			const newEntry = new AsyncQueueEntry(item, callback);
			if (this._stopped) {
				this.hooks.added.call(item);
				this._activeTasks++;
				this._handleResult(newEntry, new Error("Queue was stopped"));
			} else {
				this._entries.set(key, newEntry);
				this._queued.push(newEntry);
				if (this._willEnsureProcessing === false) {
					this._willEnsureProcessing = true;
					setImmediate(this._ensureProcessing);
				}
				this.hooks.added.call(item);
			}
		});
	}

	/**
	 * @param {T} item a item
	 * @returns {void}
	 */
	invalidate(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		this._entries.delete(key);
		if (entry.state === QUEUED_STATE) {
			const idx = this._queued.indexOf(entry);
			if (idx >= 0) {
				this._queued.splice(idx, 1);
			}
		}
	}

	/**
	 * @returns {void}
	 */
	stop() {
		this._stopped = true;
		const queue = this._queued;
		this._queued = [];
		for (const entry of queue) {
			this._entries.delete(this._getKey(entry.item));
			this._activeTasks++;
			this._handleResult(entry, new Error("Queue was stopped"));
		}
	}

	/**
	 * @returns {void}
	 */
	increaseParallelism() {
		this._parallelism++;
		if (this._willEnsureProcessing === false && this._queued.length > 0) {
			this._willEnsureProcessing = true;
			setImmediate(this._ensureProcessing);
		}
	}

	/**
	 * @returns {void}
	 */
	decreaseParallelism() {
		this._parallelism--;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently being processed
	 */
	isProcessing(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === PROCESSING_STATE;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently queued
	 */
	isQueued(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === QUEUED_STATE;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently queued
	 */
	isDone(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === DONE_STATE;
	}

	/**
	 * @returns {void}
	 */
	_ensureProcessing() {
		while (this._activeTasks < this._parallelism && this._queued.length > 0) {
			const entry = this._queued.pop();
			this._activeTasks++;
			entry.state = PROCESSING_STATE;
			this._startProcessing(entry);
		}
		this._willEnsureProcessing = false;
	}

	/**
	 * @param {AsyncQueueEntry<T, K, R>} entry the entry
	 * @returns {void}
	 */
	_startProcessing(entry) {
		this.hooks.beforeStart.callAsync(entry.item, err => {
			if (err) {
				this._handleResult(entry, err);
				return;
			}
			let inCallback = false;
			try {
				this._processor(entry.item, (e, r) => {
					inCallback = true;
					this._handleResult(entry, e, r);
				});
			} catch (err) {
				if (inCallback) throw err;
				this._handleResult(entry, err, null);
			}
			this.hooks.started.call(entry.item);
		});
	}

	/**
	 * @param {AsyncQueueEntry<T, K, R>} entry the entry
	 * @param {Error=} err error, if any
	 * @param {R=} result result, if any
	 * @returns {void}
	 */
	_handleResult(entry, err, result) {
		this.hooks.result.callAsync(entry.item, err, result, hookError => {
			const error = hookError || err;

			const callback = entry.callback;
			const callbacks = entry.callbacks;
			entry.state = DONE_STATE;
			entry.callback = undefined;
			entry.callbacks = undefined;
			entry.result = result;
			entry.error = error;
			this._activeTasks--;

			if (this._willEnsureProcessing === false && this._queued.length > 0) {
				this._willEnsureProcessing = true;
				setImmediate(this._ensureProcessing);
			}

			callback(error, result);
			if (callbacks !== undefined) {
				for (const callback of callbacks) {
					callback(error, result);
				}
			}
		});
	}
}

module.exports = AsyncQueue;
<commit_msg>Cut off long calback chains in the queue<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const { SyncHook, AsyncSeriesHook } = require("tapable");

const QUEUED_STATE = 0;
const PROCESSING_STATE = 1;
const DONE_STATE = 2;

let inHandleResult = 0;

/**
 * @template T
 * @callback Callback<T>
 * @param {Error=} err
 * @param {T=} result
 */

/**
 * @template T
 * @template K
 * @template R
 */
class AsyncQueueEntry {
	/**
	 * @param {T} item the item
	 * @param {Callback<R>} callback the callback
	 */
	constructor(item, callback) {
		this.item = item;
		/** @type {typeof QUEUED_STATE | typeof PROCESSING_STATE | typeof DONE_STATE} */
		this.state = QUEUED_STATE;
		this.callback = callback;
		/** @type {Callback<R>[] | undefined} */
		this.callbacks = undefined;
		this.result = undefined;
		this.error = undefined;
	}
}

/**
 * @template T
 * @template K
 * @template R
 */
class AsyncQueue {
	/**
	 * @param {Object} options options object
	 * @param {string=} options.name name of the queue
	 * @param {number} options.parallelism how many items should be processed at once
	 * @param {function(T): K=} options.getKey extract key from item
	 * @param {function(T, Callback<R>): void} options.processor async function to process items
	 */
	constructor({ name, parallelism, processor, getKey }) {
		this._name = name;
		this._parallelism = parallelism;
		this._processor = processor;
		this._getKey =
			getKey || /** @type {(T) => K} */ (item => /** @type {any} */ (item));
		/** @type {Map<K, AsyncQueueEntry<T, K, R>>} */
		this._entries = new Map();
		/** @type {AsyncQueueEntry<T, K, R>[]} */
		this._queued = [];
		this._activeTasks = 0;
		this._willEnsureProcessing = false;
		this._stopped = false;

		this.hooks = {
			/** @type {AsyncSeriesHook<[T]>} */
			beforeAdd: new AsyncSeriesHook(["item"]),
			/** @type {SyncHook<[T]>} */
			added: new SyncHook(["item"]),
			/** @type {AsyncSeriesHook<[T]>} */
			beforeStart: new AsyncSeriesHook(["item"]),
			/** @type {SyncHook<[T]>} */
			started: new SyncHook(["item"]),
			/** @type {SyncHook<[T, Error, R]>} */
			result: new SyncHook(["item", "error", "result"])
		};

		this._ensureProcessing = this._ensureProcessing.bind(this);
	}

	/**
	 * @param {T} item a item
	 * @param {Callback<R>} callback callback function
	 * @returns {void}
	 */
	add(item, callback) {
		if (this._stopped) return callback(new Error("Queue was stopped"));
		this.hooks.beforeAdd.callAsync(item, err => {
			if (err) {
				callback(err);
				return;
			}
			const key = this._getKey(item);
			const entry = this._entries.get(key);
			if (entry !== undefined) {
				if (entry.state === DONE_STATE) {
					process.nextTick(() => callback(entry.error, entry.result));
				} else if (entry.callbacks === undefined) {
					entry.callbacks = [callback];
				} else {
					entry.callbacks.push(callback);
				}
				return;
			}
			const newEntry = new AsyncQueueEntry(item, callback);
			if (this._stopped) {
				this.hooks.added.call(item);
				this._activeTasks++;
				process.nextTick(() =>
					this._handleResult(newEntry, new Error("Queue was stopped"))
				);
			} else {
				this._entries.set(key, newEntry);
				this._queued.push(newEntry);
				if (this._willEnsureProcessing === false) {
					this._willEnsureProcessing = true;
					setImmediate(this._ensureProcessing);
				}
				this.hooks.added.call(item);
			}
		});
	}

	/**
	 * @param {T} item a item
	 * @returns {void}
	 */
	invalidate(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		this._entries.delete(key);
		if (entry.state === QUEUED_STATE) {
			const idx = this._queued.indexOf(entry);
			if (idx >= 0) {
				this._queued.splice(idx, 1);
			}
		}
	}

	/**
	 * @returns {void}
	 */
	stop() {
		this._stopped = true;
		const queue = this._queued;
		this._queued = [];
		for (const entry of queue) {
			this._entries.delete(this._getKey(entry.item));
			this._activeTasks++;
			this._handleResult(entry, new Error("Queue was stopped"));
		}
	}

	/**
	 * @returns {void}
	 */
	increaseParallelism() {
		this._parallelism++;
		if (this._willEnsureProcessing === false && this._queued.length > 0) {
			this._willEnsureProcessing = true;
			setImmediate(this._ensureProcessing);
		}
	}

	/**
	 * @returns {void}
	 */
	decreaseParallelism() {
		this._parallelism--;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently being processed
	 */
	isProcessing(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === PROCESSING_STATE;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently queued
	 */
	isQueued(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === QUEUED_STATE;
	}

	/**
	 * @param {T} item an item
	 * @returns {boolean} true, if the item is currently queued
	 */
	isDone(item) {
		const key = this._getKey(item);
		const entry = this._entries.get(key);
		return entry !== undefined && entry.state === DONE_STATE;
	}

	/**
	 * @returns {void}
	 */
	_ensureProcessing() {
		while (this._activeTasks < this._parallelism && this._queued.length > 0) {
			const entry = this._queued.pop();
			this._activeTasks++;
			entry.state = PROCESSING_STATE;
			this._startProcessing(entry);
		}
		this._willEnsureProcessing = false;
	}

	/**
	 * @param {AsyncQueueEntry<T, K, R>} entry the entry
	 * @returns {void}
	 */
	_startProcessing(entry) {
		this.hooks.beforeStart.callAsync(entry.item, err => {
			if (err) {
				this._handleResult(entry, err);
				return;
			}
			let inCallback = false;
			try {
				this._processor(entry.item, (e, r) => {
					inCallback = true;
					this._handleResult(entry, e, r);
				});
			} catch (err) {
				if (inCallback) throw err;
				this._handleResult(entry, err, null);
			}
			this.hooks.started.call(entry.item);
		});
	}

	/**
	 * @param {AsyncQueueEntry<T, K, R>} entry the entry
	 * @param {Error=} err error, if any
	 * @param {R=} result result, if any
	 * @returns {void}
	 */
	_handleResult(entry, err, result) {
		this.hooks.result.callAsync(entry.item, err, result, hookError => {
			const error = hookError || err;

			const callback = entry.callback;
			const callbacks = entry.callbacks;
			entry.state = DONE_STATE;
			entry.callback = undefined;
			entry.callbacks = undefined;
			entry.result = result;
			entry.error = error;
			this._activeTasks--;

			if (this._willEnsureProcessing === false && this._queued.length > 0) {
				this._willEnsureProcessing = true;
				setImmediate(this._ensureProcessing);
			}

			if (inHandleResult++ > 3) {
				process.nextTick(() => {
					callback(error, result);
					if (callbacks !== undefined) {
						for (const callback of callbacks) {
							callback(error, result);
						}
					}
				});
			} else {
				callback(error, result);
				if (callbacks !== undefined) {
					for (const callback of callbacks) {
						callback(error, result);
					}
				}
			}
			inHandleResult--;
		});
	}
}

module.exports = AsyncQueue;
<|endoftext|>


<commit_before>'use strict';

var keys  = require('../keys')
  , value = require('../valid-value')

  , max = Math.max;

module.exports = function (dest, src/*, …srcn*/) {
	var error, i = 1, l = max(arguments.length, 2);
	dest = Object(value(dest));
	for (; i < l; ++i) {
		src = arguments[i];
		keys(src).forEach(function (key) {
			try { dest[key] = src[key]; } catch (e) {
				if (!error) error = e;
			}
		});
	}
	if (error !== undefined) throw error;
	return dest;
};
<commit_msg>-- lint<commit_after>'use strict';

var keys  = require('../keys')
  , value = require('../valid-value')

  , max = Math.max;

module.exports = function (dest, src/*, …srcn*/) {
	var error, i, l = max(arguments.length, 2), assign;
	dest = Object(value(dest));
	assign = function (key) {
		try { dest[key] = src[key]; } catch (e) {
			if (!error) error = e;
		}
	};
	for (i = 1; i < l; ++i) {
		src = arguments[i];
		keys(src).forEach(assign);
	}
	if (error !== undefined) throw error;
	return dest;
};
<|endoftext|>


<commit_before>define('Mobile/SalesLogix/Views/Lead/List', [
    'dojo/_base/declare',
    'dojo/string',
    'Mobile/SalesLogix/Action',
    'Sage/Platform/Mobile/Format',
    'Sage/Platform/Mobile/List'
], function(
    declare,
    string,
    action,
    format,
    List
) {

    return declare('Mobile.SalesLogix.Views.Lead.List', [List], {
        //Templates
        itemTemplate: new Simplate([
            '
{%: $.LeadNameLastFirst %}
',
            '
{% if($.Title) { %} {%: $.Title %} | {% } %} {%: $.Company %}
',
            '{% if ($.WorkPhone) { %}',
                '
',
                    '{%: $$.phoneAbbreviationText + Sage.Platform.Mobile.Format.phone($.WorkPhone) %}',
                '
',
            '{% } %}',
            '{% if ($.TollFree) { %}',
                '
',
                    '{%: $$.tollFreeAbbreviationText + Sage.Platform.Mobile.Format.phone($.tollFreeAbbreviationText) %}',
                '
',
            '{% } %}',
            '
{%: $.WebAddress %}
',
            '{% if ($.Email) { %}',
                '
',
                    '{%: $.Email %}',
                '
',
            '{% } %}',
        ]),

        //Localization
        titleText: 'Leads',
        activitiesText: 'Activities',
        notesText: 'Notes',
        scheduleText: 'Schedule',
        emailedText: 'E-mailed ${0}',
        calledText: 'Called ${0}',
        editActionText: 'Edit',
        callMainActionText: 'Call Main',
        sendEmailActionText: 'Email',
        addNoteActionText: 'Add Note',
        addActivityActionText: 'Add Activity',
        phoneAbbreviationText: 'Work: ',
        tollFreeAbbreviationText: 'Toll Free: ',

        //View Properties
        detailView: 'lead_detail',
        icon: 'content/images/icons/Leads_24x24.png',
        id: 'lead_list',
        security: 'Entities/Lead/View',
        insertView: 'lead_edit',
        queryOrderBy: 'LastNameUpper,FirstName',
        querySelect: [
            'Company',
            'LeadNameLastFirst',
            'WebAddress',
            'Email',
            'WorkPhone',
            'TollFree',
            'Title'
        ],
        resourceKind: 'leads',
        allowSelection: true,
        enableActions: true,

        createActionLayout: function() {
            return this.actions || (this.actions = [{
                        id: 'edit',
                        icon: 'content/images/icons/edit_24.png',
                        label: this.editActionText,
                        action: 'navigateToEditView'
                    }, {
                        id: 'callMain',
                        icon: 'content/images/icons/Call_24x24.png',
                        label: this.callMainActionText,
                        enabled: action.hasProperty.bindDelegate(this, 'WorkPhone'),
                        fn: action.callPhone.bindDelegate(this, 'WorkPhone')
                    }, {
                        id: 'sendEmail',
                        icon: 'content/images/icons/Send_Write_email_24x24.png',
                        label: this.sendEmailActionText,
                        enabled: action.hasProperty.bindDelegate(this, 'Email'),
                        fn: action.sendEmail.bindDelegate(this, 'Email')
                    }, {
                        id: 'addNote',
                        icon: 'content/images/icons/New_Note_24x24.png',
                        label: this.addNoteActionText,
                        fn: action.addNote.bindDelegate(this)
                    }, {
                        id: 'addActivity',
                        icon: 'content/images/icons/Schedule_ToDo_24x24.png',
                        label: this.addActivityActionText,
                        fn: action.addActivity.bindDelegate(this)
                    }]
            );
        },

        formatSearchQuery: function(searchQuery) {
            return string.substitute('(LastNameUpper like "${0}%" or upper(FirstName) like "${0}%" or CompanyUpper like "${0}%")', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
        }
    });
});

<commit_msg>[13092260] Fix extra pipe when no company exists.<commit_after>define('Mobile/SalesLogix/Views/Lead/List', [
    'dojo/_base/declare',
    'dojo/string',
    'Mobile/SalesLogix/Action',
    'Sage/Platform/Mobile/Format',
    'Sage/Platform/Mobile/List'
], function(
    declare,
    string,
    action,
    format,
    List
) {

    return declare('Mobile.SalesLogix.Views.Lead.List', [List], {
        //Templates
        itemTemplate: new Simplate([
            '
{%: $.LeadNameLastFirst %}
',
            '
',
                '{% if($.Title) { %}',
                    '{%: $.Title %}',
                '{% } %}',
                '{% if($.Title && $.Company) { %}',
                    ' | ',
                '{% } %}',
                '{% if($.Company) { %}',
                    '{%: $.Company %}',
                '{% } %}',
            '
',
            '{% if ($.WorkPhone) { %}',
                '
',
                    '{%: $$.phoneAbbreviationText + Sage.Platform.Mobile.Format.phone($.WorkPhone) %}',
                '
',
            '{% } %}',
            '{% if ($.TollFree) { %}',
                '
',
                    '{%: $$.tollFreeAbbreviationText + Sage.Platform.Mobile.Format.phone($.tollFreeAbbreviationText) %}',
                '
',
            '{% } %}',
            '
{%: $.WebAddress %}
',
            '{% if ($.Email) { %}',
                '
',
                    '{%: $.Email %}',
                '
',
            '{% } %}',
        ]),

        //Localization
        titleText: 'Leads',
        activitiesText: 'Activities',
        notesText: 'Notes',
        scheduleText: 'Schedule',
        emailedText: 'E-mailed ${0}',
        calledText: 'Called ${0}',
        editActionText: 'Edit',
        callMainActionText: 'Call Main',
        sendEmailActionText: 'Email',
        addNoteActionText: 'Add Note',
        addActivityActionText: 'Add Activity',
        phoneAbbreviationText: 'Work: ',
        tollFreeAbbreviationText: 'Toll Free: ',

        //View Properties
        detailView: 'lead_detail',
        icon: 'content/images/icons/Leads_24x24.png',
        id: 'lead_list',
        security: 'Entities/Lead/View',
        insertView: 'lead_edit',
        queryOrderBy: 'LastNameUpper,FirstName',
        querySelect: [
            'Company',
            'LeadNameLastFirst',
            'WebAddress',
            'Email',
            'WorkPhone',
            'TollFree',
            'Title'
        ],
        resourceKind: 'leads',
        allowSelection: true,
        enableActions: true,

        createActionLayout: function() {
            return this.actions || (this.actions = [{
                        id: 'edit',
                        icon: 'content/images/icons/edit_24.png',
                        label: this.editActionText,
                        action: 'navigateToEditView'
                    }, {
                        id: 'callMain',
                        icon: 'content/images/icons/Call_24x24.png',
                        label: this.callMainActionText,
                        enabled: action.hasProperty.bindDelegate(this, 'WorkPhone'),
                        fn: action.callPhone.bindDelegate(this, 'WorkPhone')
                    }, {
                        id: 'sendEmail',
                        icon: 'content/images/icons/Send_Write_email_24x24.png',
                        label: this.sendEmailActionText,
                        enabled: action.hasProperty.bindDelegate(this, 'Email'),
                        fn: action.sendEmail.bindDelegate(this, 'Email')
                    }, {
                        id: 'addNote',
                        icon: 'content/images/icons/New_Note_24x24.png',
                        label: this.addNoteActionText,
                        fn: action.addNote.bindDelegate(this)
                    }, {
                        id: 'addActivity',
                        icon: 'content/images/icons/Schedule_ToDo_24x24.png',
                        label: this.addActivityActionText,
                        fn: action.addActivity.bindDelegate(this)
                    }]
            );
        },

        formatSearchQuery: function(searchQuery) {
            return string.substitute('(LastNameUpper like "${0}%" or upper(FirstName) like "${0}%" or CompanyUpper like "${0}%")', [this.escapeSearchQuery(searchQuery.toUpperCase())]);
        }
    });
});

<|endoftext|>


<commit_before>/*!
 * numbro.js language configuration
 * language : German
 * locale: Switzerland
 * author : Michael Piefel : https://github.com/piefel (based on work from Marco Krage : https://github.com/sinky)
 */

module.exports = {
    languageTag: "de-CH",
    delimiters: {
        thousands: "'",
        decimal: "."
    },
    abbreviations: {
        thousand: "k",
        million: "m",
        billion: "b",
        trillion: "t"
    },
    ordinal: function() {
        return ".";
    },
    currency: {
        symbol: "CHF",
        position: "postfix",
        code: "CHF"
    },
    currencyFormat: {
        thousandSeparated: true,
        totalLength: 4,
        spaceSeparated: true,
        average: true
    },
    formats: {
        fourDigits: {
            totalLength: 4,
            spaceSeparated: true,
            average: true
        },
        fullWithTwoDecimals: {
            output: "currency",
            mantissa: 2,
            spaceSeparated: true,
            thousandSeparated: true
        },
        fullWithTwoDecimalsNoCurrency: {
            mantissa: 2,
            thousandSeparated: true
        },
        fullWithNoDecimals: {
            output: "currency",
            spaceSeparated: true,
            thousandSeparated: true,
            mantissa: 0
        }
    }
};
<commit_msg>fix de-CH thousands delimiter<commit_after>/*!
 * numbro.js language configuration
 * language : German
 * locale: Switzerland
 * author : Michael Piefel : https://github.com/piefel (based on work from Marco Krage : https://github.com/sinky)
 */

module.exports = {
    languageTag: "de-CH",
    delimiters: {
        thousands: "’",
        decimal: "."
    },
    abbreviations: {
        thousand: "k",
        million: "m",
        billion: "b",
        trillion: "t"
    },
    ordinal: function() {
        return ".";
    },
    currency: {
        symbol: "CHF",
        position: "postfix",
        code: "CHF"
    },
    currencyFormat: {
        thousandSeparated: true,
        totalLength: 4,
        spaceSeparated: true,
        average: true
    },
    formats: {
        fourDigits: {
            totalLength: 4,
            spaceSeparated: true,
            average: true
        },
        fullWithTwoDecimals: {
            output: "currency",
            mantissa: 2,
            spaceSeparated: true,
            thousandSeparated: true
        },
        fullWithTwoDecimalsNoCurrency: {
            mantissa: 2,
            thousandSeparated: true
        },
        fullWithNoDecimals: {
            output: "currency",
            spaceSeparated: true,
            thousandSeparated: true,
            mantissa: 0
        }
    }
};
<|endoftext|>