<commit_before>/*!
 * jQuery UI @VERSION
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function( $, undefined ) {

// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
	return;
}

$.extend( $.ui, {
	version: "@VERSION",

	keyCode: {
		ALT: 18,
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		COMMAND: 91,
		COMMAND_LEFT: 91, // COMMAND
		COMMAND_RIGHT: 93,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		MENU: 93, // COMMAND_RIGHT
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38,
		WINDOWS: 91 // COMMAND
	}
});

// plugins
$.fn.extend({
	_focus: $.fn.focus,
	focus: function( delay, fn ) {
		return typeof delay === "number" ?
			this.each(function() {
				var elem = this;
				setTimeout(function() {
					$( elem ).focus();
					if ( fn ) {
						fn.call( elem );
					}
				}, delay );
			}) :
			this._focus.apply( this, arguments );
	},

	scrollParent: function() {
		var scrollParent;
		if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					//

					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	},

	disableSelection: function() {
		return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
			".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
	},

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	}
});

$.each( [ "Width", "Height" ], function( i, name ) {
	var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
		type = name.toLowerCase(),
		orig = {
			innerWidth: $.fn.innerWidth,
			innerHeight: $.fn.innerHeight,
			outerWidth: $.fn.outerWidth,
			outerHeight: $.fn.outerHeight
		};

	function reduce( elem, size, border, margin ) {
		$.each( side, function() {
			size -= parseFloat( $.curCSS( elem, "padding" + this, true) ) || 0;
			if ( border ) {
				size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true) ) || 0;
			}
			if ( margin ) {
				size -= parseFloat( $.curCSS( elem, "margin" + this, true) ) || 0;
			}
		});
		return size;
	}

	$.fn[ "inner" + name ] = function( size ) {
		if ( size === undefined ) {
			return orig[ "inner" + name ].call( this );
		}

		return this.each(function() {
			$.style( this, type, reduce( this, size ) + "px" );
		});
	};

	$.fn[ "outer" + name] = function( size, margin ) {
		if ( typeof size !== "number" ) {
			return orig[ "outer" + name ].call( this, size );
		}

		return this.each(function() {
			$.style( this, type, reduce( this, size, true, margin ) + "px" );
		});
	};
});

// selectors
function visible( element ) {
	return !$( element ).parents().andSelf().filter(function() {
		return $.curCSS( this, "visibility" ) === "hidden" ||
			$.expr.filters.hidden( this );
	}).length;
}

$.extend( $.expr[ ":" ], {
	data: function( elem, i, match ) {
		return !!$.data( elem, match[ 3 ] );
	},

	focusable: function( element ) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr( element, "tabindex" );
		if ( "area" === nodeName ) {
			var map = element.parentNode,
				mapName = map.name,
				img;
			if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
				return false;
			}
			img = $( "img[usemap=#" + mapName + "]" )[0];
			return !!img && visible( img );
		}
		return ( /input|select|textarea|button|object/.test( nodeName )
			? !element.disabled
			: "a" == nodeName
				? element.href || !isNaN( tabIndex )
				: !isNaN( tabIndex ))
			// the element and all of its ancestors must be visible
			&& visible( element );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" );
		return ( isNaN( tabIndex ) || tabIndex >= 0 ) && $( element ).is( ":focusable" );
	}
});

// support
$(function() {
	var body = document.body,
		div = body.appendChild( div = document.createElement( "div" ) );

	$.extend( div.style, {
		minHeight: "100px",
		height: "auto",
		padding: 0,
		borderWidth: 0
	});

	$.support.minHeight = div.offsetHeight === 100;
	$.support.selectstart = "onselectstart" in div;

	// set display to none to avoid a layout bug in IE
	// http://dev.jquery.com/ticket/4014
	body.removeChild( div ).style.display = "none";
});

// deprecated
$.extend( $.ui, {
	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function( module, option, set ) {
			var proto = $.ui[ module ].prototype;
			for ( var i in set ) {
				proto.plugins[ i ] = proto.plugins[ i ] || [];
				proto.plugins[ i ].push( [ option, set[ i ] ] );
			}
		},
		call: function( instance, name, args ) {
			var set = instance.plugins[ name ];
			if ( !set || !instance.element[ 0 ].parentNode ) {
				return;
			}

			for ( var i = 0; i < set.length; i++ ) {
				if ( instance.options[ set[ i ][ 0 ] ] ) {
					set[ i ][ 1 ].apply( instance.element, args );
				}
			}
		}
	},

	// will be deprecated when we switch to jQuery 1.4 - use jQuery.contains()
	contains: function( a, b ) {
		return document.compareDocumentPosition ?
			a.compareDocumentPosition( b ) & 16 :
			a !== b && a.contains( b );
	},

	// only used by resizable
	hasScroll: function( el, a ) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},

	// these are odd functions, fix the API or move into individual plugins
	isOverAxis: function( x, reference, size ) {
		//Determines when x coordinate is over "b" element axis
		return ( x > reference ) && ( x < ( reference + size ) );
	},
	isOver: function( y, x, top, left, height, width ) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
	}
});

})( jQuery );
<commit_msg>Core: Don't use $.style since it doesn't exist in jQuery 1.3.2. Fixes #6196 - outerWidth() setter broken with jQuery 1.3.2.<commit_after>/*!
 * jQuery UI @VERSION
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function( $, undefined ) {

// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
	return;
}

$.extend( $.ui, {
	version: "@VERSION",

	keyCode: {
		ALT: 18,
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		COMMAND: 91,
		COMMAND_LEFT: 91, // COMMAND
		COMMAND_RIGHT: 93,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		MENU: 93, // COMMAND_RIGHT
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38,
		WINDOWS: 91 // COMMAND
	}
});

// plugins
$.fn.extend({
	_focus: $.fn.focus,
	focus: function( delay, fn ) {
		return typeof delay === "number" ?
			this.each(function() {
				var elem = this;
				setTimeout(function() {
					$( elem ).focus();
					if ( fn ) {
						fn.call( elem );
					}
				}, delay );
			}) :
			this._focus.apply( this, arguments );
	},

	scrollParent: function() {
		var scrollParent;
		if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					//

					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	},

	disableSelection: function() {
		return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
			".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
	},

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	}
});

$.each( [ "Width", "Height" ], function( i, name ) {
	var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
		type = name.toLowerCase(),
		orig = {
			innerWidth: $.fn.innerWidth,
			innerHeight: $.fn.innerHeight,
			outerWidth: $.fn.outerWidth,
			outerHeight: $.fn.outerHeight
		};

	function reduce( elem, size, border, margin ) {
		$.each( side, function() {
			size -= parseFloat( $.curCSS( elem, "padding" + this, true) ) || 0;
			if ( border ) {
				size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true) ) || 0;
			}
			if ( margin ) {
				size -= parseFloat( $.curCSS( elem, "margin" + this, true) ) || 0;
			}
		});
		return size;
	}

	$.fn[ "inner" + name ] = function( size ) {
		if ( size === undefined ) {
			return orig[ "inner" + name ].call( this );
		}

		return this.each(function() {
			$( this ).css( type, reduce( this, size ) + "px" );
		});
	};

	$.fn[ "outer" + name] = function( size, margin ) {
		if ( typeof size !== "number" ) {
			return orig[ "outer" + name ].call( this, size );
		}

		return this.each(function() {
			$( this).css( type, reduce( this, size, true, margin ) + "px" );
		});
	};
});

// selectors
function visible( element ) {
	return !$( element ).parents().andSelf().filter(function() {
		return $.curCSS( this, "visibility" ) === "hidden" ||
			$.expr.filters.hidden( this );
	}).length;
}

$.extend( $.expr[ ":" ], {
	data: function( elem, i, match ) {
		return !!$.data( elem, match[ 3 ] );
	},

	focusable: function( element ) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr( element, "tabindex" );
		if ( "area" === nodeName ) {
			var map = element.parentNode,
				mapName = map.name,
				img;
			if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
				return false;
			}
			img = $( "img[usemap=#" + mapName + "]" )[0];
			return !!img && visible( img );
		}
		return ( /input|select|textarea|button|object/.test( nodeName )
			? !element.disabled
			: "a" == nodeName
				? element.href || !isNaN( tabIndex )
				: !isNaN( tabIndex ))
			// the element and all of its ancestors must be visible
			&& visible( element );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" );
		return ( isNaN( tabIndex ) || tabIndex >= 0 ) && $( element ).is( ":focusable" );
	}
});

// support
$(function() {
	var body = document.body,
		div = body.appendChild( div = document.createElement( "div" ) );

	$.extend( div.style, {
		minHeight: "100px",
		height: "auto",
		padding: 0,
		borderWidth: 0
	});

	$.support.minHeight = div.offsetHeight === 100;
	$.support.selectstart = "onselectstart" in div;

	// set display to none to avoid a layout bug in IE
	// http://dev.jquery.com/ticket/4014
	body.removeChild( div ).style.display = "none";
});

// deprecated
$.extend( $.ui, {
	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function( module, option, set ) {
			var proto = $.ui[ module ].prototype;
			for ( var i in set ) {
				proto.plugins[ i ] = proto.plugins[ i ] || [];
				proto.plugins[ i ].push( [ option, set[ i ] ] );
			}
		},
		call: function( instance, name, args ) {
			var set = instance.plugins[ name ];
			if ( !set || !instance.element[ 0 ].parentNode ) {
				return;
			}

			for ( var i = 0; i < set.length; i++ ) {
				if ( instance.options[ set[ i ][ 0 ] ] ) {
					set[ i ][ 1 ].apply( instance.element, args );
				}
			}
		}
	},

	// will be deprecated when we switch to jQuery 1.4 - use jQuery.contains()
	contains: function( a, b ) {
		return document.compareDocumentPosition ?
			a.compareDocumentPosition( b ) & 16 :
			a !== b && a.contains( b );
	},

	// only used by resizable
	hasScroll: function( el, a ) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},

	// these are odd functions, fix the API or move into individual plugins
	isOverAxis: function( x, reference, size ) {
		//Determines when x coordinate is over "b" element axis
		return ( x > reference ) && ( x < ( reference + size ) );
	},
	isOver: function( y, x, top, left, height, width ) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
	}
});

})( jQuery );
<|endoftext|>


<commit_before>/*
 * jQuery UI Menu @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Menu
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function($) {

var idIncrement = 0;

$.widget("ui.menu", {
	defaultElement: "
",
	options: {
		position: {
			my: "left top",
			at: "right top"
		}
	},
	_create: function() {
		var self = this;
		this.activeMenu = this.element;
		this.menuId = this.element.attr( "id" ) || "ui-menu-" + idIncrement++;
		this.element
			.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
			.attr({
				id: this.menuId,
				role: "listbox"
			})
			.bind( "click.menu", function( event ) {
				if ( self.options.disabled ) {
					return false;
				}
				if ( !$( event.target ).closest( ".ui-menu-item a" ).length ) {
					return;
				}
				// temporary
				event.preventDefault();
				self.select( event );
			})
			.bind( "mouseover.menu", function( event ) {
				if ( self.options.disabled ) {
					return;
				}
				var target = $( event.target ).closest( ".ui-menu-item" );
				if ( target.length ) {
					self.focus( event, target );
				}
			})
			.bind("mouseout.menu", function( event ) {
				if ( self.options.disabled ) {
					return;
				}
				var target = $( event.target ).closest( ".ui-menu-item" );
				if ( target.length ) {
					self.blur( event );
				}
			});
		this.refresh();

		this.element.attr( "tabIndex", 0 ).bind( "keydown.menu", function( event ) {
			if ( self.options.disabled ) {
				return;
			}
			switch ( event.keyCode ) {
			case $.ui.keyCode.PAGE_UP:
				self.previousPage( event );
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			case $.ui.keyCode.PAGE_DOWN:
				self.nextPage( event );
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			case $.ui.keyCode.UP:
				self.previous( event );
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			case $.ui.keyCode.DOWN:
				self.next( event );
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			case $.ui.keyCode.LEFT:
				if (self.left( event )) {
					event.stopImmediatePropagation();
				}
				event.preventDefault();
				break;
			case $.ui.keyCode.RIGHT:
				if (self.right( event )) {
					event.stopImmediatePropagation();
				}
				event.preventDefault();
				break;
			case $.ui.keyCode.ENTER:
				self.select();
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			default:
				event.stopPropagation();
				clearTimeout(self.filterTimer);
				var prev = self.previousFilter || "";
				var character = String.fromCharCode(event.keyCode);
				var skip = false;
				if (character == prev) {
					skip = true;
				} else {
					character = prev + character;
				}
				function escape(value) {
					return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
				}
				var match = self.widget().children(".ui-menu-item").filter(function() {
					return new RegExp("^" + escape(character), "i").test($(this).children("a").text());
				});
				var match = skip && match.index(self.active.next()) != -1 ? self.active.nextAll(".ui-menu-item") : match;
				if (!match.length) {
					character = String.fromCharCode(event.keyCode);
					match = self.widget().children(".ui-menu-item").filter(function() {
						return new RegExp("^" + escape(character), "i").test($(this).children("a").text());
					});
				}
				if (match.length) {
					self.focus(event, match);
					if (match.length > 1) {
						self.previousFilter = character;
						self.filterTimer = setTimeout(function() {
							delete self.previousFilter;
						}, 1000);
					} else {
						delete self.previousFilter;
					}
				} else {
					delete self.previousFilter;
				}
			}
		});
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
			.removeAttr( "tabIndex" )
			.removeAttr( "role" )
			.removeAttr( "aria-activedescendant" );

		this.element.children( ".ui-menu-item" )
			.removeClass( "ui-menu-item" )
			.removeAttr( "role" )
			.children( "a" )
			.removeClass( "ui-corner-all ui-state-hover" )
			.removeAttr( "tabIndex" )
			.unbind( ".menu" );
	},

	refresh: function() {
		// initialize nested menus
		// TODO add role=listbox to these, too? or just the top level menu?
		var submenus = this.element.find("ul:not(.ui-menu)")
			.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
			.hide()

		submenus
			.prev("a")
			.prepend('');

		// don't refresh list items that are already adapted
		var items = submenus.add(this.element).children( "li:not(.ui-menu-item):has(a)" )
			.addClass( "ui-menu-item" )
			.attr( "role", "menuitem" );

		items.children( "a" )
			.addClass( "ui-corner-all" )
			.attr( "tabIndex", -1 );
	},

	focus: function( event, item ) {
		var self = this;

		this.blur();

		if ( this._hasScroll() ) {
			var borderTop = parseFloat( $.curCSS( this.element[0], "borderTopWidth", true) ) || 0,
				paddingtop = parseFloat( $.curCSS( this.element[0], "paddingTop", true) ) || 0,
				offset = item.offset().top - this.element.offset().top - borderTop - paddingtop,
				scroll = this.element.attr( "scrollTop" ),
				elementHeight = this.element.height(),
				itemHeight = item.height();
			if ( offset < 0 ) {
				this.element.attr( "scrollTop", scroll + offset );
			} else if ( offset + itemHeight > elementHeight ) {
				this.element.attr( "scrollTop", scroll + offset - elementHeight + itemHeight );
			}
		}

		this.active = item.first()
			.children( "a" )
				.addClass( "ui-state-focus" )
				.attr( "id", function(index, id) {
					return (self.itemId = id || self.menuId + "-activedescendant");
				})
			.end();
		// need to remove the attribute before adding it for the screenreader to pick up the change
		// see http://groups.google.com/group/jquery-a11y/msg/929e0c1e8c5efc8f
		this.element.removeAttr("aria-activedescendant").attr("aria-activedescendant", self.itemId)

		self._close();
		var nested = $(">ul", item);
		if (nested.length && /^mouse/.test(event.type)) {
			self._open(nested);
			this.active.find(">a:first").addClass("ui-state-active");
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	blur: function(event) {
		if (!this.active) {
			return;
		}

		this.active.children( "a" ).removeClass( "ui-state-focus" );
		// remove only generated id
		$( "#" + this.menuId + "-activedescendant" ).removeAttr( "id" );
		this.element.removeAttr( "aria-activedescenant" );
		this._trigger( "blur", event );
		this.active = null;
	},

	_open: function(submenu) {
		// TODO restrict to widget
		//only one menu can have items open at a time.
		//$(document).find(".ui-menu").not(submenu.parents()).hide().data("menu").blur();
		this.element.find(".ui-menu").not(submenu.parents()).hide();

		var position = $.extend({}, {
			of: this.active
		}, $.type(this.options.position) == "function"
			? this.options.position(this.active)
			: this.options.position
		);

		submenu.show().position(position);
	},

	closeAll: function() {
		this.element
		 .find("ul").hide().end()
		 .find("a.ui-state-active").removeClass("ui-state-active");
		this.blur();
		this.activeMenu = this.element;
	},

	_close: function() {
		this.active.parent()
		 .find("ul").hide().end()
		 .find("a.ui-state-active").removeClass("ui-state-active");
	},

	left: function(event) {
		var newItem = this.active && this.active.parents("li").first();
		if (newItem && newItem.length) {
			this.active.parent().hide();
			this.focus(event, newItem);
			return true;
		}
	},

	right: function(event) {
		var newItem = this.active && this.active.children("ul").children("li").first();
		if (newItem && newItem.length) {
			this._open(newItem.parent());
			var current = this.active;
			this.focus(event, newItem);
			return true;
		}
	},

	next: function(event) {
		this._move( "next", ".ui-menu-item", "first", event );
	},

	previous: function(event) {
		this._move( "prev", ".ui-menu-item", "last", event );
	},

	first: function() {
		return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
	},

	last: function() {
		return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
	},

	_move: function(direction, edge, filter, event) {
		if ( !this.active ) {
			this.focus( event, this.activeMenu.children(edge)[filter]() );
			return;
		}
		var next = this.active[ direction + "All" ]( ".ui-menu-item" ).eq( 0 );
		if ( next.length ) {
			this.focus( event, next );
		} else {
			this.focus( event, this.activeMenu.children(edge)[filter]() );
		}
	},

	nextPage: function( event ) {
		if ( this._hasScroll() ) {
			if ( !this.active || this.last() ) {
				this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
				return;
			}
			var base = this.active.offset().top,
				height = this.element.height(),
				result;
			this.active.nextAll( ".ui-menu-item" ).each( function() {
				result = $( this );
				return $( this ).offset().top - base - height < 0;
			});

			this.focus( event, result );
		} else {
			this.focus( event, this.activeMenu.children( ".ui-menu-item" )
				[ !this.active || this.last() ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		if ( this._hasScroll() ) {
			if ( !this.active || this.first() ) {
				this.focus( event, this.activeMenu.children( ".ui-menu-item" ).last() );
				return;
			}

			var base = this.active.offset().top,
				height = this.element.height(),
				result;
			this.active.prevAll( ".ui-menu-item" ).each( function() {
				result = $( this );
				return $(this).offset().top - base + height > 0;
			});

			this.focus( event, result );
		} else {
			this.focus( event, this.activeMenu.children( ".ui-menu-item" )
				[ !this.active || this.first() ? ":last" : ":first" ]() );
		}
	},

	_hasScroll: function() {
		return this.element.height() < this.element.attr( "scrollHeight" );
	},

	select: function( event ) {
		// save active reference before closeAll triggers blur
		var ui = {
			item: this.active
		};
		this.closeAll();
		this._trigger( "select", event, ui );
	}
});

$.ui.menu.version = "@VERSION";

}( jQuery ));
<commit_msg>Menu: Move addClass(active) call to _open to make it work for both mouse and keyboard interactions<commit_after>/*
 * jQuery UI Menu @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Menu
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function($) {

var idIncrement = 0;

$.widget("ui.menu", {
	defaultElement: "
",
	options: {
		position: {
			my: "left top",
			at: "right top"
		}
	},
	_create: function() {
		var self = this;
		this.activeMenu = this.element;
		this.menuId = this.element.attr( "id" ) || "ui-menu-" + idIncrement++;
		this.element
			.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
			.attr({
				id: this.menuId,
				role: "listbox"
			})
			.bind( "click.menu", function( event ) {
				if ( self.options.disabled ) {
					return false;
				}
				if ( !$( event.target ).closest( ".ui-menu-item a" ).length ) {
					return;
				}
				// temporary
				event.preventDefault();
				self.select( event );
			})
			.bind( "mouseover.menu", function( event ) {
				if ( self.options.disabled ) {
					return;
				}
				var target = $( event.target ).closest( ".ui-menu-item" );
				if ( target.length ) {
					self.focus( event, target );
				}
			})
			.bind("mouseout.menu", function( event ) {
				if ( self.options.disabled ) {
					return;
				}
				var target = $( event.target ).closest( ".ui-menu-item" );
				if ( target.length ) {
					self.blur( event );
				}
			});
		this.refresh();

		this.element.attr( "tabIndex", 0 ).bind( "keydown.menu", function( event ) {
			if ( self.options.disabled ) {
				return;
			}
			switch ( event.keyCode ) {
			case $.ui.keyCode.PAGE_UP:
				self.previousPage( event );
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			case $.ui.keyCode.PAGE_DOWN:
				self.nextPage( event );
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			case $.ui.keyCode.UP:
				self.previous( event );
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			case $.ui.keyCode.DOWN:
				self.next( event );
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			case $.ui.keyCode.LEFT:
				if (self.left( event )) {
					event.stopImmediatePropagation();
				}
				event.preventDefault();
				break;
			case $.ui.keyCode.RIGHT:
				if (self.right( event )) {
					event.stopImmediatePropagation();
				}
				event.preventDefault();
				break;
			case $.ui.keyCode.ENTER:
				self.select();
				event.preventDefault();
				event.stopImmediatePropagation();
				break;
			default:
				event.stopPropagation();
				clearTimeout(self.filterTimer);
				var prev = self.previousFilter || "";
				var character = String.fromCharCode(event.keyCode);
				var skip = false;
				if (character == prev) {
					skip = true;
				} else {
					character = prev + character;
				}
				function escape(value) {
					return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
				}
				var match = self.widget().children(".ui-menu-item").filter(function() {
					return new RegExp("^" + escape(character), "i").test($(this).children("a").text());
				});
				var match = skip && match.index(self.active.next()) != -1 ? self.active.nextAll(".ui-menu-item") : match;
				if (!match.length) {
					character = String.fromCharCode(event.keyCode);
					match = self.widget().children(".ui-menu-item").filter(function() {
						return new RegExp("^" + escape(character), "i").test($(this).children("a").text());
					});
				}
				if (match.length) {
					self.focus(event, match);
					if (match.length > 1) {
						self.previousFilter = character;
						self.filterTimer = setTimeout(function() {
							delete self.previousFilter;
						}, 1000);
					} else {
						delete self.previousFilter;
					}
				} else {
					delete self.previousFilter;
				}
			}
		});
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
			.removeAttr( "tabIndex" )
			.removeAttr( "role" )
			.removeAttr( "aria-activedescendant" );

		this.element.children( ".ui-menu-item" )
			.removeClass( "ui-menu-item" )
			.removeAttr( "role" )
			.children( "a" )
			.removeClass( "ui-corner-all ui-state-hover" )
			.removeAttr( "tabIndex" )
			.unbind( ".menu" );
	},

	refresh: function() {
		// initialize nested menus
		// TODO add role=listbox to these, too? or just the top level menu?
		var submenus = this.element.find("ul:not(.ui-menu)")
			.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
			.hide()

		submenus
			.prev("a")
			.prepend('');

		// don't refresh list items that are already adapted
		var items = submenus.add(this.element).children( "li:not(.ui-menu-item):has(a)" )
			.addClass( "ui-menu-item" )
			.attr( "role", "menuitem" );

		items.children( "a" )
			.addClass( "ui-corner-all" )
			.attr( "tabIndex", -1 );
	},

	focus: function( event, item ) {
		var self = this;

		this.blur();

		if ( this._hasScroll() ) {
			var borderTop = parseFloat( $.curCSS( this.element[0], "borderTopWidth", true) ) || 0,
				paddingtop = parseFloat( $.curCSS( this.element[0], "paddingTop", true) ) || 0,
				offset = item.offset().top - this.element.offset().top - borderTop - paddingtop,
				scroll = this.element.attr( "scrollTop" ),
				elementHeight = this.element.height(),
				itemHeight = item.height();
			if ( offset < 0 ) {
				this.element.attr( "scrollTop", scroll + offset );
			} else if ( offset + itemHeight > elementHeight ) {
				this.element.attr( "scrollTop", scroll + offset - elementHeight + itemHeight );
			}
		}

		this.active = item.first()
			.children( "a" )
				.addClass( "ui-state-focus" )
				.attr( "id", function(index, id) {
					return (self.itemId = id || self.menuId + "-activedescendant");
				})
			.end();
		// need to remove the attribute before adding it for the screenreader to pick up the change
		// see http://groups.google.com/group/jquery-a11y/msg/929e0c1e8c5efc8f
		this.element.removeAttr("aria-activedescendant").attr("aria-activedescendant", self.itemId)

		self._close();
		var nested = $(">ul", item);
		if (nested.length && /^mouse/.test(event.type)) {
			self._open(nested);
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	blur: function(event) {
		if (!this.active) {
			return;
		}

		this.active.children( "a" ).removeClass( "ui-state-focus" );
		// remove only generated id
		$( "#" + this.menuId + "-activedescendant" ).removeAttr( "id" );
		this.element.removeAttr( "aria-activedescenant" );
		this._trigger( "blur", event );
		this.active = null;
	},

	_open: function(submenu) {
		// TODO restrict to widget
		//only one menu can have items open at a time.
		//$(document).find(".ui-menu").not(submenu.parents()).hide().data("menu").blur();
		this.element.find(".ui-menu").not(submenu.parents()).hide();

		var position = $.extend({}, {
			of: this.active
		}, $.type(this.options.position) == "function"
			? this.options.position(this.active)
			: this.options.position
		);

		submenu.show().position(position);

		this.active.find(">a:first").addClass("ui-state-active");
	},

	closeAll: function() {
		this.element
		 .find("ul").hide().end()
		 .find("a.ui-state-active").removeClass("ui-state-active");
		this.blur();
		this.activeMenu = this.element;
	},

	_close: function() {
		this.active.parent()
		 .find("ul").hide().end()
		 .find("a.ui-state-active").removeClass("ui-state-active");
	},

	left: function(event) {
		var newItem = this.active && this.active.parents("li").first();
		if (newItem && newItem.length) {
			this.active.parent().hide();
			this.focus(event, newItem);
			return true;
		}
	},

	right: function(event) {
		var newItem = this.active && this.active.children("ul").children("li").first();
		if (newItem && newItem.length) {
			this._open(newItem.parent());
			var current = this.active;
			this.focus(event, newItem);
			return true;
		}
	},

	next: function(event) {
		this._move( "next", ".ui-menu-item", "first", event );
	},

	previous: function(event) {
		this._move( "prev", ".ui-menu-item", "last", event );
	},

	first: function() {
		return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
	},

	last: function() {
		return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
	},

	_move: function(direction, edge, filter, event) {
		if ( !this.active ) {
			this.focus( event, this.activeMenu.children(edge)[filter]() );
			return;
		}
		var next = this.active[ direction + "All" ]( ".ui-menu-item" ).eq( 0 );
		if ( next.length ) {
			this.focus( event, next );
		} else {
			this.focus( event, this.activeMenu.children(edge)[filter]() );
		}
	},

	nextPage: function( event ) {
		if ( this._hasScroll() ) {
			if ( !this.active || this.last() ) {
				this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
				return;
			}
			var base = this.active.offset().top,
				height = this.element.height(),
				result;
			this.active.nextAll( ".ui-menu-item" ).each( function() {
				result = $( this );
				return $( this ).offset().top - base - height < 0;
			});

			this.focus( event, result );
		} else {
			this.focus( event, this.activeMenu.children( ".ui-menu-item" )
				[ !this.active || this.last() ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		if ( this._hasScroll() ) {
			if ( !this.active || this.first() ) {
				this.focus( event, this.activeMenu.children( ".ui-menu-item" ).last() );
				return;
			}

			var base = this.active.offset().top,
				height = this.element.height(),
				result;
			this.active.prevAll( ".ui-menu-item" ).each( function() {
				result = $( this );
				return $(this).offset().top - base + height > 0;
			});

			this.focus( event, result );
		} else {
			this.focus( event, this.activeMenu.children( ".ui-menu-item" )
				[ !this.active || this.first() ? ":last" : ":first" ]() );
		}
	},

	_hasScroll: function() {
		return this.element.height() < this.element.attr( "scrollHeight" );
	},

	select: function( event ) {
		// save active reference before closeAll triggers blur
		var ui = {
			item: this.active
		};
		this.closeAll();
		this._trigger( "select", event, ui );
	}
});

$.ui.menu.version = "@VERSION";

}( jQuery ));
<|endoftext|>


<commit_before><commit_msg>Fix quickly jQuery dependency -- #TODO: minimize it<commit_after><|endoftext|>


<commit_before>import Promise from 'bluebird'
import Listr from 'listr'
import verboseRenderer from 'listr-verbose-renderer'

const MAX_ALLOWED_LIMIT = 1000
let pageLimit = MAX_ALLOWED_LIMIT
/**
 * Gets all the content from a space via the management API. This includes
 * content in draft state.
 */
