<commit_before>define(function(require, exports, module) {
    main.consumes = ["Plugin", "ui", "ace"];
    main.provides = ["ace.split"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var ui     = imports.ui;
        var ace    = imports.ace;
        var event  = require("ace/lib/event");

        var lang         = require("ace/lib/lang");
        var Editor       = require("ace/editor").Editor;
        var Renderer     = require("ace/virtual_renderer").VirtualRenderer;
        var EditSession  = require("ace/edit_session").EditSession;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit   = plugin.getEmitter();

        var editors = [], splits = {};

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            ace.on("create", function(e){
                if (e.editor.type != "ace")
                    return;

                draw();

                var editor = e.editor;
                var grabber;

                editor.once("draw", function(){
                    grabber = createGrabber(editor);
                }, plugin);

                editor.on("documentActivate", function(e){
                    var doc       = e.doc;
                    var session   = doc.getSession();
                    var split     = session.split;
                    var splitInfo = splits[doc.editor.name];

                    // If we are not in split mode and the editor is not split
                    // lets do nothing.
                    if (!split && !splitInfo)
                        return;

                    if (split) {
                        // Make sure we have a split inited for this editor
                        if (!splitInfo)
                            splitInfo = initSplit(editor, split.height);

                        var editor2  = splitInfo.editor2;

                        // Set Session
                        editor2.setSession(split.session2);

                        // Set Height
                        splitInfo.topPane.setHeight(split.height);

                        // Show bottom pane
                        splitInfo.topPane.show();

                        // Hide Grabber
                        grabber.style.display = "none";
                    }
                    else {
                        // Hide bottom pane
                        splitInfo.topPane.hide();

                        // Show Grabber
                        grabber.style.display = "block";
                    }
                });

                editor.on("getState", function(e){
                    var session = e.doc.getSession();
                    var state   = e.state;

                    if (e.filter || !session.split)
                        return;

                    var session2 = session.split.session2;

                    state.split = {
                        height     : session.split.height,

                        // Scroll state
                        scrolltop  : session2.getScrollTop(),
                        scrollleft : session2.getScrollLeft(),

                        // Selection
                        selection  : session2.selection.toJSON()
                    };
                });

                editor.on("setState", function(e){
                    var state   = e.state.split;
                    var session = e.doc.getSession();

                    if (!state)
                        return;

                    var splitInfo = initSplit(editor, state.height);
                    var session2  = cloneSession(session.session);

                    session.split  = {
                        height   : state.height,
                        session2 : session2
                    };

                    // Set 2nd Session
                    splitInfo.editor2.setSession(session2);

                    // Set selection
                    if (state.selection)
                        session2.selection.fromJSON(state.selection);

                    // Set scroll state
                    if (state.scrolltop)
                        session2.setScrollTop(state.scrolltop);
                    if (state.scrollleft)
                        session2.setScrollLeft(state.scrollleft);

                    if (state.options)
                        session2.setOptions(state.options);

                    var grabber = editor.aml.$int.querySelector(".splitgrabber");
                    grabber.style.display = "none";
                });

                editor.on("resize", function(e){
                    var splitInfo = splits[editor.name];
                    if (!splitInfo || !splitInfo.topPane.visible) return;
                    splitInfo.editor2.resize(true); // @Harutyun
                });

                editor.on("unload", function(e){
                    delete splits[editor.name];
                });
            });

            ace.on("themeChange", function(e){
                editors.forEach(function(editor){
                    editor.setTheme(e.path);

                    var theme = ace.theme;
                    var node  = editor.splitbox.$ext.parentNode;
                    if (theme.isDark)
                        ui.setStyleClass(node, "dark");
                    else
                        ui.setStyleClass(node, "", ["dark"]);
                });
            }, plugin);
        }

        var drawn = false;
        function draw() {
            if (drawn) return;
            drawn = true;

            // Insert CSS
            ui.insertCss(require("text!./style.css"), plugin);

            emit("draw");
        }

        function createGrabber(editor){
            var htmlNode = editor.ace.container.parentNode;
            var grabber  = document.createElement("div");
            htmlNode.appendChild(grabber);
            grabber.className = "splitgrabber";
            grabber.innerHTML = "=";

            grabber.addEventListener("mousedown", function(e){
                startSplit(e, grabber, editor);
            });

            plugin.addOther(function(){
                grabber.parentNode.removeChild(grabber);
            });

            return grabber;
        }

        /***** Methods *****/

        function startSplit(e, grabber, editor){
            var container = grabber;
            var drag      = grabber;

            // Set Top
            drag.style.zIndex = 1000000;

            var offsetY = e.clientY - (parseInt(container.style.top, 10) || 0);
            var moved   = false;
            var startY  = e.clientY - offsetY;
            var offset  = e.offsetY;

            var session = editor.activeDocument.getSession();

            event.capture(container, function(e) {
                var y = e.clientY - offsetY;

                if (!moved) {
                    if (Math.abs(y - startY) > 3) {
                        moved = true;
                        var percentage = ((y - startY) / grabber.parentNode.offsetHeight) * 100;
                        var splitInfo  = initSplit(editor, percentage);
                        session.split  = {
                            height   : percentage + "%",
                            session2 : cloneSession(editor.ace.session)
                        };

                        // Set 2nd Session
                        splitInfo.editor2.setSession(session.split.session2);

                        // Start splitter
                        splitInfo.splitbox.$handle.$ext.onmousedown({
                            clientY : e.clientY,
                            offsetY : -7 + offset
                        });

                        // Hide Grabber
                        grabber.style.display = "none";
                    }
                    else return;
                }
            }, function() {
                if (moved)
                    setFinalState(editor, session);
            });

            event.stopEvent(e);
        }

        function initSplit(editor, percentage){
            if (splits[editor.name]) {
                var splitInfo = splits[editor.name];
                splitInfo.topPane.show();
                return splitInfo;
            }

            var container = editor.aml.$int;
            var amlNode   = container.host;
            // @todo detect if this already happened

            var splitbox = amlNode.appendChild(new ui.vsplitbox({
                "class"  : "ace_split",
                padding  : 7,
                edge     : "7 0 0 0",
                splitter : true
            }));

            var topPane    = splitbox.appendChild(new ui.bar({
                height: percentage + "%"
            }));
            var bottomPane = splitbox.appendChild(new ui.bar());

            // Original Editor
            bottomPane.$int.appendChild(editor.ace.container);
            editor.ace.container.style.top = "0px";

            // New Editor
            var editor2 = new Editor(new Renderer(topPane.$int, ace.theme));
            editors.push(editor2);
            editor2.splitbox = splitbox;

            splitbox.$handle.on("dragmove", function(){
                editor.resize();
                editor2.resize();
            });
            splitbox.$handle.on("dragdrop", function(){
                editor.resize();
                editor2.resize();

                var session = editor.activeDocument.getSession();
                setFinalState(editor, session);
            });
            ace.on("settingsUpdate", function(e){
                editor2.setOptions(e.options);
            }, editor);

            splits[editor.name] = {
                splitbox   : splitbox,
                topPane    : topPane,
                bottomPane : bottomPane,
                editor     : editor,
                editor2    : editor2
            };

            return splits[editor.name];
        }

        function cloneSession(session) {
            var s = new EditSession(session.getDocument(), session.getMode());

            var undoManager = session.getUndoManager();
            if (undoManager) {
                var undoManagerProxy = new UndoManagerProxy(undoManager, s);
                s.setUndoManager(undoManagerProxy);
            }

            // Overwrite the default $informUndoManager function such that new deltas
            // aren't added to the undo manager from the new and the old session.
            s.$informUndoManager = lang.delayedCall(function() { s.$deltas = []; });

            // Copy over 'settings' from the session.
            s.setOptions(session.getOptions());
            s.$foldData = session.$cloneFoldData();

            session.on("changeAnnotation", function(){
                s.setAnnotations(session.getAnnotations());
            })();
            session.on("changeMode", function(e){
                s.setMode(session.getMode());
            });
            session.on("changeBreakpoint", function(){
                s.$breakpoints = session.$breakpoints;
                s._emit("changeBreakpoint", {});
            })();

            return s;
        }

        function setFinalState(editor, session){
            var splitInfo   = splits[editor.name];
            var pixelHeight = splitInfo.topPane.getHeight();

            var grabber = editor.aml.$int.querySelector(".splitgrabber");

            if (pixelHeight < 3) {
                // Remove the split
                splitInfo.topPane.hide();
                delete session.split;

                // Show Grabber
                grabber.style.display = "block";
            }
            else {
                // Record the height
                session.split.height = splitInfo.topPane.height;

                // Hide Grabber
                grabber.style.display = "none";
            }
        }

        function UndoManagerProxy(undoManager, session) {
            this.$u = undoManager;
            this.$doc = session;
        }

        (function() {
            this.execute = function(options) {
                this.$u.execute(options);
            };

            this.undo = function() {
                var selectionRange = this.$u.undo(true);
                if (selectionRange) {
                    this.$doc.selection.setSelectionRange(selectionRange);
                }
            };

            this.redo = function() {
                var selectionRange = this.$u.redo(true);
                if (selectionRange) {
                    this.$doc.selection.setSelectionRange(selectionRange);
                }
            };

            this.reset = function() {
                this.$u.reset();
            };

            this.hasUndo = function() {
                return this.$u.hasUndo();
            };

            this.hasRedo = function() {
                return this.$u.hasRedo();
            };
        }).call(UndoManagerProxy.prototype);

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("enable", function() {

        });
        plugin.on("disable", function() {

        });
        plugin.on("unload", function() {
            loaded = false;
            drawn  = false;
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
            _events : [
                /**
                 * @event draw
                 */
                "draw"
            ]
        });

        register(null, {
            "ace.split": plugin
        });
    }
});<commit_msg>set editor.ace to the focussed split<commit_after>define(function(require, exports, module) {
    main.consumes = ["Plugin", "ui", "ace"];
    main.provides = ["ace.split"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var ui     = imports.ui;
        var ace    = imports.ace;
        var event  = require("ace/lib/event");

        var lang         = require("ace/lib/lang");
        var Editor       = require("ace/editor").Editor;
        var Renderer     = require("ace/virtual_renderer").VirtualRenderer;
        var EditSession  = require("ace/edit_session").EditSession;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit   = plugin.getEmitter();

        var editors = [], splits = {};

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            ace.on("create", function(e){
                if (e.editor.type != "ace")
                    return;

                draw();

                var editor = e.editor;
                var grabber;

                editor.once("draw", function(){
                    grabber = createGrabber(editor);
                }, plugin);

                editor.on("documentActivate", function(e){
                    var doc       = e.doc;
                    var session   = doc.getSession();
                    var split     = session.split;
                    var splitInfo = splits[doc.editor.name];

                    // If we are not in split mode and the editor is not split
                    // lets do nothing.
                    if (!split && !splitInfo)
                        return;

                    if (split) {
                        // Make sure we have a split inited for this editor
                        if (!splitInfo)
                            splitInfo = initSplit(editor, split.height);

                        var editor2  = splitInfo.editor2;

                        // Set Session
                        editor2.setSession(split.session2);

                        // Set Height
                        splitInfo.topPane.setHeight(split.height);

                        // Show bottom pane
                        splitInfo.topPane.show();

                        // Hide Grabber
                        grabber.style.display = "none";
                    }
                    else {
                        // Hide bottom pane
                        splitInfo.topPane.hide();

                        // Show Grabber
                        grabber.style.display = "block";
                    }
                });

                editor.on("getState", function(e){
                    var session = e.doc.getSession();
                    var state   = e.state;

                    if (e.filter || !session.split)
                        return;

                    var session2 = session.split.session2;

                    state.split = {
                        height     : session.split.height,

                        // Scroll state
                        scrolltop  : session2.getScrollTop(),
                        scrollleft : session2.getScrollLeft(),

                        // Selection
                        selection  : session2.selection.toJSON()
                    };
                });

                editor.on("setState", function(e){
                    var state   = e.state.split;
                    var session = e.doc.getSession();

                    if (!state)
                        return;

                    var splitInfo = initSplit(editor, state.height);
                    var session2  = cloneSession(session.session);

                    session.split  = {
                        height   : state.height,
                        session2 : session2
                    };

                    // Set 2nd Session
                    splitInfo.editor2.setSession(session2);

                    // Set selection
                    if (state.selection)
                        session2.selection.fromJSON(state.selection);

                    // Set scroll state
                    if (state.scrolltop)
                        session2.setScrollTop(state.scrolltop);
                    if (state.scrollleft)
                        session2.setScrollLeft(state.scrollleft);

                    if (state.options)
                        session2.setOptions(state.options);

                    var grabber = editor.aml.$int.querySelector(".splitgrabber");
                    grabber.style.display = "none";
                });

                editor.on("resize", function(e){
                    var splitInfo = splits[editor.name];
                    if (!splitInfo || !splitInfo.topPane.visible) return;
                    splitInfo.editor2.resize(true); // @Harutyun
                });

                editor.on("unload", function(e){
                    delete splits[editor.name];
                });
            });

            ace.on("themeChange", function(e){
                editors.forEach(function(editor){
                    editor.setTheme(e.path);

                    var theme = ace.theme;
                    var node  = editor.splitbox.$ext.parentNode;
                    if (theme.isDark)
                        ui.setStyleClass(node, "dark");
                    else
                        ui.setStyleClass(node, "", ["dark"]);
                });
            }, plugin);
        }

        var drawn = false;
        function draw() {
            if (drawn) return;
            drawn = true;

            // Insert CSS
            ui.insertCss(require("text!./style.css"), plugin);

            emit("draw");
        }

        function createGrabber(editor){
            var htmlNode = editor.ace.container.parentNode;
            var grabber  = document.createElement("div");
            htmlNode.appendChild(grabber);
            grabber.className = "splitgrabber";
            grabber.innerHTML = "=";

            grabber.addEventListener("mousedown", function(e){
                startSplit(e, grabber, editor);
            });

            plugin.addOther(function(){
                grabber.parentNode.removeChild(grabber);
            });

            return grabber;
        }

        /***** Methods *****/

        function startSplit(e, grabber, editor){
            var container = grabber;
            var drag      = grabber;

            // Set Top
            drag.style.zIndex = 1000000;

            var offsetY = e.clientY - (parseInt(container.style.top, 10) || 0);
            var moved   = false;
            var startY  = e.clientY - offsetY;
            var offset  = e.offsetY;

            var session = editor.activeDocument.getSession();

            event.capture(container, function(e) {
                var y = e.clientY - offsetY;

                if (!moved) {
                    if (Math.abs(y - startY) > 3) {
                        moved = true;
                        var percentage = ((y - startY) / grabber.parentNode.offsetHeight) * 100;
                        var splitInfo  = initSplit(editor, percentage);
                        session.split  = {
                            height   : percentage + "%",
                            session2 : cloneSession(editor.ace.session)
                        };

                        // Set 2nd Session
                        splitInfo.editor2.setSession(session.split.session2);

                        // Start splitter
                        splitInfo.splitbox.$handle.$ext.onmousedown({
                            clientY : e.clientY,
                            offsetY : -7 + offset
                        });

                        // Hide Grabber
                        grabber.style.display = "none";
                    }
                    else return;
                }
            }, function() {
                if (moved)
                    setFinalState(editor, session);
            });

            event.stopEvent(e);
        }

        function initSplit(editor, percentage){
            if (splits[editor.name]) {
                var splitInfo = splits[editor.name];
                splitInfo.topPane.show();
                return splitInfo;
            }

            var container = editor.aml.$int;
            var amlNode   = container.host;
            // @todo detect if this already happened

            var splitbox = amlNode.appendChild(new ui.vsplitbox({
                "class"  : "ace_split",
                padding  : 7,
                edge     : "7 0 0 0",
                splitter : true
            }));

            var topPane    = splitbox.appendChild(new ui.bar({
                height: percentage + "%"
            }));
            var bottomPane = splitbox.appendChild(new ui.bar());

            // Original Editor
            bottomPane.$int.appendChild(editor.ace.container);
            editor.ace.container.style.top = "0px";

            // New Editor
            var editor2 = new Editor(new Renderer(topPane.$int, ace.theme));
            editors.push(editor2);
            editor2.splitbox = splitbox;

            splitbox.$handle.on("dragmove", function(){
                editor.resize();
                editor2.resize();
            });
            splitbox.$handle.on("dragdrop", function(){
                editor.resize();
                editor2.resize();

                var session = editor.activeDocument.getSession();
                setFinalState(editor, session);
            });
            ace.on("settingsUpdate", function(e){
                editor2.setOptions(e.options);
            }, editor);

            var lastFocused = editor2;
            editor2.on("focus", function() {
                lastFocused = editor2;
            });

            editor.ace.on("focus", function() {
                lastFocused = null;
            });

            editor.on("getAce", function() {
                if (lastFocused)
                    return editor2;
            });

            editor.addEditor(editor2);

            splits[editor.name] = {
                splitbox   : splitbox,
                topPane    : topPane,
                bottomPane : bottomPane,
                editor     : editor,
                editor2    : editor2
            };

            return splits[editor.name];
        }

        function cloneSession(session) {
            var s = new EditSession(session.getDocument(), session.getMode());

            var undoManager = session.getUndoManager();
            if (undoManager) {
                var undoManagerProxy = new UndoManagerProxy(undoManager, s);
                s.setUndoManager(undoManagerProxy);
            }

            // Overwrite the default $informUndoManager function such that new deltas
            // aren't added to the undo manager from the new and the old session.
            s.$informUndoManager = lang.delayedCall(function() { s.$deltas = []; });

            // Copy over 'settings' from the session.
            s.setOptions(session.getOptions());
            s.$foldData = session.$cloneFoldData();

            session.on("changeAnnotation", function(){
                s.setAnnotations(session.getAnnotations());
            })();
            session.on("changeMode", function(e){
                s.setMode(session.getMode());
            });
            session.on("changeBreakpoint", function(){
                s.$breakpoints = session.$breakpoints;
                s._emit("changeBreakpoint", {});
            })();

            s.c9doc = session.c9doc;

            return s;
        }

        function setFinalState(editor, session){
            var splitInfo   = splits[editor.name];
            var pixelHeight = splitInfo.topPane.getHeight();

            var grabber = editor.aml.$int.querySelector(".splitgrabber");

            if (pixelHeight < 3) {
                // Remove the split
                splitInfo.topPane.hide();
                delete session.split;

                // Show Grabber
                grabber.style.display = "block";
            }
            else {
                // Record the height
                session.split.height = splitInfo.topPane.height;

                // Hide Grabber
                grabber.style.display = "none";
            }
        }

        function UndoManagerProxy(undoManager, session) {
            this.$u = undoManager;
            this.$doc = session;
        }

        (function() {
            this.execute = function(options) {
                this.$u.execute(options);
            };

            this.undo = function() {
                var selectionRange = this.$u.undo(true);
                if (selectionRange) {
                    this.$doc.selection.setSelectionRange(selectionRange);
                }
            };

            this.redo = function() {
                var selectionRange = this.$u.redo(true);
                if (selectionRange) {
                    this.$doc.selection.setSelectionRange(selectionRange);
                }
            };

            this.reset = function() {
                this.$u.reset();
            };

            this.hasUndo = function() {
                return this.$u.hasUndo();
            };

            this.hasRedo = function() {
                return this.$u.hasRedo();
            };
        }).call(UndoManagerProxy.prototype);

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("enable", function() {

        });
        plugin.on("disable", function() {

        });
        plugin.on("unload", function() {
            loaded = false;
            drawn  = false;
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
            _events : [
                /**
                 * @event draw
                 */
                "draw"
            ]
        });

        register(null, {
            "ace.split": plugin
        });
    }
});<|endoftext|>


