<commit_before>/*!
 * jquery.event.drag - v 2.3.0
 * Copyright (c) 2010 Three Dub Media - http://threedubmedia.com
 * Open Source MIT License - http://threedubmedia.com/code/license
 */
// Created: 2008-06-04
// Updated: 2012-05-21
// Updated: 2016-08-16   Luiz Gonzaga dos Santos Filho
// REQUIRES: jquery 1.8 +, , event.drag 2.3.0
// TESTED WITH: jQuery 1.8.3, 1.11.2, 2.2.4, and 3.1.0

;(function( $ ) {
    // add the jquery instance method
    $.fn.drag = function( str, arg, opts ){
        // figure out the event type
        var type = typeof str == "string" ? str : "",
            // figure out the event handler...
            fn = $.isFunction( str ) ? str : $.isFunction( arg ) ? arg : null;
        // fix the event type
        if ( type.indexOf("drag") !== 0 )
            type = "drag"+ type;
        // were options passed
        opts = ( str == fn ? arg : opts ) || {};
        // trigger or bind event handler
        return fn ? this.on( type, opts, fn ) : this.trigger( type );
    };

    // local refs (increase compression)
    var $event = $.event,
        $special = $event.special,
        // configure the drag special event
        drag = $special.drag = {

            // these are the default settings
            defaults: {
                which: 1, // mouse button pressed to start drag sequence
                distance: 0, // distance dragged before dragstart
                not: ':input', // selector to suppress dragging on target elements
                handle: null, // selector to match handle target elements
                relative: false, // true to use "position", false to use "offset"
                drop: true, // false to suppress drop events, true or selector to allow
                click: false // false to suppress click events after dragend (no proxy)
            },

            // the key name for stored drag data
            datakey: "dragdata",

            // prevent bubbling for better performance
            noBubble: true,

            // count bound related events
            add: function( obj ){
                // read the interaction data
                var data = $.data( this, drag.datakey ),
                    // read any passed options
                    opts = obj.data || {};
                // count another realted event
                data.related += 1;
                // extend data options bound with this event
                // don't iterate "opts" in case it is a node
                $.each( drag.defaults, function( key, def ){
                    if ( opts[ key ] !== undefined )
                        data[ key ] = opts[ key ];
                });
            },

            // forget unbound related events
            remove: function(){
                $.data( this, drag.datakey ).related -= 1;
            },

            // configure interaction, capture settings
            setup: function(){
                // check for related events
                if ( $.data( this, drag.datakey ) )
                    return;
                // initialize the drag data with copied defaults
                var data = $.extend({ related:0 }, drag.defaults );
                // store the interaction data
                $.data( this, drag.datakey, data );
                // bind the mousedown event, which starts drag interactions
                $event.add( this, "touchstart mousedown", drag.init, data );
                // prevent image dragging in IE...
                if ( this.attachEvent )
                    this.attachEvent("ondragstart", drag.dontstart );
            },

            // destroy configured interaction
            teardown: function(){
                var data = $.data( this, drag.datakey ) || {};
                // check for related events
                if ( data.related )
                    return;
                // remove the stored data
                $.removeData( this, drag.datakey );
                // remove the mousedown event
                $event.remove( this, "touchstart mousedown", drag.init );
                // enable text selection
                drag.textselect( true );
                // un-prevent image dragging in IE...
                if ( this.detachEvent )
                    this.detachEvent("ondragstart", drag.dontstart );
            },

            // initialize the interaction
            init: function( event ){
                // sorry, only one touch at a time
                if ( drag.touched )
                    return;
                // the drag/drop interaction data
                var dd = event.data, results;
                // check the which directive
                if ( event.which != 0 && dd.which > 0 && event.which != dd.which )
                    return;
                // check for suppressed selector and/or
                // make sure the target css class starts with "slick" so that we know we are in a Slick Grid
                var targetClass = $( event.target ).attr('class') || "";
                if ( $( event.target ).is( dd.not ) || (!targetClass || targetClass.toString().indexOf('slick') === -1))
                    return;

                // check for handle selector
                if ( dd.handle && !$( event.target ).closest( dd.handle, event.currentTarget ).length )
                    return;

                drag.touched = event.type == 'touchstart' ? this : null;
                dd.propagates = 1;
                dd.mousedown = this;
                dd.interactions = [ drag.interaction( this, dd ) ];
                dd.target = event.target;
                dd.pageX = event.pageX;
                dd.pageY = event.pageY;
                dd.dragging = null;
                // handle draginit event...
                results = drag.hijack( event, "draginit", dd );
                // early cancel
                if ( !dd.propagates )
                    return;
                // flatten the result set
                results = drag.flatten( results );
                // insert new interaction elements
                if ( results && results.length ){
                    dd.interactions = [];
                    $.each( results, function(){
                        dd.interactions.push( drag.interaction( this, dd ) );
                    });
                }
                // remember how many interactions are propagating
                dd.propagates = dd.interactions.length;
                // locate and init the drop targets
                if ( dd.drop !== false && $special.drop )
                    $special.drop.handler( event, dd );
                // disable text selection
                drag.textselect( false );
                // bind additional events...
                if ( drag.touched )
                    $event.add( drag.touched, "touchmove touchend", drag.handler, dd );
                else
                    $event.add( document, "mousemove mouseup", drag.handler, dd );
                // helps prevent text selection or scrolling
                if ( !drag.touched || dd.live )
                    return false;
            },

            // returns an interaction object
            interaction: function( elem, dd ){
                var offset = (elem && elem.ownerDocument)
                    ? $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 }
                    : { top: 0, left: 0 };
                return {
                    drag: elem,
                    callback: new drag.callback(),
                    droppable: [],
                    offset: offset
                };
            },

            // handle drag-releatd DOM events
            handler: function( event ){
                // read the data before hijacking anything
                var dd = event.data;
                // handle various events
                switch ( event.type ){
                    // mousemove, check distance, start dragging
                    case !dd.dragging && 'touchmove':
                        event.preventDefault();
                    case !dd.dragging && 'mousemove':
                        //  drag tolerance, x² + y² = distance²
                        if ( Math.pow(  event.pageX-dd.pageX, 2 ) + Math.pow(  event.pageY-dd.pageY, 2 ) < Math.pow( dd.distance, 2 ) )
                            break; // distance tolerance not reached
                        event.target = dd.target; // force target from "mousedown" event (fix distance issue)
                        drag.hijack( event, "dragstart", dd ); // trigger "dragstart"
                        if ( dd.propagates ) // "dragstart" not rejected
                            dd.dragging = true; // activate interaction
                        // mousemove, dragging
                    case 'touchmove':
                        event.preventDefault();
                    case 'mousemove':
                        if ( dd.dragging ){
                            // trigger "drag"
                            drag.hijack( event, "drag", dd );
                            if ( dd.propagates ){
                                // manage drop events
                                if ( dd.drop !== false && $special.drop )
                                    $special.drop.handler( event, dd ); // "dropstart", "dropend"
                                break; // "drag" not rejected, stop
                            }
                            event.type = "mouseup"; // helps "drop" handler behave
                        }
                        // mouseup, stop dragging
                    case 'touchend':
                    case 'mouseup':
                    default:
                        if ( drag.touched )
                            $event.remove( drag.touched, "touchmove touchend", drag.handler ); // remove touch events
                        else
                            $event.remove( document, "mousemove mouseup", drag.handler ); // remove page events
                        if ( dd.dragging ){
                            if ( dd.drop !== false && $special.drop )
                                $special.drop.handler( event, dd ); // "drop"
                            drag.hijack( event, "dragend", dd ); // trigger "dragend"
                        }
                        drag.textselect( true ); // enable text selection
                        // if suppressing click events...
                        if ( dd.click === false && dd.dragging )
                            $.data( dd.mousedown, "suppress.click", new Date().getTime() + 5 );
                        dd.dragging = drag.touched = false; // deactivate element
                        break;
                }
            },

            // re-use event object for custom events
            hijack: function( event, type, dd, x, elem ){
                // not configured
                if ( !dd )
                    return;
                // remember the original event and type
                var orig = { event:event.originalEvent, type:event.type },
                    // is the event drag related or drog related?
                    mode = type.indexOf("drop") ? "drag" : "drop",
                    // iteration vars
                    result, i = x || 0, ia, $elems, callback,
                    len = !isNaN( x ) ? x : dd.interactions.length;
                // modify the event type
                event.type = type;
                // protects originalEvent from side-effects
                var noop = function(){};
                event.originalEvent = new jQuery.Event(orig.event, {
                    preventDefault: noop,
                    stopPropagation: noop,
                    stopImmediatePropagation: noop
                });
                // initialize the results
                dd.results = [];
                // handle each interacted element
                do if ( ia = dd.interactions[ i ] ){
                    // validate the interaction
                    if ( type !== "dragend" && ia.cancelled )
                        continue;
                    // set the dragdrop properties on the event object
                    callback = drag.properties( event, dd, ia );
                    // prepare for more results
                    ia.results = [];
                    // handle each element
                    $( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){
                        // identify drag or drop targets individually
                        callback.target = subject;
                        // force propagtion of the custom event
                        event.isPropagationStopped = function(){ return false; };
                        // handle the event
                        result = subject ? $event.dispatch.call( subject, event, callback ) : null;
                        // stop the drag interaction for this element
                        if ( result === false ){
                            if ( mode == "drag" ){
                                ia.cancelled = true;
                                dd.propagates -= 1;
                            }
                            if ( type == "drop" ){
                                ia[ mode ][p] = null;
                            }
                        }
                        // assign any dropinit elements
                        else if ( type == "dropinit" )
                            ia.droppable.push( drag.element( result ) || subject );
                        // accept a returned proxy element
                        if ( type == "dragstart" )
                            ia.proxy = $( drag.element( result ) || ia.drag )[0];
                        // remember this result
                        ia.results.push( result );
                        // forget the event result, for recycling
                        delete event.result;
                        // break on cancelled handler
                        if ( type !== "dropinit" )
                            return result;
                    });
                    // flatten the results
                    dd.results[ i ] = drag.flatten( ia.results );
                    // accept a set of valid drop targets
                    if ( type == "dropinit" )
                        ia.droppable = drag.flatten( ia.droppable );
                    // locate drop targets
                    if ( type == "dragstart" && !ia.cancelled )
                        callback.update();
                }
                while ( ++i < len )
                    // restore the original event & type
                    event.type = orig.type;
                    event.originalEvent = orig.event;
                    // return all handler results
                    return drag.flatten( dd.results );
            },

            // extend the callback object with drag/drop properties...
            properties: function( event, dd, ia ){
                var obj = ia.callback;
                // elements
                obj.drag = ia.drag;
                obj.proxy = ia.proxy || ia.drag;
                // starting mouse position
                obj.startX = dd.pageX;
                obj.startY = dd.pageY;
                // current distance dragged
                obj.deltaX = event.pageX - dd.pageX;
                obj.deltaY = event.pageY - dd.pageY;
                // original element position
                obj.originalX = ia.offset.left;
                obj.originalY = ia.offset.top;
                // adjusted element position
                obj.offsetX = obj.originalX + obj.deltaX;
                obj.offsetY = obj.originalY + obj.deltaY;
                // assign the drop targets information
                obj.drop = drag.flatten( ( ia.drop || [] ).slice() );
                obj.available = drag.flatten( ( ia.droppable || [] ).slice() );
                return obj;
            },

            // determine is the argument is an element or jquery instance
            element: function( arg ){
                if ( arg && ( arg.jquery || arg.nodeType == 1 ) )
                    return arg;
            },

            // flatten nested jquery objects and arrays into a single dimension array
            flatten: function( arr ){
                return $.map( arr, function( member ){
                    return member && member.jquery ? $.makeArray( member ) :
                        member && member.length ? drag.flatten( member ) : member;
                });
            },

            // toggles text selection attributes ON (true) or OFF (false)
            textselect: function( bool ){
                $( document )[ bool ? "off" : "on" ]("selectstart", drag.dontstart )
                    .css("MozUserSelect", bool ? "" : "none" );
                // .attr("unselectable", bool ? "off" : "on" )
                document.unselectable = bool ? "off" : "on";
            },

            // suppress "selectstart" and "ondragstart" events
            dontstart: function(){
                return false;
            },

            // a callback instance contructor
            callback: function(){}

        };

        // callback methods
        drag.callback.prototype = {
            update: function(){
                if ( $special.drop && this.available.length )
                    $.each( this.available, function( i ){
                        $special.drop.locate( this, i );
                    });
            }
        };

        // patch $.event.$dispatch to allow suppressing clicks
        var $dispatch = $event.dispatch;
        $event.dispatch = function( event ){
            if ( $.data( this, "suppress."+ event.type ) - new Date().getTime() > 0 ){
                $.removeData( this, "suppress."+ event.type );
                return;
            }
            return $dispatch.apply( this, arguments );
        };

        // share the same special event configuration with related events...
        $special.draginit = $special.dragstart = $special.dragend = drag;
})( jQuery );
<commit_msg>jquery.event.drag check for data (#655)<commit_after>/*!
 * jquery.event.drag - v 2.3.0
 * Copyright (c) 2010 Three Dub Media - http://threedubmedia.com
 * Open Source MIT License - http://threedubmedia.com/code/license
 */
// Created: 2008-06-04
// Updated: 2012-05-21
// Updated: 2016-08-16   Luiz Gonzaga dos Santos Filho
// REQUIRES: jquery 1.8 +, , event.drag 2.3.0
// TESTED WITH: jQuery 1.8.3, 1.11.2, 2.2.4, and 3.1.0

;(function( $ ) {
    // add the jquery instance method
    $.fn.drag = function( str, arg, opts ){
        // figure out the event type
        var type = typeof str == "string" ? str : "",
            // figure out the event handler...
            fn = $.isFunction( str ) ? str : $.isFunction( arg ) ? arg : null;
        // fix the event type
        if ( type.indexOf("drag") !== 0 )
            type = "drag"+ type;
        // were options passed
        opts = ( str == fn ? arg : opts ) || {};
        // trigger or bind event handler
        return fn ? this.on( type, opts, fn ) : this.trigger( type );
    };

    // local refs (increase compression)
    var $event = $.event,
        $special = $event.special,
        // configure the drag special event
        drag = $special.drag = {

            // these are the default settings
            defaults: {
                which: 1, // mouse button pressed to start drag sequence
                distance: 0, // distance dragged before dragstart
                not: ':input', // selector to suppress dragging on target elements
                handle: null, // selector to match handle target elements
                relative: false, // true to use "position", false to use "offset"
                drop: true, // false to suppress drop events, true or selector to allow
                click: false // false to suppress click events after dragend (no proxy)
            },

            // the key name for stored drag data
            datakey: "dragdata",

            // prevent bubbling for better performance
            noBubble: true,

            // count bound related events
            add: function( obj ){
                // read the interaction data
                var data = $.data( this, drag.datakey ),
                    // read any passed options
                    opts = obj.data || {};
                // count another realted event
                data.related += 1;
                // extend data options bound with this event
                // don't iterate "opts" in case it is a node
                $.each( drag.defaults, function( key, def ){
                    if ( opts[ key ] !== undefined )
                        data[ key ] = opts[ key ];
                });
            },

            // forget unbound related events
            remove: function(){
                var data = $.data( this, drag.datakey );
                if(data)
                    data.related -= 1;
            },

            // configure interaction, capture settings
            setup: function(){
                // check for related events
                if ( $.data( this, drag.datakey ) )
                    return;
                // initialize the drag data with copied defaults
                var data = $.extend({ related:0 }, drag.defaults );
                // store the interaction data
                $.data( this, drag.datakey, data );
                // bind the mousedown event, which starts drag interactions
                $event.add( this, "touchstart mousedown", drag.init, data );
                // prevent image dragging in IE...
                if ( this.attachEvent )
                    this.attachEvent("ondragstart", drag.dontstart );
            },

            // destroy configured interaction
            teardown: function(){
                var data = $.data( this, drag.datakey ) || {};
                // check for related events
                if ( data.related )
                    return;
                // remove the stored data
                $.removeData( this, drag.datakey );
                // remove the mousedown event
                $event.remove( this, "touchstart mousedown", drag.init );
                // enable text selection
                drag.textselect( true );
                // un-prevent image dragging in IE...
                if ( this.detachEvent )
                    this.detachEvent("ondragstart", drag.dontstart );
            },

            // initialize the interaction
            init: function( event ){
                // sorry, only one touch at a time
                if ( drag.touched )
                    return;
                // the drag/drop interaction data
                var dd = event.data, results;
                // check the which directive
                if ( event.which != 0 && dd.which > 0 && event.which != dd.which )
                    return;
                // check for suppressed selector and/or
                // make sure the target css class starts with "slick" so that we know we are in a Slick Grid
                var targetClass = $( event.target ).attr('class') || "";
                if ( $( event.target ).is( dd.not ) || (!targetClass || targetClass.toString().indexOf('slick') === -1))
                    return;

                // check for handle selector
                if ( dd.handle && !$( event.target ).closest( dd.handle, event.currentTarget ).length )
                    return;

                drag.touched = event.type == 'touchstart' ? this : null;
                dd.propagates = 1;
                dd.mousedown = this;
                dd.interactions = [ drag.interaction( this, dd ) ];
                dd.target = event.target;
                dd.pageX = event.pageX;
                dd.pageY = event.pageY;
                dd.dragging = null;
                // handle draginit event...
                results = drag.hijack( event, "draginit", dd );
                // early cancel
                if ( !dd.propagates )
                    return;
                // flatten the result set
                results = drag.flatten( results );
                // insert new interaction elements
                if ( results && results.length ){
                    dd.interactions = [];
                    $.each( results, function(){
                        dd.interactions.push( drag.interaction( this, dd ) );
                    });
                }
                // remember how many interactions are propagating
                dd.propagates = dd.interactions.length;
                // locate and init the drop targets
                if ( dd.drop !== false && $special.drop )
                    $special.drop.handler( event, dd );
                // disable text selection
                drag.textselect( false );
                // bind additional events...
                if ( drag.touched )
                    $event.add( drag.touched, "touchmove touchend", drag.handler, dd );
                else
                    $event.add( document, "mousemove mouseup", drag.handler, dd );
                // helps prevent text selection or scrolling
                if ( !drag.touched || dd.live )
                    return false;
            },

            // returns an interaction object
            interaction: function( elem, dd ){
                var offset = (elem && elem.ownerDocument)
                    ? $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 }
                    : { top: 0, left: 0 };
                return {
                    drag: elem,
                    callback: new drag.callback(),
                    droppable: [],
                    offset: offset
                };
            },

            // handle drag-releatd DOM events
            handler: function( event ){
                // read the data before hijacking anything
                var dd = event.data;
                // handle various events
                switch ( event.type ){
                    // mousemove, check distance, start dragging
                    case !dd.dragging && 'touchmove':
                        event.preventDefault();
                    case !dd.dragging && 'mousemove':
                        //  drag tolerance, x² + y² = distance²
                        if ( Math.pow(  event.pageX-dd.pageX, 2 ) + Math.pow(  event.pageY-dd.pageY, 2 ) < Math.pow( dd.distance, 2 ) )
                            break; // distance tolerance not reached
                        event.target = dd.target; // force target from "mousedown" event (fix distance issue)
                        drag.hijack( event, "dragstart", dd ); // trigger "dragstart"
                        if ( dd.propagates ) // "dragstart" not rejected
                            dd.dragging = true; // activate interaction
                        // mousemove, dragging
                    case 'touchmove':
                        event.preventDefault();
                    case 'mousemove':
                        if ( dd.dragging ){
                            // trigger "drag"
                            drag.hijack( event, "drag", dd );
                            if ( dd.propagates ){
                                // manage drop events
                                if ( dd.drop !== false && $special.drop )
                                    $special.drop.handler( event, dd ); // "dropstart", "dropend"
                                break; // "drag" not rejected, stop
                            }
                            event.type = "mouseup"; // helps "drop" handler behave
                        }
                        // mouseup, stop dragging
                    case 'touchend':
                    case 'mouseup':
                    default:
                        if ( drag.touched )
                            $event.remove( drag.touched, "touchmove touchend", drag.handler ); // remove touch events
                        else
                            $event.remove( document, "mousemove mouseup", drag.handler ); // remove page events
                        if ( dd.dragging ){
                            if ( dd.drop !== false && $special.drop )
                                $special.drop.handler( event, dd ); // "drop"
                            drag.hijack( event, "dragend", dd ); // trigger "dragend"
                        }
                        drag.textselect( true ); // enable text selection
                        // if suppressing click events...
                        if ( dd.click === false && dd.dragging )
                            $.data( dd.mousedown, "suppress.click", new Date().getTime() + 5 );
                        dd.dragging = drag.touched = false; // deactivate element
                        break;
                }
            },

            // re-use event object for custom events
            hijack: function( event, type, dd, x, elem ){
                // not configured
                if ( !dd )
                    return;
                // remember the original event and type
                var orig = { event:event.originalEvent, type:event.type },
                    // is the event drag related or drog related?
                    mode = type.indexOf("drop") ? "drag" : "drop",
                    // iteration vars
                    result, i = x || 0, ia, $elems, callback,
                    len = !isNaN( x ) ? x : dd.interactions.length;
                // modify the event type
                event.type = type;
                // protects originalEvent from side-effects
                var noop = function(){};
                event.originalEvent = new jQuery.Event(orig.event, {
                    preventDefault: noop,
                    stopPropagation: noop,
                    stopImmediatePropagation: noop
                });
                // initialize the results
                dd.results = [];
                // handle each interacted element
                do if ( ia = dd.interactions[ i ] ){
                    // validate the interaction
                    if ( type !== "dragend" && ia.cancelled )
                        continue;
                    // set the dragdrop properties on the event object
                    callback = drag.properties( event, dd, ia );
                    // prepare for more results
                    ia.results = [];
                    // handle each element
                    $( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){
                        // identify drag or drop targets individually
                        callback.target = subject;
                        // force propagtion of the custom event
                        event.isPropagationStopped = function(){ return false; };
                        // handle the event
                        result = subject ? $event.dispatch.call( subject, event, callback ) : null;
                        // stop the drag interaction for this element
                        if ( result === false ){
                            if ( mode == "drag" ){
                                ia.cancelled = true;
                                dd.propagates -= 1;
                            }
                            if ( type == "drop" ){
                                ia[ mode ][p] = null;
                            }
                        }
                        // assign any dropinit elements
                        else if ( type == "dropinit" )
                            ia.droppable.push( drag.element( result ) || subject );
                        // accept a returned proxy element
                        if ( type == "dragstart" )
                            ia.proxy = $( drag.element( result ) || ia.drag )[0];
                        // remember this result
                        ia.results.push( result );
                        // forget the event result, for recycling
                        delete event.result;
                        // break on cancelled handler
                        if ( type !== "dropinit" )
                            return result;
                    });
                    // flatten the results
                    dd.results[ i ] = drag.flatten( ia.results );
                    // accept a set of valid drop targets
                    if ( type == "dropinit" )
                        ia.droppable = drag.flatten( ia.droppable );
                    // locate drop targets
                    if ( type == "dragstart" && !ia.cancelled )
                        callback.update();
                }
                while ( ++i < len )
                    // restore the original event & type
                    event.type = orig.type;
                    event.originalEvent = orig.event;
                    // return all handler results
                    return drag.flatten( dd.results );
            },

            // extend the callback object with drag/drop properties...
            properties: function( event, dd, ia ){
                var obj = ia.callback;
                // elements
                obj.drag = ia.drag;
                obj.proxy = ia.proxy || ia.drag;
                // starting mouse position
                obj.startX = dd.pageX;
                obj.startY = dd.pageY;
                // current distance dragged
                obj.deltaX = event.pageX - dd.pageX;
                obj.deltaY = event.pageY - dd.pageY;
                // original element position
                obj.originalX = ia.offset.left;
                obj.originalY = ia.offset.top;
                // adjusted element position
                obj.offsetX = obj.originalX + obj.deltaX;
                obj.offsetY = obj.originalY + obj.deltaY;
                // assign the drop targets information
                obj.drop = drag.flatten( ( ia.drop || [] ).slice() );
                obj.available = drag.flatten( ( ia.droppable || [] ).slice() );
                return obj;
            },

            // determine is the argument is an element or jquery instance
            element: function( arg ){
                if ( arg && ( arg.jquery || arg.nodeType == 1 ) )
                    return arg;
            },

            // flatten nested jquery objects and arrays into a single dimension array
            flatten: function( arr ){
                return $.map( arr, function( member ){
                    return member && member.jquery ? $.makeArray( member ) :
                        member && member.length ? drag.flatten( member ) : member;
                });
            },

            // toggles text selection attributes ON (true) or OFF (false)
            textselect: function( bool ){
                $( document )[ bool ? "off" : "on" ]("selectstart", drag.dontstart )
                    .css("MozUserSelect", bool ? "" : "none" );
                // .attr("unselectable", bool ? "off" : "on" )
                document.unselectable = bool ? "off" : "on";
            },

            // suppress "selectstart" and "ondragstart" events
            dontstart: function(){
                return false;
            },

            // a callback instance contructor
            callback: function(){}

        };

        // callback methods
        drag.callback.prototype = {
            update: function(){
                if ( $special.drop && this.available.length )
                    $.each( this.available, function( i ){
                        $special.drop.locate( this, i );
                    });
            }
        };

        // patch $.event.$dispatch to allow suppressing clicks
        var $dispatch = $event.dispatch;
        $event.dispatch = function( event ){
            if ( $.data( this, "suppress."+ event.type ) - new Date().getTime() > 0 ){
                $.removeData( this, "suppress."+ event.type );
                return;
            }
            return $dispatch.apply( this, arguments );
        };

        // share the same special event configuration with related events...
        $special.draginit = $special.dragstart = $special.dragend = drag;
})( jQuery );
<|endoftext|>