export default function getFullSourceSpace ({
  managementClient,
  deliveryClient,
  spaceId,
  skipContentModel,
  skipContent,
  skipWebhooks,
  skipRoles,
  includeDrafts,
  maxAllowedLimit,
  listrOptions
}) {
  pageLimit = maxAllowedLimit || MAX_ALLOWED_LIMIT
  listrOptions = listrOptions || {
    renderer: verboseRenderer
  }

  return new Listr([
    {
      title: 'Connecting to space',
      task: (ctx) => {
        return managementClient.getSpace(spaceId)
        .then((space) => {
          ctx.space = space
        })
        .catch((err) => {
          console.error(`
The destination space was not found. This can happen for multiple reasons:
- If you haven't yet, you should create your space manually.
- If your destination space is in another organization, and your user from the source space does not have access to it, you'll need to specify separate sourceManagementToken and destinationManagementToken

Full error details below.
`)
          throw err
        })
      }
    },
    {
      title: 'Fetching content types data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getContentTypes')
        .then(extractItems)
        .then((items) => {
          ctx.data.contentTypes = items
        })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching editor interfaces data',
      task: (ctx) => {
        return getEditorInterfaces(ctx.data.contentTypes)
        .then((editorInterfaces) => {
          ctx.data.editorInterfaces = editorInterfaces.filter((editorInterface) => {
            return editorInterface !== null
          })
        })
      },
      skip: (ctx) => skipContentModel || (ctx.data.contentTypes.length === 0 && 'Skipped since no content types downloaded')
    },
    {
      title: 'Fetching content entries data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getEntries')
        .then(extractItems)
        .then((items) => filterDrafts(items, includeDrafts))
        .then((items) => {
          ctx.data.entries = items
        })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching assets data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getAssets')
        .then(extractItems)
        .then((items) => {
          ctx.data.assets = items
        })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching locales data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getLocales')
        .then(extractItems)
        .then((items) => {
          ctx.data.locales = items
        })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching webhooks data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getWebhooks')
        .then(extractItems)
        .then((items) => {
          ctx.data.webhooks = items
        })
      },
      skip: () => skipWebhooks
    },
    {
      title: 'Fetching roles data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getRoles')
        .then(extractItems)
        .then((items) => {
          ctx.data.roles = items
        })
      },
      skip: () => skipRoles
    }
  ], listrOptions)
}
function getEditorInterfaces (contentTypes) {
  const editorInterfacePromises = contentTypes.map((contentType) => {
    // old contentTypes may not have an editor interface but we'll handle in a later stage
    // but it should not stop getting the data process
    return contentType.getEditorInterface().catch(() => {
      return Promise.resolve(null)
    })
  })
  return Promise.all(editorInterfacePromises)
}