<commit_before>// polyfills
require('./polyfills/indexOf');

// Configure _ with string methods
require('./_.string');
// Configure O with string custom types
require('./o.custom');

var _ = require('_'),

    parser      = require('./D/parser'),
    utils       = require('./utils'),
    array       = require('./modules/array'),
    onready     = require('./modules/onready'),
    selectors   = require('./modules/selectors'),
    transversal = require('./modules/transversal'),
    dimensions  = require('./modules/dimensions'),
    manip       = require('./modules/manip'),
    css         = require('./modules/css'),
    attr        = require('./modules/attr'),
    prop        = require('./modules/prop'),
    val         = require('./modules/val'),
    position    = require('./modules/position'),
    classes     = require('./modules/classes'),
    data        = require('./modules/data'),
    events      = require('./modules/events'),
    deferred    = require('./modules/Deferred/Deferred'),
    when        = require('./modules/Deferred/when'),

    xaja        = require('./libs/xaja');

// Store previous reference
var _prevD = window.D;

var DOM = function(arg) {
    // Wasn't created with "new"
    if (!(this instanceof DOM)) { return new DOM(arg); }

    // Nothin
    if (!arg) { return; }

    // Element
    if (arg.nodeType || arg === window || arg === document) {
        this.push(arg);
        return;
    }

    // String
    if (_.isString(arg)) {

        // HTML string
        if (utils.isHtml(arg)) {
            utils.merge(this, parser.parseHtml(arg));
            return;
        }

        // Selector: perform a find without creating a new DOM
        utils.merge(this, selectors.find(arg, true));
        return;
    }

    // Array of Elements or NodeList
    if (_.isArray(arg) || _.isNodeList(arg)) {
        utils.merge(this, arg);
        return;
    }

    // Document a ready
    if (_.isFunction(arg)) {
        onready(arg);
    }
};

