<commit_before>var templates = require("./templates");

// Used to generate a unique view ID
var uniqueViewId = 0;

// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;

// Shadow.View. Basically a stripped-down version of Backbone.View.
var View = function(options) {
    this._setOptions(options || {});
    this._delegateEvents();
};

View.prototype._setOptions = function(options) {
    for(var key in options) {
        this[key] = options[key];
    }

    this.options = options;
    this.cid = 'view' + (uniqueViewId++);
};

View.prototype.$ = function(selector) {
    return this.el.find(selector);
};

View.prototype.on = function(eventName, selector, method) {
    if(arguments.length == 2) {
        method = selector;
        selector = null;
    }

    if('string' == typeof(method)) {
        method = this[method];

        if (!method) {
            throw new Error("Method `" + method + "` bound to event `" + eventName + "` does not exist in this view");
        }

        method = $.proxy(method, this);
    }

    eventName += '.delegateEvents' + this.cid;

    if(selector) {
        this.el.on(eventName, selector, method);
    } else {
        this.el.on(eventName, method);
    }

    return this;
};

View.prototype.off = function(eventName, selector, method) {
    if(arguments.length == 2) {
        method = selector;
        selector = null;
    }

    if('string' == typeof(method)) {
        method = $.proxy(method, this);
    }

    if(selector) {
        this.el.off(eventName, selector, method);
    } else {
        this.el.off(eventName, method);
    }

    return this;
};

View.prototype._delegateEvents = function() {
    this._undelegateEvents();

    for(var key in this.events) {
        var match = key.match(delegateEventSplitter);
        var eventName = match[1], selector = match[2];
        var method = this.events[key];
        this.on(eventName, selector, method);
    }

    return this;
};

View.prototype._undelegateEvents = function() {
    this.el.off('.delegateEvents' + this.cid);
    return this;
};

var TemplatedView = function(options) {
    this._setOptions(options || {});
};

TemplatedView.prototype = Object.create(View.prototype);

TemplatedView.prototype.constructor = TemplatedView;

TemplatedView.prototype.render = function(controller) {
    var template = templates.templates[this.templateName];
    return template(this, controller);
};

module.exports = {
    View: View,
    ComponentView: ComponentView
};
<commit_msg>updated class references<commit_after>var templates = require("./templates");

// Used to generate a unique view ID
var uniqueViewId = 0;

// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;

// Shadow.View. Basically a stripped-down version of Backbone.View.
var View = function(options) {
    this._setOptions(options || {});
    this._delegateEvents();
};

View.prototype._setOptions = function(options) {
    for(var key in options) {
        this[key] = options[key];
    }

    this.options = options;
    this.cid = 'view' + (uniqueViewId++);
};

View.prototype.$ = function(selector) {
    return this.el.find(selector);
};

View.prototype.on = function(eventName, selector, method) {
    if(arguments.length == 2) {
        method = selector;
        selector = null;
    }

    if('string' == typeof(method)) {
        method = this[method];

        if (!method) {
            throw new Error("Method `" + method + "` bound to event `" + eventName + "` does not exist in this view");
        }

        method = $.proxy(method, this);
    }

    eventName += '.delegateEvents' + this.cid;

    if(selector) {
        this.el.on(eventName, selector, method);
    } else {
        this.el.on(eventName, method);
    }

    return this;
};

View.prototype.off = function(eventName, selector, method) {
    if(arguments.length == 2) {
        method = selector;
        selector = null;
    }

    if('string' == typeof(method)) {
        method = $.proxy(method, this);
    }

    if(selector) {
        this.el.off(eventName, selector, method);
    } else {
        this.el.off(eventName, method);
    }

    return this;
};

View.prototype._delegateEvents = function() {
    this._undelegateEvents();

    for(var key in this.events) {
        var match = key.match(delegateEventSplitter);
        var eventName = match[1], selector = match[2];
        var method = this.events[key];
        this.on(eventName, selector, method);
    }

    return this;
};

View.prototype._undelegateEvents = function() {
    this.el.off('.delegateEvents' + this.cid);
    return this;
};

var TemplatedView = function(options) {
    this._setOptions(options || {});
};

TemplatedView.prototype = Object.create(View.prototype);

TemplatedView.prototype.constructor = TemplatedView;

TemplatedView.prototype.render = function(controller) {
    var template = templates.templates[this.templateName];
    return template(this, controller);
};

module.exports = {
    View: View,
    TemplatedView: TemplatedView
};
<|endoftext|>


<commit_before>(function (root) {

    function EventListener() {
        this._ = {};
    }

    EventListener.prototype._on = function (ev, fn) {
        var l = this._[ev] = this._[ev] || [];
        l.push(fn);
        return this;
    };

    EventListener.prototype._emit = function (ev) {
        var self = this
          , args = []
          , event = null
          , l = null
          ;

        if (typeof ev === "object") {
            event = ev.event;
            args = ev.args;
        } else {
            event = ev;
            args = Array.prototype.slice.call(arguments, 1)
        }

        l = this._[event];
        if (!l || !l.length) { return; }

        l.forEach(function (fn) {
            fn.apply(self, args);
        });
    };

    EventListener.prototype.on = EventListener.prototype._on;
    EventListener.prototype.emit = EventListener.prototype._emit;

    var _workers = {};

    function Worky(script, loaded) {

        var self = {};

        if (this.constructor !== Worky && script) {
            return new Worky(script, loaded);
        }

        if (!script) {
            self = Object.create(EventListener.prototype);
        } else {
            self = this;
        }

        EventListener.call(self);
        self.is_worker = !script;

        // We are inside of a worker
        if (!script) {
            root.onmessage = Worky.receiver.call(self);
            self.emit = Worky.emitter.call(root);
            return self;
        }

        // Inside of a window, creating a worker
        self.worker = new Worker(script);
        self.worker.onmessage = Worky.receiver.call(self);
        self.emit = Worky.emitter.call(self.worker);
    }

    Worky.receiver = function () {
        var self = this;
        return function (ev) {
            self._emit(ev.data);
        };
    };

    Worky.emitter = function () {
        var self = this;
        return function () {
            var ev = new Worky.Message(arguments);
            self.postMessage(ev);
        }
    }

    Worky.prototype = Object.create(EventListener.prototype);
    Worky.prototype.constructor = Worky;
    Worky.Message = function (args) {
        args = Array.prototype.slice.call(args);
        //this._ = args[0];
        this.event = args[0];
        this.args = args.slice(1);
    };

    root.Worky = Worky;
})(self);
<commit_msg>JSDoc comments and little code changes<commit_after>(function (root) {

    /**
     * EventEmitter
     * Creates a new `EventEmitter` instance. This is exposed via `Worky.EventEmitter`.
     *
     * @name EventEmitter
     * @function
     * @return {EventEmitter} The `EventEmitter` instance.
     */
    function EventEmitter() {
        this._ = {};
    }

    /**
     * _on
     * The core `on` method. By default `on` is the same with `_on`.
     * However, `on` can be rewritten, but `_on` is still the same.
     *
     * @name _on
     * @function
     * @param {String} ev The event name.
     * @param {Function} fn The listener function.
     * @return {EventEmitter} The `EventEmitter` instance.
     */
    EventEmitter.prototype._on = function (ev, fn) {
        var l = this._[ev] = this._[ev] || [];
        l.push(fn);
        return this;
    };

    /**
     * _emit
     * Emits the passed arguments. By default `emit` is the same with `_emit`.
     * However, `emit` can be rewritten, but `_emit` is still the same.
     *
     * Usage:
     *
     * ```js
     * // Using arguments - this is the convenient way
     * worker.emit("eventName", 42, { some: "object" }, "foo");
     *
     * // Internally, this method is used:
     * worker.emit({
     *     event: "eventName"
     *   , args: [42, { some: "object" }, "foo"]
     * });
     * ```
     *
     * @name _emit
     * @function
     * @param {String|Worky.Message} ev The event name or a `Worky.Message` object.
     * @return {EventEmitter} The `EventEmitter` instance.
     */
    EventEmitter.prototype._emit = function (ev) {

        var self = this
          , args = []
          , event = null
          , l = null
          ;

        if (typeof ev === "object") {
            event = ev.event;
            args = ev.args;
        } else {
            event = ev;
            args = Array.prototype.slice.call(arguments, 1)
        }

        l = this._[event];
        if (!l || !l.length) { return; }

        l.forEach(function (fn) {
            fn.apply(self, args);
        });

        return this;
    };

    EventEmitter.prototype.on = EventEmitter.prototype._on;
    EventEmitter.prototype.emit = EventEmitter.prototype._emit;

    /**
     * Worky
     * Creates or initializes a web worker. This is inherited from
     * the `EventEmitter` class.
     *
     * Usage:
     *
     * ```js
     * // In the main thread (window)
     * var worker = new Worky("some-worker.js");
     *
     * // In the worker thread (some-worker.js)
     * var worker = new Worky();
     * ```
     *
     * @name Worky
     * @function
     * @param {String} script The worker file name.
     * @return {Worky} The `Worky` instance.
     */
    function Worky(script) {

        var self = {};

        if (this.constructor !== Worky && script) {
            return new Worky(script);
        }

        if (!script) {
            self = Object.create(EventEmitter.prototype);
        } else {
            self = this;
        }

        EventEmitter.call(self);
        self.is_worker = !script;

        // Initialize the emit and onmessage handlers
        self.emit = Worky.Emitter.call(self.is_worker ? root : self.worker);
        root.onmessage = Worky.Receiver.call(self);

        // We are inside of a worker
        if (self.is_worker) {
            return self;
        }

        // Inside of a window, creating a worker
        self.worker = new Worker(script);
        self.worker.onmessage = Worky.Receiver.call(self);
    }

    // Expose the EventEmitter class
    Worky.EventEmitter = EventEmitter;

    /**
     * Worky.Receiver
     * Creates the `onmessage` handler. This method is used internally.
     *
     * @name Worky.Receiver
     * @function
     * @return {Function} The receiver handler which calls the core `_emit` function.
     */
    Worky.Receiver = function () {
        var self = this;
        return function (ev) {
            self._emit(ev.data);
        };
    };

    /**
     * Worky.Emitter
     * Creates the `emit` handler. This method is used internally.
     *
     * @name Worky.Emitter
     * @function
     * @return {Function} The emitter handler which calls the `postMessage` function.
     */
    Worky.Emitter = function () {
        var self = this;
        return function () {
            var ev = new Worky.Message(arguments);
            self.postMessage(ev);
        }
    }

    /**
     * Worky.Message
     * Creates a new `Message` instance
     *
     * @name Worky.Message
     * @function
     * @param {Arguments} args The arguments pseudo-array.
     * @return {Worky.Message} The `Message` instance containing the following fields:
     */
    Worky.Message = function (args) {
        args = Array.prototype.slice.call(args);
        //this._ = args[0];
        this.event = args[0];
        this.args = args.slice(1);
    };

    // Inherit the EventEmitter functions
    Worky.prototype = Object.create(EventEmitter.prototype);
    Worky.prototype.constructor = Worky;

    root.Worky = Worky;
})(self);
<|endoftext|>