<commit_before>//Make configurable from docType??
//Set in option
var isXHTML = false;

//List from node-htmlparser
var singleTags = {
    area: 1,
    base: 1,
    basefont: 1,
    br: 1,
    col: 1,
    frame: 1,
    hr: 1,
    img: 1,
    input: 1,
    isindex: 1,
    link: 1,
    meta: 1,
    param: 1,
    embed: 1
};

var expr = {
  upperCaseChars: /([A-Z])/g,
  breakBetweenTags: /(<(\/?\w+).*?>)(?=<(?!\/\2))/gi,
  singleTag: (function() {
      var tags = [];
      for (var i in singleTags) {
          tags.push(i);
      }
      return new RegExp('<' + tags.join('|<'), 'i');
  })()
};

var uncanon = function(str, letter) {
    return '-' + letter.toLowerCase();
};

var HTMLEncode = require('./htmlencoding').HTMLEncode;

var styleIgnore = {
    top: 1,
    left: 1,
    length : 1,
    _importants : 1
};

exports.stringifyElement = function stringifyElement(element) {
    //sys.puts('Stringify HTML for: ' + element);
    var tagName = element.tagName.toLowerCase(),
    ret = {
        start: "<" + tagName,
        end:''
    }, attributes = [], i,
    attribute = null;

    //sys.puts('Checking Attributes: ' + element._attributes.length);
    //sys.puts(sys.inspect(element));
    if (element.attributes.length) {
        ret.start += " ";
        for (i = 0; i<element.attributes.length; i++) {
            attribute = element.attributes.item(i);
            attributes.push(attribute.name + '="' +
                            HTMLEncode(attribute.nodeValue) + '"');
        }
    }
    ret.start += attributes.join(" ");

    if (element.style) {
      var
      styleAttrs = [],
      keys = Object.keys(element.style),
      i, key, value,
      l=keys.length;
      for (i=0; i<l; i++) {
        key   = keys[i];
        value =  element.style[key];

        if (!styleIgnore[key] &&
            typeof value !== 'function' &&
            !/^\d+$/.test(key) && // Skip the integral keys that specify the order of the CSS properties
            (key !== 'position' || value !== 'static') &&
            element.style[i] !== '') {

            styleAttrs.push(key.replace(expr.upperCaseChars, uncanon) + ': ' +
                            HTMLEncode(value));
        }
      }
      if (styleAttrs.length) {
        ret.start += ' style="' + styleAttrs.join('; ') + '"';
      }
    }

    if (singleTags[tagName]) {
      if (isXHTML) {
          ret.start += "/";
      }
      ret.start += ">";
      ret.end = '';
    } else {
      ret.start += ">";
      ret.end = "</" + tagName + ">";
    }

    return ret;
};