var _hasMoreConflict = false,
    _prevjQuery,
    _prev$;

_.extend(DOM,
    parser.D,
    data.D,
    deferred.D,
    when.D,
{
    each:    array.each,
    forEach: array.each,

    map:     _.map,
    extend:  _.extend,

    // proxy ajax to xaja
    ajax: xaja.ajax,
    get: xaja.get,
    post: xaja.post,
    put: xaja.put,
    del: xaja.del,

    noConflict: function() {
        if (_hasMoreConflict) {
            window.jQuery = _prevjQuery;
            window.$ = _prev$;

            _hasMoreConflict = false;
        }

        window.D = _prevD;
        return DOM;
    },

    moreConflict: function() {
        _hasMoreConflict = true;
        _prevjQuery = window.jQuery;
        _prev$ = window.$;
        window.jQuery = window.Zepto = window.$ = DOM;
    }
});

var arrayProto = (function(proto, obj) {

    _.each([
        'length',
        'toString',
        'toLocaleString',
        'join',
        'pop',
        'push',
        'concat',
        'reverse',
        'shift',
        'unshift',
        'slice',
        'splice',
        'sort',
        'some',
        'every',
        'indexOf',
        'lastIndexOf',
        'reduce',
        'reduceRight'
    ], function(key) {
        obj[key] = proto[key];
    });

    return obj;

}(Array.prototype, {}));

_.extend(
    DOM.prototype,
    { constructor: DOM },
    arrayProto,
    array.fn,
    selectors.fn,
    transversal.fn,
    manip.fn,
    dimensions.fn,
    css.fn,
    attr.fn,
    prop.fn,
    val.fn,
    classes.fn,
    position.fn,
    data.fn,
    events.fn
);

// Expose the prototype so that
// it can be hooked into for plugins
DOM.fn = DOM.prototype;

module.exports = window.D = DOM;

if (typeof define === 'function' && define.amd) {
    define('D', [], function() {
        return DOM;
    });
}
<commit_msg>Fixed failing test<commit_after>// polyfills
require('./polyfills/indexOf');

// Configure _ with string methods
require('./_.string');
// Configure O with string custom types
require('./o.custom');

var _ = require('_'),

    parser      = require('./D/parser'),
    utils       = require('./utils'),
    array       = require('./modules/array'),
    onready     = require('./modules/onready'),
    selectors   = require('./modules/selectors'),
    transversal = require('./modules/transversal'),
    dimensions  = require('./modules/dimensions'),
    manip       = require('./modules/manip'),
    css         = require('./modules/css'),
    attr        = require('./modules/attr'),
    prop        = require('./modules/prop'),
    val         = require('./modules/val'),
    position    = require('./modules/position'),
    classes     = require('./modules/classes'),
    data        = require('./modules/data'),
    events      = require('./modules/events'),
    deferred    = require('./modules/Deferred/Deferred'),
    when        = require('./modules/Deferred/when'),

    xaja        = require('./libs/xaja');

// Store previous reference
var _prevD = window.D;

var DOM = function(arg, attrs) {
    // Wasn't created with "new"
    if (!(this instanceof DOM)) { return new DOM(arg, attrs); }

    // Nothin
    if (!arg) { return; }

    // Element
    if (arg.nodeType || arg === window || arg === document) {
        this.push(arg);
        return;
    }

    // String
    if (_.isString(arg)) {

        // HTML string
        if (utils.isHtml(arg)) {
            utils.merge(this, parser.parseHtml(arg));
            if (attrs) { this.attr(attrs); }
            return;
        }

        // Selector: perform a find without creating a new DOM
        utils.merge(this, selectors.find(arg, true));
        return;
    }

    // Array of Elements or NodeList
    if (_.isArray(arg) || _.isNodeList(arg)) {
        utils.merge(this, arg);
        return;
    }

    // Document a ready
    if (_.isFunction(arg)) {
        onready(arg);
    }
};

var _hasMoreConflict = false,
    _prevjQuery,
    _prev$;

_.extend(DOM,
    parser.D,
    data.D,
    deferred.D,
    when.D,
{
    each:    array.each,
    forEach: array.each,

    map:     _.map,
    extend:  _.extend,

    // proxy ajax to xaja
    ajax: xaja.ajax,
    get: xaja.get,
    post: xaja.post,
    put: xaja.put,
    del: xaja.del,

    noConflict: function() {
        if (_hasMoreConflict) {
            window.jQuery = _prevjQuery;
            window.$ = _prev$;

            _hasMoreConflict = false;
        }

        window.D = _prevD;
        return DOM;
    },

    moreConflict: function() {
        _hasMoreConflict = true;
        _prevjQuery = window.jQuery;
        _prev$ = window.$;
        window.jQuery = window.Zepto = window.$ = DOM;
    }
});

var arrayProto = (function(proto, obj) {

    _.each([
        'length',
        'toString',
        'toLocaleString',
        'join',
        'pop',
        'push',
        'concat',
        'reverse',
        'shift',
        'unshift',
        'slice',
        'splice',
        'sort',
        'some',
        'every',
        'indexOf',
        'lastIndexOf',
        'reduce',
        'reduceRight'
    ], function(key) {
        obj[key] = proto[key];
    });

    return obj;

}(Array.prototype, {}));

_.extend(
    DOM.prototype,
    { constructor: DOM },
    arrayProto,
    array.fn,
    selectors.fn,
    transversal.fn,
    manip.fn,
    dimensions.fn,
    css.fn,
    attr.fn,
    prop.fn,
    val.fn,
    classes.fn,
    position.fn,
    data.fn,
    events.fn
);

// Expose the prototype so that
// it can be hooked into for plugins
DOM.fn = DOM.prototype;

module.exports = window.D = DOM;

if (typeof define === 'function' && define.amd) {
    define('D', [], function() {
        return DOM;
    });
}
<|endoftext|>