<commit_before>module.exports = function (data, target) {
    'use strict';

    target.on('error', function (err) {
        console.error(err);
    });

    target.write(data);
};
<commit_msg>write output utf8-encoded<commit_after>module.exports = function (data, target) {
    'use strict';

    target.on('error', function (err) {
        console.error(err);
    });

    target.write(data, 'utf8');
};
<|endoftext|>


<commit_before>/** @namespace * */
var XML3D = XML3D || {};

/** @define {string} */
XML3D.version = '%VERSION%';
/** @const */
XML3D.xml3dNS = 'http://www.xml3d.org/2009/xml3d';
/** @const */
XML3D.xhtmlNS = 'http://www.w3.org/1999/xhtml';
/** @const */
XML3D.webglNS = 'http://www.xml3d.org/2009/xml3d/webgl';
XML3D._xml3d = document.createElementNS(XML3D.xml3dNS, "xml3d");
XML3D._native = !!XML3D._xml3d.style;
XML3D._parallel = XML3D._parallel != undefined ? XML3D._parallel : false;

XML3D.createElement = function(tagName) {
    return document.createElementNS(XML3D.xml3dNS, tagName);
};

XML3D.extend = function(a, b) {
    for ( var prop in b) {
        if (b[prop] === undefined) {
            delete a[prop];
        } else if (prop !== "constructor" || a !== window) {
            a[prop] = b[prop];
        }
    }
    return a;
};

/**
 * Returns true if ctor is a superclass of subclassCtor.
 * @param ctor
 * @param subclassCtor
 * @return {Boolean}
 */
XML3D.isSuperclassOf = function(ctor, subclassCtor) {
    while (subclassCtor && subclassCtor.superclass) {
        if (subclassCtor.superclass === ctor.prototype)
            return true;
        subclassCtor = subclassCtor.superclass.constructor;
    }
    return false;
}

/**
 *
 * @param {Object} ctor Constructor
 * @param {Object} parent Parent class
 * @param {Object=} methods Methods to add to the class
 * @returns
 */
XML3D.createClass = function(ctor, parent, methods) {
    methods = methods || {};
    if (parent) {
        /** @constructor */
        var F = function() {
        };
        F.prototype = parent.prototype;
        ctor.prototype = new F();
        ctor.prototype.constructor = ctor;
        ctor.superclass = parent.prototype;
    }
    ctor.isSuperclassOf = XML3D.isSuperclassOf.bind(ctor, ctor);
    for ( var m in methods) {
        ctor.prototype[m] = methods[m];
    }
    return ctor;
};

(function() {
    function displayWebGLNotSupportedInfo(xml3dElement) {

        // Place xml3dElement inside an invisible div
        var hideDiv = document.createElementNS(XML3D.xhtmlNS, 'div');

        xml3dElement.parentNode.insertBefore(hideDiv, xml3dElement);
        hideDiv.appendChild(xml3dElement);
        hideDiv.style.display = "none";

        var infoDiv = document.createElementNS(XML3D.xhtmlNS, 'div');
        infoDiv.setAttribute("class", xml3dElement.getAttribute("class"));
        infoDiv.setAttribute("style", xml3dElement.getAttribute("style"));
        infoDiv.style.border = "2px solid red";
        infoDiv.style.color = "red";
        infoDiv.style.padding = "10px";
        infoDiv.style.backgroundColor = "rgba(255, 0, 0, 0.3)";

        var width = xml3dElement.getAttribute("width");
        if (width !== null) {
            infoDiv.style.width = width;
        }

        var height = xml3dElement.getAttribute("height");
        if (height !== null) {
            infoDiv.style.height = height;
        }

        var hElement = document.createElement("h3");
        var hTxt = document.createTextNode("Your browser doesn't appear to support XML3D.");
        hElement.appendChild(hTxt);

        var pElement = document.createElement("p");
        pElement.appendChild(document.createTextNode("Please visit "));
        var link = document.createElement("a");
        link.setAttribute("href", "http://www.xml3d.org");
        link.appendChild(document.createTextNode("http://www.xml3d.org"));
        pElement.appendChild(link);
        pElement.appendChild(document.createTextNode(" to get information about browsers supporting XML3D."));
        infoDiv.appendChild(hElement);
        infoDiv.appendChild(pElement);

        hideDiv.parentNode.insertBefore(infoDiv, hideDiv);
    };

    function initXML3DElement(xml3dElement) {

        if (XML3D._native)
            return;

        var debug = XML3D.debug.setup();

        if (!(XML3D.webgl && XML3D.webgl.supported())) {
            debug && XML3D.debug.logWarning("Could not initialise WebGL, sorry :-(");
            displayWebGLNotSupportedInfo(xml3dElement);
            return;
        }

        try {
            XML3D.config.configure(xml3dElement);
        } catch (e) {
            debug && XML3D.debug.logException(e);
            return;
        }
        try {
            XML3D.webgl.configure(xml3dElement);
        } catch (e) {
            debug && XML3D.debug.logException(e);
            return;
        }

        // initialize all attached adapters
        XML3D.base.sendAdapterEvent(xml3dElement, {onConfigured : []});
    };

    function onNodeInsertedIntoDocument(evt) {

        if(evt.target.tagName === "xml3d") {
            initXML3DElement(evt.target);
        }
    };

    function onLoad() {

        XML3D.css.init();

        var debug = XML3D.debug.setup();
        debug && XML3D.debug.logInfo("xml3d.js version: " + XML3D.version);

        // Find all the XML3D tags in the document
        var xml3ds = document.querySelectorAll("xml3d");
        xml3ds = Array.map(xml3ds, function(n) {
            return n;
        });

        debug && XML3D.debug.logInfo("Found " + xml3ds.length + " xml3d nodes...");

        if (xml3ds.length && XML3D._native) {
            debug && XML3D.debug.logInfo("Using native implementation.");
            return;
        }

        for(var i = 0; i < xml3ds.length; i++) {
            initXML3DElement(xml3ds[i]);
        }
    };

    function onUnload() {
        if (XML3D.document)
            XML3D.document.onunload();
    };

    window.addEventListener('DOMContentLoaded', onLoad, false);
    window.addEventListener('unload', onUnload, false);
    window.addEventListener('reload', onUnload, false);
    window.addEventListener('DOMNodeInsertedIntoDocument', onNodeInsertedIntoDocument, false);

})();
<commit_msg>xml3d-loading: fixed bug<commit_after>/** @namespace * */
var XML3D = XML3D || {};

/** @define {string} */
XML3D.version = '%VERSION%';
/** @const */
XML3D.xml3dNS = 'http://www.xml3d.org/2009/xml3d';
/** @const */
XML3D.xhtmlNS = 'http://www.w3.org/1999/xhtml';
/** @const */
XML3D.webglNS = 'http://www.xml3d.org/2009/xml3d/webgl';
XML3D._xml3d = document.createElementNS(XML3D.xml3dNS, "xml3d");
XML3D._native = !!XML3D._xml3d.style;
XML3D._parallel = XML3D._parallel != undefined ? XML3D._parallel : false;

XML3D.createElement = function(tagName) {
    return document.createElementNS(XML3D.xml3dNS, tagName);
};

XML3D.extend = function(a, b) {
    for ( var prop in b) {
        if (b[prop] === undefined) {
            delete a[prop];
        } else if (prop !== "constructor" || a !== window) {
            a[prop] = b[prop];
        }
    }
    return a;
};

/**
 * Returns true if ctor is a superclass of subclassCtor.
 * @param ctor
 * @param subclassCtor
 * @return {Boolean}
 */
XML3D.isSuperclassOf = function(ctor, subclassCtor) {
    while (subclassCtor && subclassCtor.superclass) {
        if (subclassCtor.superclass === ctor.prototype)
            return true;
        subclassCtor = subclassCtor.superclass.constructor;
    }
    return false;
}

/**
 *
 * @param {Object} ctor Constructor
 * @param {Object} parent Parent class
 * @param {Object=} methods Methods to add to the class
 * @returns
 */
XML3D.createClass = function(ctor, parent, methods) {
    methods = methods || {};
    if (parent) {
        /** @constructor */
        var F = function() {
        };
        F.prototype = parent.prototype;
        ctor.prototype = new F();
        ctor.prototype.constructor = ctor;
        ctor.superclass = parent.prototype;
    }
    ctor.isSuperclassOf = XML3D.isSuperclassOf.bind(ctor, ctor);
    for ( var m in methods) {
        ctor.prototype[m] = methods[m];
    }
    return ctor;
};

(function() {
    function displayWebGLNotSupportedInfo(xml3dElement) {

        // Place xml3dElement inside an invisible div
        var hideDiv = document.createElementNS(XML3D.xhtmlNS, 'div');

        xml3dElement.parentNode.insertBefore(hideDiv, xml3dElement);
        hideDiv.appendChild(xml3dElement);
        hideDiv.style.display = "none";

        var infoDiv = document.createElementNS(XML3D.xhtmlNS, 'div');
        infoDiv.setAttribute("class", xml3dElement.getAttribute("class"));
        infoDiv.setAttribute("style", xml3dElement.getAttribute("style"));
        infoDiv.style.border = "2px solid red";
        infoDiv.style.color = "red";
        infoDiv.style.padding = "10px";
        infoDiv.style.backgroundColor = "rgba(255, 0, 0, 0.3)";

        var width = xml3dElement.getAttribute("width");
        if (width !== null) {
            infoDiv.style.width = width;
        }

        var height = xml3dElement.getAttribute("height");
        if (height !== null) {
            infoDiv.style.height = height;
        }

        var hElement = document.createElement("h3");
        var hTxt = document.createTextNode("Your browser doesn't appear to support XML3D.");
        hElement.appendChild(hTxt);

        var pElement = document.createElement("p");
        pElement.appendChild(document.createTextNode("Please visit "));
        var link = document.createElement("a");
        link.setAttribute("href", "http://www.xml3d.org");
        link.appendChild(document.createTextNode("http://www.xml3d.org"));
        pElement.appendChild(link);
        pElement.appendChild(document.createTextNode(" to get information about browsers supporting XML3D."));
        infoDiv.appendChild(hElement);
        infoDiv.appendChild(pElement);

        hideDiv.parentNode.insertBefore(infoDiv, hideDiv);
    };

    function initXML3DElement(xml3dElement) {

        if (XML3D._native)
            return;

        var debug = XML3D.debug.setup();

        if (!(XML3D.webgl && XML3D.webgl.supported())) {
            debug && XML3D.debug.logWarning("Could not initialise WebGL, sorry :-(");
            displayWebGLNotSupportedInfo(xml3dElement);
            return;
        }

        try {
            XML3D.config.configure(xml3dElement);
        } catch (e) {
            debug && XML3D.debug.logException(e);
            return;
        }
        try {
            XML3D.webgl.configure(xml3dElement);
        } catch (e) {
            debug && XML3D.debug.logException(e);
            return;
        }

        // initialize all attached adapters
        XML3D.base.sendAdapterEvent(xml3dElement, {onConfigured : []});
    };

    function onNodeInserted(evt) {

        if(evt.target.tagName === "xml3d") {
            initXML3DElement(evt.target);
        }
    };

    function onLoad() {

        XML3D.css.init();

        var debug = XML3D.debug.setup();
        debug && XML3D.debug.logInfo("xml3d.js version: " + XML3D.version);

        // Find all the XML3D tags in the document
        var xml3ds = document.querySelectorAll("xml3d");
        xml3ds = Array.map(xml3ds, function(n) {
            return n;
        });

        debug && XML3D.debug.logInfo("Found " + xml3ds.length + " xml3d nodes...");

        if (xml3ds.length && XML3D._native) {
            debug && XML3D.debug.logInfo("Using native implementation.");
            return;
        }

        for(var i = 0; i < xml3ds.length; i++) {
            initXML3DElement(xml3ds[i]);
        }
    };

    function onUnload() {
        if (XML3D.document)
            XML3D.document.onunload();
    };

    window.addEventListener('DOMContentLoaded', onLoad, false);
    window.addEventListener('unload', onUnload, false);
    window.addEventListener('reload', onUnload, false);
    document.addEventListener('DOMNodeInserted', onNodeInserted, false);

})();
<|endoftext|>