var rawTextElements = /SCRIPT|STYLE/i;

function stringifyDoctype (doctype) {
  if (doctype.ownerDocument && doctype.ownerDocument._fullDT) {
    return doctype.ownerDocument._fullDT;
  }

  var dt = '<!DOCTYPE ' + doctype.name;
  if (doctype.publicId) {
    // Public ID may never contain double quotes, so this is always safe.
    dt += ' PUBLIC "' + doctype.publicId + '" ';
  }
  if (!doctype.publicId && doctype.systemId) {
    dt += ' SYSTEM '
  }
  if (doctype.systemId) {
    // System ID may contain double quotes OR single quotes, not never both.
    if (doctype.systemId.indexOf('"') > -1) {
      dt += "'" + doctype.systemId + "'";
    } else {
      dt += '"' + doctype.systemId + '"';
    }
  }
  dt += '>';
  return dt;
}

exports.makeHtmlGenerator = function makeHtmlGenerator(indentUnit, eol) {
  indentUnit = indentUnit || "";
  eol = eol || "";

  return function generateHtmlRecursive(node, rawText, curIndent) {
    var ret = "", parent, current, i;
    curIndent = curIndent || "";
    if (node) {
      if (node.nodeType &&
          node.nodeType === node.ENTITY_REFERENCE_NODE)
      {
        node = node._entity;
      }

      var childNodesRawText = rawText || rawTextElements.test(node.nodeName);

      switch (node.nodeType) {
        case node.ELEMENT_NODE:
          current = exports.stringifyElement(node);
          if (childNodesRawText) {
            ret += curIndent + current.start;
          } else {
            ret += curIndent + current.start;
          }
          if (node._childNodes.length > 0) {
            if (node._childNodes[0].nodeType !== node.TEXT_NODE) {
              ret += eol;
            }
            for (i=0; i<node._childNodes.length; i++) {
              ret += generateHtmlRecursive(node._childNodes[i], childNodesRawText, curIndent + indentUnit);
            }
            if (node._childNodes[node._childNodes.length - 1].nodeType !== node.TEXT_NODE) {
              ret += curIndent;
            }
            ret += current.end + eol;
          } else {
            ret += ((rawText ? node.nodeValue : HTMLEncode(node.nodeValue)) || '') + current.end + eol;
          }
          break;
        case node.TEXT_NODE:
          // Skip pure whitespace nodes if we're indenting
          if (!indentUnit || !/^[\s\n]*$/.test(node.nodeValue)) {
            ret += (rawText ? node.nodeValue : HTMLEncode(node.nodeValue)) || '';
          }
          break;
        case node.COMMENT_NODE:
          ret += curIndent + '<!--' + node.nodeValue + '-->' + eol;
          break;
        case node.DOCUMENT_NODE:
          for (i=0; i<node._childNodes.length; i++) {
            ret += generateHtmlRecursive(node._childNodes[i], childNodesRawText, curIndent);
          }
          break;
        case node.DOCUMENT_TYPE_NODE:
          ret += stringifyDoctype(node);
        break;
      }
    }
    //require('sys').puts(require('sys').inspect(ret));
    return ret;
  };
};