/**
 * Gets all the existing entities based on pagination parameters.
 * The first call will have no aggregated response. Subsequent calls will
 * concatenate the new responses to the original one.
 */
function pagedGet (space, method, skip = 0, aggregatedResponse = null) {
  return space[method]({
    skip: skip,
    limit: pageLimit,
    order: 'sys.createdAt'
  })
  .then((response) => {
    if (!aggregatedResponse) {
      aggregatedResponse = response
    } else {
      aggregatedResponse.items = aggregatedResponse.items.concat(response.items)
    }
    if (skip + pageLimit <= response.total) {
      return pagedGet(space, method, skip + pageLimit, aggregatedResponse)
    }
    return aggregatedResponse
  })
}

function extractItems (response) {
  return response.items
}

function filterDrafts (items, includeDrafts) {
  return includeDrafts ? items : items.filter((item) => item.sys.publishedVersion)
}
<commit_msg>fix: Force the value to be boolean<commit_after>import Promise from 'bluebird'
import Listr from 'listr'
import verboseRenderer from 'listr-verbose-renderer'

const MAX_ALLOWED_LIMIT = 1000
let pageLimit = MAX_ALLOWED_LIMIT
/**
 * Gets all the content from a space via the management API. This includes
 * content in draft state.
 */
export default function getFullSourceSpace ({
  managementClient,
  deliveryClient,
  spaceId,
  skipContentModel,
  skipContent,
  skipWebhooks,
  skipRoles,
  includeDrafts,
  maxAllowedLimit,
  listrOptions
}) {
  pageLimit = maxAllowedLimit || MAX_ALLOWED_LIMIT
  listrOptions = listrOptions || {
    renderer: verboseRenderer
  }

  return new Listr([
    {
      title: 'Connecting to space',
      task: (ctx) => {
        return managementClient.getSpace(spaceId)
        .then((space) => {
          ctx.space = space
        })
        .catch((err) => {
          console.error(`
The destination space was not found. This can happen for multiple reasons:
- If you haven't yet, you should create your space manually.
- If your destination space is in another organization, and your user from the source space does not have access to it, you'll need to specify separate sourceManagementToken and destinationManagementToken

Full error details below.
`)
          throw err
        })
      }
    },
    {
      title: 'Fetching content types data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getContentTypes')
        .then(extractItems)
        .then((items) => {
          ctx.data.contentTypes = items
        })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching editor interfaces data',
      task: (ctx) => {
        return getEditorInterfaces(ctx.data.contentTypes)
        .then((editorInterfaces) => {
          ctx.data.editorInterfaces = editorInterfaces.filter((editorInterface) => {
            return editorInterface !== null
          })
        })
      },
      skip: (ctx) => skipContentModel || (ctx.data.contentTypes.length === 0 && 'Skipped since no content types downloaded')
    },
    {
      title: 'Fetching content entries data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getEntries')
        .then(extractItems)
        .then((items) => filterDrafts(items, includeDrafts))
        .then((items) => {
          ctx.data.entries = items
        })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching assets data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getAssets')
        .then(extractItems)
        .then((items) => {
          ctx.data.assets = items
        })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching locales data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getLocales')
        .then(extractItems)
        .then((items) => {
          ctx.data.locales = items
        })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching webhooks data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getWebhooks')
        .then(extractItems)
        .then((items) => {
          ctx.data.webhooks = items
        })
      },
      skip: () => skipWebhooks
    },
    {
      title: 'Fetching roles data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getRoles')
        .then(extractItems)
        .then((items) => {
          ctx.data.roles = items
        })
      },
      skip: () => skipRoles
    }
  ], listrOptions)
}
function getEditorInterfaces (contentTypes) {
  const editorInterfacePromises = contentTypes.map((contentType) => {
    // old contentTypes may not have an editor interface but we'll handle in a later stage
    // but it should not stop getting the data process
    return contentType.getEditorInterface().catch(() => {
      return Promise.resolve(null)
    })
  })
  return Promise.all(editorInterfacePromises)
}