<commit_before>/** @namespace * */
var XML3D = XML3D || {};

/** @define {string} */
XML3D.version = '%VERSION%';
/** @const */
XML3D.xml3dNS = 'http://www.xml3d.org/2009/xml3d';
/** @const */
XML3D.xhtmlNS = 'http://www.w3.org/1999/xhtml';
/** @const */
XML3D.webglNS = 'http://www.xml3d.org/2009/xml3d/webgl';
XML3D._xml3d = document.createElementNS(XML3D.xml3dNS, "xml3d");
XML3D._native = !!XML3D._xml3d.style;
XML3D._parallel = XML3D._parallel != undefined ? XML3D._parallel : false;

(function () {
    if (navigator.userAgent.match(/(iPad|iPhone|iPod touch)/i)) {
        var m = document.createElement("meta");
        m.name = "format-detection";
        m.content = "telephone=no";
        document.head.appendChild(m)
    }
}());

XML3D.createElement = function(tagName) {
    return document.createElementNS(XML3D.xml3dNS, tagName);
};

XML3D.extend = function(a, b) {
    for ( var prop in b) {
        var g = b.__lookupGetter__(prop), s = b.__lookupSetter__(prop);
        if (g||s) {
            if (g) {
                a.__defineGetter__(prop, g);
            }
            if (s) {
                a.__defineSetter__(prop, s);
            }
        } else {
            if (b[prop] === undefined) {
                delete a[prop];
            } else if (prop !== "constructor" || a !== window) {
                a[prop] = b[prop];
            }
        }
    }
    return a;
};

/**
 * Returns true if ctor is a superclass of subclassCtor.
 * @param ctor
 * @param subclassCtor
 * @return {Boolean}
 */
XML3D.isSuperclassOf = function(ctor, subclassCtor) {
    while (subclassCtor && subclassCtor.superclass) {
        if (subclassCtor.superclass === ctor.prototype)
            return true;
        subclassCtor = subclassCtor.superclass.constructor;
    }
    return false;
}

/**
 *
 * @param {Object} ctor Constructor
 * @param {Object} parent Parent class
 * @param {Object=} methods Methods to add to the class
 * @return {Object!}
 */
XML3D.createClass = function(ctor, parent, methods) {
    methods = methods || {};
    if (parent) {
        /** @constructor */
        var F = function() {
        };
        F.prototype = parent.prototype;
        ctor.prototype = new F();
        ctor.prototype.constructor = ctor;
        ctor.superclass = parent.prototype;
    }
    ctor.isSuperclassOf = XML3D.isSuperclassOf.bind(ctor, ctor);
    for ( var m in methods) {
        ctor.prototype[m] = methods[m];
    }
    return ctor;
};

(function() {
    function displayWebGLNotSupportedInfo(xml3dElement){

        if(xml3dElement.hasAttribute("onunsupported")){
            var callback = new Function("event", xml3dElement.getAttribute("onunsupported"));
            xml3dElement.addEventListener('unsupported', callback, false);
        }
        var doDefault = XML3D.util.dispatchCustomEvent(xml3dElement, 'unsupported', false, true, null);
        if(doDefault){
            // Place xml3dElement inside an invisible div
            var hideDiv = document.createElementNS(XML3D.xhtmlNS, 'div');

            xml3dElement.parentNode.insertBefore(hideDiv, xml3dElement);
            hideDiv.appendChild(xml3dElement);
            hideDiv.style.display = "none";

            var infoDiv = document.createElementNS(XML3D.xhtmlNS, 'div');
            if(xml3dElement.hasAttribute("class")){
                infoDiv.setAttribute("class", xml3dElement.getAttribute("class"));
            }

            infoDiv.setAttribute("style", xml3dElement.getAttribute("style"));
            infoDiv.style.border = "2px solid red";
            infoDiv.style.color = "red";
            infoDiv.style.padding = "10px";
            infoDiv.style.backgroundColor = "rgba(255, 0, 0, 0.3)";

            var width = xml3dElement.getAttribute("width");
            if (width !== null) {
                infoDiv.style.width = width;
            }

            var height = xml3dElement.getAttribute("height");
            if (height !== null) {
                infoDiv.style.height = height;
            }

            var hElement = document.createElement("h3");
            var hTxt = document.createTextNode("Your browser doesn't appear to support XML3D.");
            hElement.appendChild(hTxt);

            var pElement = document.createElement("p");
            pElement.appendChild(document.createTextNode("Please visit "));
            var link = document.createElement("a");
            link.setAttribute("href", "http://www.xml3d.org");
            link.appendChild(document.createTextNode("http://www.xml3d.org"));
            pElement.appendChild(link);
            pElement.appendChild(document.createTextNode(" to get information about browsers supporting XML3D."));
            infoDiv.appendChild(hElement);
            infoDiv.appendChild(pElement);

            hideDiv.parentNode.insertBefore(infoDiv, hideDiv);
        }

    };

    /*  a list of elements that are currently initialized. More specifically,
     *  they're currently in a call to the method below.
     *
     *  Why?
     *  In webgl we actually reattach the xml3d element in the DOM. Thus, when
     *  we're in the middle of working on a onNodeInserted event, there will probably
     *  come right another event which we actually don't care for.
     *  So we use this list to keep track of which elements are currently initializing.
     */
    var curXML3DInitElements = [];

    /**
     * @param {Element} xml3dElement
     */
    function initXML3DElement(xml3dElement) {

        if (XML3D._native)
            return;

        if(-1 < curXML3DInitElements.indexOf(xml3dElement))
            return;

        curXML3DInitElements.push(xml3dElement);

        var debug = XML3D.debug.setup();

        if (!(XML3D.webgl && XML3D.webgl.supported())) {
            debug && XML3D.debug.logWarning("Could not initialise WebGL, sorry :-(");
            displayWebGLNotSupportedInfo(xml3dElement);
            curXML3DInitElements.splice(curXML3DInitElements.indexOf(xml3dElement), 1);
            return;
        }

        XML3D.debug.logInfo("Configuring", xml3dElement.querySelectorAll("*").length, "elements");

        try {
            XML3D.config.configure(xml3dElement);
        } catch (e) {
            debug && XML3D.debug.logException(e);
            curXML3DInitElements.splice(curXML3DInitElements.indexOf(xml3dElement), 1);
            return;
        }
        try {
            XML3D.webgl.configure(xml3dElement);
        } catch (e) {
            debug && XML3D.debug.logException(e);
            curXML3DInitElements.splice(curXML3DInitElements.indexOf(xml3dElement), 1);
            return;
        }

        // initialize all attached adapters
        XML3D.base.sendAdapterEvent(xml3dElement, {onConfigured : []});

        curXML3DInitElements.splice(curXML3DInitElements.indexOf(xml3dElement), 1);
    };

    /**
     * @param {Element} xml3dElement
     */
    function destroyXML3DElement(xml3dElement)
    {
        if(-1 < curXML3DInitElements.indexOf(xml3dElement))
            return;

        xml3dElement._configured = undefined;

        if(!xml3dElement.parentNode)
            return; // already removed

        var canvas = xml3dElement.parentNode.previousElementSibling;

        var grandParentNode = xml3dElement.parentNode.parentNode;
        if(!grandParentNode)
            return; // subtree containing canvas is not attached, can't remove it

        if(!canvas || canvas.tagName !== "canvas")
            return; // an element we didn't create, skip deletion

        grandParentNode.removeChild(xml3dElement.parentNode);
        grandParentNode.removeChild(canvas);
    };

    /**
     * @param {Event} evt
     */
    function onNodeInserted(evt) {

        if(evt.target.tagName === "xml3d") {
            initXML3DElement(evt.target);
        }
    };

    /**
     * @param {Event} evt
     */
    function onNodeRemoved(evt) {

        if(evt.target.tagName === "xml3d") {
            destroyXML3DElement(evt.target);
        }
    };

    function onLoad() {

        XML3D.options.setOptionsFromQuery();

        XML3D.css.init();

        var debug = XML3D.debug.setup();
        debug && XML3D.debug.logInfo("xml3d.js version: " + XML3D.version);

        /**
         * Find all the XML3D tags in the document
         * @type {NodeList}
         */
        var xml3ds = document.querySelectorAll("xml3d");

        debug && XML3D.debug.logInfo("Found " + xml3ds.length + " xml3d node(s)");

        if (xml3ds.length && XML3D._native) {
            debug && XML3D.debug.logInfo("Using native implementation.");
            return;
        }

        XML3D.xhtml = (document.xmlEncoding != null);

        for(var i = 0; i < xml3ds.length; i++) {
            initXML3DElement(xml3ds[i]);
        }
    };

    function onUnload() {
        if (XML3D.document)
            XML3D.document.onunload();
    };

    document.addEventListener('DOMContentLoaded', onLoad, false);
    window.addEventListener('unload', onUnload, false);
    window.addEventListener('reload', onUnload, false);
    document.addEventListener('DOMNodeInserted', onNodeInserted, false);
    document.addEventListener('DOMNodeRemoved', onNodeRemoved, false);

})();
<commit_msg>Annihilated last remaining MutationEvents.<commit_after>/** @namespace * */
var XML3D = XML3D || {};