exports.domToHtml = function(dom, noformat, raw) {
  var htmlGenerator = exports.makeHtmlGenerator(noformat ? "" : "  ",
                                                noformat ? "" : "\n");
  if (dom.toArray) {
    // node list
    dom = dom.toArray();
  }
  if (Array.isArray(dom)) {
    var ret = "";
    for (var i=0,len=dom.length; i<len; i++) {
      ret += htmlGenerator(dom[i], raw);
    }
    return ret;
  } else {
    // single node
    return htmlGenerator(dom, raw);
  }
};
<commit_msg>domtohtml: Fixed indentation, removed outdated debug code and trailing whitespace.<commit_after>//Make configurable from docType??
//Set in option
var isXHTML = false;

//List from node-htmlparser
var singleTags = {
  area: 1,
  base: 1,
  basefont: 1,
  br: 1,
  col: 1,
  frame: 1,
  hr: 1,
  img: 1,
  input: 1,
  isindex: 1,
  link: 1,
  meta: 1,
  param: 1,
  embed: 1
};

var expr = {
  upperCaseChars: /([A-Z])/g,
  breakBetweenTags: /(<(\/?\w+).*?>)(?=<(?!\/\2))/gi,
  singleTag: (function() {
    var tags = [];
    for (var i in singleTags) {
      tags.push(i);
    }
    return new RegExp('<' + tags.join('|<'), 'i');
  })()
};

var uncanon = function(str, letter) {
  return '-' + letter.toLowerCase();
};

var HTMLEncode = require('./htmlencoding').HTMLEncode;

var styleIgnore = {
  top: 1,
  left: 1,
  length : 1,
  _importants : 1
};

exports.stringifyElement = function stringifyElement(element) {
  var tagName = element.tagName.toLowerCase(),
      ret = {
        start: "<" + tagName,
        end:''
      },
      attributes = [],
      i,
      attribute = null;

  //sys.puts('Checking Attributes: ' + element._attributes.length);
  //sys.puts(sys.inspect(element));
  if (element.attributes.length) {
    ret.start += " ";
    for (i = 0; i<element.attributes.length; i++) {
      attribute = element.attributes.item(i);
      attributes.push(attribute.name + '="' +
                      HTMLEncode(attribute.nodeValue) + '"');
    }
  }
  ret.start += attributes.join(" ");

  if (element.style) {
    var styleAttrs = [],
        keys = Object.keys(element.style),
        key, value,
        l = keys.length;
    for (i=0; i<l; i++) {
      key   = keys[i];
      value = element.style[key];

      if (!styleIgnore[key] &&
          typeof value !== 'function' &&
          !/^\d+$/.test(key) && // Skip the integral keys that specify the order of the CSS properties
          (key !== 'position' || value !== 'static') &&
          element.style[i] !== '') {

        styleAttrs.push(key.replace(expr.upperCaseChars, uncanon) + ': ' +
                        HTMLEncode(value));
      }
    }
    if (styleAttrs.length) {
      ret.start += ' style="' + styleAttrs.join('; ') + '"';
    }
  }

  if (singleTags[tagName]) {
    if (isXHTML) {
        ret.start += "/";
    }
    ret.start += ">";
    ret.end = '';
  } else {
    ret.start += ">";
    ret.end = "</" + tagName + ">";
  }

  return ret;
};

var rawTextElements = /SCRIPT|STYLE/i;

function stringifyDoctype (doctype) {
  if (doctype.ownerDocument && doctype.ownerDocument._fullDT) {
    return doctype.ownerDocument._fullDT;
  }

  var dt = '<!DOCTYPE ' + doctype.name;
  if (doctype.publicId) {
    // Public ID may never contain double quotes, so this is always safe.
    dt += ' PUBLIC "' + doctype.publicId + '" ';
  }
  if (!doctype.publicId && doctype.systemId) {
    dt += ' SYSTEM ';
  }
  if (doctype.systemId) {
    // System ID may contain double quotes OR single quotes, not never both.
    if (doctype.systemId.indexOf('"') > -1) {
      dt += "'" + doctype.systemId + "'";
    } else {
      dt += '"' + doctype.systemId + '"';
    }
  }
  dt += '>';
  return dt;
}

exports.makeHtmlGenerator = function makeHtmlGenerator(indentUnit, eol) {
  indentUnit = indentUnit || "";
  eol = eol || "";

  return function generateHtmlRecursive(node, rawText, curIndent) {
    var ret = "", parent, current, i;
    curIndent = curIndent || "";
    if (node) {
      if (node.nodeType &&
          node.nodeType === node.ENTITY_REFERENCE_NODE) {
        node = node._entity;
      }

      var childNodesRawText = rawText || rawTextElements.test(node.nodeName);

      switch (node.nodeType) {
        case node.ELEMENT_NODE:
          current = exports.stringifyElement(node);
          if (childNodesRawText) {
            ret += curIndent + current.start;
          } else {
            ret += curIndent + current.start;
          }
          if (node._childNodes.length > 0) {
            if (node._childNodes[0].nodeType !== node.TEXT_NODE) {
              ret += eol;
            }
            for (i=0; i<node._childNodes.length; i++) {
              ret += generateHtmlRecursive(node._childNodes[i], childNodesRawText, curIndent + indentUnit);
            }
            if (node._childNodes[node._childNodes.length - 1].nodeType !== node.TEXT_NODE) {
              ret += curIndent;
            }
            ret += current.end + eol;
          } else {
            ret += ((rawText ? node.nodeValue : HTMLEncode(node.nodeValue)) || '') + current.end + eol;
          }
          break;
        case node.TEXT_NODE:
          // Skip pure whitespace nodes if we're indenting
          if (!indentUnit || !/^[\s\n]*$/.test(node.nodeValue)) {
            ret += (rawText ? node.nodeValue : HTMLEncode(node.nodeValue)) || '';
          }
          break;
        case node.COMMENT_NODE:
          ret += curIndent + '<!--' + node.nodeValue + '-->' + eol;
          break;
        case node.DOCUMENT_NODE:
          for (i=0; i<node._childNodes.length; i++) {
            ret += generateHtmlRecursive(node._childNodes[i], childNodesRawText, curIndent);
          }
          break;
        case node.DOCUMENT_TYPE_NODE:
          ret += stringifyDoctype(node);
        break;
      }
    }
    return ret;
  };
};

exports.domToHtml = function(dom, noformat, raw) {
  var htmlGenerator = exports.makeHtmlGenerator(noformat ? "" : "  ",
                                                noformat ? "" : "\n");
  if (dom.toArray) {
    // node list
    dom = dom.toArray();
  }
  if (Array.isArray(dom)) {
    var ret = "";
    for (var i=0,len=dom.length; i<len; i++) {
      ret += htmlGenerator(dom[i], raw);
    }
    return ret;
  } else {
    // single node
    return htmlGenerator(dom, raw);
  }
};
<|endoftext|>


<commit_before>var CANNON = require('cannon'),
    mesh2shape = require('../../lib/CANNON-mesh2shape');

require('../../lib/CANNON-shape2mesh');

module.exports = {
  dependencies: ['quaternion'],

  /**
   * Initializes a body component, assigning it to the physics system and binding listeners for
   * parsing the elements geometry.
   */
  init: function () {
    this.system = this.el.sceneEl.systems.physics;

    if (this.el.sceneEl.hasLoaded) {
      this.initBody();
    } else {
      this.el.sceneEl.addEventListener('loaded', this.initBody.bind(this));
    }
  },

  /**
   * Parses an element's geometry and component metadata to create a CANNON.Body instance for the
   * component.
   */
  initBody: function () {
    var shape,
        el = this.el,
        data = this.data,
        pos = el.getComputedAttribute('position'),
        options = data.shape === 'auto' ? undefined : {
          type: mesh2shape.Type[data.shape.toUpperCase()],
          sphereRadius: data.sphereRadius
        };

    // Matrix World must be updated at root level, if scale is to be applied – updateMatrixWorld()
    // only checks an object's parent, not the rest of the ancestors. Hence, a wrapping entity with
    // scale="0.5 0.5 0.5" will be ignored.
    // Reference: https://github.com/mrdoob/three.js/blob/master/src/core/Object3D.js#L511-L541
    // Potential fix: https://github.com/mrdoob/three.js/pull/7019
    this.el.object3D.updateMatrixWorld(true);
    shape = mesh2shape(this.el.object3D, options);

    if (!shape) {
      this.el.addEventListener('model-loaded', this.initBody.bind(this));
      return;
    }

    this.body = new CANNON.Body({
      mass: data.mass || 0,
      material: this.system.material,
      position: new CANNON.Vec3(pos.x, pos.y, pos.z),
      linearDamping: data.linearDamping,
      angularDamping: data.angularDamping
    });
    this.body.addShape(shape, shape.offset, shape.orientation);

    // Apply rotation
    var rot = el.getComputedAttribute('rotation');
    this.body.quaternion.setFromEuler(
      THREE.Math.degToRad(rot.x),
      THREE.Math.degToRad(rot.y),
      THREE.Math.degToRad(rot.z),
      'XYZ'
    ).normalize();

    // Show wireframe
    if (this.system.debug) {
      this.createWireframe(this.body, shape);
    }

    this.el.body = this.body;
    this.body.el = this.el;
    this.isLoaded = true;

    // If component wasn't initialized when play() was called, finish up.
    if (this.isPlaying) {
      this._play();
    }

    this.el.emit('body-loaded', {body: this.el.body});
  },

  /**
   * Registers the component with the physics system, if ready.
   */
  play: function () {
    if (this.isLoaded) this._play();
  },

  /**
   * Internal helper to register component with physics system.
   */
  _play: function () {
    this.system.addBehavior(this, this.system.Phase.SIMULATE);
    this.system.addBody(this.body);
    if (this.wireframe) this.el.sceneEl.object3D.add(this.wireframe);

    this.syncToPhysics();
  },

  /**
   * Unregisters the component with the physics system.
   */
  pause: function () {
    if (!this.isLoaded) return;

    this.system.removeBehavior(this, this.system.Phase.SIMULATE);
    this.system.removeBody(this.body);
    if (this.wireframe) this.el.sceneEl.object3D.remove(this.wireframe);
  },

  /**
   * Removes the component and all physics and scene side effects.
   */
  remove: function () {
    this.pause();
    delete this.body.el;
    delete this.body;
    delete this.el.body;
    delete this.wireframe;
  },

  /**
   * Creates a wireframe for the body, for debugging.
   * TODO(donmccurdy) – Refactor this into a standalone utility or component.
   * @param  {CANNON.Body} body
   * @param  {CANNON.Shape} shape
   */
  createWireframe: function (body, shape) {
    var offset = shape.offset,
        orientation = shape.orientation,
        mesh = CANNON.shape2mesh(body).children[0];
    this.wireframe = new THREE.EdgesHelper(mesh, 0xff0000);

    if (offset) {
      this.wireframe.offset = offset.clone();
    }

    if (orientation) {
      orientation.inverse(orientation);
      this.wireframe.orientation = new THREE.Quaternion(
        orientation.x,
        orientation.y,
        orientation.z,
        orientation.w
      );
    }

    this.syncWireframe();
  },

  /**
   * Updates the debugging wireframe's position and rotation.
   */
  syncWireframe: function () {
    var offset,
        wireframe = this.wireframe;

    if (!this.wireframe) return;

    // Apply rotation. If the shape required custom orientation, also apply
    // that on the wireframe.
    wireframe.quaternion.copy(this.body.quaternion);
    if (wireframe.orientation) {
      wireframe.quaternion.multiply(wireframe.orientation);
    }

    // Apply position. If the shape required custom offset, also apply that on
    // the wireframe.
    wireframe.position.copy(this.body.position);
    if (wireframe.offset) {
      offset = wireframe.offset.clone().applyQuaternion(wireframe.quaternion);
      wireframe.position.add(offset);
    }

    wireframe.updateMatrix();
  },

  /**
   * Updates the CANNON.Body instance's position, velocity, and rotation, based on the scene.
   */
  syncToPhysics: function () {
    var body = this.body;
    if (!body) return;
    if (this.el.components.velocity) body.velocity.copy(this.el.getComputedAttribute('velocity'));
    if (this.el.components.position) body.position.copy(this.el.getComputedAttribute('position'));
    // TODO(donmccurdy) - Quaternion should also be synced, but no reason currently.
    if (this.wireframe) this.syncWireframe();
  },

  /**
   * Updates the scene object's position and rotation, based on the physics simulation.
   */
  syncFromPhysics: function () {
    if (!this.body) return;
    this.el.setAttribute('quaternion', this.body.quaternion);
    this.el.setAttribute('position', this.body.position);
    if (this.wireframe) this.syncWireframe();
  }
};
<commit_msg>Use world coordinates in body.sync methods<commit_after>var CANNON = require('cannon'),
    mesh2shape = require('../../lib/CANNON-mesh2shape');