/**
 * Gets all the existing entities based on pagination parameters.
 * The first call will have no aggregated response. Subsequent calls will
 * concatenate the new responses to the original one.
 */
function pagedGet (space, method, skip = 0, aggregatedResponse = null) {
  return space[method]({
    skip: skip,
    limit: pageLimit,
    order: 'sys.createdAt'
  })
  .then((response) => {
    if (!aggregatedResponse) {
      aggregatedResponse = response
    } else {
      aggregatedResponse.items = aggregatedResponse.items.concat(response.items)
    }
    if (skip + pageLimit <= response.total) {
      return pagedGet(space, method, skip + pageLimit, aggregatedResponse)
    }
    return aggregatedResponse
  })
}

function extractItems (response) {
  return response.items
}

function filterDrafts (items, includeDrafts) {
  return includeDrafts ? items : items.filter((item) => !!item.sys.publishedVersion)
}
<|endoftext|>


<commit_before>import Promise from 'bluebird'
import Listr from 'listr'
import verboseRenderer from 'listr-verbose-renderer'

import { logEmitter, logToTaskOutput } from '../utils/logging'
import sortEntries from '../utils/sort-entries'

const MAX_ALLOWED_LIMIT = 1000
let pageLimit = MAX_ALLOWED_LIMIT