/** @define {string} */
XML3D.version = '%VERSION%';
/** @const */
XML3D.xml3dNS = 'http://www.xml3d.org/2009/xml3d';
/** @const */
XML3D.xhtmlNS = 'http://www.w3.org/1999/xhtml';
/** @const */
XML3D.webglNS = 'http://www.xml3d.org/2009/xml3d/webgl';
XML3D._xml3d = document.createElementNS(XML3D.xml3dNS, "xml3d");
XML3D._native = !!XML3D._xml3d.style;
XML3D._parallel = XML3D._parallel != undefined ? XML3D._parallel : false;

(function () {
    if (navigator.userAgent.match(/(iPad|iPhone|iPod touch)/i)) {
        var m = document.createElement("meta");
        m.name = "format-detection";
        m.content = "telephone=no";
        document.head.appendChild(m)
    }
}());

XML3D.createElement = function(tagName) {
    return document.createElementNS(XML3D.xml3dNS, tagName);
};

XML3D.extend = function(a, b) {
    for ( var prop in b) {
        var g = b.__lookupGetter__(prop), s = b.__lookupSetter__(prop);
        if (g||s) {
            if (g) {
                a.__defineGetter__(prop, g);
            }
            if (s) {
                a.__defineSetter__(prop, s);
            }
        } else {
            if (b[prop] === undefined) {
                delete a[prop];
            } else if (prop !== "constructor" || a !== window) {
                a[prop] = b[prop];
            }
        }
    }
    return a;
};

/**
 * Returns true if ctor is a superclass of subclassCtor.
 * @param ctor
 * @param subclassCtor
 * @return {Boolean}
 */
XML3D.isSuperclassOf = function(ctor, subclassCtor) {
    while (subclassCtor && subclassCtor.superclass) {
        if (subclassCtor.superclass === ctor.prototype)
            return true;
        subclassCtor = subclassCtor.superclass.constructor;
    }
    return false;
}

/**
 *
 * @param {Object} ctor Constructor
 * @param {Object} parent Parent class
 * @param {Object=} methods Methods to add to the class
 * @return {Object!}
 */
XML3D.createClass = function(ctor, parent, methods) {
    methods = methods || {};
    if (parent) {
        /** @constructor */
        var F = function() {
        };
        F.prototype = parent.prototype;
        ctor.prototype = new F();
        ctor.prototype.constructor = ctor;
        ctor.superclass = parent.prototype;
    }
    ctor.isSuperclassOf = XML3D.isSuperclassOf.bind(ctor, ctor);
    for ( var m in methods) {
        ctor.prototype[m] = methods[m];
    }
    return ctor;
};

(function() {
    function displayWebGLNotSupportedInfo(xml3dElement){

        if(xml3dElement.hasAttribute("onunsupported")){
            var callback = new Function("event", xml3dElement.getAttribute("onunsupported"));
            xml3dElement.addEventListener('unsupported', callback, false);
        }
        var doDefault = XML3D.util.dispatchCustomEvent(xml3dElement, 'unsupported', false, true, null);
        if(doDefault){
            // Place xml3dElement inside an invisible div
            var hideDiv = document.createElementNS(XML3D.xhtmlNS, 'div');

            xml3dElement.parentNode.insertBefore(hideDiv, xml3dElement);
            hideDiv.appendChild(xml3dElement);
            hideDiv.style.display = "none";

            var infoDiv = document.createElementNS(XML3D.xhtmlNS, 'div');
            if(xml3dElement.hasAttribute("class")){
                infoDiv.setAttribute("class", xml3dElement.getAttribute("class"));
            }

            infoDiv.setAttribute("style", xml3dElement.getAttribute("style"));
            infoDiv.style.border = "2px solid red";
            infoDiv.style.color = "red";
            infoDiv.style.padding = "10px";
            infoDiv.style.backgroundColor = "rgba(255, 0, 0, 0.3)";

            var width = xml3dElement.getAttribute("width");
            if (width !== null) {
                infoDiv.style.width = width;
            }

            var height = xml3dElement.getAttribute("height");
            if (height !== null) {
                infoDiv.style.height = height;
            }

            var hElement = document.createElement("h3");
            var hTxt = document.createTextNode("Your browser doesn't appear to support XML3D.");
            hElement.appendChild(hTxt);

            var pElement = document.createElement("p");
            pElement.appendChild(document.createTextNode("Please visit "));
            var link = document.createElement("a");
            link.setAttribute("href", "http://www.xml3d.org");
            link.appendChild(document.createTextNode("http://www.xml3d.org"));
            pElement.appendChild(link);
            pElement.appendChild(document.createTextNode(" to get information about browsers supporting XML3D."));
            infoDiv.appendChild(hElement);
            infoDiv.appendChild(pElement);

            hideDiv.parentNode.insertBefore(infoDiv, hideDiv);
        }

    };

    /*  a list of elements that are currently initialized. More specifically,
     *  they're currently in a call to the method below.
     *
     *  Why?
     *  In webgl we actually reattach the xml3d element in the DOM. Thus, when
     *  we're in the middle of working on a onNodeInserted event, there will probably
     *  come right another event which we actually don't care for.
     *  So we use this list to keep track of which elements are currently initializing.
     */
    var curXML3DInitElements = [];

    /**
     * @param {Element} xml3dElement
     */
    function initXML3DElement(xml3dElement) {
        if (XML3D._native)
            return;

        if(-1 < curXML3DInitElements.indexOf(xml3dElement))
            return;

        curXML3DInitElements.push(xml3dElement);

        var debug = XML3D.debug.setup();

        if (!(XML3D.webgl && XML3D.webgl.supported())) {
            debug && XML3D.debug.logWarning("Could not initialise WebGL, sorry :-(");
            displayWebGLNotSupportedInfo(xml3dElement);
            curXML3DInitElements.splice(curXML3DInitElements.indexOf(xml3dElement), 1);
            return;
        }

        XML3D.debug.logInfo("Configuring", xml3dElement.querySelectorAll("*").length, "elements");

        try {
            XML3D.config.configure(xml3dElement);
        } catch (e) {
            debug && XML3D.debug.logException(e);
            curXML3DInitElements.splice(curXML3DInitElements.indexOf(xml3dElement), 1);
            return;
        }
        try {
            XML3D.webgl.configure(xml3dElement);
        } catch (e) {
            debug && XML3D.debug.logException(e);
            curXML3DInitElements.splice(curXML3DInitElements.indexOf(xml3dElement), 1);
            return;
        }

        // initialize all attached adapters
        XML3D.base.sendAdapterEvent(xml3dElement, {onConfigured : []});

        curXML3DInitElements.splice(curXML3DInitElements.indexOf(xml3dElement), 1);
        clearObserver();
    };

    /**
     * @param {Element} xml3dElement
     */
    function destroyXML3DElement(xml3dElement)
    {
        if(-1 < curXML3DInitElements.indexOf(xml3dElement))
            return;

        xml3dElement._configured = undefined;

        if(!xml3dElement.parentNode)
            return; // already removed

        var canvas = xml3dElement.parentNode.previousElementSibling;

        var grandParentNode = xml3dElement.parentNode.parentNode;
        if(!grandParentNode)
            return; // subtree containing canvas is not attached, can't remove it

        if(!canvas || canvas.tagName !== "canvas")
            return; // an element we didn't create, skip deletion

        grandParentNode.removeChild(xml3dElement.parentNode);
        grandParentNode.removeChild(canvas);
    };

    /**
     * @param {Event} evt
     */
    function onNodeInserted(evt) {

        if(evt.target.tagName === "xml3d") {
            initXML3DElement(evt.target);
        }
    };

    /**
     * @param {Event} evt
     */
    function onNodeRemoved(evt) {

        if(evt.target.tagName === "xml3d") {
            destroyXML3DElement(evt.target);
        }
    };

    function onLoad() {

        XML3D.options.setOptionsFromQuery();

        XML3D.css.init();

        var debug = XML3D.debug.setup();
        debug && XML3D.debug.logInfo("xml3d.js version: " + XML3D.version);

        /**
         * Find all the XML3D tags in the document
         * @type {NodeList}
         */
        var xml3ds = document.querySelectorAll("xml3d");

        debug && XML3D.debug.logInfo("Found " + xml3ds.length + " xml3d node(s)");

        if (xml3ds.length && XML3D._native) {
            debug && XML3D.debug.logInfo("Using native implementation.");
            return;
        }

        XML3D.xhtml = (document.xmlEncoding != null);

        for(var i = 0; i < xml3ds.length; i++) {
            initXML3DElement(xml3ds[i]);
        }

        if(!MutationObserver){
            document.addEventListener('DOMNodeInserted', onNodeInserted, false);
            document.addEventListener('DOMNodeRemoved', onNodeRemoved, false);
        }
        else{
            observer = new MutationObserver(resolveMutations);
            observer.observe(document.documentElement, { childList: true, subtree: true} );
        }
    };

    function onUnload() {
        if (XML3D.document)
            XML3D.document.onunload();
    };

    var MutationObserver = (window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver),
        observer = null;

    function resolveMutations(mutations){
        for(var i = 0; i < mutations.length; ++i){
            var mutation = mutations[i];
            if(mutation.type == 'childList'){
                var addedNodes = mutation.addedNodes;
                var j = addedNodes.length;
                while(j--){
                    if(addedNodes[j].tagName == "xml3d")
                        initXML3DElement(addedNodes[j]);
                }
                var removedNodes = mutation.removedNodes;
                var j = removedNodes.length;
                while(j--) {
                    if(removedNodes[j].tagName == "xml3d")
                        destroyXML3DElement(removedNodes[j]);
                }

            }
        }
    }

    function flushObserver(){
        if(observer){
            resolveMutations(observer.takeRecords());
        }
    }
    function clearObserver(){
        if(observer){
            observer.takeRecords();
        }
    }

    document.addEventListener('DOMContentLoaded', onLoad, false);
    window.addEventListener('unload', onUnload, false);
    window.addEventListener('reload', onUnload, false);

})();
<|endoftext|>


