<commit_before>/**
 * Created by Diogo on 23/10/2015.
 */
(function() {
    'use strict';

    describe('Teste de Directiva: oobjRadio', function() {

        // variaveis globais
        var $rootScope,
            $compile,
            scope, // scope onde nossa directiva esta inserida
            element, // elemento jqlite
            isolatedScope;

        beforeEach(function() {
            // carregando modulo q ira ser testado
            module('oobj-directives');
            // carregando templates
            angular.mock.module('templates');
        });

        // cria um novo scope antes de cada teste
        beforeEach(inject(function(_$compile_, _$rootScope_){
            $rootScope = _$rootScope_;
            scope = $rootScope.$new();
            $compile = _$compile_;

            scope.id = "testeid";
            scope.label = "testelabel";
            scope.btnClass = "testebtnClass";
            scope.icon = "testeicon";
            scope.colspan = "testecolspan";

            element = getCompiledElement();
            isolatedScope = element.isolateScope();
        }));

        function getCompiledElement(xml){
            var $element;
            if(xml == null) {
                $element = angular.element('<oobj-button></oobj-button>');
            } else {
                $element = angular.element(xml);
            }
            var compiledElement = $compile($element)(scope);
            scope.$digest();

            return compiledElement;
        }

        it('deve ter a classe oobj-radio', function () {
            var elementTemp = angular.element("

");
            $compile(elementTemp);
            scope.$digest();
            expect(elementTemp.hasClass('oobj-button')).toBeTruthy();
        });

        it('Teste atributos com scope isolado - one way binding ("@").', function(){

            expect(scope.btnClass).toEqual('testebtnClass');
            isolatedScope.btnClass = "isoladobtnClass";
            expect(scope.btnClass).toEqual('testebtnClass');

            expect(scope.icon).toEqual('testeicon');
            isolatedScope.icon = "isoladoicon";
            expect(scope.icon).toEqual('testeicon');

            expect(scope.colspan).toEqual('testecolspan');
            isolatedScope.colspan = "isoladocolspan";
            expect(scope.colspan).toEqual('testecolspan');

        });

        it('Teste btnClass nao definido', function() {
            var classng  = element.find('[ng-class]');
            expect(classng.length).toBe(2);
            expect(classng.hasClass('btn-default')).toBeTruthy();
        });

        it('Teste btnClass definido.', function() {
            scope.btnClass = null;
            element = getCompiledElement('<oobj-button btn-class="teste"></oobj-button>');
            var classng  = element.find('[ng-class]');
            expect(classng.length).toBe(2);
            expect(classng.hasClass('teste')).toBeTruthy();
        });
    });
})();<commit_msg>Nome no describe errado<commit_after>/**
 * Created by Diogo on 23/10/2015.
 */
(function() {
    'use strict';

    describe('Teste de Directiva: oobjButton', function() {

        // variaveis globais
        var $rootScope,
            $compile,
            scope, // scope onde nossa directiva esta inserida
            element, // elemento jqlite
            isolatedScope;

        beforeEach(function() {
            // carregando modulo q ira ser testado
            module('oobj-directives');
            // carregando templates
            angular.mock.module('templates');
        });

        // cria um novo scope antes de cada teste
        beforeEach(inject(function(_$compile_, _$rootScope_){
            $rootScope = _$rootScope_;
            scope = $rootScope.$new();
            $compile = _$compile_;

            scope.id = "testeid";
            scope.label = "testelabel";
            scope.btnClass = "testebtnClass";
            scope.icon = "testeicon";
            scope.colspan = "testecolspan";

            element = getCompiledElement();
            isolatedScope = element.isolateScope();
        }));

        function getCompiledElement(xml){
            var $element;
            if(xml == null) {
                $element = angular.element('<oobj-button></oobj-button>');
            } else {
                $element = angular.element(xml);
            }
            var compiledElement = $compile($element)(scope);
            scope.$digest();

            return compiledElement;
        }

        it('deve ter a classe oobj-radio', function () {
            var elementTemp = angular.element("

");
            $compile(elementTemp);
            scope.$digest();
            expect(elementTemp.hasClass('oobj-button')).toBeTruthy();
        });

        it('Teste atributos com scope isolado - one way binding ("@").', function(){

            expect(scope.btnClass).toEqual('testebtnClass');
            isolatedScope.btnClass = "isoladobtnClass";
            expect(scope.btnClass).toEqual('testebtnClass');

            expect(scope.icon).toEqual('testeicon');
            isolatedScope.icon = "isoladoicon";
            expect(scope.icon).toEqual('testeicon');

            expect(scope.colspan).toEqual('testecolspan');
            isolatedScope.colspan = "isoladocolspan";
            expect(scope.colspan).toEqual('testecolspan');

        });

        it('Teste btnClass nao definido', function() {
            var classng  = element.find('[ng-class]');
            expect(classng.length).toBe(2);
            expect(classng.hasClass('btn-default')).toBeTruthy();
        });

        it('Teste btnClass definido.', function() {
            scope.btnClass = null;
            element = getCompiledElement('<oobj-button btn-class="teste"></oobj-button>');
            var classng  = element.find('[ng-class]');
            expect(classng.length).toBe(2);
            expect(classng.hasClass('teste')).toBeTruthy();
        });
    });
})();<|endoftext|>


<commit_before>/*
 * cmdrjs
 * Version 1.0.2-alpha
 * Copyright 2014 Shaftware.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Project: https://github.com/shaftware/cmdrjs
 */

; (function (define) {
    define(['jquery'], function ($) {

        var version = '1.0.2-alpha',
            commands = {},
            activated = false,
            template = '

',
            container,
            input,
            prefix,
            prompt,
            output,
            outputLine,
            current,
            queue = [],
            history = [],
            historyIndex = -1,
            config = {
                autoOpen: false,
                openKey: 192,
                closeKey: 27,
                echo: true,
                promptPrefix: '> '
            };

        var cmdr = {
            activate: activate,
            deactivate: deactivate,
            reactivate: reactivate,
            open: open,
            close: close,
            read: read,
            readLine: readLine,
            write: write,
            writeLine: writeLine,
            clear: clear,
            execute: execute,
            setup: setup,
            commands: commands,
            config: config,
            version: version
        };

        cmdr.setup(['HELP','?','/?'], function () {
            cmdr.writeLine('The following commands are available:');
            cmdr.writeLine();
            for (var key in commands) {
                var definition = commands[key];
                if (!!unwrap(definition.available)) {
                    cmdr.write(pad(key, ' ', 10));
                    cmdr.writeLine(definition.description);
                }
            }
            cmdr.writeLine();
        }, {
            description: 'Lists the available commands'
        });

        cmdr.setup(['VERSION', 'VER'], function () {
            cmdr.writeLine('cmdrjs (version ' + cmdr.version + ')');
        }, {
            description: 'Displays the cmdrjs version'
        });

        cmdr.setup('ECHO', function (arg) {
            var toggle = arg.toUpperCase();
            if (toggle === 'ON') {
                cmdr.config.echo = true;
            } else if (toggle === 'OFF') {
                cmdr.config.echo = false;
            } else {
                cmdr.writeLine(arg);
            }
        }, {
            parse: false,
            description: 'Displays provided text or toggles command echoing'
        });

        cmdr.setup(['CLEAR','CLS'], function () {
            cmdr.clear();
        }, {
            description: 'Clears the command prompt'
        });

        cmdr.setup(['QUIT','EXIT'], function () {
            cmdr.close();
        }, {
            description: 'Closes the command prompt'
        });

        return cmdr;

        function activate() {
            if (activated) return;

            container = $(template).appendTo('body');
            input = $('.input', container);
            prefix = $('.prefix', container);
            prompt = $('.prompt', container);
            output = $('.output', container);

            $(document).on('keydown.cmdr', function (event) {
                if (!isOpen() && !$(event.target).is('input, textarea, select, [contenteditable]') && event.keyCode ==  config.openKey) {
                    event.preventDefault();
                    open();
                } else if (isOpen() && event.keyCode == config.closeKey) {
                    close();
                }
            });

            prompt.on('keydown', function (event) {
                if (!current) {
                    switch (event.keyCode) {
                        case 13:
                            var value = promptVal();
                            if (value) {
                                execute(value);
                            }
                            event.preventDefault();
                            return false;
                        case 38:
                            historyBack();
                            event.preventDefault();
                            return false;
                        case 40:
                            historyForward();
                            event.preventDefault();
                            return false;
                        case 9:
                            event.preventDefault();
                            return false;
                    }
                } else if (current.readLine && event.keyCode === 13) {
                    current.readLine.resolve(promptVal());
                    return false;
                }
                return true;
            });

            prompt.on('keypress', function(event) {
                if (current && current.read) {
                    if (event.charCode !== 0) {
                        current.read.char = String.fromCharCode(event.charCode);
                        if (current.read.capture) {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
                return true;
            });

            prompt.on('keyup', function () {
                if (current && current.read && current.read.char) {
                    current.read.resolve(current.read.char);
                }
            });

            prompt.on('paste', function () {
                setTimeout(function () {
                    var value = promptVal();
                    var lines = value.split(/\r\n|\r|\n/g);
                    var length = lines.length;
                    if (length > 1) {
                        for (var i = 1; i < length; i++) {
                            if (lines[i].length > 0) {
                                queue.push(lines[i]);
                            }
                        }
                        if (current && current.readLine) {
                            current.readLine.resolve(lines[0]);
                        } else if (current && current.read) {
                            current.read.resolve(lines[0][0]);
                        } else {
                            execute(lines[0]);
                        }
                    }
                }, 0);
            });

            container.on('click', function (event) {
                if (!$(event.target).is('.input *, .output *')) {
                    prompt.focus();
                }
            });

            activateInput();

            activated = true;

            if (config.autoOpen) {
                open();
            }
        }

        function deactivate() {
            if (!activated) return;

            container.remove();
            container = null;
            input = null;
            prefix = null;
            prompt = null;
            output = null;

            $(document).off('keydown.cmdr');

            activated = false;
        }

        function reactivate() {
            if (activated) {
                deactivate();
            }
            activate();
        }

        function isOpen() {
            return container.is(':visible');
        }

        function open() {
            if (!activated) return;

            container.show();

            setTimeout(function () {
                prompt.css('text-indent', getPrefixWidth() + 'px').focus();
            }, 0);
        }

        function close() {
            if (!activated) return;

            container.hide();
            prompt.blur();
        }

        function read(callback, capture) {
            if (!activated) return;
            if (!current) return;

            activateInput(true);

            current.read = $.Deferred().always(function (value) {
                current.read = null;
                if (!capture) {
                    promptVal(value);
                }
                deactivateInput();
                if (callback.call(current, value) === true) {
                    read(callback, capture);
                } else {
                    flushInput();
                }
            });
            current.read.capture = capture;

            if (queue.length > 0) {
                current.read.resolve(queue.shift()[0]);
            }
        }

        function readLine(callback) {
            if (!activated) return;
            if (!current) return;

            activateInput(true);

            current.readLine = $.Deferred().always(function (value) {
                current.readLine = null;
                promptVal(value);
                deactivateInput();
                flushInput();
                if (callback.call(current, value) === true) {
                    readLine(callback);
                }
            });

            if (queue.length > 0) {
                current.readLine.resolve(queue.shift());
            }
        }

        function write(value, cssClass) {
            if (!activated) return;

            value = value || '';

            var outputValue = $('').addClass(cssClass).text(value);
            if (!outputLine) {
                outputLine = $('
').appendTo(output);
            }
            outputLine.append(outputValue);
        }

        function writeLine(value, cssClass) {
            if (!activated) return;

            value = (value || '') + '\n';

            write(value, cssClass);
            outputLine = null;
        }

        function clear() {
            if (!activated) return;

            output.html('');
        }

        function execute(command) {
            if (!activated) return;
            if (current) {
                queue.push(command);
                return;
            };

            if (typeof command !== 'string' || command.length === 0) {
                throw 'Invalid command';
            }

            promptVal(command);
            flushInput(!config.echo);
            historyAdd(command);
            deactivateInput();

            command = command.trim();

            var parsed = parseCommand(command);
            var definition = commands[parsed.name.toUpperCase()];
            if (!definition || !unwrap(definition.available)) {
                writeLine('Invalid command', 'error');
                activateInput();
                return;
            }

            current = {
                command: command,
                definition: definition
            };

            var args = parsed.args;
            if (!definition.parse) {
                args = [parsed.arg];
            }

            var result = definition.callback.apply(current, args);

            $.when(result).always(function () {
                setTimeout(function () {
                    current = null;
                    activateInput();
                    if (queue.length > 0) {
                        execute(queue.shift());
                    }
                }, 0);
            });
        }

        function setup(name, callback, settings) {
            var definition = resolveDefinition(name, callback, settings);
            for (var i = 0, l = definition.names.length; i < l; i++) {
                commands[definition.names[i].toUpperCase()] = definition;
            }
        }

        function activateInput(inline) {
            if (inline) {
                if (outputLine) {
                    prefix.text(outputLine.text());
                    outputLine.remove();
                    outputLine = null;
                }
            } else {
                prefix.text(config.promptPrefix);
            }
            input.show();
            setTimeout(function () {
                prompt.prop('disabled', false).css('text-indent', getPrefixWidth() + 'px').focus();
                container.animate({
                    scrollTop: container[0].scrollHeight
                }, 1000);
            }, 0);
        }

        function deactivateInput() {
            prompt.prop('disabled', true);
            input.hide();
        }

        function flushInput(preventWrite) {
            if (!preventWrite) {
                write(prefix.text());
                writeLine(promptVal());
            }
            prefix.text('');
            promptVal('');
        }

        function historyAdd(command) {
            history.unshift(command);
            historyIndex = -1;
        }

        function historyBack() {
            if (history.length > historyIndex + 1) {
                historyIndex++;
                promptVal(history[historyIndex]);
                prompt.change();
            }
        }

        function historyForward() {
            if (historyIndex > 0) {
                historyIndex--;
                promptVal(history[historyIndex]);
                prompt.change();
            }
        }

        function parseCommand(command) {
            var exp = /[^\s"]+|"([^"]*)"/gi,
                name = null,
                arg = null,
                args = [];

            do {
                var match = exp.exec(command);
                if (match != null) {
                    var value = match[1] ? match[1] : match[0];
                    if (match.index === 0) {
                        name = value;
                        arg = command.substr(value.length + (match[1] ? 3 : 1));
                    } else {
                        args.push(value);
                    }
                }
            } while (match != null);

            return {
                name: name,
                arg: arg,
                args: args
            };
        }

        function resolveDefinition(names, callback, settings) {
            if (typeof names !== 'string' && !$.isArray(names)) {
                settings = callback;
                callback = names;
                names = null;
            }
            if (typeof callback !== 'function') {
                settings = callback;
                callback = null;
            }

            if (typeof names === 'string') {
                names = [names]
            } else if ($.isArray(names)) {
                names = $.grep(names, function(value) {
                    return typeof value === 'string';
                });
            }

            var definition = {
                names: names,
                callback: callback,
                parse: true,
                available: true
            };

            $.extend(definition, settings);

            if (!$.isArray(definition.names) ||
                definition.names.length === 0 ||
                typeof definition.callback !== 'function') {
                throw 'Invalid command definition';
            }

            return definition;
        }

        function getPrefixWidth() {
            var width = prefix.width();
            var text = prefix.text();
            var spacePadding = text.length - text.trim().length;
            width += spacePadding * getPrefixSpaceWidth();
            return width;
        }

        function getPrefixSpaceWidth() {
            if (!prefix._spaceWidth) {
                var elem1 = $('| |').appendTo(prefix);
                var elem2 = $('||').appendTo(prefix);
                prefix._spaceWidth = elem1.innerWidth() - elem2.innerWidth();
                elem1.remove();
                elem2.remove();
            }
            return prefix._spaceWidth;
        }

        function pad(value, padding, length) {
            var right = length >= 0;
            length = Math.abs(length);
            while (value.length < length) {
                value = right ? value + padding : padding + value;
            }
            return value;
        }

        function unwrap(value) {
            return typeof value === 'function' ? value() : value;
        }

        function promptVal(value) {
            if (typeof value === 'undefined') {
                return prompt.text();
            } else {
                prompt.text(value);
            }
        }

    });
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(require('jquery'));
    } else {
        window['cmdr'] = factory(window['jQuery']);
    }
}));
<commit_msg>added hack for Firefox text-indent cursor bug<commit_after>/*
 * cmdrjs
 * Version 1.0.3-alpha
 * Copyright 2014 Shaftware.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Project: https://github.com/shaftware/cmdrjs
 */

; (function (define) {
    define(['jquery'], function ($) {

        var version = '1.0.3-alpha',
            commands = {},
            activated = false,
            template = '

',
            container,
            input,
            prefix,
            prompt,
            output,
            outputLine,
            current,
            queue = [],
            history = [],
            historyIndex = -1,
            config = {
                autoOpen: false,
                openKey: 192,
                closeKey: 27,
                echo: true,
                promptPrefix: '> '
            },
            hacks = {
                promptIndentPadding: typeof InstallTrigger !== 'undefined' // Firefox - misplaced cursor when using 'text-indent'
            };

        var cmdr = {
            activate: activate,
            deactivate: deactivate,
            reactivate: reactivate,
            open: open,
            close: close,
            read: read,
            readLine: readLine,
            write: write,
            writeLine: writeLine,
            clear: clear,
            execute: execute,
            setup: setup,
            commands: commands,
            config: config,
            version: version
        };

        cmdr.setup(['HELP','?','/?'], function () {
            cmdr.writeLine('The following commands are available:');
            cmdr.writeLine();
            for (var key in commands) {
                var definition = commands[key];
                if (!!unwrap(definition.available)) {
                    cmdr.write(pad(key, ' ', 10));
                    cmdr.writeLine(definition.description);
                }
            }
            cmdr.writeLine();
        }, {
            description: 'Lists the available commands'
        });

        cmdr.setup(['VERSION', 'VER'], function () {
            cmdr.writeLine('cmdrjs (version ' + cmdr.version + ')');
        }, {
            description: 'Displays the cmdrjs version'
        });

        cmdr.setup('ECHO', function (arg) {
            var toggle = arg.toUpperCase();
            if (toggle === 'ON') {
                cmdr.config.echo = true;
            } else if (toggle === 'OFF') {
                cmdr.config.echo = false;
            } else {
                cmdr.writeLine(arg);
            }
        }, {
            parse: false,
            description: 'Displays provided text or toggles command echoing'
        });

        cmdr.setup(['CLEAR','CLS'], function () {
            cmdr.clear();
        }, {
            description: 'Clears the command prompt'
        });

        cmdr.setup(['QUIT','EXIT'], function () {
            cmdr.close();
        }, {
            description: 'Closes the command prompt'
        });

        return cmdr;

        function activate() {
            if (activated) return;

            container = $(template).appendTo('body');
            input = $('.input', container);
            prefix = $('.prefix', container);
            prompt = $('.prompt', container);
            output = $('.output', container);

            $(document).on('keydown.cmdr', function (event) {
                if (!isOpen() && !$(event.target).is('input, textarea, select, [contenteditable]') && event.keyCode ==  config.openKey) {
                    event.preventDefault();
                    open();
                } else if (isOpen() && event.keyCode == config.closeKey) {
                    close();
                }
            });

            prompt.on('keydown', function (event) {
                if (!current) {
                    switch (event.keyCode) {
                        case 13:
                            var value = promptVal();
                            if (value) {
                                execute(value);
                            }
                            event.preventDefault();
                            return false;
                        case 38:
                            historyBack();
                            event.preventDefault();
                            return false;
                        case 40:
                            historyForward();
                            event.preventDefault();
                            return false;
                        case 9:
                            event.preventDefault();
                            return false;
                    }
                } else if (current.readLine && event.keyCode === 13) {
                    current.readLine.resolve(promptVal());
                    return false;
                }
                return true;
            });

            prompt.on('keypress', function(event) {
                if (current && current.read) {
                    if (event.charCode !== 0) {
                        current.read.char = String.fromCharCode(event.charCode);
                        if (current.read.capture) {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }
                return true;
            });

            prompt.on('keyup', function () {
                if (current && current.read && current.read.char) {
                    current.read.resolve(current.read.char);
                }
            });

            prompt.on('paste', function () {
                setTimeout(function () {
                    var value = promptVal();
                    var lines = value.split(/\r\n|\r|\n/g);
                    var length = lines.length;
                    if (length > 1) {
                        for (var i = 1; i < length; i++) {
                            if (lines[i].length > 0) {
                                queue.push(lines[i]);
                            }
                        }
                        if (current && current.readLine) {
                            current.readLine.resolve(lines[0]);
                        } else if (current && current.read) {
                            current.read.resolve(lines[0][0]);
                        } else {
                            execute(lines[0]);
                        }
                    }
                }, 0);
            });

            if (hacks.promptIndentPadding) {
                prompt.on('input', function() {
                    prompt.css(getPromptIndent())
                });
            }

            container.on('click', function (event) {
                if (!$(event.target).is('.input *, .output *')) {
                    prompt.focus();
                }
            });

            activateInput();

            activated = true;

            if (config.autoOpen) {
                open();
            }
        }

        function deactivate() {
            if (!activated) return;

            container.remove();
            container = null;
            input = null;
            prefix = null;
            prompt = null;
            output = null;

            $(document).off('keydown.cmdr');

            activated = false;
        }

        function reactivate() {
            if (activated) {
                deactivate();
            }
            activate();
        }

        function isOpen() {
            return container.is(':visible');
        }

        function open() {
            if (!activated) return;

            container.show();

            setTimeout(function () {
                prompt.css(getPromptIndent()).focus();
            }, 0);
        }

        function close() {
            if (!activated) return;

            container.hide();
            prompt.blur();
        }

        function read(callback, capture) {
            if (!activated) return;
            if (!current) return;

            activateInput(true);

            current.read = $.Deferred().always(function (value) {
                current.read = null;
                if (!capture) {
                    promptVal(value);
                }
                deactivateInput();
                if (callback.call(current, value) === true) {
                    read(callback, capture);
                } else {
                    flushInput();
                }
            });
            current.read.capture = capture;

            if (queue.length > 0) {
                current.read.resolve(queue.shift()[0]);
            }
        }

        function readLine(callback) {
            if (!activated) return;
            if (!current) return;

            activateInput(true);

            current.readLine = $.Deferred().always(function (value) {
                current.readLine = null;
                promptVal(value);
                deactivateInput();
                flushInput();
                if (callback.call(current, value) === true) {
                    readLine(callback);
                }
            });

            if (queue.length > 0) {
                current.readLine.resolve(queue.shift());
            }
        }

        function write(value, cssClass) {
            if (!activated) return;

            value = value || '';

            var outputValue = $('').addClass(cssClass).text(value);
            if (!outputLine) {
                outputLine = $('
').appendTo(output);
            }
            outputLine.append(outputValue);
        }

        function writeLine(value, cssClass) {
            if (!activated) return;

            value = (value || '') + '\n';

            write(value, cssClass);
            outputLine = null;
        }

        function clear() {
            if (!activated) return;

            output.html('');
        }

        function execute(command) {
            if (!activated) return;
            if (current) {
                queue.push(command);
                return;
            };

            if (typeof command !== 'string' || command.length === 0) {
                throw 'Invalid command';
            }

            promptVal(command);
            flushInput(!config.echo);
            historyAdd(command);
            deactivateInput();

            command = command.trim();

            var parsed = parseCommand(command);
            var definition = commands[parsed.name.toUpperCase()];
            if (!definition || !unwrap(definition.available)) {
                writeLine('Invalid command', 'error');
                activateInput();
                return;
            }

            current = {
                command: command,
                definition: definition
            };

            var args = parsed.args;
            if (!definition.parse) {
                args = [parsed.arg];
            }

            var result = definition.callback.apply(current, args);

            $.when(result).always(function () {
                setTimeout(function () {
                    current = null;
                    activateInput();
                    if (queue.length > 0) {
                        execute(queue.shift());
                    }
                }, 0);
            });
        }

        function setup(name, callback, settings) {
            var definition = resolveDefinition(name, callback, settings);
            for (var i = 0, l = definition.names.length; i < l; i++) {
                commands[definition.names[i].toUpperCase()] = definition;
            }
        }

        function activateInput(inline) {
            if (inline) {
                if (outputLine) {
                    prefix.text(outputLine.text());
                    outputLine.remove();
                    outputLine = null;
                }
            } else {
                prefix.text(config.promptPrefix);
            }
            input.show();
            setTimeout(function () {
                prompt.prop('disabled', false).css(getPromptIndent()).focus();
                container.animate({
                    scrollTop: container[0].scrollHeight
                }, 1000);
            }, 0);
        }

        function deactivateInput() {
            prompt.prop('disabled', true);
            input.hide();
        }

        function flushInput(preventWrite) {
            if (!preventWrite) {
                write(prefix.text());
                writeLine(promptVal());
            }
            prefix.text('');
            promptVal('');
        }

        function historyAdd(command) {
            history.unshift(command);
            historyIndex = -1;
        }

        function historyBack() {
            if (history.length > historyIndex + 1) {
                historyIndex++;
                promptVal(history[historyIndex]);
                prompt.change();
            }
        }

        function historyForward() {
            if (historyIndex > 0) {
                historyIndex--;
                promptVal(history[historyIndex]);
                prompt.change();
            }
        }

        function parseCommand(command) {
            var exp = /[^\s"]+|"([^"]*)"/gi,
                name = null,
                arg = null,
                args = [];

            do {
                var match = exp.exec(command);
                if (match != null) {
                    var value = match[1] ? match[1] : match[0];
                    if (match.index === 0) {
                        name = value;
                        arg = command.substr(value.length + (match[1] ? 3 : 1));
                    } else {
                        args.push(value);
                    }
                }
            } while (match != null);

            return {
                name: name,
                arg: arg,
                args: args
            };
        }

        function resolveDefinition(names, callback, settings) {
            if (typeof names !== 'string' && !$.isArray(names)) {
                settings = callback;
                callback = names;
                names = null;
            }
            if (typeof callback !== 'function') {
                settings = callback;
                callback = null;
            }

            if (typeof names === 'string') {
                names = [names]
            } else if ($.isArray(names)) {
                names = $.grep(names, function(value) {
                    return typeof value === 'string';
                });
            }

            var definition = {
                names: names,
                callback: callback,
                parse: true,
                available: true
            };

            $.extend(definition, settings);

            if (!$.isArray(definition.names) ||
                definition.names.length === 0 ||
                typeof definition.callback !== 'function') {
                throw 'Invalid command definition';
            }

            return definition;
        }

        function getPrefixWidth() {
            var width = prefix.width();
            var text = prefix.text();
            var spacePadding = text.length - text.trim().length;
            width += spacePadding * getPrefixSpaceWidth();
            return width;
        }

        function getPrefixSpaceWidth() {
            if (!prefix._spaceWidth) {
                var elem1 = $('| |').appendTo(prefix);
                var elem2 = $('||').appendTo(prefix);
                prefix._spaceWidth = elem1.innerWidth() - elem2.innerWidth();
                elem1.remove();
                elem2.remove();
            }
            return prefix._spaceWidth;
        }

        function pad(value, padding, length) {
            var right = length >= 0;
            length = Math.abs(length);
            while (value.length < length) {
                value = right ? value + padding : padding + value;
            }
            return value;
        }

        function unwrap(value) {
            return typeof value === 'function' ? value() : value;
        }

        function promptVal(value) {
            if (typeof value === 'undefined') {
                return prompt.text();
            } else {
                prompt.text(value);
            }
        }

        function getPromptIndent() {
            if (hacks.promptIndentPadding && !promptVal()) {
                return {
                    'padding-left': getPrefixWidth() + 'px',
                    'text-indent': ''
                };
            } else {
                return {
                    'text-indent': getPrefixWidth() + 'px',
                    'padding-left': ''
                };
            }
        }

    });
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(require('jquery'));
    } else {
        window['cmdr'] = factory(window['jQuery']);
    }
}));
<|endoftext|>


<commit_before>var port = process.env.PORT || 3000;
var http = require('http');
var url  = require('url');

var finalhandler = require('finalhandler');
var serveStatic = require('serve-static')("./");

var server = http.createServer(function(req, res) {
	console.log(req.url);

	var done = finalhandler(req, res);
	var urlParts = url.parse(req.url);

	switch (urlParts.path) {
		case '/':
			res.writeHead(301, {Location: '/joust/'})
			res.end();
			break;
		default:
			serveStatic(req, res, done);
	}
})
.listen(port);

console.log('listening on port', port);
<commit_msg>fix(redirect): use temp redirect code 302 instead of permenant 301<commit_after>var port = process.env.PORT || 3000;
var http = require('http');
var url  = require('url');

var finalhandler = require('finalhandler');
var serveStatic = require('serve-static')("./");

var server = http.createServer(function(req, res) {
	console.log(req.url);

	var done = finalhandler(req, res);
	var urlParts = url.parse(req.url);

	switch (urlParts.path) {
		case '/':
			res.writeHead(302, {Location: '/joust/'})
			res.end();
			break;
		default:
			serveStatic(req, res, done);
	}
})
.listen(port);

console.log('listening on port', port);
<|endoftext|>


<commit_before>var createServer = require('http-raw');
var BufferedStream = require('morestreams').BufferedStream;

var insertHeaders = require('./lib/insert_headers');
var updatePath = require('./lib/update_path');
var parseArgs = require('./lib/parse_args');

var net = require('net');
var tls = require('tls');

var bouncy = module.exports = function (opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }

    if (opts && opts.key && opts.cert) {
        throw new Error('not supported');
    }
    else {
        var server = createServer(function (req, res) {
            var bounce = makeBounce(req, res);
            cb(req, bounce);
        });

        server.on('upgrade', function (req, sock, buf) {
            if (req.headers.upgrade || req.method === 'CONNECT') {
                var bounce = makeBounce(req, sock);
                cb(req, bounce);
            }
        });

        return server;
    }
};

function makeBounce (req, res) {
    var bounce = function (stream, opts) {
        var bs = req.createRawStream();

        if (!stream || !stream.write) {
            opts = parseArgs(arguments);
            stream = opts.stream;
        }
        if (!opts) opts = {};

        if (!opts.headers) opts.headers = {};
        if (!('x-forwarded-for' in opts.headers)) {
            opts.headers['x-forwarded-for'] = req.connection.remoteAddress;
        }
        if (!('x-forwarded-port' in opts.headers)) {
            var m = (req.headers.host || '').match(/:(\d+)/);
            opts.headers['x-forwarded-port'] = m && m[1] || 80;
        }
        if (!('x-forwarded-proto' in opts.headers)) {
            opts.headers['x-forwarded-proto'] =
                req.connection.encrypted ? 'https' : 'http';
        }

        insertHeaders(bs.buffers, opts.headers);
        if (opts.path) updatePath(bs.buffers, opts.path);

        if (stream.writable) {
            bs.pipe(stream);
            stream.pipe(bs);
        }
        else if (opts.emitter) {
            opts.emitter.emit('drop', bs);
        }

        stream.on('error', function (err) {
            if (stream.listeners('error').length === 1) {
                // destroy the request and stream if nobody is listening
                req.destroy();
                stream.destroy();
            }
        });

        stream.on('close', function () {
            _onclose.forEach(function (fn) { fn() });
        });

        return stream;
    };

    var _onclose = [];
    bounce._onclose = function (fn) {
        _onclose.push(fn);
    };

    bounce.respond = function () {
        return res;
    };

    return bounce;
}
<commit_msg>https test passes, all tests now pass<commit_after>var httpRaw = require('http-raw');
var BufferedStream = require('morestreams').BufferedStream;

var insertHeaders = require('./lib/insert_headers');
var updatePath = require('./lib/update_path');
var parseArgs = require('./lib/parse_args');

var net = require('net');
var tls = require('tls');

var bouncy = module.exports = function (opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }

    var createServer = opts && opts.key && opts.cert
        ? function (cb_) { return httpRaw.https(opts, cb_) }
        : httpRaw.http
    ;

    var server = createServer(function (req, res) {
        var bounce = makeBounce(req, res);
        cb(req, bounce);
    });

    server.on('upgrade', function (req, sock, buf) {
        if (req.headers.upgrade || req.method === 'CONNECT') {
            var bounce = makeBounce(req, sock);
            cb(req, bounce);
        }
    });

    return server;
};

function makeBounce (req, res) {
    var bounce = function (stream, opts) {
        var bs = req.createRawStream();

        if (!stream || !stream.write) {
            opts = parseArgs(arguments);
            stream = opts.stream;
        }
        if (!opts) opts = {};

        if (!opts.headers) opts.headers = {};
        if (!('x-forwarded-for' in opts.headers)) {
            opts.headers['x-forwarded-for'] = req.connection.remoteAddress;
        }
        if (!('x-forwarded-port' in opts.headers)) {
            var m = (req.headers.host || '').match(/:(\d+)/);
            opts.headers['x-forwarded-port'] = m && m[1] || 80;
        }
        if (!('x-forwarded-proto' in opts.headers)) {
            opts.headers['x-forwarded-proto'] =
                req.connection.encrypted ? 'https' : 'http';
        }

        insertHeaders(bs.buffers, opts.headers);
        if (opts.path) updatePath(bs.buffers, opts.path);

        if (stream.writable) {
            bs.pipe(stream);
            stream.pipe(bs);
        }
        else if (opts.emitter) {
            opts.emitter.emit('drop', bs);
        }

        stream.on('error', function (err) {
            if (stream.listeners('error').length === 1) {
                // destroy the request and stream if nobody is listening
                req.destroy();
                stream.destroy();
            }
        });

        stream.on('close', function () {
            _onclose.forEach(function (fn) { fn() });
        });

        return stream;
    };

    var _onclose = [];
    bounce._onclose = function (fn) {
        _onclose.push(fn);
    };

    bounce.respond = function () {
        return res;
    };

    return bounce;
}
<|endoftext|>


<commit_before>/**
  This file is part of the "FnordMetric" project
    Copyright (c) 2015 Laura Schlimmer
    Copyright (c) 2015 Paul Asmuth

  FnordMetric is free software: you can redistribute it and/or modify it under
  the terms of the GNU General Public License v3.0. You should have received a
  copy of the GNU General Public License along with this program. If not, see
  <http://www.gnu.org/licenses/>.
*/

var ZChartComponent = function() {
  // renders line chart
  this.render = function(x_values, y_values) {
    var data = {
      x: x_values,
      y: [{
          values: y_values,
          min: (this.hasAttribute('data-min')) ?
            parseFloat(this.getAttribute('data-min')) : 0.0,
          max: (this.hasAttribute('data-max')) ?
            parseFloat(this.getAttribute('data-max')) : Math.max.apply(null, y_values)
      }]
    };

    this.renderChart(data);
  };

  //render multiple lines
  this.renderLines = function(values) {
    console.log(values);
  };

  this.renderChart = function(data) {
    var height = this.getDimension('height');
    var width = this.getDimension("width");

    var tpl = $.getTemplate(
        "widgets/z-chart",
        "z-chart-tpl");

    this.innerHTML = "";
    this.appendChild(tpl);

    var svg = this.querySelector("svg");
    svg.style.height = height + "px";
    svg.style.width = width + "px";

    for (var i = 0; i < data.y.length; i++) {
      this.renderLine(height, width, data.x, data.y[i]);
    }
  };

  this.renderLine = function(height, width, data_x, data_y) {
    var points = this.scaleValues(data_y);
    var svg = this.querySelector("svg");
    var padding_x = 8;
    var padding_y = 8;

    var svg_line = [];
    var svg_circles = [];
    for (var i = 0; i < points.length; ++i) {
      if (!isNaN(points[i].y)) {
        var dx = padding_x + (points[i].x * (width - padding_x * 2));
        var dy = padding_y + ((1.0 - points[i].y) * (height - padding_y * 2));
        svg_line.push(i == 0 ? "M" : "L", dx, dy);
        svg_circles.push([dx, dy]);
      }
    }

    //var path = this.querySelector("path");
    var path = document.createElement("path");
    svg.appendChild(path);
    path.setAttribute("d", svg_line.join(" "));

    var rect_width = width / (data_x.length - 1);
    var x = (rect_width / 2) * -1;

    for (var i = 0; i < svg_circles.length; i++) {
      svg.innerHTML += "<g><circle cx='" + svg_circles[i][0] + "' cy='" +
          svg_circles[i][1] + "' r='2.5' />" +
          "<rect width='" + rect_width  + "' height='" + height +
          "' y='0' x='" + x + "' /></g>";
      x += rect_width;
    }

    var groups = svg.querySelectorAll("g");
    for (var i = 0; i < groups.length; i++) {
      this.setupTooltip(groups[i], data_x[i], data_y.values[i]);
    }
  }

  this.setupTooltip = function(html, x_value, y_value) {
    var tooltip = this.querySelector("z-chart-tooltip");
    var rect = html.querySelector("rect");
    var _this = this;
    rect.addEventListener("mouseenter", function(e) {
      tooltip.innerHTML = _this.formatX(x_value) + ": " + _this.formatY(y_value);
      tooltip.classList.remove("hidden");

      var pos = html.querySelector("circle").getBoundingClientRect();
      tooltip.style.top = (pos.top - pos.height - tooltip.offsetHeight) + "px";
      tooltip.style.left = (pos.left - tooltip.offsetWidth / 2) + "px";

    }, false);

    tooltip.addEventListener("mouseenter", function(e) {
      this.classList.remove("hidden");
    }, false);

    tooltip.addEventListener("mouseout", function(e) {
      this.classList.add("hidden");
    }, false);

    rect.addEventListener("mouseout", function(e) {
      tooltip.classList.add("hidden");
    }, false);
  };

  this.getDimension = function(dimension) {
    var value = this.getAttribute(dimension);

    var idx = value.indexOf("%");
    if (idx > -1) {
      return this.offsetWidth * (parseInt(value.substr(0, idx), 10) / 100);
    }

    return parseFloat(value);
  };

  this.scaleValues = function(y) {
    var scaled = [];

    for (var i = 0; i < y.values.length; ++i) {
      var v = y.values[i];
      var x  = i / (y.values.length - 1);

      if (v < y.min) {
        scaled.push({x : x, y: 0});
        continue;
      }

      if (v > y.max) {
        scaled.push({x: x, y: 1.0});
        continue;
      }

      if (y.max - y.min == 0) {
        scaled.push({x: x, y: v});
      } else {
        scaled.push({x: x, y:(v - y.min) / (y.max - y.min)});
      }
    }

    return scaled;
  };

};

var proto = Object.create(HTMLElement.prototype);
ZChartComponent.apply(proto);
document.registerElement("z-chart", { prototype: proto });
<commit_msg>render multiple lines<commit_after>/**
  This file is part of the "FnordMetric" project
    Copyright (c) 2015 Laura Schlimmer
    Copyright (c) 2015 Paul Asmuth

  FnordMetric is free software: you can redistribute it and/or modify it under
  the terms of the GNU General Public License v3.0. You should have received a
  copy of the GNU General Public License along with this program. If not, see
  <http://www.gnu.org/licenses/>.
*/

var ZChartComponent = function() {
  // renders line chart
  this.render = function(x_values, y_values) {
    var data = {
      x: x_values,
      y: [{
          values: y_values,
          min: (this.hasAttribute('data-min')) ?
            parseFloat(this.getAttribute('data-min')) : 0.0,
          max: (this.hasAttribute('data-max')) ?
            parseFloat(this.getAttribute('data-max')) : Math.max.apply(null, y_values)
      }]
    };

    this.renderChart(data);
  };

  //render multiple lines
  this.renderLines = function(values) {
    this.renderChart(values);
  };

  this.renderChart = function(data) {
    var height = this.getDimension('height');
    var width = this.getDimension("width");

    var tpl = $.getTemplate(
        "widgets/z-chart",
        "z-chart-tpl");

    this.innerHTML = "";
    this.appendChild(tpl);

    var svg = this.querySelector("svg");
    svg.style.height = height + "px";
    svg.style.width = width + "px";

    for (var i = 0; i < data.y.length; i++) {
      if (!data.y[i].min) {
        data.y[i].min = 0;
      }
      if (!data.y[i].max) {
        data.y[i].max = Math.max.apply(null, data.y[i].values);
      }
      this.renderLine(height, width, data.x, data.y[i]);
    }
  };

  this.renderLine = function(height, width, data_x, data_y) {
    var points = this.scaleValues(data_y);
    var svg = this.querySelector("svg");
    var padding_x = 8;
    var padding_y = 8;

    var svg_line = [];
    var svg_circles = [];
    for (var i = 0; i < points.length; ++i) {
      if (!isNaN(points[i].y)) {
        var dx = padding_x + (points[i].x * (width - padding_x * 2));
        var dy = padding_y + ((1.0 - points[i].y) * (height - padding_y * 2));
        svg_line.push(i == 0 ? "M" : "L", dx, dy);
        svg_circles.push([dx, dy]);
      }
    }

    //var path = this.querySelector("path");
    var path = document.createElement("path");
    svg.appendChild(path);
    path.setAttribute("d", svg_line.join(" "));

    var rect_width = width / (data_x.length - 1);
    var x = (rect_width / 2) * -1;

    for (var i = 0; i < svg_circles.length; i++) {
      svg.innerHTML += "<g><circle cx='" + svg_circles[i][0] + "' cy='" +
          svg_circles[i][1] + "' r='2.5' />" +
          "<rect width='" + rect_width  + "' height='" + height +
          "' y='0' x='" + x + "' /></g>";
      x += rect_width;
    }

    var groups = svg.querySelectorAll("g");
    for (var i = 0; i < groups.length; i++) {
      this.setupTooltip(groups[i], data_x[i], data_y.values[i]);
    }
  }

  this.setupTooltip = function(html, x_value, y_value) {
    var tooltip = this.querySelector("z-chart-tooltip");
    var rect = html.querySelector("rect");
    var _this = this;
    rect.addEventListener("mouseenter", function(e) {
      tooltip.innerHTML = _this.formatX(x_value) + ": " + _this.formatY(y_value);
      tooltip.classList.remove("hidden");

      var pos = html.querySelector("circle").getBoundingClientRect();
      tooltip.style.top = (pos.top - pos.height - tooltip.offsetHeight) + "px";
      tooltip.style.left = (pos.left - tooltip.offsetWidth / 2) + "px";

    }, false);

    tooltip.addEventListener("mouseenter", function(e) {
      this.classList.remove("hidden");
    }, false);

    tooltip.addEventListener("mouseout", function(e) {
      this.classList.add("hidden");
    }, false);

    rect.addEventListener("mouseout", function(e) {
      tooltip.classList.add("hidden");
    }, false);
  };

  this.getDimension = function(dimension) {
    var value = this.getAttribute(dimension);

    var idx = value.indexOf("%");
    if (idx > -1) {
      return this.offsetWidth * (parseInt(value.substr(0, idx), 10) / 100);
    }

    return parseFloat(value);
  };

  this.scaleValues = function(y) {
    var scaled = [];

    for (var i = 0; i < y.values.length; ++i) {
      var v = y.values[i];
      var x  = i / (y.values.length - 1);

      if (v < y.min) {
        scaled.push({x : x, y: 0});
        continue;
      }

      if (v > y.max) {
        scaled.push({x: x, y: 1.0});
        continue;
      }

      if (y.max - y.min == 0) {
        scaled.push({x: x, y: v});
      } else {
        scaled.push({x: x, y:(v - y.min) / (y.max - y.min)});
      }
    }

    return scaled;
  };

};

var proto = Object.create(HTMLElement.prototype);
ZChartComponent.apply(proto);
document.registerElement("z-chart", { prototype: proto });
<|endoftext|>


<commit_before>/**
 * The Onus object
 * @type {Object}
 */
onus = function(config){

    // Take this into the local scope
    var self = this;
    var cfg = {
        reportId: null,
        alreadySentCount: 0
    };

    // Add the config array passed to onus
    cfg = cfg.concat(config);

    /**
     * Specifies all of the drivers currently supported
     * @type {Object}
     */
    var drivers = {

        'chrome' : {

            /**
             * Returns all the data that chrome can
             * @return {[type]}
             */
            getData  : function(){
                return window.performance.getEntries();
            }
        },

        'msie' : {

            /**
             * Returns all the data the msie can
             * @return {[type]}
             */
            getData : function(){
                return window.performance.getEntries();
            }
        },

        'firefox' : {

            getData : function(){
                return window.performance;
            }
        }
    }

    // Connect to the socket
    self.cfg.socket = io.connect(self.cfg.serverUrl);

    // On connection, we can run the rest of Onus
    self.socket.on('connect', function(){

        // Check the state of the load
        if(document.readyState == 'complete') self.init();
        else
            // We need to wait until all of the resources have loaded, then we can start
            window.addEventListener('load', function (){
                self.init();
            });

        // Set up some events
        self.socket.on('partum', function(id){

            // We have been given an ID! Save it for later so we can send it back to the server
            self.cfg.reportId = id;
        });

    });
};

/**
 * Function definitions
 */
onus.prototype = {

    /**
     * Determines the correct driver and use it to collect the data
     * @return {[type]}
     */
    gather : function(){

        // TODO - make this better across all browsers.
        var data = window.bowser.chrome ? this.drivers.chrome.getData() : (
            window.bowser.firefox ?  this.drivers.firefox.getData() : (
                window.bowser.msie ?  this.drivers.msie.getData() : null
            )
        );

        // Now remove the ones we have already sent
        data.splice(0, this.cfg.alreadySentCount);

        return {data: data, bowser: window.bowser, id: this.cfg.reportId, url: document.location.toString()};
    },

    /**
     *
     * @return {[type]} [description]
     */
    report : function(){

        var report = this.gather();

        // Don't send 0 data to the server
        if(report.data.length === 0) return;

        // Now increase the sent count
        this.cfg.alreadySentCount += report.data.length;

        this.socket.emit('renuntio', report);
    },

    init: function(){

        var self = this;

        // Gather up the data and report immediately, then start a 5 second interval
        self.report();

        // Start the interval
        setInterval(function(){
            self.report();
        }, 5000);
    }
}

// Create a new instance
window.onus = new onus({
    serverUrl : 'http://127.0.0.1:1337/'
});
<commit_msg>jeez reworked so it actually works. Note to self: write tests so people can at least try and submit working pull requests.<commit_after>/**
 * The Onus object
 * @type {Object}
 */
onus = function(config){

    // Take this into the local scope
    var self = this;

    // This might be dangerous...
    self.cfg = config;

    // Overwrite these things
    self.cfg.reportId = null;
    self.cfg.alreadySentCount = 0;

    /**
     * Specifies all of the drivers currently supported
     * @type {Object}
     */
    self.drivers = {

        'chrome' : {

            /**
             * Returns all the data that chrome can
             * @return {[type]}
             */
            getData  : function(){
                return window.performance.getEntries();
            }
        },

        'msie' : {

            /**
             * Returns all the data the msie can
             * @return {[type]}
             */
            getData : function(){
                return window.performance.getEntries();
            }
        },

        'firefox' : {

            getData : function(){
                return window.performance;
            }
        }
    }

    // Connect to the socket
    self.cfg.socket = io.connect(self.cfg.serverUrl);

    // On connection, we can run the rest of Onus
    self.cfg.socket.on('connect', function(){

        // Check the state of the load
        if(document.readyState == 'complete') self.init();
        else
            // We need to wait until all of the resources have loaded, then we can start
            window.addEventListener('load', function (){
                self.init();
            });

        // Set up some events
        self.cfg.socket.on('partum', function(id){

            // We have been given an ID! Save it for later so we can send it back to the server
            self.cfg.reportId = id;
        });

    });
};

/**
 * Function definitions
 */
onus.prototype = {

    /**
     * Determines the correct driver and use it to collect the data
     * @return {[type]}
     */
    gather : function(){

        // TODO - make this better across all browsers.
        var data = window.bowser.chrome ? this.drivers.chrome.getData() : (
            window.bowser.firefox ?  this.drivers.firefox.getData() : (
                window.bowser.msie ?  this.drivers.msie.getData() : null
            )
        );

        // Now remove the ones we have already sent
        data.splice(0, this.cfg.alreadySentCount);

        return {data: data, bowser: window.bowser, id: this.cfg.reportId, url: document.location.toString()};
    },

    /**
     *
     * @return {[type]} [description]
     */
    report : function(){

        var report = this.gather();

        // Don't send 0 data to the server
        if(report.data.length === 0) return;

        // Now increase the sent count
        this.cfg.alreadySentCount += report.data.length;

        this.cfg.socket.emit('renuntio', report);
    },

    init: function(){

        var self = this;

        // Gather up the data and report immediately, then start a 5 second interval
        self.report();

        // Start the interval
        setInterval(function(){
            self.report();
        }, 5000);
    }
}

// Create a new instance
window.onus = new onus({
    serverUrl : 'http://127.0.0.1:1337/'
});
<|endoftext|>


<commit_before>/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

(function ( $ ) {
    'use strict';

    $(document).ready(function() {
        $('select[name$="[country]"]').on('change', function(event) {
            var $select = $(event.currentTarget);
            var $provinceContainer = $select.closest('div.form-group').next('div.province-container');
            var provinceName = $select.attr('name').replace('country', 'province');

            if (null === $select.val()) {
                return;
            }

            $.get($provinceContainer.attr('data-url'), {countryId: $(this).val()}, function (response) {
                if (!response.content) {
                    $provinceContainer.fadeOut('slow', function () {
                        $provinceContainer.html('');
                    });
                } else {
                    $provinceContainer.fadeOut('slow', function () {
                        $provinceContainer.html(response.content.replace(
                            'name="sylius_address_province"',
                            'name="' + provinceName + '"'
                        ));

                        $provinceContainer.fadeIn();
                    });
                }
            });
        });

        if('' === $.trim($('div.province-container').text())) {
            $('select.country-select').trigger('change');
        }

        var $billingAddressCheckbox  = $('input[type="checkbox"][name$="[differentBillingAddress]"]');
        var $billingAddressContainer = $('#sylius-billing-address-container');
        var toggleBillingAddress = function() {
            $billingAddressContainer.toggle($billingAddressCheckbox.prop('checked'));
        };
        toggleBillingAddress();
        $billingAddressCheckbox.on('change', toggleBillingAddress);
    });
})( jQuery );
<commit_msg>Don't make ajax request for provinces if contry value is empty<commit_after>/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

(function ( $ ) {
    'use strict';

    $(document).ready(function() {
        $('select[name$="[country]"]').on('change', function(event) {
            var $select = $(event.currentTarget);
            var $provinceContainer = $select.closest('div.form-group').next('div.province-container');
            var provinceName = $select.attr('name').replace('country', 'province');

            if ('' === $select.val()) {
                $provinceContainer.fadeOut('slow', function () {
                    $provinceContainer.html('');
                });
                return;
            }

            $.get($provinceContainer.attr('data-url'), {countryId: $(this).val()}, function (response) {
                if (!response.content) {
                    $provinceContainer.fadeOut('slow', function () {
                        $provinceContainer.html('');
                    });
                } else {
                    $provinceContainer.fadeOut('slow', function () {
                        $provinceContainer.html(response.content.replace(
                            'name="sylius_address_province"',
                            'name="' + provinceName + '"'
                        ));

                        $provinceContainer.fadeIn();
                    });
                }
            });
        });

        if('' === $.trim($('div.province-container').text())) {
            $('select.country-select').trigger('change');
        }

        var $billingAddressCheckbox  = $('input[type="checkbox"][name$="[differentBillingAddress]"]');
        var $billingAddressContainer = $('#sylius-billing-address-container');
        var toggleBillingAddress = function() {
            $billingAddressContainer.toggle($billingAddressCheckbox.prop('checked'));
        };
        toggleBillingAddress();
        $billingAddressCheckbox.on('change', toggleBillingAddress);
    });
})( jQuery );
<|endoftext|>


<commit_before>const FetchRequest = require('./fetch-request');
const QueryResultBuilder = require('../query/query-result-builder');

class LocalFetchRequest extends FetchRequest {
    execute() {
        const store = this.bridge.getStore();
        if (!store) {
            throw new Error('Illegal state. Could not resolve local store');
        }

        let possibleMatches;
        let result;
        if (this._resource) {
            if ('attachments' === this._resource) {
                if (!(possibleMatches = store[this.type])) {
                    throw new Error('404 the requested resource type was not found in the local store');
                }
                result = possibleMatches[this._uid + '/attachments'];
                if (!result) {
                    throw new Error('404 the requested attachment resource was not found in the local store');
                } else {
                    result = QueryResultBuilder.buildResultSet(result);
                }
            } else {
                if (!(possibleMatches = store[this._resource])) {
                    throw new Error('404 the requested resource type was not found in the local store');
                }
                result = possibleMatches[this._uid];
                if (!result) {
                    throw new Error('404 the requested resource was not found in the local store');
                }
            }
        } else {
            if (!(possibleMatches = store[this.type])) {
                throw new Error(`404 the requested type: ${this.type} was not found in the local store`);
            }
            result = possibleMatches[String(this._uid)];
            if (!result) {
                throw new Error(`404 the requested type: ${this.type} uid: ${this._uid}::${Object.prototype.toString.call(this._uid)} was not found in the local store
                  Possible matches included:
                  ${explain(possibleMatches)}`);
            }
        }
        return result;
    }
}

function explain(possibleMatches) {
    const i = Object
        .keys(possibleMatches)
        .reduce((acc, next) => {
          acc.push(`${next}::${Object.prototype.toString.call(next)} -> \n${JSON.stringify(possibleMatches[next])}`);
          return acc;
        }, []);
    return i.join('\n');
}

module.exports = LocalFetchRequest;
<commit_msg>cleaning up local-fetch-request<commit_after>const FetchRequest = require('./fetch-request');
const QueryResultBuilder = require('../query/query-result-builder');

class LocalFetchRequest extends FetchRequest {
    execute() {
        const store = this.bridge.getStore();
        if (!store) {
            throw new Error('Illegal state. Could not resolve local store');
        }
        let possibleMatches;
        let result;
        if (this._resource) {
            return fetchResource.call(this);
        } else {
            if (!(possibleMatches = store[this.type])) {
                httpError({
                    type: this.type
                });
            }
            result = possibleMatches[String(this._uid)];
            if (!result) {
                httpError({
                    type: this.type,
                    uid: this._uid
                });
            }
        }
        return result;
    }
}

function fetchResource() {
    if (this._resource === 'attachments') {
        return fetchAttachments.call(this);
    }
    let possibleMatches;
    if (!(possibleMatches = store[this._resource])) {
        httpError({
            resource: this._resource
        });
    }
    result = possibleMatches[this._uid];
    if (!result) {
        httpError({
            resource: this_resource,
            uid: this._uid
        });
    }
    return result;
}

function fetchAttachments() {
    const store = this.bridge.getStore();
    let possibleMatches, result;
    if (!(possibleMatches = store[this.type])) {
        httpError({
            type: this.type
        });
    }
    result = possibleMatches[this._uid + '/attachments'];
    if (!result) {
        httpError({
            resource: this.type,
            uid: this._uid
        });
    }
    return QueryResultBuilder.buildResultSet(result);
}

function httpError(info) {
    const subMsg = Object.keys(info).reduce((acc, k) => {
        acc.push(`${k}::${info[k]}`);
    }, []).join(', ');
    throw new Error(`404 the requested ${subMsg} was not found in the local store`);
}

function explain(possibleMatches) {
    const i = Object
        .keys(possibleMatches)
        .reduce((acc, next) => {
            const nextTag = Object.prototype.toString.call(next);
            const matchJson = JSON.stringify(possibleMatches[next]);
            acc.push(`${next}::${nextTag} -> \n${matchJson}`);
            return acc;
        }, []);
    return i.join('\n');
}

module.exports = LocalFetchRequest;
<|endoftext|>


<commit_before>$(document).on('ready', function () {

    // Add CSRF ajax requests.
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': CSRF_TOKEN
        }
    });

    // Initialize Bootstrap tooltips.
    $('[data-toggle="tooltip"]').tooltip();

    // Initialize Bootstrap popovers.
    $('[data-toggle="popover"]').popover();

    // Initialize scrollbars.
    $('.scrollbar').perfectScrollbar();

    // Flush the footer to the bottom.
    $('#main').css('min-height', $(window).height() - $('#brand').outerHeight() - $('#footer').outerHeight() - 24);

    var $window = $(window);
    var $table = $('table.table:not(.no-affix)');
    var $responsiveTable = $table.closest('.table-responsive');

    if ($table.length === 1) {
        var $topBar = $('#topbar');
        var $thead = $table.find('thead');
        var topBarHeight = $topBar.height();
        var tableTop = $table.offset().top;

        /**
         * Gets the table cols sizes.
         *
         * @param $tbody
         * @returns {Array}
         */
        var getTableColsSizes = function ($tbody) {
            var columns = [];

            $tbody.find('tr:first-child td').each(function (index, el) {
                columns.push($(el).width());
            });

            return columns;
        };

        /**
         * Manually size all of the heads / columns.
         */
        var setTableColsSizes = function () {
            var $tbody = $('table.table').children('tbody');
            var tableColsSizes = getTableColsSizes($tbody);

            $thead.find('th').each(function (index, el) {
                $(el).width(tableColsSizes[index] + 'px');
            });

            $tbody.find('tr').first().find('td').each(function (index, el) {
                $(el).width(tableColsSizes[index] + 'px');
            });

            checkTableFixed();

            $thead.css({width: $table.width() + 'px'});
        };

        /**
         * Determines if at top.
         *
         * @return     {boolean}  True if at top, False otherwise.
         */
        var isAtTop = function () {
            return $('body').scrollTop() <= tableTop - topBarHeight;
        };

        /**
         * Fix if we're scrolled past.
         */
        var checkTableFixed = function () {
            if ($responsiveTable.outerWidth() < $table.outerWidth() || window.innerWidth < 992 || isAtTop()) {
                $thead.css({position: 'relative', top: '0px'});
                $thead.css({zIndex: '1010'});
                $table.css({marginTop: '0'});
            } else {
                $thead.css({position: 'fixed', top: topBarHeight + 'px'});
                $table.css({marginTop: $thead.height() + 'px'});
                $thead.css({zIndex: '1010'});
            }
        };

        /**
         * Make sure the table head is visible as an overlay.
         */
        $thead.css({backgroundColor: '#fff', width: $table.width() + 'px'});

        setTableColsSizes();

        $window.on('scroll', checkTableFixed);
        $window.on('resize', setTableColsSizes);
    }

    var $form = $('form.form:not(.no-affix)');

    if ($form.length === 1) {

        var $controls = $form.find('> .controls').first();
        var controlsHeight = $controls.height();

        var affixControls = function ($el) {
            $el.addClass('affix');
            $el.css({width: $form.width() + 'px'});
            $form.css({paddingBottom: 'calc(' + controlsHeight + 'px + 1.5rem)'});
        };

        var releaseControls = function ($el) {
            $el.removeClass('affix');
            $el.css({width: 'inherit'});
            $form.removeAttr('style');
        };

        var isAtBottom = function () {
            var scrollTop = $('body').scrollTop() || $('html').scrollTop();
            var windowHeight = window.innerHeight;
            var documentHeight = document.body.scrollHeight;

            return scrollTop + windowHeight - documentHeight + controlsHeight + 30 > 0;
        };

        var checkControlsFixed = function () {
            if (window.innerWidth < 992 || isAtBottom()) {
                releaseControls($controls);
            } else {
                affixControls($controls);
            }
        };

        $window.on('resize', checkControlsFixed);
        $window.on('scroll', checkControlsFixed);

        $('a[data-toggle="tab"]').on('shown.bs.tab', function () {
            checkControlsFixed();
        });

        setTimeout(function () {
            $window.trigger('resize');
        }, 20);
    }
});
<commit_msg>Slower<commit_after>$(document).on('ready', function () {

    // Add CSRF ajax requests.
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': CSRF_TOKEN
        }
    });

    // Initialize Bootstrap tooltips.
    $('[data-toggle="tooltip"]').tooltip();

    // Initialize Bootstrap popovers.
    $('[data-toggle="popover"]').popover();

    // Initialize scrollbars.
    $('.scrollbar').perfectScrollbar();

    // Flush the footer to the bottom.
    $('#main').css('min-height', $(window).height() - $('#brand').outerHeight() - $('#footer').outerHeight() - 24);

    var $window = $(window);
    var $table = $('table.table:not(.no-affix)');
    var $responsiveTable = $table.closest('.table-responsive');

    if ($table.length === 1) {
        var $topBar = $('#topbar');
        var $thead = $table.find('thead');
        var topBarHeight = $topBar.height();
        var tableTop = $table.offset().top;

        /**
         * Gets the table cols sizes.
         *
         * @param $tbody
         * @returns {Array}
         */
        var getTableColsSizes = function ($tbody) {
            var columns = [];

            $tbody.find('tr:first-child td').each(function (index, el) {
                columns.push($(el).width());
            });

            return columns;
        };

        /**
         * Manually size all of the heads / columns.
         */
        var setTableColsSizes = function () {
            var $tbody = $('table.table').children('tbody');
            var tableColsSizes = getTableColsSizes($tbody);

            $thead.find('th').each(function (index, el) {
                $(el).width(tableColsSizes[index] + 'px');
            });

            $tbody.find('tr').first().find('td').each(function (index, el) {
                $(el).width(tableColsSizes[index] + 'px');
            });

            checkTableFixed();

            $thead.css({width: $table.width() + 'px'});
        };

        /**
         * Determines if at top.
         *
         * @return     {boolean}  True if at top, False otherwise.
         */
        var isAtTop = function () {
            return $('body').scrollTop() <= tableTop - topBarHeight;
        };

        /**
         * Fix if we're scrolled past.
         */
        var checkTableFixed = function () {
            if ($responsiveTable.outerWidth() < $table.outerWidth() || window.innerWidth < 992 || isAtTop()) {
                $thead.css({position: 'relative', top: '0px'});
                $thead.css({zIndex: '1010'});
                $table.css({marginTop: '0'});
            } else {
                $thead.css({position: 'fixed', top: topBarHeight + 'px'});
                $table.css({marginTop: $thead.height() + 'px'});
                $thead.css({zIndex: '1010'});
            }
        };

        /**
         * Make sure the table head is visible as an overlay.
         */
        $thead.css({backgroundColor: '#fff', width: $table.width() + 'px'});

        setTableColsSizes();

        $window.on('scroll', checkTableFixed);
        $window.on('resize', setTableColsSizes);
    }

    var $form = $('form.form:not(.no-affix)');

    if ($form.length === 1) {

        var $controls = $form.find('> .controls').first();
        var controlsHeight = $controls.height();

        var affixControls = function ($el) {
            $el.addClass('affix');
            $el.css({width: $form.width() + 'px'});
            $form.css({paddingBottom: 'calc(' + controlsHeight + 'px + 1.5rem)'});
        };

        var releaseControls = function ($el) {
            $el.removeClass('affix');
            $el.css({width: 'inherit'});
            $form.removeAttr('style');
        };

        var isAtBottom = function () {
            var scrollTop = $('body').scrollTop() || $('html').scrollTop();
            var windowHeight = window.innerHeight;
            var documentHeight = document.body.scrollHeight;

            return scrollTop + windowHeight - documentHeight + controlsHeight + 30 > 0;
        };

        var checkControlsFixed = function () {
            if (window.innerWidth < 992 || isAtBottom()) {
                releaseControls($controls);
            } else {
                affixControls($controls);
            }
        };

        $window.on('resize', checkControlsFixed);
        $window.on('scroll', checkControlsFixed);

        $('a[data-toggle="tab"]').on('shown.bs.tab', function () {
            checkControlsFixed();
        });

        setTimeout(function () {
            $window.trigger('resize');
        }, 50);
    }
});
<|endoftext|>