/**
 * Gets all the content from a space via the management API. This includes
 * content in draft state.
 */
export default function getFullSourceSpace ({
  managementClient,
  deliveryClient,
  spaceId,
  skipContentModel,
  skipContent,
  skipWebhooks,
  skipRoles,
  includeDrafts,
  maxAllowedLimit,
  listrOptions
}) {
  pageLimit = maxAllowedLimit || MAX_ALLOWED_LIMIT
  listrOptions = listrOptions || {
    renderer: verboseRenderer
  }

  return new Listr([
    {
      title: 'Connecting to space',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return managementClient.getSpace(spaceId)
          .then((space) => {
            ctx.space = space
            teardownTaskListeners()
          })
      }
    },
    {
      title: 'Fetching content types data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getContentTypes')
          .then(extractItems)
          .then((items) => {
            ctx.data.contentTypes = items
            teardownTaskListeners()
          })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching editor interfaces data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return getEditorInterfaces(ctx.data.contentTypes)
          .then((editorInterfaces) => {
            ctx.data.editorInterfaces = editorInterfaces.filter((editorInterface) => {
              return editorInterface !== null
            })
            teardownTaskListeners()
          })
      },
      skip: (ctx) => skipContentModel || (ctx.data.contentTypes.length === 0 && 'Skipped since no content types downloaded')
    },
    {
      title: 'Fetching content entries data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getEntries')
          .then(extractItems)
          .then(sortEntries)
          .then((items) => filterDrafts(items, includeDrafts))
          .then((items) => {
            ctx.data.entries = items
            teardownTaskListeners()
          })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching assets data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getAssets')
          .then(extractItems)
          .then((items) => {
            ctx.data.assets = items
            teardownTaskListeners()
          })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching locales data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getLocales')
          .then(extractItems)
          .then((items) => {
            ctx.data.locales = items
            teardownTaskListeners()
          })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching webhooks data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getWebhooks')
          .then(extractItems)
          .then((items) => {
            ctx.data.webhooks = items
            teardownTaskListeners()
          })
      },
      skip: () => skipWebhooks
    },
    {
      title: 'Fetching roles data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getRoles')
          .then(extractItems)
          .then((items) => {
            ctx.data.roles = items
            teardownTaskListeners()
          })
      },
      skip: () => skipRoles
    }
  ], listrOptions)
}

function getEditorInterfaces (contentTypes) {
  return Promise.map(contentTypes, (contentType, index, length) => {
    return contentType.getEditorInterface()
      .then((editorInterface) => {
        logEmitter.emit('info', `Fetched editor interface for ${contentType.name}`)
        return editorInterface
      })
      .catch(() => {
      // old contentTypes may not have an editor interface but we'll handle in a later stage
      // but it should not stop getting the data process
        logEmitter.emit('warning', `No editor interface found for ${contentType}`)
        return Promise.resolve(null)
      })
  }, {
    concurrency: 6
  })
}

/**
 * Gets all the existing entities based on pagination parameters.
 * The first call will have no aggregated response. Subsequent calls will
 * concatenate the new responses to the original one.
 */
function pagedGet (space, method, skip = 0, aggregatedResponse = null) {
  return space[method]({
    skip: skip,
    limit: pageLimit,
    order: 'sys.createdAt,sys.id'
  })
    .then((response) => {
      if (!aggregatedResponse) {
        aggregatedResponse = response
      } else {
        aggregatedResponse.items = aggregatedResponse.items.concat(response.items)
      }
      const page = Math.ceil(skip / pageLimit) + 1
      const pages = Math.ceil(response.total / pageLimit)
      logEmitter.emit('info', `Fetched page ${page} of ${pages}`)
      if (skip + pageLimit <= response.total) {
        return pagedGet(space, method, skip + pageLimit, aggregatedResponse)
      }
      return aggregatedResponse
    })
}

function extractItems (response) {
  return response.items
}

function filterDrafts (items, includeDrafts) {
  return includeDrafts ? items : items.filter((item) => !!item.sys.publishedVersion)
}
<commit_msg>feat: add query option<commit_after>import Promise from 'bluebird'
import Listr from 'listr'
import verboseRenderer from 'listr-verbose-renderer'

import { logEmitter, logToTaskOutput } from '../utils/logging'
import sortEntries from '../utils/sort-entries'

const MAX_ALLOWED_LIMIT = 1000
let pageLimit = MAX_ALLOWED_LIMIT

/**
 * Gets all the content from a space via the management API. This includes
 * content in draft state.
 */
export default function getFullSourceSpace ({
  managementClient,
  deliveryClient,
  spaceId,
  skipContentModel,
  skipContent,
  skipWebhooks,
  skipRoles,
  includeDrafts,
  maxAllowedLimit,
  listrOptions,
  query
}) {
  pageLimit = maxAllowedLimit || MAX_ALLOWED_LIMIT
  listrOptions = listrOptions || {
    renderer: verboseRenderer
  }

  return new Listr([
    {
      title: 'Connecting to space',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return managementClient.getSpace(spaceId)
          .then((space) => {
            ctx.space = space
            teardownTaskListeners()
          })
      }
    },
    {
      title: 'Fetching content types data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getContentTypes')
          .then(extractItems)
          .then((items) => {
            ctx.data.contentTypes = items
            teardownTaskListeners()
          })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching editor interfaces data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return getEditorInterfaces(ctx.data.contentTypes)
          .then((editorInterfaces) => {
            ctx.data.editorInterfaces = editorInterfaces.filter((editorInterface) => {
              return editorInterface !== null
            })
            teardownTaskListeners()
          })
      },
      skip: (ctx) => skipContentModel || (ctx.data.contentTypes.length === 0 && 'Skipped since no content types downloaded')
    },
    {
      title: 'Fetching content entries data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getEntries', 0, null, query)
          .then(extractItems)
          .then(sortEntries)
          .then((items) => filterDrafts(items, includeDrafts))
          .then((items) => {
            ctx.data.entries = items
            teardownTaskListeners()
          })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching assets data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getAssets')
          .then(extractItems)
          .then((items) => {
            ctx.data.assets = items
            teardownTaskListeners()
          })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching locales data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getLocales')
          .then(extractItems)
          .then((items) => {
            ctx.data.locales = items
            teardownTaskListeners()
          })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching webhooks data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getWebhooks')
          .then(extractItems)
          .then((items) => {
            ctx.data.webhooks = items
            teardownTaskListeners()
          })
      },
      skip: () => skipWebhooks
    },
    {
      title: 'Fetching roles data',
      task: (ctx, task) => {
        const teardownTaskListeners = logToTaskOutput(task)
        return pagedGet(ctx.space, 'getRoles')
          .then(extractItems)
          .then((items) => {
            ctx.data.roles = items
            teardownTaskListeners()
          })
      },
      skip: () => skipRoles
    }
  ], listrOptions)
}

function getEditorInterfaces (contentTypes) {
  return Promise.map(contentTypes, (contentType, index, length) => {
    return contentType.getEditorInterface()
      .then((editorInterface) => {
        logEmitter.emit('info', `Fetched editor interface for ${contentType.name}`)
        return editorInterface
      })
      .catch(() => {
      // old contentTypes may not have an editor interface but we'll handle in a later stage
      // but it should not stop getting the data process
        logEmitter.emit('warning', `No editor interface found for ${contentType}`)
        return Promise.resolve(null)
      })
  }, {
    concurrency: 6
  })
}

/**
 * Gets all the existing entities based on pagination parameters.
 * The first call will have no aggregated response. Subsequent calls will
 * concatenate the new responses to the original one.
 */
function pagedGet (space, method, skip = 0, aggregatedResponse = null, query = null) {
  const fullQuery = Object.assign({},
    {
      skip: skip,
      limit: pageLimit,
      order: 'sys.createdAt,sys.id'
    },
    query
  )

  return space[method](fullQuery)
    .then((response) => {
      if (!aggregatedResponse) {
        aggregatedResponse = response
      } else {
        aggregatedResponse.items = aggregatedResponse.items.concat(response.items)
      }
      const page = Math.ceil(skip / pageLimit) + 1
      const pages = Math.ceil(response.total / pageLimit)
      logEmitter.emit('info', `Fetched page ${page} of ${pages}`)
      if (skip + pageLimit <= response.total) {
        return pagedGet(space, method, skip + pageLimit, aggregatedResponse, query)
      }
      return aggregatedResponse
    })
}

function extractItems (response) {
  return response.items
}

function filterDrafts (items, includeDrafts) {
  return includeDrafts ? items : items.filter((item) => !!item.sys.publishedVersion)
}
<|endoftext|>


<commit_before>import Promise from 'bluebird'
import Listr from 'listr'
import verboseRenderer from 'listr-verbose-renderer'