<commit_before>var Zepto = (function() {
  var slice = [].slice, key, css, $$, fragmentRE, container, document = window.document, undefined,
    classList, elemDisplay = {},
    getComputedStyle = document.defaultView.getComputedStyle;

  function classRE(name){ return new RegExp('(^|\\s)' + name + '(\\s|$)') }
  function compact(array){ return array.filter(function(item){ return item !== undefined && item !== null }) }
  function flatten(array){ return [].concat.apply([], array); }
  function camelize(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
  function defaultDisplay(nodeName) {
    if (!elemDisplay[nodeName]) {
      var elem = document.createElement(nodeName);
      document.body.insertAdjacentElement("beforeEnd", elem);
      var display = getComputedStyle(elem, '').getPropertyValue("display");
      elem.parentNode.removeChild(elem);
      display == "none" && (display = "block");
      elemDisplay[nodeName] = display
    }
    return elemDisplay[nodeName]
  }
  function uniq(array){
    var r = [];
    for(var i=0,n=array.length;i<n;i++)
      if(r.indexOf(array[i])<0) r.push(array[i]);
    return r;
  }
  function isF(value) { return ({}).toString.call(value) == "[object Function]" }
  function isO(value) { return value instanceof Object }
  function isA(value) { return value instanceof Array }

  fragmentRE = /^\s*<[^>]+>/;
  container = document.createElement('div');
  function fragment(html) {
    container.innerHTML = ('' + html).trim();
    var result = slice.call(container.childNodes);
    container.innerHTML = '';
    return result;
  }

  function Z(dom, selector){
    dom = dom || [];
    dom.__proto__ = Z.prototype;
    dom.selector = selector || '';
    return dom;
  }

  function $(selector, context){
    if (!selector) return Z();
    if (context !== undefined) return $(context).find(selector);
    else if (isF(selector)) return $(document).ready(selector);
    else if (selector instanceof Z) return selector;
    else {
      var dom;
      if (isA(selector)) dom = compact(selector);
      else if (selector instanceof Element || selector === window || selector === document)
        dom = [selector], selector = null;
      else if (fragmentRE.test(selector)) dom = fragment(selector);
      else if (selector.nodeType && selector.nodeType == 3) dom = [selector];
      else dom = $$(document, selector);
      return Z(dom, selector);
    }
  }

  $.extend = function(target, source){ for (key in source) target[key] = source[key]; return target }
  $.qsa = $$ = function(element, selector){ return slice.call(element.querySelectorAll(selector)) }

  function filtered(nodes, selector){
    return selector === undefined ? $(nodes) : $(nodes).filter(selector);
  }

  function funcArg(context,arg,idx,payload){
   return isF(arg) ? arg.call(context, idx, payload) : arg;
  }

  $.isFunction = isF;
  $.isObject = isO;
  $.isArray = isA;

  $.fn = {
    forEach: [].forEach,
    map: [].map,
    reduce: [].reduce,
    push: [].push,
    indexOf: [].indexOf,
    concat: [].concat,
    ready: function(callback){
      if (document.readyState == 'complete' || document.readyState == 'loaded') callback();
      document.addEventListener('DOMContentLoaded', callback, false); return this;
    },
    get: function(idx){ return idx === undefined ? this : this[idx] },
    size: function(){ return this.length },
    remove: function(){ return this.each(function(){ this.parentNode.removeChild(this) }) },
    each: function(callback){
      this.forEach(function(el, idx){ callback.call(el, idx, el) });
      return this;
    },
    filter: function(selector){
      return $([].filter.call(this, function(element){
        return $$(element.parentNode, selector).indexOf(element) >= 0;
      }));
    },
    is: function(selector){
      return this.length > 0 && $(this[0]).filter(selector).length > 0;
    },
    not: function(selector){
      var nodes=[];
      if (isF(selector) && selector.call !== undefined)
        this.each(function(idx){
          if (!selector.call(this,idx)) nodes.push(this);
        });
      else {
        var ignores = slice.call(
          typeof selector == 'string' ?
            this.filter(selector) :
            selector instanceof NodeList ? selector : $(selector));
        slice.call(this).forEach(function(el){
          if (ignores.indexOf(el) < 0) nodes.push(el);
        });
      }
      return $(nodes);
    },
    eq: function(idx){ return $(this[idx]) },
    first: function(){ return $(this[0]) },
    last: function(){ return $(this[this.length - 1]) },
    find: function(selector){
      var result;
      if (this.length == 1) result = $$(this[0], selector);
      else result = flatten(this.map(function(el){ return $$(el, selector) }));
      return $(result);
    },
    closest: function(selector, context){
      var node = this[0], nodes = $$(context !== undefined ? context : document, selector);
      if (nodes.length === 0) node = null;
      while(node && node !== document && nodes.indexOf(node) < 0) node = node.parentNode;
      return $(node !== document && node);
    },
    parents: function(selector){
      var ancestors = [], nodes = this;
      while (nodes.length > 0)
        nodes = compact(nodes.map(function(node){
          if ((node = node.parentNode) && node !== document && ancestors.indexOf(node) < 0) {
            ancestors.push(node);
            return node;
          }
        }));
      return filtered(ancestors, selector);
    },
    parent: function(selector){
      return filtered(uniq(compact(this.pluck('parentNode'))), selector);
    },
    children: function(selector){
      return filtered(flatten(this.map(function(el){ return slice.call(el.children) })), selector);
    },
    siblings: function(selector){
      return filtered(flatten(this.map(function(el){
        return slice.call(el.parentNode.children).filter(function(child){ return child!==el });
      })), selector);
    },
    empty: function(){ return this.each(function(){ this.innerHTML = '' }) },
    pluck: function(property){ return this.map(function(element){ return element[property] }) },
    show: function(){
      return this.each(function() {
        this.style.display == "none" && (this.style.display = null);
        if (getComputedStyle(this, '').getPropertyValue("display") == "none") {
          this.style.display = defaultDisplay(this.nodeName)
        }
      })
    },
    replaceWith: function(newContent) {
      return this.each(function() {
        var element = $(this),
            prev = element.prev();
        element.remove();
        prev.after(newContent);
      });
    },
    hide: function(){
      return this.css("display", "none")
    },
    toggle: function(){
      this.css("display") == "none" && this.show() || this.hide();
      return this
    },
    prev: function(){ return $(this.pluck('previousElementSibling')) },
    next: function(){ return $(this.pluck('nextElementSibling')) },
    html: function(html){
      return html === undefined ?
        (this.length > 0 ? this[0].innerHTML : null) :
        this.each(function(idx){ this.innerHTML = isF(html) ? html.call(this, idx, this.innerHTML) : html });
    },
    text: function(text){
      return text === undefined ?
        (this.length > 0 ? this[0].innerText : null) :
        this.each(function(){ this.innerText = text });
    },
    attr: function(name, value){
      return (typeof name == 'string' && value === undefined) ?
        (this.length > 0 && this[0].nodeName == 'INPUT' && this[0].type == 'text' && name == 'value') ? (this.val()) :
        (this.length > 0 ? this[0].getAttribute(name) || (name in this[0] ? this[0][name] : undefined) : undefined) :
        this.each(function(idx){
          if (isO(name)) for (key in name) this.setAttribute(key, name[key])
          else this.setAttribute(name, isF(value) ? value.call(this, idx, this.getAttribute(name)) : value);
        });
    },
    removeAttr: function(name) {
      return this.each(function() { this.removeAttribute(name); });
    },
    data: function(name, value){
      return this.attr('data-' + name, value);
    },
    val: function(value){
      return (value === undefined) ?
        (this.length > 0 ? this[0].value : null) :
        this.each(function(){
          this.value = value;
        });
    },
    offset: function(){
      if(this.length==0) return null;
      var obj = this[0].getBoundingClientRect();
      return {
        left: obj.left + document.body.scrollLeft,
        top: obj.top + document.body.scrollTop,
        width: obj.width,
        height: obj.height
      };
    },
    css: function(property, value){
      if (value === undefined && typeof property == 'string')
        return this[0].style[camelize(property)] || getComputedStyle(this[0], '').getPropertyValue(property);
      css = '';
      for (key in property) css += key + ':' + property[key] + ';';
      if (typeof property == 'string') css = property + ':' + value;
      return this.each(function() { this.style.cssText += ';' + css });
    },
    index: function(element){
      return this.indexOf($(element)[0]);
    },
    hasClass: function(name){
      return classRE(name).test(this[0].className);
    },
    addClass: function(name){
      return this.each(function(idx) {
        classList = [];
        var cls = this.className, newName = funcArg(this,name,idx,cls);
        newName.split(/\s+/g).forEach(function(klass) {
          if (!$(this).hasClass(klass)) {
            classList.push(klass)
          }
        }, this);
        classList.length && (this.className += (cls ? " " : "") + classList.join(" "))
      })
    },
    removeClass: function(name){
      return this.each(function(idx) {
        classList = this.className;
        funcArg(this,name,idx,classList).split(/\s+/g).forEach(function(klass) {
          classList = classList.replace(classRE(klass), " ")
        });
        this.className = classList.trim()
      })
    },
    toggleClass: function(name, when){
      return this.each(function(idx){
       var cls = this.className, newName = funcArg(this,name,idx,cls);
       ((when !== undefined && !when) || $(this).hasClass(newName)) ?
         $(this).removeClass(newName) : $(this).addClass(newName)
      });
    },
    submit: function () {
      return this.each(function () {
        try {
          // Submit first form element
          this.submit();
          return;
        } catch(e) {};
      });
    }
  };

  ['width', 'height'].forEach(function(property){
    $.fn[property] = function(){ var offset = this.offset(); return offset ? offset[property] : null }
  });

  var adjacencyOperators = {append: 'beforeEnd', prepend: 'afterBegin', before: 'beforeBegin', after: 'afterEnd'};

  for (key in adjacencyOperators)
    $.fn[key] = (function(operator) {
      return function(html){
        return this.each(function(index, element){
          if (html instanceof Z) {
            dom = html;
            if (operator == 'afterBegin' || operator == 'afterEnd')
              for (var i=0; i<dom.length; i++) element['insertAdjacentElement'](operator, dom[dom.length-i-1]);
            else
              for (var i=0; i<dom.length; i++) element['insertAdjacentElement'](operator, dom[i]);
          } else {
            element['insertAdjacent'+(html instanceof Element ? 'Element' : 'HTML')](operator, html);
          }
        });
      };
    })(adjacencyOperators[key]);

  Z.prototype = $.fn;

  return $;
})();

'$' in window || (window.$ = Zepto);
<commit_msg>modify .htl and .attr to use new funcArg internal  helper function<commit_after>var Zepto = (function() {
  var slice = [].slice, key, css, $$, fragmentRE, container, document = window.document, undefined,
    classList, elemDisplay = {},
    getComputedStyle = document.defaultView.getComputedStyle;

  function classRE(name){ return new RegExp('(^|\\s)' + name + '(\\s|$)') }
  function compact(array){ return array.filter(function(item){ return item !== undefined && item !== null }) }
  function flatten(array){ return [].concat.apply([], array); }
  function camelize(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
  function defaultDisplay(nodeName) {
    if (!elemDisplay[nodeName]) {
      var elem = document.createElement(nodeName);
      document.body.insertAdjacentElement("beforeEnd", elem);
      var display = getComputedStyle(elem, '').getPropertyValue("display");
      elem.parentNode.removeChild(elem);
      display == "none" && (display = "block");
      elemDisplay[nodeName] = display
    }
    return elemDisplay[nodeName]
  }
  function uniq(array){
    var r = [];
    for(var i=0,n=array.length;i<n;i++)
      if(r.indexOf(array[i])<0) r.push(array[i]);
    return r;
  }
  function isF(value) { return ({}).toString.call(value) == "[object Function]" }
  function isO(value) { return value instanceof Object }
  function isA(value) { return value instanceof Array }

  fragmentRE = /^\s*<[^>]+>/;
  container = document.createElement('div');
  function fragment(html) {
    container.innerHTML = ('' + html).trim();
    var result = slice.call(container.childNodes);
    container.innerHTML = '';
    return result;
  }

  function Z(dom, selector){
    dom = dom || [];
    dom.__proto__ = Z.prototype;
    dom.selector = selector || '';
    return dom;
  }

  function $(selector, context){
    if (!selector) return Z();
    if (context !== undefined) return $(context).find(selector);
    else if (isF(selector)) return $(document).ready(selector);
    else if (selector instanceof Z) return selector;
    else {
      var dom;
      if (isA(selector)) dom = compact(selector);
      else if (selector instanceof Element || selector === window || selector === document)
        dom = [selector], selector = null;
      else if (fragmentRE.test(selector)) dom = fragment(selector);
      else if (selector.nodeType && selector.nodeType == 3) dom = [selector];
      else dom = $$(document, selector);
      return Z(dom, selector);
    }
  }

  $.extend = function(target, source){ for (key in source) target[key] = source[key]; return target }
  $.qsa = $$ = function(element, selector){ return slice.call(element.querySelectorAll(selector)) }

  function filtered(nodes, selector){
    return selector === undefined ? $(nodes) : $(nodes).filter(selector);
  }

  function funcArg(context,arg,idx,payload){
   return isF(arg) ? arg.call(context, idx, payload) : arg;
  }

  $.isFunction = isF;
  $.isObject = isO;
  $.isArray = isA;

  $.fn = {
    forEach: [].forEach,
    map: [].map,
    reduce: [].reduce,
    push: [].push,
    indexOf: [].indexOf,
    concat: [].concat,
    ready: function(callback){
      if (document.readyState == 'complete' || document.readyState == 'loaded') callback();
      document.addEventListener('DOMContentLoaded', callback, false); return this;
    },
    get: function(idx){ return idx === undefined ? this : this[idx] },
    size: function(){ return this.length },
    remove: function(){ return this.each(function(){ this.parentNode.removeChild(this) }) },
    each: function(callback){
      this.forEach(function(el, idx){ callback.call(el, idx, el) });
      return this;
    },
    filter: function(selector){
      return $([].filter.call(this, function(element){
        return $$(element.parentNode, selector).indexOf(element) >= 0;
      }));
    },
    is: function(selector){
      return this.length > 0 && $(this[0]).filter(selector).length > 0;
    },
    not: function(selector){
      var nodes=[];
      if (isF(selector) && selector.call !== undefined)
        this.each(function(idx){
          if (!selector.call(this,idx)) nodes.push(this);
        });
      else {
        var ignores = slice.call(
          typeof selector == 'string' ?
            this.filter(selector) :
            selector instanceof NodeList ? selector : $(selector));
        slice.call(this).forEach(function(el){
          if (ignores.indexOf(el) < 0) nodes.push(el);
        });
      }
      return $(nodes);
    },
    eq: function(idx){ return $(this[idx]) },
    first: function(){ return $(this[0]) },
    last: function(){ return $(this[this.length - 1]) },
    find: function(selector){
      var result;
      if (this.length == 1) result = $$(this[0], selector);
      else result = flatten(this.map(function(el){ return $$(el, selector) }));
      return $(result);
    },
    closest: function(selector, context){
      var node = this[0], nodes = $$(context !== undefined ? context : document, selector);
      if (nodes.length === 0) node = null;
      while(node && node !== document && nodes.indexOf(node) < 0) node = node.parentNode;
      return $(node !== document && node);
    },
    parents: function(selector){
      var ancestors = [], nodes = this;
      while (nodes.length > 0)
        nodes = compact(nodes.map(function(node){
          if ((node = node.parentNode) && node !== document && ancestors.indexOf(node) < 0) {
            ancestors.push(node);
            return node;
          }
        }));
      return filtered(ancestors, selector);
    },
    parent: function(selector){
      return filtered(uniq(compact(this.pluck('parentNode'))), selector);
    },
    children: function(selector){
      return filtered(flatten(this.map(function(el){ return slice.call(el.children) })), selector);
    },
    siblings: function(selector){
      return filtered(flatten(this.map(function(el){
        return slice.call(el.parentNode.children).filter(function(child){ return child!==el });
      })), selector);
    },
    empty: function(){ return this.each(function(){ this.innerHTML = '' }) },
    pluck: function(property){ return this.map(function(element){ return element[property] }) },
    show: function(){
      return this.each(function() {
        this.style.display == "none" && (this.style.display = null);
        if (getComputedStyle(this, '').getPropertyValue("display") == "none") {
          this.style.display = defaultDisplay(this.nodeName)
        }
      })
    },
    replaceWith: function(newContent) {
      return this.each(function() {
        var element = $(this),
            prev = element.prev();
        element.remove();
        prev.after(newContent);
      });
    },
    hide: function(){
      return this.css("display", "none")
    },
    toggle: function(){
      this.css("display") == "none" && this.show() || this.hide();
      return this
    },
    prev: function(){ return $(this.pluck('previousElementSibling')) },
    next: function(){ return $(this.pluck('nextElementSibling')) },
    html: function(html){
      return html === undefined ?
        (this.length > 0 ? this[0].innerHTML : null) :
        this.each(function(idx){ this.innerHTML = funcArg(this,html,idx,this.innerHTML) });
    },
    text: function(text){
      return text === undefined ?
        (this.length > 0 ? this[0].innerText : null) :
        this.each(function(){ this.innerText = text });
    },
    attr: function(name, value){
      return (typeof name == 'string' && value === undefined) ?
        (this.length > 0 && this[0].nodeName == 'INPUT' && this[0].type == 'text' && name == 'value') ? (this.val()) :
        (this.length > 0 ? this[0].getAttribute(name) || (name in this[0] ? this[0][name] : undefined) : undefined) :
        this.each(function(idx){
          if (isO(name)) for (key in name) this.setAttribute(key, name[key])
          else this.setAttribute(name, funcArg(this,value,idx,this.getAttribute(name)));
        });
    },
    removeAttr: function(name) {
      return this.each(function() { this.removeAttribute(name); });
    },
    data: function(name, value){
      return this.attr('data-' + name, value);
    },
    val: function(value){
      return (value === undefined) ?
        (this.length > 0 ? this[0].value : null) :
        this.each(function(){
          this.value = value;
        });
    },
    offset: function(){
      if(this.length==0) return null;
      var obj = this[0].getBoundingClientRect();
      return {
        left: obj.left + document.body.scrollLeft,
        top: obj.top + document.body.scrollTop,
        width: obj.width,
        height: obj.height
      };
    },
    css: function(property, value){
      if (value === undefined && typeof property == 'string')
        return this[0].style[camelize(property)] || getComputedStyle(this[0], '').getPropertyValue(property);
      css = '';
      for (key in property) css += key + ':' + property[key] + ';';
      if (typeof property == 'string') css = property + ':' + value;
      return this.each(function() { this.style.cssText += ';' + css });
    },
    index: function(element){
      return this.indexOf($(element)[0]);
    },
    hasClass: function(name){
      return classRE(name).test(this[0].className);
    },
    addClass: function(name){
      return this.each(function(idx) {
        classList = [];
        var cls = this.className, newName = funcArg(this,name,idx,cls);
        newName.split(/\s+/g).forEach(function(klass) {
          if (!$(this).hasClass(klass)) {
            classList.push(klass)
          }
        }, this);
        classList.length && (this.className += (cls ? " " : "") + classList.join(" "))
      })
    },
    removeClass: function(name){
      return this.each(function(idx) {
        classList = this.className;
        funcArg(this,name,idx,classList).split(/\s+/g).forEach(function(klass) {
          classList = classList.replace(classRE(klass), " ")
        });
        this.className = classList.trim()
      })
    },
    toggleClass: function(name, when){
      return this.each(function(idx){
       var cls = this.className, newName = funcArg(this,name,idx,cls);
       ((when !== undefined && !when) || $(this).hasClass(newName)) ?
         $(this).removeClass(newName) : $(this).addClass(newName)
      });
    },
    submit: function () {
      return this.each(function () {
        try {
          // Submit first form element
          this.submit();
          return;
        } catch(e) {};
      });
    }
  };

  ['width', 'height'].forEach(function(property){
    $.fn[property] = function(){ var offset = this.offset(); return offset ? offset[property] : null }
  });

  var adjacencyOperators = {append: 'beforeEnd', prepend: 'afterBegin', before: 'beforeBegin', after: 'afterEnd'};

  for (key in adjacencyOperators)
    $.fn[key] = (function(operator) {
      return function(html){
        return this.each(function(index, element){
          if (html instanceof Z) {
            dom = html;
            if (operator == 'afterBegin' || operator == 'afterEnd')
              for (var i=0; i<dom.length; i++) element['insertAdjacentElement'](operator, dom[dom.length-i-1]);
            else
              for (var i=0; i<dom.length; i++) element['insertAdjacentElement'](operator, dom[i]);
          } else {
            element['insertAdjacent'+(html instanceof Element ? 'Element' : 'HTML')](operator, html);
          }
        });
      };
    })(adjacencyOperators[key]);

  Z.prototype = $.fn;

  return $;
})();

'$' in window || (window.$ = Zepto);
<|endoftext|>


<commit_before>var Zepto = (function() {
  var slice = [].slice, key, css, $$, fragmentRE, container, document = window.document, undefined,
    classList, elemDisplay = {},
    getComputedStyle = document.defaultView.getComputedStyle;

  function classRE(name){ return new RegExp('(^|\\s)' + name + '(\\s|$)') }
  function compact(array){ return array.filter(function(item){ return item !== undefined && item !== null }) }
  function flatten(array){ return [].concat.apply([], array); }
  function camelize(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
  function defaultDisplay(nodeName) {
    if (!elemDisplay[nodeName]) {
      var elem = document.createElement(nodeName);
      document.body.insertAdjacentElement("beforeEnd", elem);
      var display = getComputedStyle(elem, '').getPropertyValue("display");
      elem.parentNode.removeChild(elem);
      display == "none" && (display = "block");
      elemDisplay[nodeName] = display
    }
    return elemDisplay[nodeName]
  }
  function uniq(array){
    var r = [];
    for(var i=0,n=array.length;i<n;i++)
      if(r.indexOf(array[i])<0) r.push(array[i]);
    return r;
  }
  function isF(value) { return ({}).toString.call(value) == "[object Function]" }
  function isO(value) { return value instanceof Object }
  function isA(value) { return value instanceof Array }

  fragmentRE = /^\s*<[^>]+>/;
  container = document.createElement('div');
  function fragment(html) {
    container.innerHTML = ('' + html).trim();
    var result = slice.call(container.childNodes);
    container.innerHTML = '';
    return result;
  }

  function Z(dom, selector){
    dom = dom || [];
    dom.__proto__ = Z.prototype;
    dom.selector = selector || '';
    return dom;
  }

  function $(selector, context){
    if (!selector) return Z();
    if (context !== undefined) return $(context).find(selector);
    else if (isF(selector)) return $(document).ready(selector);
    else if (selector instanceof Z) return selector;
    else {
      var dom;
      if (isA(selector)) dom = compact(selector);
      else if (selector instanceof Element || selector === window || selector === document)
        dom = [selector], selector = null;
      else if (fragmentRE.test(selector)) dom = fragment(selector);
      else if (selector.nodeType && selector.nodeType == 3) dom = [selector];
      else dom = $$(document, selector);
      return Z(dom, selector);
    }
  }

  $.extend = function(target, source){ for (key in source) target[key] = source[key]; return target }
  $.qsa = $$ = function(element, selector){ return slice.call(element.querySelectorAll(selector)) }

  function filtered(nodes, selector){
    return selector === undefined ? $(nodes) : $(nodes).filter(selector);
  }

  function funcArg(context, arg, idx, payload){
   return isF(arg) ? arg.call(context, idx, payload) : arg;
  }

  $.isFunction = isF;
  $.isObject = isO;
  $.isArray = isA;

  $.fn = {
    forEach: [].forEach,
    map: [].map,
    reduce: [].reduce,
    push: [].push,
    indexOf: [].indexOf,
    concat: [].concat,
    ready: function(callback){
      if (document.readyState == 'complete' || document.readyState == 'loaded') callback();
      document.addEventListener('DOMContentLoaded', callback, false); return this;
    },
    get: function(idx){ return idx === undefined ? this : this[idx] },
    size: function(){ return this.length },
    remove: function(){ return this.each(function(){ this.parentNode.removeChild(this) }) },
    each: function(callback){
      this.forEach(function(el, idx){ callback.call(el, idx, el) });
      return this;
    },
    filter: function(selector){
      return $([].filter.call(this, function(element){
        return $$(element.parentNode, selector).indexOf(element) >= 0;
      }));
    },
    is: function(selector){
      return this.length > 0 && $(this[0]).filter(selector).length > 0;
    },
    not: function(selector){
      var nodes=[];
      if (isF(selector) && selector.call !== undefined)
        this.each(function(idx){
          if (!selector.call(this,idx)) nodes.push(this);
        });
      else {
        var ignores = slice.call(
          typeof selector == 'string' ?
            this.filter(selector) :
            selector instanceof NodeList ? selector : $(selector));
        slice.call(this).forEach(function(el){
          if (ignores.indexOf(el) < 0) nodes.push(el);
        });
      }
      return $(nodes);
    },
    eq: function(idx){ return $(this[idx]) },
    first: function(){ return $(this[0]) },
    last: function(){ return $(this[this.length - 1]) },
    find: function(selector){
      var result;
      if (this.length == 1) result = $$(this[0], selector);
      else result = flatten(this.map(function(el){ return $$(el, selector) }));
      return $(result);
    },
    closest: function(selector, context){
      var node = this[0], nodes = $$(context !== undefined ? context : document, selector);
      if (nodes.length === 0) node = null;
      while(node && node !== document && nodes.indexOf(node) < 0) node = node.parentNode;
      return $(node !== document && node);
    },
    parents: function(selector){
      var ancestors = [], nodes = this;
      while (nodes.length > 0)
        nodes = compact(nodes.map(function(node){
          if ((node = node.parentNode) && node !== document && ancestors.indexOf(node) < 0) {
            ancestors.push(node);
            return node;
          }
        }));
      return filtered(ancestors, selector);
    },
    parent: function(selector){
      return filtered(uniq(compact(this.pluck('parentNode'))), selector);
    },
    children: function(selector){
      return filtered(flatten(this.map(function(el){ return slice.call(el.children) })), selector);
    },
    siblings: function(selector){
      return filtered(flatten(this.map(function(el){
        return slice.call(el.parentNode.children).filter(function(child){ return child!==el });
      })), selector);
    },
    empty: function(){ return this.each(function(){ this.innerHTML = '' }) },
    pluck: function(property){ return this.map(function(element){ return element[property] }) },
    show: function(){
      return this.each(function() {
        this.style.display == "none" && (this.style.display = null);
        if (getComputedStyle(this, '').getPropertyValue("display") == "none") {
          this.style.display = defaultDisplay(this.nodeName)
        }
      })
    },
    replaceWith: function(newContent) {
      return this.each(function() {
        var element = $(this),
            prev = element.prev();
        element.remove();
        prev.after(newContent);
      });
    },
    hide: function(){
      return this.css("display", "none")
    },
    toggle: function(){
      this.css("display") == "none" && this.show() || this.hide();
      return this
    },
    prev: function(){ return $(this.pluck('previousElementSibling')) },
    next: function(){ return $(this.pluck('nextElementSibling')) },
    html: function(html){
      return html === undefined ?
        (this.length > 0 ? this[0].innerHTML : null) :
        this.each(function(idx){ this.innerHTML = funcArg(this, html, idx, this.innerHTML) });
    },
    text: function(text){
      return text === undefined ?
        (this.length > 0 ? this[0].innerText : null) :
        this.each(function(){ this.innerText = text });
    },
    attr: function(name, value){
      return (typeof name == 'string' && value === undefined) ?
        (this.length > 0 && this[0].nodeName == 'INPUT' && this[0].type == 'text' && name == 'value') ? (this.val()) :
        (this.length > 0 ? this[0].getAttribute(name) || (name in this[0] ? this[0][name] : undefined) : undefined) :
        this.each(function(idx){
          if (isO(name)) for (key in name) this.setAttribute(key, name[key])
          else this.setAttribute(name, funcArg(this, value, idx, this.getAttribute(name)));
        });
    },
    removeAttr: function(name) {
      return this.each(function() { this.removeAttribute(name); });
    },
    data: function(name, value){
      return this.attr('data-' + name, value);
    },
    val: function(value){
      return (value === undefined) ?
        (this.length > 0 ? this[0].value : null) :
        this.each(function(){
          this.value = value;
        });
    },
    offset: function(){
      if(this.length==0) return null;
      var obj = this[0].getBoundingClientRect();
      return {
        left: obj.left + document.body.scrollLeft,
        top: obj.top + document.body.scrollTop,
        width: obj.width,
        height: obj.height
      };
    },
    css: function(property, value){
      if (value === undefined && typeof property == 'string')
        return this[0].style[camelize(property)] || getComputedStyle(this[0], '').getPropertyValue(property);
      css = '';
      for (key in property) css += key + ':' + property[key] + ';';
      if (typeof property == 'string') css = property + ':' + value;
      return this.each(function() { this.style.cssText += ';' + css });
    },
    index: function(element){
      return this.indexOf($(element)[0]);
    },
    hasClass: function(name){
      return classRE(name).test(this[0].className);
    },
    addClass: function(name){
      return this.each(function(idx) {
        classList = [];
        var cls = this.className, newName = funcArg(this, name, idx, cls);
        newName.split(/\s+/g).forEach(function(klass) {
          if (!$(this).hasClass(klass)) {
            classList.push(klass)
          }
        }, this);
        classList.length && (this.className += (cls ? " " : "") + classList.join(" "))
      })
    },
    removeClass: function(name){
      return this.each(function(idx) {
        classList = this.className;
        funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass) {
          classList = classList.replace(classRE(klass), " ")
        });
        this.className = classList.trim()
      })
    },
    toggleClass: function(name, when){
      return this.each(function(idx){
       var cls = this.className, newName = funcArg(this, name, idx, cls);
       ((when !== undefined && !when) || $(this).hasClass(newName)) ?
         $(this).removeClass(newName) : $(this).addClass(newName)
      });
    },
    submit: function () {
      return this.each(function () {
        try {
          // Submit first form element
          this.submit();
          return;
        } catch(e) {};
      });
    }
  };

  ['width', 'height'].forEach(function(property){
    $.fn[property] = function(){ var offset = this.offset(); return offset ? offset[property] : null }
  });

  var adjacencyOperators = {append: 'beforeEnd', prepend: 'afterBegin', before: 'beforeBegin', after: 'afterEnd'};

  for (key in adjacencyOperators)
    $.fn[key] = (function(operator) {
      return function(html){
        return this.each(function(index, element){
          if (html instanceof Z) {
            dom = html;
            if (operator == 'afterBegin' || operator == 'afterEnd')
              for (var i=0; i<dom.length; i++) element['insertAdjacentElement'](operator, dom[dom.length-i-1]);
            else
              for (var i=0; i<dom.length; i++) element['insertAdjacentElement'](operator, dom[i]);
          } else {
            element['insertAdjacent'+(html instanceof Element ? 'Element' : 'HTML')](operator, html);
          }
        });
      };
    })(adjacencyOperators[key]);

  Z.prototype = $.fn;

  return $;
})();

'$' in window || (window.$ = Zepto);
<commit_msg>Remove uses of insertAdjacentElement()<commit_after>var Zepto = (function() {
  var slice = [].slice, key, css, $$, fragmentRE, container, document = window.document, undefined,
    classList, elemDisplay = {},
    getComputedStyle = document.defaultView.getComputedStyle;

  function classRE(name){ return new RegExp('(^|\\s)' + name + '(\\s|$)') }
  function compact(array){ return array.filter(function(item){ return item !== undefined && item !== null }) }
  function flatten(array){ return [].concat.apply([], array); }
  function camelize(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
  function defaultDisplay(nodeName) {
    if (!elemDisplay[nodeName]) {
      var elem = document.createElement(nodeName);
      document.body.appendChild(elem);
      var display = getComputedStyle(elem, '').getPropertyValue("display");
      elem.parentNode.removeChild(elem);
      display == "none" && (display = "block");
      elemDisplay[nodeName] = display
    }
    return elemDisplay[nodeName]
  }
  function uniq(array){
    var r = [];
    for(var i=0,n=array.length;i<n;i++)
      if(r.indexOf(array[i])<0) r.push(array[i]);
    return r;
  }
  function isF(value) { return ({}).toString.call(value) == "[object Function]" }
  function isO(value) { return value instanceof Object }
  function isA(value) { return value instanceof Array }

  fragmentRE = /^\s*<[^>]+>/;
  container = document.createElement('div');
  function fragment(html) {
    container.innerHTML = ('' + html).trim();
    var result = slice.call(container.childNodes);
    container.innerHTML = '';
    return result;
  }

  function Z(dom, selector){
    dom = dom || [];
    dom.__proto__ = Z.prototype;
    dom.selector = selector || '';
    return dom;
  }

  function $(selector, context){
    if (!selector) return Z();
    if (context !== undefined) return $(context).find(selector);
    else if (isF(selector)) return $(document).ready(selector);
    else if (selector instanceof Z) return selector;
    else {
      var dom;
      if (isA(selector)) dom = compact(selector);
      else if (selector instanceof Element || selector === window || selector === document)
        dom = [selector], selector = null;
      else if (fragmentRE.test(selector)) dom = fragment(selector);
      else if (selector.nodeType && selector.nodeType == 3) dom = [selector];
      else dom = $$(document, selector);
      return Z(dom, selector);
    }
  }

  $.extend = function(target, source){ for (key in source) target[key] = source[key]; return target }
  $.qsa = $$ = function(element, selector){ return slice.call(element.querySelectorAll(selector)) }

  function filtered(nodes, selector){
    return selector === undefined ? $(nodes) : $(nodes).filter(selector);
  }

  function funcArg(context, arg, idx, payload){
   return isF(arg) ? arg.call(context, idx, payload) : arg;
  }

  $.isFunction = isF;
  $.isObject = isO;
  $.isArray = isA;

  $.fn = {
    forEach: [].forEach,
    map: [].map,
    reduce: [].reduce,
    push: [].push,
    indexOf: [].indexOf,
    concat: [].concat,
    ready: function(callback){
      if (document.readyState == 'complete' || document.readyState == 'loaded') callback();
      document.addEventListener('DOMContentLoaded', callback, false); return this;
    },
    get: function(idx){ return idx === undefined ? this : this[idx] },
    size: function(){ return this.length },
    remove: function(){ return this.each(function(){ this.parentNode.removeChild(this) }) },
    each: function(callback){
      this.forEach(function(el, idx){ callback.call(el, idx, el) });
      return this;
    },
    filter: function(selector){
      return $([].filter.call(this, function(element){
        return $$(element.parentNode, selector).indexOf(element) >= 0;
      }));
    },
    is: function(selector){
      return this.length > 0 && $(this[0]).filter(selector).length > 0;
    },
    not: function(selector){
      var nodes=[];
      if (isF(selector) && selector.call !== undefined)
        this.each(function(idx){
          if (!selector.call(this,idx)) nodes.push(this);
        });
      else {
        var ignores = slice.call(
          typeof selector == 'string' ?
            this.filter(selector) :
            selector instanceof NodeList ? selector : $(selector));
        slice.call(this).forEach(function(el){
          if (ignores.indexOf(el) < 0) nodes.push(el);
        });
      }
      return $(nodes);
    },
    eq: function(idx){ return $(this[idx]) },
    first: function(){ return $(this[0]) },
    last: function(){ return $(this[this.length - 1]) },
    find: function(selector){
      var result;
      if (this.length == 1) result = $$(this[0], selector);
      else result = flatten(this.map(function(el){ return $$(el, selector) }));
      return $(result);
    },
    closest: function(selector, context){
      var node = this[0], nodes = $$(context !== undefined ? context : document, selector);
      if (nodes.length === 0) node = null;
      while(node && node !== document && nodes.indexOf(node) < 0) node = node.parentNode;
      return $(node !== document && node);
    },
    parents: function(selector){
      var ancestors = [], nodes = this;
      while (nodes.length > 0)
        nodes = compact(nodes.map(function(node){
          if ((node = node.parentNode) && node !== document && ancestors.indexOf(node) < 0) {
            ancestors.push(node);
            return node;
          }
        }));
      return filtered(ancestors, selector);
    },
    parent: function(selector){
      return filtered(uniq(compact(this.pluck('parentNode'))), selector);
    },
    children: function(selector){
      return filtered(flatten(this.map(function(el){ return slice.call(el.children) })), selector);
    },
    siblings: function(selector){
      return filtered(flatten(this.map(function(el){
        return slice.call(el.parentNode.children).filter(function(child){ return child!==el });
      })), selector);
    },
    empty: function(){ return this.each(function(){ this.innerHTML = '' }) },
    pluck: function(property){ return this.map(function(element){ return element[property] }) },
    show: function(){
      return this.each(function() {
        this.style.display == "none" && (this.style.display = null);
        if (getComputedStyle(this, '').getPropertyValue("display") == "none") {
          this.style.display = defaultDisplay(this.nodeName)
        }
      })
    },
    replaceWith: function(newContent) {
      return this.each(function() {
        var element = $(this),
            prev = element.prev();
        element.remove();
        prev.after(newContent);
      });
    },
    hide: function(){
      return this.css("display", "none")
    },
    toggle: function(){
      this.css("display") == "none" && this.show() || this.hide();
      return this
    },
    prev: function(){ return $(this.pluck('previousElementSibling')) },
    next: function(){ return $(this.pluck('nextElementSibling')) },
    html: function(html){
      return html === undefined ?
        (this.length > 0 ? this[0].innerHTML : null) :
        this.each(function(idx){ this.innerHTML = funcArg(this, html, idx, this.innerHTML) });
    },
    text: function(text){
      return text === undefined ?
        (this.length > 0 ? this[0].innerText : null) :
        this.each(function(){ this.innerText = text });
    },
    attr: function(name, value){
      return (typeof name == 'string' && value === undefined) ?
        (this.length > 0 && this[0].nodeName == 'INPUT' && this[0].type == 'text' && name == 'value') ? (this.val()) :
        (this.length > 0 ? this[0].getAttribute(name) || (name in this[0] ? this[0][name] : undefined) : undefined) :
        this.each(function(idx){
          if (isO(name)) for (key in name) this.setAttribute(key, name[key])
          else this.setAttribute(name, funcArg(this, value, idx, this.getAttribute(name)));
        });
    },
    removeAttr: function(name) {
      return this.each(function() { this.removeAttribute(name); });
    },
    data: function(name, value){
      return this.attr('data-' + name, value);
    },
    val: function(value){
      return (value === undefined) ?
        (this.length > 0 ? this[0].value : null) :
        this.each(function(){
          this.value = value;
        });
    },
    offset: function(){
      if(this.length==0) return null;
      var obj = this[0].getBoundingClientRect();
      return {
        left: obj.left + document.body.scrollLeft,
        top: obj.top + document.body.scrollTop,
        width: obj.width,
        height: obj.height
      };
    },
    css: function(property, value){
      if (value === undefined && typeof property == 'string')
        return this[0].style[camelize(property)] || getComputedStyle(this[0], '').getPropertyValue(property);
      css = '';
      for (key in property) css += key + ':' + property[key] + ';';
      if (typeof property == 'string') css = property + ':' + value;
      return this.each(function() { this.style.cssText += ';' + css });
    },
    index: function(element){
      return this.indexOf($(element)[0]);
    },
    hasClass: function(name){
      return classRE(name).test(this[0].className);
    },
    addClass: function(name){
      return this.each(function(idx) {
        classList = [];
        var cls = this.className, newName = funcArg(this, name, idx, cls);
        newName.split(/\s+/g).forEach(function(klass) {
          if (!$(this).hasClass(klass)) {
            classList.push(klass)
          }
        }, this);
        classList.length && (this.className += (cls ? " " : "") + classList.join(" "))
      })
    },
    removeClass: function(name){
      return this.each(function(idx) {
        classList = this.className;
        funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass) {
          classList = classList.replace(classRE(klass), " ")
        });
        this.className = classList.trim()
      })
    },
    toggleClass: function(name, when){
      return this.each(function(idx){
       var cls = this.className, newName = funcArg(this, name, idx, cls);
       ((when !== undefined && !when) || $(this).hasClass(newName)) ?
         $(this).removeClass(newName) : $(this).addClass(newName)
      });
    },
    submit: function () {
      return this.each(function () {
        try {
          // Submit first form element
          this.submit();
          return;
        } catch(e) {};
      });
    }
  };

  ['width', 'height'].forEach(function(property){
    $.fn[property] = function(){ var offset = this.offset(); return offset ? offset[property] : null }
  });

  var adjacencyOperators = [ 'prepend', 'after', 'before', 'append' ];
  function insert(operator, element, other) {
    var parent = (!operator || operator == 3) ? element : element.parentNode;
    parent.insertBefore(other,
      !operator ? parent.firstChild :         // prepend
      operator == 1 ? element.nextSibling :   // after
      operator == 2 ? element :               // before
      null);                                  // append
  }

  adjacencyOperators.forEach(function(key, operator) {
    $.fn[key] = function(html){
      if (typeof(html) != 'object')
        html = fragment(html);

      return this.each(function(index, element){
        if (html.length || html instanceof Z) {
          dom = html;
          for (var i=0; i<dom.length; i++) {
            var e = dom[operator < 2 ? dom.length-i-1 : i];
            insert(operator, element, e);
          }
        } else {
          insert(operator, element, html);
        }
      });
    };
  });

  Z.prototype = $.fn;

  return $;
})();