<commit_before>var step = 2;
var P = {

    getRegionsByColors: function (img, colors) { // (HTMLImageElement, Array) -> Object
        var canvas = this._wrapByCanvas(img),
            colors = this._extendColors(this._colorsToRgb(colors), 1),
            regionsPxs = this._getRegionsPixels(canvas, colors),
            regions = this._splitRegionsByDist(regionsPxs, 10);

        return regions;
    },

    _getRegionsPixels: function (canvas, colors) { // (HTMLCanvasElement, Array) -> Array
        var res = [];

        for (var x = 0; x < img.clientWidth; x = x+step) {
            for (var y = 0; y < img.clientHeight; y = y+step) {
                var px = { x: x, y: y },
                    pxCol = this._getPixelColor(canvas, px),
                    nPxs = this._getNeighborPixels(px, {
                        w: canvas.width - step,
                        h: canvas.height - step
                    }),
                    nPxCols = this._getPixelsColors(canvas, nPxs);

                // skip if px is not a boundary pixel of the feature
                if (this._areColorsEqualToColor(P.Util.Color.areEqual, nPxCols, pxCol) === true) {
                    continue;
                };

                // is it pixel of the feature?
                if(this._isColorInColors(P.Util.Color.areEqual, pxCol, colors)) {
                    res.push(px);
                }
            }
        }

        return res;
    },

    _splitRegionsByDist: function (pixels, dist) { // (Array, Number) -> Array
        var disjointSet = new P.Struct.DisjointSet(),
            res;

        for (var i = 0; i < pixels.length; i++) {
            disjointSet.add(pixels[i]);
            for (var j = 0; j < pixels.length; j++) {
                disjointSet.add(pixels[j]);
                if (P.Util.Math.getDistance(pixels[i], pixels[j]) <= dist) {
                    if (!disjointSet.find(pixels[i], pixels[j])) {
                        disjointSet.union(pixels[i], pixels[j]);
                    };
                };
            };
        };

        res = disjointSet.extract();
        disjointSet.destroy();
        return res;
    },

    _wrapByCanvas: function (img) { // (HTMLImageElement) -> HTMLCanvasElement
        var canv = document.createElement('canvas');
        canv.width = img.width;
        canv.height = img.height;
        canv.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
        return canv;
    },

    _colorsToRgb: function (cols) { // (Array) -> Array
        for (var i = 0; i < cols.length; i++) {
            cols[i] = P.Util.Color.toRGB(cols[i]);
        };
        return cols;
    },

    _extendColors: function (cols, step) { // (Array) -> Array
        var res = [];
        for (var i = 0; i < cols.length; i++) {
            res.push(cols[i]);
            for (var j = 0; j < step; j++) {
                res.push([cols[i][0] + j, cols[i][1], cols[i][2]]);
                res.push([cols[i][0] + j, cols[i][1] + j, cols[i][2]]);
                res.push([cols[i][0] + j, cols[i][1], cols[i][2] + j]);
                res.push([cols[i][0] + j, cols[i][1] + j, cols[i][2] + j]);

                res.push([cols[i][0], cols[i][1] + j, cols[i][2]]);
                res.push([cols[i][0], cols[i][1] + j, cols[i][2] + j]);

                res.push([cols[i][0], cols[i][1], cols[i][2] + j]);
                res.push([cols[i][0] + j, cols[i][1], cols[i][2] + j]);
            };
        };
        return res;
    },

    _getPixelColor: function (canvas, px) { // (HTMLCanvasElement, Object) -> Array
        return canvas.getContext('2d').getImageData(px.x, px.y, 1, 1).data;
    },

    _getPixelsColors: function (canvas, pxs) { // (HTMLCanvasElement, Array) -> Array
        var list = [];
        for (var i = 0; i < pxs.length; i++) {
        	list.push(canvas.getContext('2d').getImageData(pxs[i].x, pxs[i].y, 1, 1).data);
        };
        return list;
    },

    _isColorInColors: function (checkingFunc, col, cols) { // (Function, Array, Array) -> Boolean
        for (var i = 0; i < cols.length; i++) {
            if (checkingFunc(col, cols[i]) === true) {
                return true;
            };
        };
        return false;
    },

    _areColorsEqualToColor: function (checkingFunc, cols, col) { // (Function, Array, Array) -> Boolean
        for (var i = 0; i < cols.length; i++) {
            if (checkingFunc(col, cols[i]) === false) {
                return false;
            };
        };
        return true;
    },

    _getNeighborPixels: function (px, imgSize) { // (Object, Object) -> Array
        var res = [];

        if (px.x > 0 && px.y > 0) {
            res.push({ x: px.x-step, y: px.y-step }); // tl
        };

        if (px.y > 0) {
            res.push({ x: px.x,   y: px.y-step }); // t
        };

        if (px.x < imgSize.w && px.y > 0) {
            res.push({ x: px.x+step, y: px.y-step }); // tr
        };

        if (px.x < imgSize.w) {
            res.push({ x: px.x+step, y: px.y }); // r
        };

        if (px.x < imgSize.w && px.y < imgSize.h) {
            res.push({ x: px.x+step, y: px.y+step }); // br
        };

        if (px.y < imgSize.h) {
            res.push({ x: px.x, y: px.y+step }); // b
        };

        if (px.x > 0 && px.y < imgSize.h) {
            res.push({ x: px.x-step, y: px.y+step }); // bl
        };

        if (px.x > 0) {
            res.push({ x: px.x-step, y: px.y }); // l
        };

        return res;
    }
}<commit_msg>_extendColors function removed<commit_after>var step = 3;
var P = {

    getRegionsByColors: function (img, colors) { // (HTMLImageElement, Array) -> Object
        var canvas = this._wrapByCanvas(img),
            colors = this._colorsToRgb(colors),
            regionsPxs = this._getRegionsPixels(canvas, colors),
            regions = this._splitRegionsByDist(regionsPxs, 10);

        return regions;
    },

    _getRegionsPixels: function (canvas, colors) { // (HTMLCanvasElement, Array) -> Array
        var res = [];

        for (var x = 0; x < img.clientWidth; x = x+step) {
            for (var y = 0; y < img.clientHeight; y = y+step) {
                var px = { x: x, y: y },
                    pxCol = this._getPixelColor(canvas, px),
                    nPxs = this._getNeighborPixels(px, {
                        w: canvas.width - step,
                        h: canvas.height - step
                    }),
                    nPxCols = this._getPixelsColors(canvas, nPxs);

                // skip if px is not a boundary pixel of the feature
                if (this._areColorsEqualToColor(P.Util.Color.areEqual, nPxCols, pxCol) === true) {
                    continue;
                };

                // is it pixel of the feature?
                if(this._isColorInColors(P.Util.Color.areEqual, pxCol, colors)) {
                    res.push(px);
                }
            }
        }

        return res;
    },

    _splitRegionsByDist: function (pixels, dist) { // (Array, Number) -> Array
        var disjointSet = new P.Struct.DisjointSet(),
            res;

        for (var i = 0; i < pixels.length; i++) {
            disjointSet.add(pixels[i]);
            for (var j = 0; j < pixels.length; j++) {
                disjointSet.add(pixels[j]);
                if (P.Util.Math.getDistance(pixels[i], pixels[j]) <= dist) {
                    if (!disjointSet.find(pixels[i], pixels[j])) {
                        disjointSet.union(pixels[i], pixels[j]);
                    };
                };
            };
        };

        res = disjointSet.extract();
        disjointSet.destroy();
        return res;
    },

    _wrapByCanvas: function (img) { // (HTMLImageElement) -> HTMLCanvasElement
        var canv = document.createElement('canvas');
        canv.width = img.width;
        canv.height = img.height;
        canv.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
        return canv;
    },

    _colorsToRgb: function (cols) { // (Array) -> Array
        for (var i = 0; i < cols.length; i++) {
            cols[i] = P.Util.Color.toRGB(cols[i]);
        };
        return cols;
    },

    _getPixelColor: function (canvas, px) { // (HTMLCanvasElement, Object) -> Array
        return canvas.getContext('2d').getImageData(px.x, px.y, 1, 1).data;
    },

    _getPixelsColors: function (canvas, pxs) { // (HTMLCanvasElement, Array) -> Array
        var list = [];
        for (var i = 0; i < pxs.length; i++) {
        	list.push(canvas.getContext('2d').getImageData(pxs[i].x, pxs[i].y, 1, 1).data);
        };
        return list;
    },

    _isColorInColors: function (checkingFunc, col, cols) { // (Function, Array, Array) -> Boolean
        for (var i = 0; i < cols.length; i++) {
            if (checkingFunc(col, cols[i]) === true) {
                return true;
            };
        };
        return false;
    },

    _areColorsEqualToColor: function (checkingFunc, cols, col) { // (Function, Array, Array) -> Boolean
        for (var i = 0; i < cols.length; i++) {
            if (checkingFunc(col, cols[i]) === false) {
                return false;
            };
        };
        return true;
    },

    _getNeighborPixels: function (px, imgSize) { // (Object, Object) -> Array
        var res = [];

        if (px.x > 0 && px.y > 0) {
            res.push({ x: px.x-step, y: px.y-step }); // tl
        };

        if (px.y > 0) {
            res.push({ x: px.x,   y: px.y-step }); // t
        };

        if (px.x < imgSize.w && px.y > 0) {
            res.push({ x: px.x+step, y: px.y-step }); // tr
        };

        if (px.x < imgSize.w) {
            res.push({ x: px.x+step, y: px.y }); // r
        };

        if (px.x < imgSize.w && px.y < imgSize.h) {
            res.push({ x: px.x+step, y: px.y+step }); // br
        };

        if (px.y < imgSize.h) {
            res.push({ x: px.x, y: px.y+step }); // b
        };

        if (px.x > 0 && px.y < imgSize.h) {
            res.push({ x: px.x-step, y: px.y+step }); // bl
        };

        if (px.x > 0) {
            res.push({ x: px.x-step, y: px.y }); // l
        };

        return res;
    }
}<|endoftext|>