const MAX_ALLOWED_LIMIT = 1000
let pageLimit = MAX_ALLOWED_LIMIT
/**
 * Gets all the content from a space via the management API. This includes
 * content in draft state.
 */
export default function getFullSourceSpace ({
  managementClient,
  deliveryClient,
  spaceId,
  skipContentModel,
  skipContent,
  skipWebhooks,
  skipRoles,
  includeDrafts,
  maxAllowedLimit,
  listrOptions
}) {
  pageLimit = maxAllowedLimit || MAX_ALLOWED_LIMIT
  listrOptions = listrOptions || {
    renderer: verboseRenderer
  }

  return new Listr([
    {
      title: 'Connecting to space',
      task: (ctx) => {
        return managementClient.getSpace(spaceId)
        .then((space) => {
          ctx.space = space
        })
        .catch((err) => {
          console.error(`
The destination space was not found. This can happen for multiple reasons:
- If you haven't yet, you should create your space manually.
- If your destination space is in another organization, and your user from the source space does not have access to it, you'll need to specify separate sourceManagementToken and destinationManagementToken

Full error details below.
`)
          throw err
        })
      }
    },
    {
      title: 'Fetching content types data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getContentTypes')
        .then(extractItems)
        .then((items) => {
          ctx.data.contentTypes = items
        })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching editor interfaces data',
      task: (ctx) => {
        return getEditorInterfaces(ctx.data.contentTypes)
        .then((editorInterfaces) => {
          ctx.data.editorInterfaces = editorInterfaces.filter((editorInterface) => {
            return editorInterface !== null
          })
        })
      },
      skip: (ctx) => skipContentModel || (ctx.data.contentTypes.length === 0 && 'Skipped since no content types downloaded')
    },
    {
      title: 'Fetching content entries data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getEntries')
        .then(extractItems)
        .then((items) => filterDrafts(items, includeDrafts))
        .then((items) => {
          ctx.data.entries = items
        })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching assets data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getAssets')
        .then(extractItems)
        .then((items) => {
          ctx.data.assets = items
        })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching locales data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getLocales')
        .then(extractItems)
        .then((items) => {
          ctx.data.locales = items
        })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching webhooks data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getWebhooks')
        .then(extractItems)
        .then((items) => {
          ctx.data.webhooks = items
        })
      },
      skip: () => skipWebhooks
    },
    {
      title: 'Fetching roles data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getRoles')
        .then(extractItems)
        .then((items) => {
          ctx.data.roles = items
        })
      },
      skip: () => skipRoles
    }
  ], listrOptions)
}
function getEditorInterfaces (contentTypes) {
  const editorInterfacePromises = contentTypes.map((contentType) => {
    // old contentTypes may not have an editor interface but we'll handle in a later stage
    // but it should not stop getting the data process
    return contentType.getEditorInterface().catch(() => {
      return Promise.resolve(null)
    })
  })
  return Promise.all(editorInterfacePromises)
}

/**
 * Gets all the existing entities based on pagination parameters.
 * The first call will have no aggregated response. Subsequent calls will
 * concatenate the new responses to the original one.
 */
function pagedGet (space, method, skip = 0, aggregatedResponse = null) {
  return space[method]({
    skip: skip,
    limit: pageLimit,
    order: 'sys.createdAt'
  })
  .then((response) => {
    if (!aggregatedResponse) {
      aggregatedResponse = response
    } else {
      aggregatedResponse.items = aggregatedResponse.items.concat(response.items)
    }
    if (skip + pageLimit <= response.total) {
      return pagedGet(space, method, skip + pageLimit, aggregatedResponse)
    }
    return aggregatedResponse
  })
}

function extractItems (response) {
  return response.items
}

function filterDrafts (items, includeDrafts) {
  return includeDrafts ? items : items.filter((item) => !!item.sys.publishedVersion)
}
<commit_msg>fix(get-full-source-space): Sort Exported entries<commit_after>import Promise from 'bluebird'
import Listr from 'listr'
import verboseRenderer from 'listr-verbose-renderer'
import sortEntries from './sort-entries'

const MAX_ALLOWED_LIMIT = 1000
let pageLimit = MAX_ALLOWED_LIMIT
/**
 * Gets all the content from a space via the management API. This includes
 * content in draft state.
 */
export default function getFullSourceSpace ({
  managementClient,
  deliveryClient,
  spaceId,
  skipContentModel,
  skipContent,
  skipWebhooks,
  skipRoles,
  includeDrafts,
  maxAllowedLimit,
  listrOptions
}) {
  pageLimit = maxAllowedLimit || MAX_ALLOWED_LIMIT
  listrOptions = listrOptions || {
    renderer: verboseRenderer
  }

  return new Listr([
    {
      title: 'Connecting to space',
      task: (ctx) => {
        return managementClient.getSpace(spaceId)
        .then((space) => {
          ctx.space = space
        })
        .catch((err) => {
          console.error(`
The destination space was not found. This can happen for multiple reasons:
- If you haven't yet, you should create your space manually.
- If your destination space is in another organization, and your user from the source space does not have access to it, you'll need to specify separate sourceManagementToken and destinationManagementToken

Full error details below.
`)
          throw err
        })
      }
    },
    {
      title: 'Fetching content types data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getContentTypes')
        .then(extractItems)
        .then((items) => {
          ctx.data.contentTypes = items
        })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching editor interfaces data',
      task: (ctx) => {
        return getEditorInterfaces(ctx.data.contentTypes)
        .then((editorInterfaces) => {
          ctx.data.editorInterfaces = editorInterfaces.filter((editorInterface) => {
            return editorInterface !== null
          })
        })
      },
      skip: (ctx) => skipContentModel || (ctx.data.contentTypes.length === 0 && 'Skipped since no content types downloaded')
    },
    {
      title: 'Fetching content entries data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getEntries')
        .then(extractItems)
        .then(sortEntries)
        .then((items) => filterDrafts(items, includeDrafts))
        .then((items) => {
          ctx.data.entries = items
        })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching assets data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getAssets')
        .then(extractItems)
        .then((items) => {
          ctx.data.assets = items
        })
      },
      skip: () => skipContent
    },
    {
      title: 'Fetching locales data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getLocales')
        .then(extractItems)
        .then((items) => {
          ctx.data.locales = items
        })
      },
      skip: () => skipContentModel
    },
    {
      title: 'Fetching webhooks data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getWebhooks')
        .then(extractItems)
        .then((items) => {
          ctx.data.webhooks = items
        })
      },
      skip: () => skipWebhooks
    },
    {
      title: 'Fetching roles data',
      task: (ctx) => {
        return pagedGet(ctx.space, 'getRoles')
        .then(extractItems)
        .then((items) => {
          ctx.data.roles = items
        })
      },
      skip: () => skipRoles
    }
  ], listrOptions)
}
function getEditorInterfaces (contentTypes) {
  const editorInterfacePromises = contentTypes.map((contentType) => {
    // old contentTypes may not have an editor interface but we'll handle in a later stage
    // but it should not stop getting the data process
    return contentType.getEditorInterface().catch(() => {
      return Promise.resolve(null)
    })
  })
  return Promise.all(editorInterfacePromises)
}

/**
 * Gets all the existing entities based on pagination parameters.
 * The first call will have no aggregated response. Subsequent calls will
 * concatenate the new responses to the original one.
 */
function pagedGet (space, method, skip = 0, aggregatedResponse = null) {
  return space[method]({
    skip: skip,
    limit: pageLimit,
    order: 'sys.createdAt'
  })
  .then((response) => {
    if (!aggregatedResponse) {
      aggregatedResponse = response
    } else {
      aggregatedResponse.items = aggregatedResponse.items.concat(response.items)
    }
    if (skip + pageLimit <= response.total) {
      return pagedGet(space, method, skip + pageLimit, aggregatedResponse)
    }
    return aggregatedResponse
  })
}

function extractItems (response) {
  return response.items
}

function filterDrafts (items, includeDrafts) {
  return includeDrafts ? items : items.filter((item) => !!item.sys.publishedVersion)
}
<|endoftext|>


<commit_before>var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec');

var PLUGIN_NAME = "CameraPreview";

var CameraPreview = function(){};

CameraPreview.startCamera = function(options, onSuccess, onError){
  options = options || {};
  options.x = options.x || 0;
  options.y = options.y || 0;
  options.width = options.width || window.screen.width;
  options.height = options.height || window.screen.height;
  options.camera = options.camera || 'front';
  if(typeof(options.tapPhoto) === 'undefined'){
    options.tapPhoto = true;
  }
  options.previewDrag = options.previewDrag || false;
  options.toBack = options.toBack || false;
  if(typeof(options.alpha) === 'undefined'){
    options.alpha = 1;
  }

  exec(onSuccess, onError, PLUGIN_NAME, "startCamera", [options.x, options.y, options.width, options.height, options.camera, options.tapPhoto, options.previewDrag, options.toBack, options.alpha]);
};

CameraPreview.stopCamera = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "stopCamera", []);
};

CameraPreview.switchCamera = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "switchCamera", []);
};

CameraPreview.hide = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "hideCamera", []);
};

CameraPreview.show = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "showCamera", []);
};

CameraPreview.takePicture = function(opts, onError){
  opts = opts || {};
  opts.width = opts.width || 0;
  opts.height = opts.height || 0;

  if(!opts.quality || opts.quality > 100 || opts.quality < 0){
    opts.quality = 85;
  }

  exec(null, onError, PLUGIN_NAME, "takePicture", [opts.width, opts.height, opts.quality]);
};