require('../../lib/CANNON-shape2mesh');

module.exports = {
  dependencies: ['quaternion'],

  /**
   * Initializes a body component, assigning it to the physics system and binding listeners for
   * parsing the elements geometry.
   */
  init: function () {
    this.system = this.el.sceneEl.systems.physics;

    if (this.el.sceneEl.hasLoaded) {
      this.initBody();
    } else {
      this.el.sceneEl.addEventListener('loaded', this.initBody.bind(this));
    }
  },

  /**
   * Parses an element's geometry and component metadata to create a CANNON.Body instance for the
   * component.
   */
  initBody: function () {
    var shape,
        el = this.el,
        data = this.data,
        pos = el.getComputedAttribute('position'),
        options = data.shape === 'auto' ? undefined : {
          type: mesh2shape.Type[data.shape.toUpperCase()],
          sphereRadius: data.sphereRadius
        };

    // Matrix World must be updated at root level, if scale is to be applied – updateMatrixWorld()
    // only checks an object's parent, not the rest of the ancestors. Hence, a wrapping entity with
    // scale="0.5 0.5 0.5" will be ignored.
    // Reference: https://github.com/mrdoob/three.js/blob/master/src/core/Object3D.js#L511-L541
    // Potential fix: https://github.com/mrdoob/three.js/pull/7019
    this.el.object3D.updateMatrixWorld(true);
    shape = mesh2shape(this.el.object3D, options);

    if (!shape) {
      this.el.addEventListener('model-loaded', this.initBody.bind(this));
      return;
    }

    this.body = new CANNON.Body({
      mass: data.mass || 0,
      material: this.system.material,
      position: new CANNON.Vec3(pos.x, pos.y, pos.z),
      linearDamping: data.linearDamping,
      angularDamping: data.angularDamping
    });
    this.body.addShape(shape, shape.offset, shape.orientation);

    // Apply rotation
    var rot = el.getComputedAttribute('rotation');
    this.body.quaternion.setFromEuler(
      THREE.Math.degToRad(rot.x),
      THREE.Math.degToRad(rot.y),
      THREE.Math.degToRad(rot.z),
      'XYZ'
    ).normalize();

    // Show wireframe
    if (this.system.debug) {
      this.createWireframe(this.body, shape);
    }

    this.el.body = this.body;
    this.body.el = this.el;
    this.isLoaded = true;

    // If component wasn't initialized when play() was called, finish up.
    if (this.isPlaying) {
      this._play();
    }

    this.el.emit('body-loaded', {body: this.el.body});
  },

  /**
   * Registers the component with the physics system, if ready.
   */
  play: function () {
    if (this.isLoaded) this._play();
  },

  /**
   * Internal helper to register component with physics system.
   */
  _play: function () {
    this.system.addBehavior(this, this.system.Phase.SIMULATE);
    this.system.addBody(this.body);
    if (this.wireframe) this.el.sceneEl.object3D.add(this.wireframe);

    this.syncToPhysics();
  },

  /**
   * Unregisters the component with the physics system.
   */
  pause: function () {
    if (!this.isLoaded) return;

    this.system.removeBehavior(this, this.system.Phase.SIMULATE);
    this.system.removeBody(this.body);
    if (this.wireframe) this.el.sceneEl.object3D.remove(this.wireframe);
  },

  /**
   * Removes the component and all physics and scene side effects.
   */
  remove: function () {
    this.pause();
    delete this.body.el;
    delete this.body;
    delete this.el.body;
    delete this.wireframe;
  },

  /**
   * Creates a wireframe for the body, for debugging.
   * TODO(donmccurdy) – Refactor this into a standalone utility or component.
   * @param  {CANNON.Body} body
   * @param  {CANNON.Shape} shape
   */
  createWireframe: function (body, shape) {
    var offset = shape.offset,
        orientation = shape.orientation,
        mesh = CANNON.shape2mesh(body).children[0];
    this.wireframe = new THREE.EdgesHelper(mesh, 0xff0000);

    if (offset) {
      this.wireframe.offset = offset.clone();
    }

    if (orientation) {
      orientation.inverse(orientation);
      this.wireframe.orientation = new THREE.Quaternion(
        orientation.x,
        orientation.y,
        orientation.z,
        orientation.w
      );
    }

    this.syncWireframe();
  },

  /**
   * Updates the debugging wireframe's position and rotation.
   */
  syncWireframe: function () {
    var offset,
        wireframe = this.wireframe;

    if (!this.wireframe) return;

    // Apply rotation. If the shape required custom orientation, also apply
    // that on the wireframe.
    wireframe.quaternion.copy(this.body.quaternion);
    if (wireframe.orientation) {
      wireframe.quaternion.multiply(wireframe.orientation);
    }

    // Apply position. If the shape required custom offset, also apply that on
    // the wireframe.
    wireframe.position.copy(this.body.position);
    if (wireframe.offset) {
      offset = wireframe.offset.clone().applyQuaternion(wireframe.quaternion);
      wireframe.position.add(offset);
    }

    wireframe.updateMatrix();
  },

  /**
   * Updates the CANNON.Body instance's position, velocity, and rotation, based on the scene.
   */
  syncToPhysics: function () {
    var el = this.el,
        body = this.body;
    if (!body) return;
    if (el.components.velocity)   body.velocity.copy(el.getComputedAttribute('velocity'));
    // TODO - this line somehow prevents setting default rotation of dynamic body.
    if (el.components.quaternion) body.quaternion.copy(el.object3D.getWorldQuaternion());
    if (el.components.position)   body.position.copy(el.object3D.getWorldPosition());
    if (this.wireframe)           this.syncWireframe();
  },

  /**
   * Updates the scene object's position and rotation, based on the physics simulation.
   */
  syncFromPhysics: (function () {
    var v = new THREE.Vector3(),
        q1 = new THREE.Quaternion(),
        q2 = new THREE.Quaternion();
    return function () {
      var el = this.el,
          parentEl = el.parentEl,
          body = this.body;

      if (!body) return;

      if (parentEl.isScene) {
          el.setAttribute('quaternion', body.quaternion);
          el.setAttribute('position', body.position);
      } else {
        q1.copy(body.quaternion);
        q2.setFromRotationMatrix(parentEl.object3D.matrixWorld).inverse();
        q1.multiply(q2);
        el.setAttribute('quaternion', {x: q1.x, y: q1.y, z: q1.z, w: q1.w});

        v.copy(body.position);
        parentEl.object3D.worldToLocal(v);
        el.setAttribute('position', {x: v.x, y: v.y, z: v.z});
      }

      if (this.wireframe) this.syncWireframe();
    };
  }())
};
<|endoftext|>


<commit_before>/**
 * Opengraph meta tags
 */

var htmlparser = require("htmlparser2");
var URL = require('url');

var tags = [
    // Facebook, Google+
    {
        type: "facebook",
        attribute : "property",
        name : "og:image",
        value : "content"
    },
    // Old Facebook
    {
        type: "facebook",
        attribute : "rel",
        name : "image_src",
        value : "href"
    },
    // Old Twitter card
    {
        type: "twitter",
        attribute : "name",
        name : "twitter:image",
        value : "value"
    },
    // New Twitter card
    {
        type: "twitter",
        attribute : "name",
        name : "twitter:image",
        value : "content"
    }
];

function Opengraph() {
}
Opengraph.prototype.resolve = function(url, clbk, options, utils) {
    var self = this;

    utils.fetch(
        url,
        function onSuccess( data, response ) {
            self.parseHTML( data, url, clbk, options, utils );
        },
        function onError(){
            clbk(null);
        }
    );
};