<commit_before>/*!
* Copyright 2015 linkFLy - http://www.cnblogs.com/silin6/
* Released under the MIT license
* http://opensource.org/licenses/mit-license.php
* Help documenthttps://github.com/linkFly6/X
* Date: 2014-8-24 20:17:18
*/
(function (window, undefined) {
    'use strcit';
    var push = Array.prototype.push,
    splice = Array.prototype.splice,
    slice = Array.prototype.slice,
    toString = Object.prototype.toString,
    each = Array.prototype.forEach,
    filter = Array.prototype.filter,
    map = Array.prototype.map,
    class2type = {},
    XType = function (obj) {
        return obj == null ? toString(obj) : class2type[toString.call(obj)] || "object";
    },
    isFunction = function (fn) {
        return XType(fn) === 'function';
    },
    isArrayLike = function (obj) {
        if (obj == null) return false;
        var length = obj.length, type = XType(obj);
        if (obj == obj.window)
            return true;
        if (obj.nodeType === 1 && length)
            return true;
        // invalid 'in' operand objin ַЧ
        return type === 'array' || type !== 'function' && type !== 'string' && (length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj);
    },
    matchRouting = function (name) {
        var res = [];
        if (name) {
            var matchResult = name.match(regRoutingExpression);
            if (matchResult && matchResult[1]) {// //dispolay/item[position()='abc'] [ƥı,position,=,'abc']
                res[1] = function (elems) {
                    return specialExec[matchResult[1]] && specialExec[matchResult[1]].call(elems, elems, matchResult);
                };
            }
            res[0] = name.replace(regRouting, '');
        }
        return res;
    },
    regRouting = /\[([^\]]*)\]/g,//ƥxpathѡ//display/test[position()=1]
    regRoutingExpression = /\[(.+)(?:\(\))([=<>])([^\]]+)]/,//ƥ䲢ֽѡʽ
    specialFind = function (context, xpath) {
        var selectors = xpath.replace('//', function () {
            while (context.parentNode)//ȡĵڵ
                context = context.parentNode;
            return '';
        }).split('/'),
           tmp,
           len = selectors.length,
           tagName = selectors[len - 1],//һǩΪӼ
           specialFn,
           filters,//()
           results;//˼
        //matchRoutingй TODO
        if (tagName) {
            tmp = matchRouting(tagName);
            filters = context.getElementsByTagName(tmp[0]);
            if (tmp[1])
                filters = tmp[1](filters);
            results = filters && slice.call(filters);
        }
        if (!filters) return [];
        selectors.pop();
        //ʼ
        while (tagName = selectors.pop()) {
            //Ӽ
            tmp = matchRouting(tagName);
            specialFn = tmp[1];
            tagName = tmp[0];
            if (tagName)
                filters = map.call(filters, function (elem, i) {
                    if (!results[i]) return null;
                    tmp = results[i].parentNode;
                    if (tmp.tagName == tagName) {//нڵ
                        results[i] = tmp;//Ӧµ¸ڵ
                        return elem;
                    } else {
                        return filters[i] = null;//ɾӦ
                    }
                });
            if (specialFn)
                filters = specialFn(filters);
        }
        return filter.call(filters, function (elem) {
            return elem != null;
        });
    },
    specialExec = {
        'position': function (elems, routingExpressionArray) {
            //TODO ˽
            if (!elems) return [];
            var symbol = routingExpressionArray[2].replace(/'/g, ''),
                max = +routingExpressionArray[3],
                //symbolȷjs߼ᱨ
                fn = new Function("index", "max", "return index" + (symbol === '=' ? '==' : symbol) + "max");
            return filter.call(elems, function (elem, index) {
                return fn(index, max);
            });
        }
    },
    domParser = new DOMParser(),
    xPathEvaluator = function () {
        try {
            return new XPathEvaluator();
        } catch (e) {
            return false;
        }
    }(),
    isNode = function (node) {
        /// <summary>
        ///
 1.1 - isNode(node)һǷElementElement
        /// </summary>
        /// <param name="node" type="Object">
        /// ҪĶ
        /// </param>
        /// <returns type="boolean" />
        var nodeType = node && node.nodeType;
        return nodeType && nodeType === 1 || nodeType === 9;
    },
    find = function (xPath, context) {
        /// <summary>
        /// X.find(xPath,context) - ģcontextXMLԪ
        /// </summary>
        /// <param name="xPath" type="String">
        /// *xPath
        /// </param>
        /// <param name="context" type="Element">
        /// *XML
        /// </param>
        /// <returns type="Array" />
        //webkit || IE>8 if you want to support IE<=8 : selectNodes
        //		alert('XPathEvaluator'+window.XPathEvaluator+',DOMParser:'+window.DOMParser+',XPathResult'+XPathResult);
        var nodeList = [], isStr = XType(xPath) === 'string', node;
        if (!isStr) return nodeList;
        if (isArrayLike(context)) {
            each.call(context, function (elem) {
                nodeList = nodeList.concat(find(xPath, elem));
            });
            return nodeList;
        }
        if (!isNode(context)) return nodeList;
        if (xPathEvaluator)//w3c
            try {
                var result = xPathEvaluator.evaluate(xPath, context, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
                while (node = result.iterateNext())
                    nodeList.push(node);
            } catch (e) { }
        else {
            //֧XPathEvaluator()дʷ[Ŀǰ֧position()]
            nodeList = specialFind(context, xPath);
        }
        //else //else
        //    alert('selectSingleNode()' + context.selectSingleNode + ',selectNodes()' + context.selectNodes);
        return nodeList;
    },
    addElem = function (target, item) {
        /// <summary>
        ///
 1.1 - addElem(target, item)׷һԪأitemĿ꣨target
        /// </summary>
        /// <param name="target" type="X">
        /// X
        /// </param>
        /// <param name="item" type="Elements">
        /// ElementNodeListArrayLike
        /// </param>
        /// <returns type="Array" />
        if (isArrayLike(item))
            each.call(item, function (elem) {
                addElem(target, elem);
            });
        else if (isNode(item))
            push.call(target, item);
    };
    'Boolean Number String Function Array Date RegExp Object'.split(' ').forEach(function (name) {
        class2type['[object ' + name + ']'] = name.toLowerCase();
    });
    var X = function (xml, xPath) {
        /// <summary>
        /// 1: XMLX,documentxmlĵģҪ
        ///
 1.1 - X(xml)xmlַ
        ///
 1.2 - X(document[,xPath])documentɣԸָxPath
        ///
 1.3 - X(Element[,xPath])ElementԸָxPath
        ///
 1.4 - X(NodeList)NodeList
        /// </summary>
        /// <param name="xml" type="String">
        /// *xmlıdocument
        /// </param>
        /// <param name="filter" type="boolean">
        /// ˣĬ(false)ˣtruehtml><ǩҲԴһΪ˺ձ뷵һõDocumentxmlַǩ
        /// </param>
        /// <returns type="X" />
        if (!(this instanceof X))
            return new X(xml, xPath);
        if (!xml) return;
        var context = [];
        //[object String]
        if (XType(xml) === 'string') {
            try {
                context.push(domParser.parseFromString(xml, 'text/xml'));
            } catch (e) {
                //console.log(e);
            }
        } else if (isNode(xml))//Element or Document
            context.push(xml);
        else if (isArrayLike(xml))//X Object or ArrayLike
            context = xml;
        if (XType(xPath) === 'string')
            addElem(this, find(xPath, context));
        else if (xml instanceof X)
            return xml;
        else
            addElem(this, context);
    };
    X.prototype = {
        version: 'linkFly.X.1.2',
        constructor: X,
        length: 0,
        find: function (xPath, context) {
            /// <summary>
            /// 1: xpathǩ
            ///
 1.1 - find(xPath[,context])xpath
            /// </summary>
            /// <param name="xPath" type="String">
            /// xpath
            /// </param>
            /// <param name="context" type="Document">
            ///
            /// </param>
            /// <returns type="X" />
            return X(context || this, xPath);
        },
        text: function (value) {
            /// <summary>
            /// 1: ȡElementеı
            ///
 1.1 - text()ȡ
            ///
 1.2 - text(value)
            /// </summary>
            /// <param name="value" type="String">
            /// ȡõֵ
            /// </param>
            /// <returns type="X" />
            if (!arguments.length && value == undefined) {
                var first = this[0];
                return (first && first.firstChild && first.firstChild.nodeValue) || '';
            }
            if (this.length)
                each.call(this, function (item) {
                    item.firstChild.nodeValue = value;
                });
            return this;
        },
        attr: function (attr, value) {
            /// <summary>
            /// 1: ȡElement
            ///
 1.1 - attr(attr)ȡ
            ///
 1.2 - attr(attr,value)
            /// </summary>
            /// <param name="value" type="String">
            /// ȡõ
            /// </param>
            /// <returns type="X" />
            if (arguments.length === 2) {
                value = value == undefined ? '' : value;
                if (this.length)
                    each.call(this, function (item) {
                        item.setAttribute(attr, value);
                    });
                return this;
            }
            var first = this[0];
            return first && first.getAttribute && first.getAttribute(attr) || '';
        },
        each: function (fn) {
            /// <summary>
            /// 1: ѭXеÿXML DOM
            ///
 1.1 - each(fn)ȡ
            /// </summary>
            /// <param name="fn" type="Function">
            /// ÿѭҪִеĺúthisָǰѭXMLԪأElementһǸԪصXװڶXMLĵ
            /// </param>
            /// <returns type="X" />
            if (!isFunction(fn)) return;
            for (var i = 0, len = this.length; i < len; i++)
                if (fn.call(this[i], this[i], i) === false) return false;
            return this;
        }
    };
    [
    ['eq', function (args) {
        /// <summary>
        /// 1: ȡָеX
        ///
 1.1 - eq(index)xpath
        /// </summary>
        /// <param name="index" type="Int">
        ///
        /// </param>
        /// <returns type="X" />
        return X(this[args[0]]);
    }],
    ['slice', function (args) {
        /// <summary>
        /// 1: ȡXָʼX󣬷صһȫµX
        ///
 1.1 - slice(start[,end])xpath
        /// </summary>
        /// <param name="index" type="Int">
        /// ʼ
        /// </param>
        /// <param name="end" type="Int">
        /// Ĭȫȡ
        /// </param>
        /// <returns type="X" />
        return X(slice.call(this, args[0] || 0, args[1] || this.length - 1));
    }],
    ['splice', function (args) {
        /// <summary>
        /// 1: οsplice - /X/ɾĿȻ󷵻رɾĿ
        ///
 1.1 - splice(index,howmany,item1)/X/ɾĿȻ󷵻رɾĿ
        /// </summary>
        /// <param name="index" type="Int">
        /// 涨/ɾλ
        /// </param>
        /// <param name="howmany" type="Int">
        /// Ҫɾ
        /// </param>
        /// <param name="item1" type="Int">
        /// X׷ӵ
        /// </param>
        /// <returns type="X" />
        var items = [args[0] || 0, args[1] || 0].concat(slice.call(args, 2));
        return X(splice.apply(this, items));
    }]
    ].forEach(function (array) {
        X.prototype[array[0]] = function () {
            if (!this.length) return null;
            return array[1].call(this, arguments);
        };
    });
    X.isXML = function (doc) {
        /// <summary>
        /// X.isXML(doc) - һDocumentǷXML Document
        /// </summary>
        /// <param name="doc" type="Document">
        /// ҪXML Document
        /// </param>
        /// <returns type="Array" />
        return doc && doc.createElement && doc.createElement('P').nodeName !== doc.createElement('p').nodeName;
    };
    X.find = find;
    window.X = X;
})(window);<commit_msg>兼容AMD规范<commit_after>/*!
* Copyright 2015 linkFLy - http://www.cnblogs.com/silin6/
* Released under the MIT license
* http://opensource.org/licenses/mit-license.php
* Help documenthttps://github.com/linkFly6/X
* Date: 2014-8-24 20:17:18
*/
(function (window, undefined) {
    'use strcit';
    var push = Array.prototype.push,
    splice = Array.prototype.splice,
    slice = Array.prototype.slice,
    toString = Object.prototype.toString,
    each = Array.prototype.forEach,
    filter = Array.prototype.filter,
    map = Array.prototype.map,
    class2type = {},
    XType = function (obj) {
        return obj == null ? toString(obj) : class2type[toString.call(obj)] || "object";
    },
    isFunction = function (fn) {
        return XType(fn) === 'function';
    },
    isArrayLike = function (obj) {
        if (obj == null) return false;
        var length = obj.length, type = XType(obj);
        if (obj == obj.window)
            return true;
        if (obj.nodeType === 1 && length)
            return true;
        // invalid 'in' operand objin ַЧ
        return type === 'array' || type !== 'function' && type !== 'string' && (length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj);
    },
    matchRouting = function (name) {
        var res = [];
        if (name) {
            var matchResult = name.match(regRoutingExpression);
            if (matchResult && matchResult[1]) {// //dispolay/item[position()='abc'] [ƥı,position,=,'abc']
                res[1] = function (elems) {
                    return specialExec[matchResult[1]] && specialExec[matchResult[1]].call(elems, elems, matchResult);
                };
            }
            res[0] = name.replace(regRouting, '');
        }
        return res;
    },
    regRouting = /\[([^\]]*)\]/g,//ƥxpathѡ//display/test[position()=1]
    regRoutingExpression = /\[(.+)(?:\(\))([=<>])([^\]]+)]/,//ƥ䲢ֽѡʽ
    specialFind = function (context, xpath) {
        var selectors = xpath.replace('//', function () {
            while (context.parentNode)//ȡĵڵ
                context = context.parentNode;
            return '';
        }).split('/'),
           tmp,
           len = selectors.length,
           tagName = selectors[len - 1],//һǩΪӼ
           specialFn,
           filters,//()
           results;//˼
        //matchRoutingй TODO
        if (tagName) {
            tmp = matchRouting(tagName);
            filters = context.getElementsByTagName(tmp[0]);
            if (tmp[1])
                filters = tmp[1](filters);
            results = filters && slice.call(filters);
        }
        if (!filters) return [];
        selectors.pop();
        //ʼ
        while (tagName = selectors.pop()) {
            //Ӽ
            tmp = matchRouting(tagName);
            specialFn = tmp[1];
            tagName = tmp[0];
            if (tagName)
                filters = map.call(filters, function (elem, i) {
                    if (!results[i]) return null;
                    tmp = results[i].parentNode;
                    if (tmp.tagName == tagName) {//нڵ
                        results[i] = tmp;//Ӧµ¸ڵ
                        return elem;
                    } else {
                        return filters[i] = null;//ɾӦ
                    }
                });
            if (specialFn)
                filters = specialFn(filters);
        }
        return filter.call(filters, function (elem) {
            return elem != null;
        });
    },
    specialExec = {
        'position': function (elems, routingExpressionArray) {
            //TODO ˽
            if (!elems) return [];
            var symbol = routingExpressionArray[2].replace(/'/g, ''),
                max = +routingExpressionArray[3],
                //symbolȷjs߼ᱨ
                fn = new Function("index", "max", "return index" + (symbol === '=' ? '==' : symbol) + "max");
            return filter.call(elems, function (elem, index) {
                return fn(index, max);
            });
        }
    },
    domParser = new DOMParser(),
    xPathEvaluator = function () {
        try {
            return new XPathEvaluator();
        } catch (e) {
            return false;
        }
    }(),
    isNode = function (node) {
        /// <summary>
        ///
 1.1 - isNode(node)һǷElementElement
        /// </summary>
        /// <param name="node" type="Object">
        /// ҪĶ
        /// </param>
        /// <returns type="boolean" />
        var nodeType = node && node.nodeType;
        return nodeType && nodeType === 1 || nodeType === 9;
    },
    find = function (xPath, context) {
        /// <summary>
        /// X.find(xPath,context) - ģcontextXMLԪ
        /// </summary>
        /// <param name="xPath" type="String">
        /// *xPath
        /// </param>
        /// <param name="context" type="Element">
        /// *XML
        /// </param>
        /// <returns type="Array" />
        //webkit || IE>8 if you want to support IE<=8 : selectNodes
        //		alert('XPathEvaluator'+window.XPathEvaluator+',DOMParser:'+window.DOMParser+',XPathResult'+XPathResult);
        var nodeList = [], isStr = XType(xPath) === 'string', node;
        if (!isStr) return nodeList;
        if (isArrayLike(context)) {
            each.call(context, function (elem) {
                nodeList = nodeList.concat(find(xPath, elem));
            });
            return nodeList;
        }
        if (!isNode(context)) return nodeList;
        if (xPathEvaluator)//w3c
            try {
                var result = xPathEvaluator.evaluate(xPath, context, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
                while (node = result.iterateNext())
                    nodeList.push(node);
            } catch (e) { }
        else {
            //֧XPathEvaluator()дʷ[Ŀǰ֧position()]
            nodeList = specialFind(context, xPath);
        }
        //else //else
        //    alert('selectSingleNode()' + context.selectSingleNode + ',selectNodes()' + context.selectNodes);
        return nodeList;
    },
    addElem = function (target, item) {
        /// <summary>
        ///
 1.1 - addElem(target, item)׷һԪأitemĿ꣨target
        /// </summary>
        /// <param name="target" type="X">
        /// X
        /// </param>
        /// <param name="item" type="Elements">
        /// ElementNodeListArrayLike
        /// </param>
        /// <returns type="Array" />
        if (isArrayLike(item))
            each.call(item, function (elem) {
                addElem(target, elem);
            });
        else if (isNode(item))
            push.call(target, item);
    };
    'Boolean Number String Function Array Date RegExp Object'.split(' ').forEach(function (name) {
        class2type['[object ' + name + ']'] = name.toLowerCase();
    });
    var X = function (xml, xPath) {
        /// <summary>
        /// 1: XMLX,documentxmlĵģҪ
        ///
 1.1 - X(xml)xmlַ
        ///
 1.2 - X(document[,xPath])documentɣԸָxPath
        ///
 1.3 - X(Element[,xPath])ElementԸָxPath
        ///
 1.4 - X(NodeList)NodeList
        /// </summary>
        /// <param name="xml" type="String">
        /// *xmlıdocument
        /// </param>
        /// <param name="filter" type="boolean">
        /// ˣĬ(false)ˣtruehtml><ǩҲԴһΪ˺ձ뷵һõDocumentxmlַǩ
        /// </param>
        /// <returns type="X" />
        if (!(this instanceof X))
            return new X(xml, xPath);
        if (!xml) return;
        var context = [];
        //[object String]
        if (XType(xml) === 'string') {
            try {
                context.push(domParser.parseFromString(xml, 'text/xml'));
            } catch (e) {
                //console.log(e);
            }
        } else if (isNode(xml))//Element or Document
            context.push(xml);
        else if (isArrayLike(xml))//X Object or ArrayLike
            context = xml;
        if (XType(xPath) === 'string')
            addElem(this, find(xPath, context));
        else if (xml instanceof X)
            return xml;
        else
            addElem(this, context);
    };
    X.prototype = {
        version: 'linkFly.X.1.2',
        constructor: X,
        length: 0,
        find: function (xPath, context) {
            /// <summary>
            /// 1: xpathǩ
            ///
 1.1 - find(xPath[,context])xpath
            /// </summary>
            /// <param name="xPath" type="String">
            /// xpath
            /// </param>
            /// <param name="context" type="Document">
            ///
            /// </param>
            /// <returns type="X" />
            return X(context || this, xPath);
        },
        text: function (value) {
            /// <summary>
            /// 1: ȡElementеı
            ///
 1.1 - text()ȡ
            ///
 1.2 - text(value)
            /// </summary>
            /// <param name="value" type="String">
            /// ȡõֵ
            /// </param>
            /// <returns type="X" />
            if (!arguments.length && value == undefined) {
                var first = this[0];
                return (first && first.firstChild && first.firstChild.nodeValue) || '';
            }
            if (this.length)
                each.call(this, function (item) {
                    item.firstChild.nodeValue = value;
                });
            return this;
        },
        attr: function (attr, value) {
            /// <summary>
            /// 1: ȡElement
            ///
 1.1 - attr(attr)ȡ
            ///
 1.2 - attr(attr,value)
            /// </summary>
            /// <param name="value" type="String">
            /// ȡõ
            /// </param>
            /// <returns type="X" />
            if (arguments.length === 2) {
                value = value == undefined ? '' : value;
                if (this.length)
                    each.call(this, function (item) {
                        item.setAttribute(attr, value);
                    });
                return this;
            }
            var first = this[0];
            return first && first.getAttribute && first.getAttribute(attr) || '';
        },
        each: function (fn) {
            /// <summary>
            /// 1: ѭXеÿXML DOM
            ///
 1.1 - each(fn)ȡ
            /// </summary>
            /// <param name="fn" type="Function">
            /// ÿѭҪִеĺúthisָǰѭXMLԪأElementһǸԪصXװڶXMLĵ
            /// </param>
            /// <returns type="X" />
            if (!isFunction(fn)) return;
            for (var i = 0, len = this.length; i < len; i++)
                if (fn.call(this[i], this[i], i) === false) return false;
            return this;
        }
    };
    [
    ['eq', function (args) {
        /// <summary>
        /// 1: ȡָеX
        ///
 1.1 - eq(index)xpath
        /// </summary>
        /// <param name="index" type="Int">
        ///
        /// </param>
        /// <returns type="X" />
        return X(this[args[0]]);
    }],
    ['slice', function (args) {
        /// <summary>
        /// 1: ȡXָʼX󣬷صһȫµX
        ///
 1.1 - slice(start[,end])xpath
        /// </summary>
        /// <param name="index" type="Int">
        /// ʼ
        /// </param>
        /// <param name="end" type="Int">
        /// Ĭȫȡ
        /// </param>
        /// <returns type="X" />
        return X(slice.call(this, args[0] || 0, args[1] || this.length - 1));
    }],
    ['splice', function (args) {
        /// <summary>
        /// 1: οsplice - /X/ɾĿȻ󷵻رɾĿ
        ///
 1.1 - splice(index,howmany,item1)/X/ɾĿȻ󷵻رɾĿ
        /// </summary>
        /// <param name="index" type="Int">
        /// 涨/ɾλ
        /// </param>
        /// <param name="howmany" type="Int">
        /// Ҫɾ
        /// </param>
        /// <param name="item1" type="Int">
        /// X׷ӵ
        /// </param>
        /// <returns type="X" />
        var items = [args[0] || 0, args[1] || 0].concat(slice.call(args, 2));
        return X(splice.apply(this, items));
    }]
    ].forEach(function (array) {
        X.prototype[array[0]] = function () {
            if (!this.length) return null;
            return array[1].call(this, arguments);
        };
    });
    X.isXML = function (doc) {
        /// <summary>
        /// X.isXML(doc) - һDocumentǷXML Document
        /// </summary>
        /// <param name="doc" type="Document">
        /// ҪXML Document
        /// </param>
        /// <returns type="Array" />
        return doc && doc.createElement && doc.createElement('P').nodeName !== doc.createElement('p').nodeName;
    };
    X.find = find;
    if (typeof define === "function" && define.amd) {
        define(function () {
            return X;
        })
    } else {
        window.so = window.so || {};
        window.so.X = X;
    }
})(window);<|endoftext|>