CameraPreview.setOnPictureTakenHandler = function(cb) {
  exec(cb, null, PLUGIN_NAME, "setOnPictureTakenHandler", []);
};

CameraPreview.setColorEffect = function(effect, onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "setColorEffect", [effect]);
};

CameraPreview.setZoom = function(zoom, onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "setZoom", [zoom]);
}

CameraPreview.setPreviewSize = function(dimensions, onSuccess, onError){
  dimensions = dimensions || {};
  dimensions.width = dimensions.width || window.screen.width;
  dimensions.height = dimensions.height || window.screen.height;

  return exec(onSuccess, onError, PLUGIN_NAME, "setPreviewSize", [dimensions.width, dimensions.height]);
}

CameraPreview.getSupportedPictureSizes = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "getSupportedPictureSizes", []);
};

CameraPreview.setFlashMode = function(flashMode, onSuccess, onError) {
  flashMode = flashMode.toLowerCase();
  if(flashMode === 'off'){
    flashMode = 0;
  }else if(flashMode === 'on'){
    flashMode = 1;
  }else if(flashMode === 'auto'){
    flashMode = 2;
  }else if(flashMode === 'torch' && window.device.platform() === 'Android'){
    flashMode = 3;
  }else{
    return false;
  }

  exec(onSuccess, onError, PLUGIN_NAME, "setFlashMode", [flashMode]);
};

module.exports = CameraPreview;
<commit_msg>This will fix torch mode flash only!<commit_after>var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec');

var PLUGIN_NAME = "CameraPreview";

var CameraPreview = function(){};

CameraPreview.startCamera = function(options, onSuccess, onError){
  options = options || {};
  options.x = options.x || 0;
  options.y = options.y || 0;
  options.width = options.width || window.screen.width;
  options.height = options.height || window.screen.height;
  options.camera = options.camera || 'front';
  if(typeof(options.tapPhoto) === 'undefined'){
    options.tapPhoto = true;
  }
  options.previewDrag = options.previewDrag || false;
  options.toBack = options.toBack || false;
  if(typeof(options.alpha) === 'undefined'){
    options.alpha = 1;
  }

  exec(onSuccess, onError, PLUGIN_NAME, "startCamera", [options.x, options.y, options.width, options.height, options.camera, options.tapPhoto, options.previewDrag, options.toBack, options.alpha]);
};

CameraPreview.stopCamera = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "stopCamera", []);
};

CameraPreview.switchCamera = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "switchCamera", []);
};

CameraPreview.hide = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "hideCamera", []);
};

CameraPreview.show = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "showCamera", []);
};

CameraPreview.takePicture = function(opts, onError){
  opts = opts || {};
  opts.width = opts.width || 0;
  opts.height = opts.height || 0;

  if(!opts.quality || opts.quality > 100 || opts.quality < 0){
    opts.quality = 85;
  }

  exec(null, onError, PLUGIN_NAME, "takePicture", [opts.width, opts.height, opts.quality]);
};

CameraPreview.setOnPictureTakenHandler = function(cb) {
  exec(cb, null, PLUGIN_NAME, "setOnPictureTakenHandler", []);
};

CameraPreview.setColorEffect = function(effect, onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "setColorEffect", [effect]);
};

CameraPreview.setZoom = function(zoom, onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "setZoom", [zoom]);
}

CameraPreview.setPreviewSize = function(dimensions, onSuccess, onError){
  dimensions = dimensions || {};
  dimensions.width = dimensions.width || window.screen.width;
  dimensions.height = dimensions.height || window.screen.height;

  return exec(onSuccess, onError, PLUGIN_NAME, "setPreviewSize", [dimensions.width, dimensions.height]);
}

CameraPreview.getSupportedPictureSizes = function(onSuccess, onError){
  exec(onSuccess, onError, PLUGIN_NAME, "getSupportedPictureSizes", []);
};

CameraPreview.setFlashMode = function(flashMode, onSuccess, onError) {
  flashMode = flashMode.toLowerCase();
  if(flashMode === 'off'){
    flashMode = 0;
  }else if(flashMode === 'on'){
    flashMode = 1;
  }else if(flashMode === 'auto'){
    flashMode = 2;
  }else if(flashMode === 'torch' && window.device.platform === 'Android'){
    flashMode = 3;
  }else{
    return false;
  }

  exec(onSuccess, onError, PLUGIN_NAME, "setFlashMode", [flashMode]);
};

module.exports = CameraPreview;
<|endoftext|>


<commit_before>var async = require( "async" );
var nomnom = require( "nomnom" );
var mongoose = require( "mongoose" );
var cta = require( "./chicago-cta" );
var utils = require( "../utils" );
var TransitStop = require( "../models" ).TransitStop;

var options = nomnom.option( "file", {
                    abbr: "f",
                    default: null,
                    help: "Path to output file for JSON export"
                } )
                .parse();

mongoose.connect( process.env.MONGO_URL );

var rebuildData = function ( transitStops, done ) {

    TransitStop.remove( {}, function ( err, result ) {

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

        console.log( "Old TransitStop data removed..." );

        TransitStop.collection.insert( transitStops, function ( err, data ) {

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

            return done( null, data );

        } );

    } );

};

var tasksCompleted = function ( err, result ) {

    console.log( "CTA data collected..." );

    if ( options.file ) {
        utils.writeJSONFile( options.file, result, function ( err ) {

            if ( err ) {
                console.log( "Error generating JSON file" );
                process.exit( 1 );
            }

            process.exit( 0 );

        } );
    }

    rebuildData( result, function ( err, data ) {

        if ( err ) {
            console.log( err );
            process.exit( 1 );
        }

        process.exit( 0 );

    } );

};

var main = function() {

    var tasks = [
        cta.bus.getRoutes,
        cta.bus.getDirections,
        cta.bus.getStops
    ];

    async.waterfall( tasks, tasksCompleted );

};

if ( require.main === module ) {

    main();

}
<commit_msg>Remove a couple log statements<commit_after>var async = require( "async" );
var nomnom = require( "nomnom" );
var mongoose = require( "mongoose" );
var cta = require( "./chicago-cta" );
var utils = require( "../utils" );
var TransitStop = require( "../models" ).TransitStop;

var options = nomnom.option( "file", {
                    abbr: "f",
                    default: null,
                    help: "Path to output file for JSON export"
                } )
                .parse();

mongoose.connect( process.env.MONGO_URL );

var rebuildData = function ( transitStops, done ) {

    TransitStop.remove( {}, function ( err, result ) {

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

        TransitStop.collection.insert( transitStops, function ( err, data ) {

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

            return done( null, data );

        } );

    } );

};

var tasksCompleted = function ( err, result ) {

    if ( options.file ) {
        utils.writeJSONFile( options.file, result, function ( err ) {

            if ( err ) {
                console.log( "Error generating JSON file" );
                process.exit( 1 );
            }

            process.exit( 0 );

        } );
    }

    rebuildData( result, function ( err, data ) {

        if ( err ) {
            console.log( err );
            process.exit( 1 );
        }

        process.exit( 0 );

    } );

};

var main = function() {

    var tasks = [
        cta.bus.getRoutes,
        cta.bus.getDirections,
        cta.bus.getStops
    ];

    async.waterfall( tasks, tasksCompleted );

};

if ( require.main === module ) {

    main();

}
<|endoftext|>


<commit_before>/**
 * @param {string[]} words
 * @return {string[]}
 */
var findWords = function(words) {
  const map = new Map();
  "qwertyuiop".split("").forEach(c => {
    map.set(c, 1);
  });
  "asdfghjkl".split("").forEach(c => {
    map.set(c, 2);
  });
  "zxcvbnm".split("").forEach(c => {
    map.set(c, 3);
  });
  let ans = [];
  for (let w of words) {
    let valid = true;
    for (let i = 1; i < w.length; ++i) {
      if (map.get(w[i].toLowerCase()) !== map.get(w[i - 1].toLowerCase())) {
        valid = false;
        break;
      }
    }
    if (valid) ans.push(w);
  }
  return ans;
};
var findWordsV2 = function(words) {
  return words.filter(
    word =>
      /\b[qwertyuiop]+\b/i.test(word) ||
      /\b[asdfghjkl]+\b/i.test(word) ||
      /\b[zxcvbnm]+\b/i.test(word)
  );
};
// TESTS
[["Hello", "Alaska", "Dad", "Peace"]].forEach(t => {
  console.log("Words can be typed on one row ->", findWords(t));
});
<commit_msg>line breaking<commit_after>/**
 * @param {string[]} words
 * @return {string[]}
 */
var findWords = function(words) {
  const map = new Map();
  "qwertyuiop".split("").forEach(c => {
    map.set(c, 1);
  });
  "asdfghjkl".split("").forEach(c => {
    map.set(c, 2);
  });
  "zxcvbnm".split("").forEach(c => {
    map.set(c, 3);
  });
  let ans = [];
  for (let w of words) {
    let valid = true;
    for (let i = 1; i < w.length; ++i) {
      if (map.get(w[i].toLowerCase()) !== map.get(w[i - 1].toLowerCase())) {
        valid = false;
        break;
      }
    }
    if (valid) ans.push(w);
  }
  return ans;
};