Opengraph.prototype.parseHTML = function( html, url, clbk, options, utils ) {
    var domutils = htmlparser.DomUtils;

    var handler = new htmlparser.DomHandler( function( error, dom ) {

        if ( error ) {
            clbk(null);
            return;
        }

        var meta = [].concat(
            domutils.getElementsByTagName('meta', dom, true),
            domutils.getElementsByTagName('link', dom, true)
        );

        var images = [];
        var image;
        var tag;

        // Find Opengraph tags
        for (var i=0,l=meta.length; i<l; i++) {
            tag = meta[i];
            for (var j=0, m=tags.length; j<m; j++) {
                if (
                    tag.attribs[tags[j].attribute] &&
                    tag.attribs[tags[j].attribute] === tags[j].name &&
                    tag.attribs[tags[j].value]
                ) {
                    images.push({
                        url: tag.attribs[tags[j].value],
                        type: tags[j].type,
                        score: 0
                    });
                }
            }
        }

        // Find best image among candidates
        if (images.length === 1) {
            image = images[0].url;
        } else if (images.length > 1) {
            for (i=0, l=images.length; i<l; i++) {
                //Increase score for image containing "large" or "big" in url
                if (images[i].url.match(/(large|big)/i)) {
                    images[i].score++;
                }
                // Increase score for twitter
                // Websites tend to limit image size to the size of Facebook preview
                if (images[i].type === 'twitter') {
                    images[i].score++;
                }
            }
            images.sort(function(a,b){
                return b.score - a.score;
            });
            image = images[0].url;
        }

        //Resolve relative url
        if (image && !image.match(/^http/)) {
            image = URL.resolve( url, image);
        }

        clbk(image);
    } );
    var parser = new htmlparser.Parser( handler );
    parser.write( html );
    parser.done();
};

module.exports = Opengraph;<commit_msg>Fixes OpenGraph plugin<commit_after>/**
 * Opengraph meta tags
 */

var htmlparser = require("htmlparser2");
var URL = require('url');

var tags = [
    // Facebook, Google+
    {
        type: "facebook",
        attribute : "property",
        name : "og:image",
        value : "content"
    },
    // Old Facebook
    {
        type: "facebook",
        attribute : "rel",
        name : "image_src",
        value : "href"
    },
    // Old Twitter card
    {
        type: "twitter",
        attribute : "name",
        name : "twitter:image",
        value : "value"
    },
    // New Twitter card
    {
        type: "twitter",
        attribute : "name",
        name : "twitter:image",
        value : "content"
    }
];

function Opengraph() {
}
Opengraph.prototype.resolve = function(url, clbk, options, utils) {
    var self = this;

    utils.fetch(
        url,
        function onSuccess( data, response ) {
            self.parseHTML( data, url, clbk, options, utils );
        },
        function onError(){
            clbk(null);
        }
    );
};

Opengraph.prototype.parseHTML = function( html, url, clbk, options, utils ) {
    var domutils = htmlparser.DomUtils;

    var handler = new htmlparser.DomHandler( function( error, dom ) {

        if ( error ) {
            clbk(null);
            return;
        }

        var meta = [].concat(
            domutils.getElementsByTagName('meta', dom, true),
            domutils.getElementsByTagName('link', dom, true)
        );

        var images = [];
        var image;
        var tag;

        // Find Opengraph tags
        for (var i=0,l=meta.length; i<l; i++) {
            tag = meta[i];
            for (var j=0, m=tags.length; j<m; j++) {
                if (
                    tag.attribs[tags[j].attribute] &&
                    tag.attribs[tags[j].attribute] === tags[j].name &&
                    tag.attribs[tags[j].value]
                ) {
                    images.push({
                        url: tag.attribs[tags[j].value],
                        type: tags[j].type,
                        score: 0
                    });
                }
            }
        }

        // Find best image among candidates
        if (images.length === 1) {
            image = images[0].url;
        } else if (images.length > 1) {
            for (i=0, l=images.length; i<l; i++) {
                //Increase score for image containing "large" or "big" in url
                if (images[i].url.match(/(large|big)/i)) {
                    images[i].score++;
                }
                // Increase score for twitter
                // Websites tend to limit image size to the size of Facebook preview
                if (images[i].type === 'twitter') {
                    images[i].score++;
                }
            }
            images.sort(function(a,b){
                return b.score - a.score;
            });
            image = images[0].url;
        }

        if ( image ) {
            //Resolve relative url
            if (!image.match(/^http/)) {
                image = URL.resolve( url, image);
            }
            clbk(image);
        } else {
            clbk(null);
        }

    } );
    var parser = new htmlparser.Parser( handler );
    parser.write( html );
    parser.done();
};

module.exports = Opengraph;<|endoftext|>


<commit_before>const createRetry = require('../retry')
const createSocket = require('./socket')
const createRequest = require('../protocol/request')
const Decoder = require('../protocol/decoder')
const { KafkaJSConnectionError } = require('../errors')
const { INT_32_MAX_VALUE } = require('../constants')
const getEnv = require('../env')
const RequestQueue = require('./requestQueue')

const requestInfo = ({ apiName, apiKey, apiVersion }) =>
  `${apiName}(key: ${apiKey}, version: ${apiVersion})`

/**
 * @param {string} host
 * @param {number} port
 * @param {Object} logger
 * @param {string} clientId='kafkajs'
 * @param {string} [rack=null]
 * @param {Object} [ssl=null] Options for the TLS Secure Context. It accepts all options,
 *                            usually "cert", "key" and "ca". More information at
 *                            https://nodejs.org/api/tls.html#tls_tls_createsecurecontext_options
 * @param {Object} [sasl=null] Attributes used for SASL authentication. Options based on the
 *                             key "mechanism". Connection is not actively using the SASL attributes
 *                             but acting as a data object for this information
 * @param {number} [connectionTimeout=1000] The connection timeout, in milliseconds
 * @param {number} [requestTimeout=30000] The maximum amount of time the client will wait for the response of a request,
 *                                        in milliseconds
 * @param {Object} [retry=null] Configurations for the built-in retry mechanism. More information at the
 *                              retry module inside network
 * @param {number} [maxInFlightRequests=null] The maximum number of unacknowledged requests on a connection before
 *                                            enqueuing
 * @param {InstrumentationEventEmitter} [instrumentationEmitter=null]
 */