'$' in window || (window.$ = Zepto);
<|endoftext|>


<commit_before>var opts = {
  redis: {
    host: 'localhost',
    port: process.env.redis_PORT
  }
}

require('seneca')()
  .use('entity')
  .use('../lib/npm.js')
  .use('redis-store', opts.redis)
  .add('role:info,req:part', function (args, done) {
    done()

    this.act('role:npm,cmd:get', {name: args.name}, function (err, mod) {
      if (err) {
        return done(err)
      }

      this.act('role:info,res:part,part:npm', {name: args.name, data: mod.data$()})
    })
  })

  .add('role:npm,info:change', function (args, done) {
    done()
    this.act('role:npm,cmd:get', {name: args.name, update: true})
  })
  .use('mesh', {auto: true, pins: ['role:npm', 'role:info,req:part'], model: 'publish'})
<commit_msg>added default redis port<commit_after>var opts = {
  redis: {
    host: 'localhost',
    port: process.env.redis_PORT || 6379
  }
}

require('seneca')()
  .use('entity')
  .use('../lib/npm.js')
  .use('redis-store', opts.redis)
  .add('role:info,req:part', function (args, done) {
    done()

    this.act('role:npm,cmd:get', {name: args.name}, function (err, mod) {
      if (err) {
        return done(err)
      }

      this.act('role:info,res:part,part:npm', {name: args.name, data: mod.data$()})
    })
  })

  .add('role:npm,info:change', function (args, done) {
    done()
    this.act('role:npm,cmd:get', {name: args.name, update: true})
  })
  .use('mesh', {auto: true, pins: ['role:npm', 'role:info,req:part'], model: 'publish'})
<|endoftext|>