var findWordsV2 = function(words) {
  return words.filter(
    word =>
      /\b[qwertyuiop]+\b/i.test(word) ||
      /\b[asdfghjkl]+\b/i.test(word) ||
      /\b[zxcvbnm]+\b/i.test(word)
  );
};

// TESTS
[["Hello", "Alaska", "Dad", "Peace"]].forEach(t => {
  console.log("Words can be typed on one row ->", findWords(t));
});
<|endoftext|>


<commit_before>// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
(function ($) {
	$.fn = $.extend($.fn, {
		/**
		 * options:
		 * 	trackerId: int
		 * 	success: function (data) {}
		 */
		tracker_add_field: function (options) {
			this.tracker_service_dialog({
				title: tr('Add Field'),
				data: {
					controller: 'tracker',
					action: 'add_field',
					trackerId: options.trackerId
				},
				success: options.success,
				load: function () {
					var dialog = this;
					$('select', dialog).change(function () {
						$('.description', dialog)
							.hide()
							.filter('.' + $(this).val())
							.show();
					}).change();
				}
			});
		},
		/**
		 * options:
		 * 	trackerId: int
		 * 	success: function (data) {}
		 */
		tracker_edit_field: function (options) {
			this.tracker_service_dialog({
				title: tr('Edit Field'),
				data: {
					controller: 'tracker',
					action: 'edit_field',
					trackerId: options.trackerId,
					fieldId: options.fieldId
				},
				load: function () {
					function split( val ) {
						return val.split( /,\s*/ );
					}
					function extractLast( term ) {
						return split( term ).pop();
					}

					$('.groupselector', this).tiki('autocomplete', 'groupname', {
						tiki_replace_term: function (term) {
							return extractLast(term);
						},
						focus: function() {
							return false;
						},
						select: function( event, ui ) {
							var terms = split( this.value );
							terms.pop();

							terms.push( ui.item.value );

							terms.push( "" );
							this.value = terms.join( ", " );
							return false;
						}
					});
				},
				success: options.success
			});

			return this;
		},
		tracker_service_dialog: function (options) {
			this.each(function () {
				var $dialog = $('
'), origin = this;
				$(this).append($dialog);

				$dialog.dialog({
					title: options.title,
					minWidth: 500,
					height: 600,
					close: function () {
						$(this).dialog('destroy');
					}
				});

				$dialog.load('tiki-ajax_services.php', options.data, function () {
					$dialog.find('form').submit(function (e) {
						var form = this;
						$.ajax('tiki-ajax_services.php', {
							type: 'POST',
							dataType: 'json',
							data: $(form).serialize(),
							success: function (data) {
								$dialog.dialog('destroy');
								if (options.success) {
									options.success.apply(origin, [data]);
								}
							},
							error: function (jqxhr) {
								$(form.name).showError(jqxhr);
							}
						});

						return false;
					});

					if (options.load) {
						options.load.apply($dialog[0], []);
					}
				});
			});

			return this;
		},
		tracker_load_fields: function (trackerId) {
			this.each(function () {
				var $container = $(this).empty();

				$.getJSON('tiki-ajax_services.php', {
					controller: 'tracker',
					action: 'list_fields',
					trackerId: trackerId
				}, function (data) {
					$.each(data.fields, function (k, field) {
						var $row = $('
');
						$row.append($('').append($('<input type="checkbox" name="fields[]"/>').val(field.fieldId)));
						$row.append($('')
							.text(field.fieldId)
							.append($('<input type="hidden" name="field~' + field.fieldId + '~position"/>').val(field.position))
						);
						$row.append($('').append($('')
							.text(field.name)
							.attr('href', 'tiki-ajax_services.php?controller=tracker&action=edit_field&trackerId=' + trackerId + '&fieldId=' + field.fieldId)
							.click(function () {
								$(this).tracker_edit_field({
									trackerId: trackerId,
									fieldId: field.fieldId,
									success: function () {
										$container.tracker_load_fields(trackerId);
									}
								});
								return false;
							})
						));
						$row.append($('').text(data.types[field.type].name));

						var addCheckbox = function (name) {
							$row.append($('').append(
								$('<input type="checkbox" name="field~' + field.fieldId + '~' + name + '" value="1"/>')
									.attr('checked', field[name] === 'y')
							));
						};

						addCheckbox('isTblVisible');
						addCheckbox('isMain');
						addCheckbox('isSearchable');
						addCheckbox('isPublic');
						addCheckbox('isMandatory');

						$row.append($('').append($('')
							.click(function () {
								var link = this;
								if (confirm(tr('Removing the field will result in data loss. Are you sure?'))) {
									$.post($(this).attr('href'), {confirm: true}, function () {
										$(link).closest('tr').remove();
									}, 'json');
								}

								return false;
							})
						));

						$container.append($row);
					});
				});
			});

			return this;
		}
	});
}(jQuery));
<commit_msg>Add css class for table styling<commit_after>// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
(function ($) {
	$.fn = $.extend($.fn, {
		/**
		 * options:
		 * 	trackerId: int
		 * 	success: function (data) {}
		 */
		tracker_add_field: function (options) {
			this.tracker_service_dialog({
				title: tr('Add Field'),
				data: {
					controller: 'tracker',
					action: 'add_field',
					trackerId: options.trackerId
				},
				success: options.success,
				load: function () {
					var dialog = this;
					$('select', dialog).change(function () {
						$('.description', dialog)
							.hide()
							.filter('.' + $(this).val())
							.show();
					}).change();
				}
			});
		},
		/**
		 * options:
		 * 	trackerId: int
		 * 	success: function (data) {}
		 */
		tracker_edit_field: function (options) {
			this.tracker_service_dialog({
				title: tr('Edit Field'),
				data: {
					controller: 'tracker',
					action: 'edit_field',
					trackerId: options.trackerId,
					fieldId: options.fieldId
				},
				load: function () {
					function split( val ) {
						return val.split( /,\s*/ );
					}
					function extractLast( term ) {
						return split( term ).pop();
					}

					$('.groupselector', this).tiki('autocomplete', 'groupname', {
						tiki_replace_term: function (term) {
							return extractLast(term);
						},
						focus: function() {
							return false;
						},
						select: function( event, ui ) {
							var terms = split( this.value );
							terms.pop();

							terms.push( ui.item.value );

							terms.push( "" );
							this.value = terms.join( ", " );
							return false;
						}
					});
				},
				success: options.success
			});

			return this;
		},
		tracker_service_dialog: function (options) {
			this.each(function () {
				var $dialog = $('
'), origin = this;
				$(this).append($dialog);

				$dialog.dialog({
					title: options.title,
					minWidth: 500,
					height: 600,
					close: function () {
						$(this).dialog('destroy');
					}
				});

				$dialog.load('tiki-ajax_services.php', options.data, function () {
					$dialog.find('form').submit(function (e) {
						var form = this;
						$.ajax('tiki-ajax_services.php', {
							type: 'POST',
							dataType: 'json',
							data: $(form).serialize(),
							success: function (data) {
								$dialog.dialog('destroy');
								if (options.success) {
									options.success.apply(origin, [data]);
								}
							},
							error: function (jqxhr) {
								$(form.name).showError(jqxhr);
							}
						});

						return false;
					});

					if (options.load) {
						options.load.apply($dialog[0], []);
					}
				});
			});

			return this;
		},
		tracker_load_fields: function (trackerId) {
			this.each(function () {
				var $container = $(this).empty();

				$.getJSON('tiki-ajax_services.php', {
					controller: 'tracker',
					action: 'list_fields',
					trackerId: trackerId
				}, function (data) {
					$.each(data.fields, function (k, field) {
						var $row = $('
');
						$row.append($('').append($('<input type="checkbox" name="fields[]"/>').val(field.fieldId)));
						$row.append($('')
							.text(field.fieldId)
							.append($('<input type="hidden" name="field~' + field.fieldId + '~position"/>').val(field.position))
						);
						$row.append($('').append($('')
							.text(field.name)
							.attr('href', 'tiki-ajax_services.php?controller=tracker&action=edit_field&trackerId=' + trackerId + '&fieldId=' + field.fieldId)
							.click(function () {
								$(this).tracker_edit_field({
									trackerId: trackerId,
									fieldId: field.fieldId,
									success: function () {
										$container.tracker_load_fields(trackerId);
									}
								});
								return false;
							})
						));
						$row.append($('').text(data.types[field.type].name));

						var addCheckbox = function (name) {
							$row.append($('').append(
								$('<input type="checkbox" name="field~' + field.fieldId + '~' + name + '" value="1"/>')
									.attr('checked', field[name] === 'y')
							));
						};

						addCheckbox('isTblVisible');
						addCheckbox('isMain');
						addCheckbox('isSearchable');
						addCheckbox('isPublic');
						addCheckbox('isMandatory');

						$row.append($('').append($('')
							.click(function () {
								var link = this;
								if (confirm(tr('Removing the field will result in data loss. Are you sure?'))) {
									$.post($(this).attr('href'), {confirm: true}, function () {
										$(link).closest('tr').remove();
									}, 'json');
								}

								return false;
							})
						));

						$container.append($row);
					});
				});
			});

			return this;
		}
	});
}(jQuery));
<|endoftext|>