module.exports = class Connection {
  constructor({
    host,
    port,
    logger,
    socketFactory,
    rack = null,
    ssl = null,
    sasl = null,
    clientId = 'kafkajs',
    connectionTimeout = 1000,
    requestTimeout = 30000,
    enforceRequestTimeout = false,
    maxInFlightRequests = null,
    instrumentationEmitter = null,
    retry = {},
  }) {
    this.host = host
    this.port = port
    this.rack = rack
    this.clientId = clientId
    this.broker = `${this.host}:${this.port}`
    this.logger = logger.namespace('Connection')

    this.socketFactory = socketFactory
    this.ssl = ssl
    this.sasl = sasl

    this.retry = retry
    this.retrier = createRetry({ ...this.retry })
    this.requestTimeout = requestTimeout
    this.connectionTimeout = connectionTimeout

    this.buffer = Buffer.alloc(0)
    this.connected = false
    this.correlationId = 0
    this.requestQueue = new RequestQueue({
      instrumentationEmitter,
      maxInFlightRequests,
      requestTimeout,
      enforceRequestTimeout,
      clientId,
      broker: this.broker,
      logger: logger.namespace('RequestQueue'),
    })

    this.authHandlers = null
    this.authExpectResponse = false

    const log = level => (message, extra = {}) => {
      const logFn = this.logger[level]
      logFn(message, { broker: this.broker, clientId, ...extra })
    }

    this.logDebug = log('debug')
    this.logError = log('error')
    this.shouldLogBuffers = getEnv().KAFKAJS_DEBUG_PROTOCOL_BUFFERS === '1'
    this.shouldLogFetchBuffer =
      this.shouldLogBuffers && getEnv().KAFKAJS_DEBUG_EXTENDED_PROTOCOL_BUFFERS === '1'
  }

  /**
   * @public
   * @returns {Promise}
   */
  connect() {
    return new Promise((resolve, reject) => {
      if (this.connected) {
        return resolve(true)
      }

      let timeoutId

      const onConnect = () => {
        clearTimeout(timeoutId)
        this.connected = true
        resolve(true)
      }

      const onData = data => {
        this.processData(data)
      }

      const onEnd = async () => {
        clearTimeout(timeoutId)

        const wasConnected = this.connected
        await this.disconnect()

        if (this.authHandlers) {
          this.authHandlers.onError()
        } else if (wasConnected) {
          this.logDebug('Kafka server has closed connection')
          this.rejectRequests(
            new KafkaJSConnectionError('Closed connection', {
              broker: `${this.host}:${this.port}`,
            })
          )
        }
      }

      const onError = async e => {
        clearTimeout(timeoutId)

        const error = new KafkaJSConnectionError(`Connection error: ${e.message}`, {
          broker: `${this.host}:${this.port}`,
          code: e.code,
        })

        this.logError(error.message, { stack: e.stack })
        await this.disconnect()
        this.rejectRequests(error)

        reject(error)
      }

      const onTimeout = async () => {
        const error = new KafkaJSConnectionError('Connection timeout', {
          broker: `${this.host}:${this.port}`,
        })

        this.logError(error.message)
        await this.disconnect()
        this.rejectRequests(error)
        reject(error)
      }

      this.logDebug(`Connecting`, {
        ssl: !!this.ssl,
        sasl: !!this.sasl,
      })

      try {
        timeoutId = setTimeout(onTimeout, this.connectionTimeout)
        this.socket = createSocket({
          socketFactory: this.socketFactory,
          host: this.host,
          port: this.port,
          ssl: this.ssl,
          onConnect,
          onData,
          onEnd,
          onError,
          onTimeout,
        })
      } catch (e) {
        clearTimeout(timeoutId)
        reject(
          new KafkaJSConnectionError(`Failed to connect: ${e.message}`, {
            broker: `${this.host}:${this.port}`,
          })
        )
      }
    })
  }

  /**
   * @public
   * @returns {Promise}
   */
  async disconnect() {
    if (!this.connected) {
      return true
    }

    this.logDebug('disconnecting...')
    this.connected = false
    this.socket.end()
    this.socket.unref()
    this.logDebug('disconnected')
    return true
  }

  /**
   * @public
   * @returns {Promise}
   */
  authenticate({ authExpectResponse = false, request, response }) {
    this.authExpectResponse = authExpectResponse

    /**
     * TODO: rewrite removing the async promise executor
     */

    /* eslint-disable no-async-promise-executor */
    return new Promise(async (resolve, reject) => {
      this.authHandlers = {
        onSuccess: rawData => {
          this.authHandlers = null
          this.authExpectResponse = false

          response
            .decode(rawData)
            .then(data => response.parse(data))
            .then(resolve)
            .catch(reject)
        },
        onError: () => {
          this.authHandlers = null
          this.authExpectResponse = false

          reject(
            new KafkaJSConnectionError('Connection closed by the server', {
              broker: `${this.host}:${this.port}`,
            })
          )
        },
      }

      try {
        const requestPayload = await request.encode()

        this.failIfNotConnected()
        this.socket.write(requestPayload.buffer, 'binary')
      } catch (e) {
        reject(e)
      }
    })
  }

  /**
   * @public
   * @param {object} request It is defined by the protocol and consists of an object with "apiKey",
   *                         "apiVersion", "apiName" and an "encode" function. The encode function
   *                         must return an instance of Encoder
   *
   * @param {object} response It is defined by the protocol and consists of an object with two functions:
   *                          "decode" and "parse"
   *
   * @param {number} [requestTimeout=null] Override for the default requestTimeout
   * @returns {Promise<data>} where data is the return of "response#parse"
   */
  async send({ request, response, requestTimeout = null }) {
    this.failIfNotConnected()

    const expectResponse = !request.expectResponse || request.expectResponse()
    const sendRequest = async () => {
      const { clientId } = this
      const correlationId = this.nextCorrelationId()

      const requestPayload = await createRequest({ request, correlationId, clientId })
      const { apiKey, apiName, apiVersion } = request
      this.logDebug(`Request ${requestInfo(request)}`, {
        correlationId,
        expectResponse,
        size: Buffer.byteLength(requestPayload.buffer),
      })

      return new Promise((resolve, reject) => {
        try {
          this.failIfNotConnected()
          const entry = { apiKey, apiName, apiVersion, correlationId, resolve, reject }

          this.requestQueue.push({
            entry,
            expectResponse,
            requestTimeout,
            sendRequest: () => {
              this.socket.write(requestPayload.buffer, 'binary')
            },
          })
        } catch (e) {
          reject(e)
        }
      })
    }

    const { correlationId, size, entry, payload } = await sendRequest()

    if (!expectResponse) {
      return
    }

    try {
      const payloadDecoded = await response.decode(payload)
      const data = await response.parse(payloadDecoded)
      const isFetchApi = entry.apiName === 'Fetch'
      this.logDebug(`Response ${requestInfo(entry)}`, {
        correlationId,
        size,
        data: isFetchApi && !this.shouldLogFetchBuffer ? '[filtered]' : data,
      })

      return data
    } catch (e) {
      if (entry.apiName !== 'ApiVersions') {
        this.logError(`Response ${requestInfo(entry)}`, {
          error: e.message,
          correlationId,
          size,
        })
      }

      const isBuffer = Buffer.isBuffer(payload)
      this.logDebug(`Response ${requestInfo(entry)}`, {
        error: e.message,
        correlationId,
        payload:
          isBuffer && !this.shouldLogBuffers ? { type: 'Buffer', data: '[filtered]' } : payload,
      })

      throw e
    }
  }

  /**
   * @private
   */
  failIfNotConnected() {
    if (!this.connected) {
      throw new KafkaJSConnectionError('Not connected', {
        broker: `${this.host}:${this.port}`,
      })
    }
  }

  /**
   * @private
   */
  nextCorrelationId() {
    if (this.correlationId >= INT_32_MAX_VALUE) {
      this.correlationId = 0
    }

    return this.correlationId++
  }

  /**
   * @private
   */
  processData(rawData) {
    if (this.authHandlers && !this.authExpectResponse) {
      return this.authHandlers.onSuccess(rawData)
    }

    this.buffer = Buffer.concat([this.buffer, rawData])

    // Process data if there are enough bytes to read the expected response size,
    // otherwise keep buffering
    while (Buffer.byteLength(this.buffer) > Decoder.int32Size()) {
      const data = Buffer.from(this.buffer)
      const decoder = new Decoder(data)
      const expectedResponseSize = decoder.readInt32()

      if (!decoder.canReadBytes(expectedResponseSize)) {
        return
      }

      const response = new Decoder(decoder.readBytes(expectedResponseSize))
      // Reset the buffer as the rest of the bytes
      this.buffer = decoder.readAll()

      if (this.authHandlers) {
        const rawResponseSize = Decoder.int32Size() + expectedResponseSize
        const rawResponseBuffer = data.slice(0, rawResponseSize)
        return this.authHandlers.onSuccess(rawResponseBuffer)
      }

      const correlationId = response.readInt32()
      const payload = response.readAll()

      this.requestQueue.fulfillRequest({
        size: expectedResponseSize,
        correlationId,
        payload,
      })
    }
  }

  /**
   * @private
   */
  rejectRequests(error) {
    this.requestQueue.rejectAll(error)
  }
}
<commit_msg>Don't read environment variables twice<commit_after>const createRetry = require('../retry')
const createSocket = require('./socket')
const createRequest = require('../protocol/request')
const Decoder = require('../protocol/decoder')
const { KafkaJSConnectionError } = require('../errors')
const { INT_32_MAX_VALUE } = require('../constants')
const getEnv = require('../env')
const RequestQueue = require('./requestQueue')

const requestInfo = ({ apiName, apiKey, apiVersion }) =>
  `${apiName}(key: ${apiKey}, version: ${apiVersion})`

/**
 * @param {string} host
 * @param {number} port
 * @param {Object} logger
 * @param {string} clientId='kafkajs'
 * @param {string} [rack=null]
 * @param {Object} [ssl=null] Options for the TLS Secure Context. It accepts all options,
 *                            usually "cert", "key" and "ca". More information at
 *                            https://nodejs.org/api/tls.html#tls_tls_createsecurecontext_options
 * @param {Object} [sasl=null] Attributes used for SASL authentication. Options based on the
 *                             key "mechanism". Connection is not actively using the SASL attributes
 *                             but acting as a data object for this information
 * @param {number} [connectionTimeout=1000] The connection timeout, in milliseconds
 * @param {number} [requestTimeout=30000] The maximum amount of time the client will wait for the response of a request,
 *                                        in milliseconds
 * @param {Object} [retry=null] Configurations for the built-in retry mechanism. More information at the
 *                              retry module inside network
 * @param {number} [maxInFlightRequests=null] The maximum number of unacknowledged requests on a connection before
 *                                            enqueuing
 * @param {InstrumentationEventEmitter} [instrumentationEmitter=null]
 */