<commit_before>window.c.h = ((m, moment) => {
    //Date Helpers

    const hashMatch = (str) => { return window.location.hash === str; },
        paramByName = (name) => {
            const normalName = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'),
                regex = new RegExp('[\\?&]' + normalName + '=([^&#]*)'),
                results = regex.exec(location.search);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        },
        setMomentifyLocale = () => {
            moment.locale('pt', {
                    monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_')
                });
        },
        existy = (x) => {
            return x != null;
        },

        momentify = (date, format) => {
            format = format || 'DD/MM/YYYY';
            return date ? moment(date).locale('pt').format(format) : 'no date';
        },

        storeAction = (action) => {
            if (!sessionStorage.getItem(action)) {
                return sessionStorage.setItem(action, action);
            }
        },

        callStoredAction = (action, func) => {
            if (sessionStorage.getItem(action)) {
                func.call();
                return sessionStorage.removeItem(action);
            }
        },

        discuss = (page, identifier) => {
            const d = document,
                s = d.createElement('script');
            window.disqus_config = function() {
                this.page.url = page;
                this.page.identifier = identifier;
            };
            s.src = '//catarseflex.disqus.com/embed.js';
            s.setAttribute('data-timestamp', +new Date());
            (d.head || d.body).appendChild(s);
            return m('');
        },

        momentFromString = (date, format) => {
            const european = moment(date, format || 'DD/MM/YYYY');
            return european.isValid() ? european : moment(date);
        },

        translatedTimeUnits = {
            days: 'dias',
            minutes: 'minutos',
            hours: 'horas',
            seconds: 'segundos'
        },
        //Object manipulation helpers
        translatedTime = (time) => {
            const translatedTime = translatedTimeUnits,
                unit = () => {
                    const projUnit = translatedTime[time.unit || 'seconds'];

                    return (time.total <= 1) ? projUnit.slice(0, -1) : projUnit;
                };

            return {
                unit: unit(),
                total: time.total
            };
        },

        //Number formatting helpers
        generateFormatNumber = (s, c) => {
            return (number, n, x) => {
                if (!_.isNumber(number)) {
                    return null;
                }

                const re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
                    num = number.toFixed(Math.max(0, ~~n));
                return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
            };
        },
        formatNumber = generateFormatNumber('.', ','),

        toggleProp = (defaultState, alternateState) => {
            const p = m.prop(defaultState);
            p.toggle = () => {
                return p(((p() === alternateState) ? defaultState : alternateState));
            };

            return p;
        },

        idVM = m.postgrest.filtersVM({
            id: 'eq'
        }),

        getUser = () => {
            const body = document.getElementsByTagName('body'),
                data = _.first(body).getAttribute('data-user');
            if (data) {
                return JSON.parse(data);
            } else {
                return false;
            }
        },

        locationActionMatch = (action) => {
            const act = window.location.pathname.split('/').slice(-1)[0];
            return action === act;
        },

        useAvatarOrDefault = (avatarPath) => {
            return avatarPath || '/assets/catarse_bootstrap/user.jpg';
        },

        //Templates
        loader = () => {
            return m('.u-text-center.u-margintop-30 u-marginbottom-30', [
                m('img[alt="Loader"][src="https://s3.amazonaws.com/catarse.files/loader.gif"]')
            ]);
        },

        fbParse = () => {
            const tryParse = () => {
                try {
                    window.FB.XFBML.parse();
                } catch (e) {
                    console.log(e);
                }
            };

            return window.setTimeout(tryParse, 500); //use timeout to wait async of facebook
        },

        pluralize = (count, s, p) => {
            return (count > 1 ? count + p : count + s);
        },

        simpleFormat = (str = '') => {
            str = str.replace(/\r\n?/, '\n');
            if (str.length > 0) {
                str = str.replace(/\n\n+/g, '

');
                str = str.replace(/\n/g, '
');
                str = '
' + str + '
';
            }
            return str;
        },

        rewardSouldOut = (reward) => {
            return (reward.maximum_contributions > 0 ?
                (reward.paid_count + reward.waiting_payment_count >= reward.maximum_contributions) : false);
        },

        rewardRemaning = (reward) => {
            return reward.maximum_contributions - (reward.paid_count + reward.waiting_payment_count);
        },

        parseUrl = (href) => {
            const l = document.createElement('a');
            l.href = href;
            return l;
        },

        mixpanelTrack = () => {
            return (el, isInitialized) => {
                if (!isInitialized) {
                    window.CatarseMixpanel.activate();
                }
            };
        },

        UIHelper = () => {
            return (el, isInitialized) => {
                if (!isInitialized && $) {
                    window.UIHelper.setupResponsiveIframes($(el));
                }
            };
        },

        toAnchor = () => {
            return (el, isInitialized) => {
                if (!isInitialized){
                    const hash = window.location.hash.substr(1);
                    if (hash === el.id) {
                        window.location.hash = '';
                        setTimeout(function(){
                            window.location.hash = el.id;
                        });
                    }
                }
            };
        },

        validateEmail = (email) => {
            const re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
            return re.test(email);
        },

        navigateToDevise = () => {
            window.location.href = '/pt/login';
            return false;
        },

        cumulativeOffset = (element) => {
            let top = 0, left = 0;
            do {
                top += element.offsetTop  || 0;
                left += element.offsetLeft || 0;
                element = element.offsetParent;
            } while (element);

            return {
                top: top,
                left: left
            };
        },

        closeFlash = () => {
            let el = document.getElementsByClassName('icon-close')[0];
            if (_.isElement(el)){
                el.onclick = (event) => {
                    event.preventDefault();

                    el.parentElement.remove();
                };
            };
        },

        i18nScope = (scope, obj) => {
            obj = obj || {};
            return _.extend({}, obj, {scope: scope});
        };

    setMomentifyLocale();
    closeFlash();

    return {
        cumulativeOffset: cumulativeOffset,
        discuss: discuss,
        existy: existy,
        validateEmail: validateEmail,
        momentify: momentify,
        momentFromString: momentFromString,
        formatNumber: formatNumber,
        idVM: idVM,
        getUser: getUser,
        toggleProp: toggleProp,
        loader: loader,
        fbParse: fbParse,
        pluralize: pluralize,
        simpleFormat: simpleFormat,
        translatedTime: translatedTime,
        rewardSouldOut: rewardSouldOut,
        rewardRemaning: rewardRemaning,
        parseUrl: parseUrl,
        hashMatch: hashMatch,
        useAvatarOrDefault: useAvatarOrDefault,
        locationActionMatch: locationActionMatch,
        mixpanelTrack: mixpanelTrack,
        navigateToDevise: navigateToDevise,
        storeAction: storeAction,
        callStoredAction: callStoredAction,
        UIHelper: UIHelper,
        toAnchor: toAnchor,
        paramByName: paramByName,
        i18nScope: i18nScope
    };
}(window.m, window.moment));
<commit_msg>Adds new feature badge helper<commit_after>window.c.h = ((m, moment, I18n) => {
    //Date Helpers

    const hashMatch = (str) => { return window.location.hash === str; },
        paramByName = (name) => {
            const normalName = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'),
                regex = new RegExp('[\\?&]' + normalName + '=([^&#]*)'),
                results = regex.exec(location.search);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        },
        setMomentifyLocale = () => {
            moment.locale('pt', {
                    monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_')
                });
        },
        existy = (x) => {
            return x != null;
        },

        momentify = (date, format) => {
            format = format || 'DD/MM/YYYY';
            return date ? moment(date).locale('pt').format(format) : 'no date';
        },

        storeAction = (action) => {
            if (!sessionStorage.getItem(action)) {
                return sessionStorage.setItem(action, action);
            }
        },

        callStoredAction = (action, func) => {
            if (sessionStorage.getItem(action)) {
                func.call();
                return sessionStorage.removeItem(action);
            }
        },

        discuss = (page, identifier) => {
            const d = document,
                s = d.createElement('script');
            window.disqus_config = function() {
                this.page.url = page;
                this.page.identifier = identifier;
            };
            s.src = '//catarseflex.disqus.com/embed.js';
            s.setAttribute('data-timestamp', +new Date());
            (d.head || d.body).appendChild(s);
            return m('');
        },

        momentFromString = (date, format) => {
            const european = moment(date, format || 'DD/MM/YYYY');
            return european.isValid() ? european : moment(date);
        },

        translatedTimeUnits = {
            days: 'dias',
            minutes: 'minutos',
            hours: 'horas',
            seconds: 'segundos'
        },
        //Object manipulation helpers
        translatedTime = (time) => {
            const translatedTime = translatedTimeUnits,
                unit = () => {
                    const projUnit = translatedTime[time.unit || 'seconds'];

                    return (time.total <= 1) ? projUnit.slice(0, -1) : projUnit;
                };

            return {
                unit: unit(),
                total: time.total
            };
        },

        //Number formatting helpers
        generateFormatNumber = (s, c) => {
            return (number, n, x) => {
                if (!_.isNumber(number)) {
                    return null;
                }

                const re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
                    num = number.toFixed(Math.max(0, ~~n));
                return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
            };
        },
        formatNumber = generateFormatNumber('.', ','),

        toggleProp = (defaultState, alternateState) => {
            const p = m.prop(defaultState);
            p.toggle = () => {
                return p(((p() === alternateState) ? defaultState : alternateState));
            };

            return p;
        },

        idVM = m.postgrest.filtersVM({
            id: 'eq'
        }),

        getUser = () => {
            const body = document.getElementsByTagName('body'),
                data = _.first(body).getAttribute('data-user');
            if (data) {
                return JSON.parse(data);
            } else {
                return false;
            }
        },

        locationActionMatch = (action) => {
            const act = window.location.pathname.split('/').slice(-1)[0];
            return action === act;
        },

        useAvatarOrDefault = (avatarPath) => {
            return avatarPath || '/assets/catarse_bootstrap/user.jpg';
        },

        //Templates
        loader = () => {
            return m('.u-text-center.u-margintop-30 u-marginbottom-30', [
                m('img[alt="Loader"][src="https://s3.amazonaws.com/catarse.files/loader.gif"]')
            ]);
        },

        newFeatureBadge = () => {
            return m('span.badge.badge-success.margin-side-5', I18n.t('projects.new_feature_badge'));
        },

        fbParse = () => {
            const tryParse = () => {
                try {
                    window.FB.XFBML.parse();
                } catch (e) {
                    console.log(e);
                }
            };

            return window.setTimeout(tryParse, 500); //use timeout to wait async of facebook
        },

        pluralize = (count, s, p) => {
            return (count > 1 ? count + p : count + s);
        },

        simpleFormat = (str = '') => {
            str = str.replace(/\r\n?/, '\n');
            if (str.length > 0) {
                str = str.replace(/\n\n+/g, '

');
                str = str.replace(/\n/g, '
');
                str = '
' + str + '
';
            }
            return str;
        },

        rewardSouldOut = (reward) => {
            return (reward.maximum_contributions > 0 ?
                (reward.paid_count + reward.waiting_payment_count >= reward.maximum_contributions) : false);
        },

        rewardRemaning = (reward) => {
            return reward.maximum_contributions - (reward.paid_count + reward.waiting_payment_count);
        },

        parseUrl = (href) => {
            const l = document.createElement('a');
            l.href = href;
            return l;
        },

        mixpanelTrack = () => {
            return (el, isInitialized) => {
                if (!isInitialized) {
                    window.CatarseMixpanel.activate();
                }
            };
        },

        UIHelper = () => {
            return (el, isInitialized) => {
                if (!isInitialized && $) {
                    window.UIHelper.setupResponsiveIframes($(el));
                }
            };
        },

        toAnchor = () => {
            return (el, isInitialized) => {
                if (!isInitialized){
                    const hash = window.location.hash.substr(1);
                    if (hash === el.id) {
                        window.location.hash = '';
                        setTimeout(function(){
                            window.location.hash = el.id;
                        });
                    }
                }
            };
        },

        validateEmail = (email) => {
            const re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
            return re.test(email);
        },

        navigateToDevise = () => {
            window.location.href = '/pt/login';
            return false;
        },

        cumulativeOffset = (element) => {
            let top = 0, left = 0;
            do {
                top += element.offsetTop  || 0;
                left += element.offsetLeft || 0;
                element = element.offsetParent;
            } while (element);

            return {
                top: top,
                left: left
            };
        },

        closeFlash = () => {
            let el = document.getElementsByClassName('icon-close')[0];
            if (_.isElement(el)){
                el.onclick = (event) => {
                    event.preventDefault();

                    el.parentElement.remove();
                };
            };
        },

        i18nScope = (scope, obj) => {
            obj = obj || {};
            return _.extend({}, obj, {scope: scope});
        };

    setMomentifyLocale();
    closeFlash();

    return {
        cumulativeOffset: cumulativeOffset,
        discuss: discuss,
        existy: existy,
        validateEmail: validateEmail,
        momentify: momentify,
        momentFromString: momentFromString,
        formatNumber: formatNumber,
        idVM: idVM,
        getUser: getUser,
        toggleProp: toggleProp,
        loader: loader,
        newFeatureBadge: newFeatureBadge,
        fbParse: fbParse,
        pluralize: pluralize,
        simpleFormat: simpleFormat,
        translatedTime: translatedTime,
        rewardSouldOut: rewardSouldOut,
        rewardRemaning: rewardRemaning,
        parseUrl: parseUrl,
        hashMatch: hashMatch,
        useAvatarOrDefault: useAvatarOrDefault,
        locationActionMatch: locationActionMatch,
        mixpanelTrack: mixpanelTrack,
        navigateToDevise: navigateToDevise,
        storeAction: storeAction,
        callStoredAction: callStoredAction,
        UIHelper: UIHelper,
        toAnchor: toAnchor,
        paramByName: paramByName,
        i18nScope: i18nScope
    };
}(window.m, window.moment, window.I18n));
<|endoftext|>


<commit_before>import webpack from 'webpack'
import WebpackDevServer from 'webpack-dev-server'

import ClientDevConfig from './webpack.client.dev.config'

const APP_PATH = process.cwd()
const DEV_PORT = process.env.DEV_PORT || 8081

function runDevServer() {
  const compiler = webpack(ClientDevConfig)
  const server = new WebpackDevServer(compiler, ClientDevConfig.devServer)
  server.listen(DEV_PORT, 'localhost', () => {
    console.log('Webpack dev server listening on port', DEV_PORT)
    cb()
  })
}

runDevServer()
<commit_msg>Fix npm start<commit_after>import webpack from 'webpack'
import WebpackDevServer from 'webpack-dev-server'

import ClientDevConfig from './webpack.client.dev.config'

const APP_PATH = process.cwd()
const DEV_PORT = process.env.DEV_PORT || 8081

function runDevServer() {
  const compiler = webpack(ClientDevConfig)
  const server = new WebpackDevServer(compiler, ClientDevConfig.devServer)
  server.listen(DEV_PORT, 'localhost', () => {
    console.log('Webpack dev server listening on port', DEV_PORT)
  })
}

runDevServer()
<|endoftext|>