module.exports = class Connection {
  constructor({
    host,
    port,
    logger,
    socketFactory,
    rack = null,
    ssl = null,
    sasl = null,
    clientId = 'kafkajs',
    connectionTimeout = 1000,
    requestTimeout = 30000,
    enforceRequestTimeout = false,
    maxInFlightRequests = null,
    instrumentationEmitter = null,
    retry = {},
  }) {
    this.host = host
    this.port = port
    this.rack = rack
    this.clientId = clientId
    this.broker = `${this.host}:${this.port}`
    this.logger = logger.namespace('Connection')

    this.socketFactory = socketFactory
    this.ssl = ssl
    this.sasl = sasl

    this.retry = retry
    this.retrier = createRetry({ ...this.retry })
    this.requestTimeout = requestTimeout
    this.connectionTimeout = connectionTimeout

    this.buffer = Buffer.alloc(0)
    this.connected = false
    this.correlationId = 0
    this.requestQueue = new RequestQueue({
      instrumentationEmitter,
      maxInFlightRequests,
      requestTimeout,
      enforceRequestTimeout,
      clientId,
      broker: this.broker,
      logger: logger.namespace('RequestQueue'),
    })

    this.authHandlers = null
    this.authExpectResponse = false

    const log = level => (message, extra = {}) => {
      const logFn = this.logger[level]
      logFn(message, { broker: this.broker, clientId, ...extra })
    }

    this.logDebug = log('debug')
    this.logError = log('error')

    const env = getEnv()
    this.shouldLogBuffers = env.KAFKAJS_DEBUG_PROTOCOL_BUFFERS === '1'
    this.shouldLogFetchBuffer =
      this.shouldLogBuffers && env.KAFKAJS_DEBUG_EXTENDED_PROTOCOL_BUFFERS === '1'
  }

  /**
   * @public
   * @returns {Promise}
   */
  connect() {
    return new Promise((resolve, reject) => {
      if (this.connected) {
        return resolve(true)
      }

      let timeoutId

      const onConnect = () => {
        clearTimeout(timeoutId)
        this.connected = true
        resolve(true)
      }

      const onData = data => {
        this.processData(data)
      }

      const onEnd = async () => {
        clearTimeout(timeoutId)

        const wasConnected = this.connected
        await this.disconnect()

        if (this.authHandlers) {
          this.authHandlers.onError()
        } else if (wasConnected) {
          this.logDebug('Kafka server has closed connection')
          this.rejectRequests(
            new KafkaJSConnectionError('Closed connection', {
              broker: `${this.host}:${this.port}`,
            })
          )
        }
      }

      const onError = async e => {
        clearTimeout(timeoutId)

        const error = new KafkaJSConnectionError(`Connection error: ${e.message}`, {
          broker: `${this.host}:${this.port}`,
          code: e.code,
        })

        this.logError(error.message, { stack: e.stack })
        await this.disconnect()
        this.rejectRequests(error)

        reject(error)
      }

      const onTimeout = async () => {
        const error = new KafkaJSConnectionError('Connection timeout', {
          broker: `${this.host}:${this.port}`,
        })

        this.logError(error.message)
        await this.disconnect()
        this.rejectRequests(error)
        reject(error)
      }

      this.logDebug(`Connecting`, {
        ssl: !!this.ssl,
        sasl: !!this.sasl,
      })

      try {
        timeoutId = setTimeout(onTimeout, this.connectionTimeout)
        this.socket = createSocket({
          socketFactory: this.socketFactory,
          host: this.host,
          port: this.port,
          ssl: this.ssl,
          onConnect,
          onData,
          onEnd,
          onError,
          onTimeout,
        })
      } catch (e) {
        clearTimeout(timeoutId)
        reject(
          new KafkaJSConnectionError(`Failed to connect: ${e.message}`, {
            broker: `${this.host}:${this.port}`,
          })
        )
      }
    })
  }

  /**
   * @public
   * @returns {Promise}
   */
  async disconnect() {
    if (!this.connected) {
      return true
    }

    this.logDebug('disconnecting...')
    this.connected = false
    this.socket.end()
    this.socket.unref()
    this.logDebug('disconnected')
    return true
  }

  /**
   * @public
   * @returns {Promise}
   */
  authenticate({ authExpectResponse = false, request, response }) {
    this.authExpectResponse = authExpectResponse

    /**
     * TODO: rewrite removing the async promise executor
     */

    /* eslint-disable no-async-promise-executor */
    return new Promise(async (resolve, reject) => {
      this.authHandlers = {
        onSuccess: rawData => {
          this.authHandlers = null
          this.authExpectResponse = false

          response
            .decode(rawData)
            .then(data => response.parse(data))
            .then(resolve)
            .catch(reject)
        },
        onError: () => {
          this.authHandlers = null
          this.authExpectResponse = false

          reject(
            new KafkaJSConnectionError('Connection closed by the server', {
              broker: `${this.host}:${this.port}`,
            })
          )
        },
      }

      try {
        const requestPayload = await request.encode()

        this.failIfNotConnected()
        this.socket.write(requestPayload.buffer, 'binary')
      } catch (e) {
        reject(e)
      }
    })
  }

  /**
   * @public
   * @param {object} request It is defined by the protocol and consists of an object with "apiKey",
   *                         "apiVersion", "apiName" and an "encode" function. The encode function
   *                         must return an instance of Encoder
   *
   * @param {object} response It is defined by the protocol and consists of an object with two functions:
   *                          "decode" and "parse"
   *
   * @param {number} [requestTimeout=null] Override for the default requestTimeout
   * @returns {Promise<data>} where data is the return of "response#parse"
   */
  async send({ request, response, requestTimeout = null }) {
    this.failIfNotConnected()

    const expectResponse = !request.expectResponse || request.expectResponse()
    const sendRequest = async () => {
      const { clientId } = this
      const correlationId = this.nextCorrelationId()

      const requestPayload = await createRequest({ request, correlationId, clientId })
      const { apiKey, apiName, apiVersion } = request
      this.logDebug(`Request ${requestInfo(request)}`, {
        correlationId,
        expectResponse,
        size: Buffer.byteLength(requestPayload.buffer),
      })

      return new Promise((resolve, reject) => {
        try {
          this.failIfNotConnected()
          const entry = { apiKey, apiName, apiVersion, correlationId, resolve, reject }

          this.requestQueue.push({
            entry,
            expectResponse,
            requestTimeout,
            sendRequest: () => {
              this.socket.write(requestPayload.buffer, 'binary')
            },
          })
        } catch (e) {
          reject(e)
        }
      })
    }

    const { correlationId, size, entry, payload } = await sendRequest()

    if (!expectResponse) {
      return
    }

    try {
      const payloadDecoded = await response.decode(payload)
      const data = await response.parse(payloadDecoded)
      const isFetchApi = entry.apiName === 'Fetch'
      this.logDebug(`Response ${requestInfo(entry)}`, {
        correlationId,
        size,
        data: isFetchApi && !this.shouldLogFetchBuffer ? '[filtered]' : data,
      })

      return data
    } catch (e) {
      if (entry.apiName !== 'ApiVersions') {
        this.logError(`Response ${requestInfo(entry)}`, {
          error: e.message,
          correlationId,
          size,
        })
      }

      const isBuffer = Buffer.isBuffer(payload)
      this.logDebug(`Response ${requestInfo(entry)}`, {
        error: e.message,
        correlationId,
        payload:
          isBuffer && !this.shouldLogBuffers ? { type: 'Buffer', data: '[filtered]' } : payload,
      })

      throw e
    }
  }

  /**
   * @private
   */
  failIfNotConnected() {
    if (!this.connected) {
      throw new KafkaJSConnectionError('Not connected', {
        broker: `${this.host}:${this.port}`,
      })
    }
  }

  /**
   * @private
   */
  nextCorrelationId() {
    if (this.correlationId >= INT_32_MAX_VALUE) {
      this.correlationId = 0
    }

    return this.correlationId++
  }

  /**
   * @private
   */
  processData(rawData) {
    if (this.authHandlers && !this.authExpectResponse) {
      return this.authHandlers.onSuccess(rawData)
    }

    this.buffer = Buffer.concat([this.buffer, rawData])

    // Process data if there are enough bytes to read the expected response size,
    // otherwise keep buffering
    while (Buffer.byteLength(this.buffer) > Decoder.int32Size()) {
      const data = Buffer.from(this.buffer)
      const decoder = new Decoder(data)
      const expectedResponseSize = decoder.readInt32()

      if (!decoder.canReadBytes(expectedResponseSize)) {
        return
      }

      const response = new Decoder(decoder.readBytes(expectedResponseSize))
      // Reset the buffer as the rest of the bytes
      this.buffer = decoder.readAll()

      if (this.authHandlers) {
        const rawResponseSize = Decoder.int32Size() + expectedResponseSize
        const rawResponseBuffer = data.slice(0, rawResponseSize)
        return this.authHandlers.onSuccess(rawResponseBuffer)
      }

      const correlationId = response.readInt32()
      const payload = response.readAll()

      this.requestQueue.fulfillRequest({
        size: expectedResponseSize,
        correlationId,
        payload,
      })
    }
  }

  /**
   * @private
   */
  rejectRequests(error) {
    this.requestQueue.rejectAll(error)
  }
}
<|endoftext|>


<commit_before>(function(angular) {
'use strict';

  angular.module('ngPrettyJson')
  .run(['$templateCache', function ($templateCache) {
    $templateCache.put('ng-prettyjson/ng-prettyjson-panel.tmpl.html',
    '
' +
    '<button ng-click="edit()" ng-show="edition && !editActivated">Edit</button>' +
    '<button ng-click="edit()" ng-show="edition && editActivated">Cancel</button>' +
    '<button ng-click="update()" ng-show="editActivated && parsable">Update</button>' +
    '

' +
    '
');
  }]);

})(window.angular);
<commit_msg>Update ng-prettyjson-tmpl.js<commit_after>(function(angular) {
'use strict';

  angular.module('ngPrettyJson')
  .run(['$templateCache', function ($templateCache) {
    $templateCache.put('ng-prettyjson/ng-prettyjson-panel.tmpl.html',
    '
' +
    '<button type="button" ng-click="edit()" ng-show="edition && !editActivated">Edit</button>' +
    '<button type="button" ng-click="edit()" ng-show="edition && editActivated">Cancel</button>' +
    '<button type="button" ng-click="update()" ng-show="editActivated && parsable">Update</button>' +
    '

' +
    '
');
  }]);

})(window.angular);
<|endoftext|>


<commit_before>// A prototypical subject object cunningly written
// to enable easy mixins.
//
var LIB_subject = {

    // "event" is an event name string.
    // "listener" is a callback function.
    //
    // One listener can be added multiple times.
    //
    addEventListener: function(event, listener) {
        this.listeners = this.listeners || {};
        if (this.listeners[event]) {
            this.listeners[event].push(listener);
        }
        else {
            this.listeners[event] = [listener];
        }
    },

    // addEventListener allows one listener to
    // be added multiple times. We removed all references
    // to "listener".
    //
    // No complaints if the "listener" is not found in the list.
    //
    removeEventListener: function(event, listener) {
        if (this.listeners && this.listeners[event]) {
            // Loop backwards through the array so adjacent references
            // to "listener" are all removed.
            for (var i = this.listeners[event].length; i--; ) {
                if (this.listeners[event][i] === listener) {
                    this.listeners[event].splice(i, 1);
                }
            }
        }
    },

    // The "data" will be pushed to each listener.
    // The "data.type" value is required and must be a string name
    // of an event type.
    //
    dispatchEvent: function(data) {
        if (this.listeners && this.listeners[data.type]) {
            // Copy the list of listeners in case one of the
            // listeners modifies the list while we are
            // iterating over the list.
            var listeners = this.listeners[data.type].slice(0);
            for (var i = 0, ilen = listeners.length; i < ilen; i++) {
                listeners[i](data);
            }
        }
    }

};

var LIB_mixinSubject = function(obj) {
    for (var p in LIB_subject) {
        if (Object.prototype.hasOwnProperty.call(LIB_subject, p)) {
            obj[p] = LIB_subject[p];
        }
    }
};

// function APP_Newspaper(name) {
//     this.name = name;
// };
// LIB_mixinSubject(APP_Newspaper.prototype);
//
// var times = new APP_Newspaper('The Times');
// times.addEventListener('publish', function() {});
// times.dispatchEvent({type:'publish'});
<commit_msg>in prototype version can make a subject object also<commit_after>// A prototypical subject object cunningly written
// to enable easy mixins.
//
var LIB_subject = {

    // "event" is an event name string.
    // "listener" is a callback function.
    //
    // One listener can be added multiple times.
    //
    addEventListener: function(event, listener) {
        this.listeners = this.listeners || {};
        if (this.listeners[event]) {
            this.listeners[event].push(listener);
        }
        else {
            this.listeners[event] = [listener];
        }
    },

    // addEventListener allows one listener to
    // be added multiple times. We removed all references
    // to "listener".
    //
    // No complaints if the "listener" is not found in the list.
    //
    removeEventListener: function(event, listener) {
        if (this.listeners && this.listeners[event]) {
            // Loop backwards through the array so adjacent references
            // to "listener" are all removed.
            for (var i = this.listeners[event].length; i--; ) {
                if (this.listeners[event][i] === listener) {
                    this.listeners[event].splice(i, 1);
                }
            }
        }
    },

    // The "data" will be pushed to each listener.
    // The "data.type" value is required and must be a string name
    // of an event type.
    //
    dispatchEvent: function(data) {
        if (this.listeners && this.listeners[data.type]) {
            // Copy the list of listeners in case one of the
            // listeners modifies the list while we are
            // iterating over the list.
            var listeners = this.listeners[data.type].slice(0);
            for (var i = 0, ilen = listeners.length; i < ilen; i++) {
                listeners[i](data);
            }
        }
    }

};

var LIB_mixinSubject = function(obj) {
    for (var p in LIB_subject) {
        if (Object.prototype.hasOwnProperty.call(LIB_subject, p)) {
            obj[p] = LIB_subject[p];
        }
    }
};

var LIB_makeSubject = function() {
    var subject = {};
    LIB_mixinSubject(subject);
    return subject;
};

// function APP_Newspaper(name) {
//     this.name = name;
// };
// LIB_mixinSubject(APP_Newspaper.prototype);
//
// var times = new APP_Newspaper('The Times');
// times.addEventListener('publish', function() {});
// times.dispatchEvent({type:'publish'});
<|endoftext|>