<commit_before>/*eslint quotes: [2, "single"]*/

/*global document, window */

/*global utils */

/*global TermGlobals */
/*global termKey */
/*global Parser */
/*global Terminal */

/*global Mousetrap */

// TODO 0 move
var http = {};
http.get = function (url, success) {
  var request = new XMLHttpRequest();
  request.onload = function (e) {
    success(JSON.parse(request.responseText));
  };
  request.open("get", url, true);
  request.send();
};

(function(){
    'use strict';
    // Keyboard shortcuts.

    var setCurrentBlock = function (block) {
        var current = document.querySelector('z-block.current');
        block.classList.toggle('current');
        current.classList.toggle('current');
    };

    var setCurrentPort = function (port) {
        var current = document.querySelector('z-port.current');
        port.classList.toggle('current');
        current.classList.toggle('current');
    };

    var offsetCurrentBlock = function (offset) {
        var elements = document.querySelectorAll('z-block');
        var current = document.querySelector('z-block.current');
        for (var i = 0; i < elements.length; i++) {
            if (elements[i] === current) {
                var index = (elements.length + i + offset) % elements.length;
                setCurrentBlock(elements[index]);
            }
        }
    };
    window.setCurrentBlock = setCurrentBlock;

    // TODO 'context' or 'mode'?
    var context = 'block';
    var offsetCurrentPort = function (offset) {
        var elements = document.querySelectorAll('z-block.current-off-context * z-port.' + context);
        var current = document.querySelector('z-port.current');
        for (var i = 0; i < elements.length; i++) {
            if (elements[i] === current) {
                var index = (elements.length + i + offset) % elements.length;
                setCurrentPort(elements[index]);
            }
        }
    };

    window.commands = {};
    var commands = window.commands;
    var offsetCurrent = function (offset) {
        if (context === 'block') {
            offsetCurrentBlock(offset);
        } else if (context === 'input' || context === 'output') {
            offsetCurrentPort(offset);
        }
    };

    commands.prev = offsetCurrent.bind(null, -1);
    commands.next = offsetCurrent.bind(null, 1);

    commands.createBlockElement = function (content, nInputs, nOutputs) {
        var patch = document.querySelector('#patch');
        content = [
            '<z-port class="input"></z-port>'.repeat(nInputs),
            content,
            '<z-port class="output"></z-port>'.repeat(nOutputs)
        ].join('');
        var htmlString = '<z-block>' + content + '</z-block>';
        var fragment = utils.dom.createFragment(htmlString);
        var block = fragment.querySelector('z-block');

        var currentBlock = document.querySelector('z-block.current');
        var position = utils.dom.getPosition(currentBlock, currentBlock.parentNode);
        var top = position.y + currentBlock.getBoundingClientRect().height + 23;
        var left = position.x;
        block.style.top = top + 'px';
        block.style.left = left + 'px';

        setCurrentBlock(block);
        patch.appendChild(fragment);
    };

    commands.addBlock = function (type) {
        var args = arguments;
        var zeClass = '';
        if (args[1] === 'number') {
            type = 'html';
            args[1] = 'span';
            zeClass = 'zed-number';
        }
        if (type === 'html') {
            var tagName = args[1];
            var content = args[2];
            var newContent = '<' + tagName + ' class="ze-content ' + zeClass + '" contenteditable>' + content + '</' + tagName + '>';
            if (tagName === 'script') {
                newContent = '<script class="ze-content" type="application/x-prevent-script-execution-onload" style="display: block;" contenteditable oninput="compileScript(this)">' + content + '</script>';
            }
            if (tagName === 'button') {
                newContent = '<button onclick="sendEventToOutputPort(this)" class="ze-content" contenteditable>' + content + '</button>';
            }
            if (tagName[0] === '<') {
                // Actually tagName contains a HTML string.
                newContent = tagName;
            }
            args = Array.prototype.slice.call(args, 2);
            args[0] = newContent;
        }
        commands.createBlockElement.apply(null, args);
    };

    commands.add = function () {
        var current;
        if (context === 'block') {
            commands.addBlock.apply(null, arguments);
        } else if (context === 'input') {
            current = document.querySelector('z-block.current-off-context');
            current.addPort('<z-port class="input"></z-port>');
        } else if (context === 'output') {
            current = document.querySelector('z-block.current-off-context');
            current.addPort('<z-port class="output"></z-port>');
        }
    };

    commands.remove = function () {
        var selected = document.querySelector('.selected');
        if (selected !== null && selected.tagName === 'Z-LINK') {
            var link = selected;
            link.unconnect();
        } else if (context === 'block') {
            var block = document.querySelector('z-block.current');
            offsetCurrentBlock(1);
            block.unplug();
            block.parentNode.removeChild(block);
        } else if (context === 'input' || context === 'output') {
            var port = document.querySelector('z-port.current');
            offsetCurrentPort(1);
            port.unplug();
            port.parentNode.removeChild(port);
        }
    };

    var switchCurrentOnOffContext = function (elementTagName, onOrOff) {
        var className = 'current';
        if (onOrOff === 'on') {
            className += '-off-context';
        }
        var element = document.querySelector(elementTagName + '.' + className);
        element.classList.toggle('current-off-context');
        element.classList.toggle('current');
    };

    commands.port = function (inputOrOutput) {
        if (context !== 'block') {
            return;
        }
        try {
            switchCurrentOnOffContext('z-block.current * z-port.' + inputOrOutput, 'on');
        } catch (e) {
            var port = document.querySelector('z-block.current * z-port.' + inputOrOutput);
            if (port !== null) {
                port.classList.toggle('current');
            }
        }
        switchCurrentOnOffContext('z-block', 'off');
        context = inputOrOutput;
    };
    commands.inputs = commands.port.bind(null, 'input');
    commands.outputs = commands.port.bind(null, 'output');

    commands.block = function () {
        context = 'block';
        switchCurrentOnOffContext('z-block', 'on');
        try {
            switchCurrentOnOffContext('z-port.input', 'off');
        } catch(e) {}
        try {
            switchCurrentOnOffContext('z-port.output', 'off');
        } catch(e) {}
    };

    var goOutOfCommandLine = function () {
        TermGlobals.keylock = true;
        TermGlobals.activeTerm.cursorOff();
        bindKeysForMainMode();
        var termDiv = document.querySelector('#termDiv');
        termDiv.classList.toggle('focused');
    };

    var ctrlHandler = function () {
        if (this.inputChar === termKey.ESC) {
            goOutOfCommandLine();
        }
    };

    var termHandler = function () {
        this.newLine();
        var parser = new Parser();
        parser.parseLine(this);
        var commandName = this.argv[0];
        if (commands.hasOwnProperty(commandName)) {
            var args = this.argv.slice(1);
            try {
                commands[commandName].apply(null, args);
            } catch (e) {
                this.write(e.message);
            }
        } else {
            this.write('unknown command "' + commandName + '".');
        }
        this.prompt();
    };

    var initHandler = function () {
        this.prompt();
    };

    var term = new Terminal( {
        handler: termHandler,
        bgColor: '#f0f0f0',
        crsrBlinkMode: true,
        crsrBlockMode: false,
        rows: 10,
        frameWidth: 0,
        closeOnESC: false,
        ctrlHandler: ctrlHandler,
        initHandler: initHandler

    } );
    var res = term.open();

    commands.goToCommandLine = function () {
        TermGlobals.keylock = false;
        Mousetrap.reset();
        TermGlobals.activeTerm.cursorOn();
        var termDiv = document.querySelector('#termDiv');
        termDiv.classList.toggle('focused');
    };

    commands.editBlock = function (block) {
        Mousetrap.reset();
        Mousetrap.bind('esc', commands.escape);
        block.content.focus();
    };

    commands.edit = function () {
        if (context === 'block') {
            var block = document.querySelector('z-block.current');
            commands.editBlock(block);
            return false;
        }
    };

    commands.fire = function () {
        if (context === 'block') {
            var block = document.querySelector('z-block.current');
            var content = block.content;
            if (content.tagName === 'BUTTON') {
                sendEventToOutputPort(content);
            } else if (content.tagName === 'SCRIPT') {
                fireEvent2(block);
            }
        }
    };

    commands.help = function (subject) {
        if (subject === undefined) {
            term.write('Press Esc to leave the command line and go back to normal mode.');
            term.newLine();
            term.newLine();
            term.write('Commands: next, prev, remove and add.');
        } else if (subject === 'add') {
            term.write('Add a new block just below the current block.');
            term.newLine();
            term.newLine();
            term.write('add html <what> <content> <nb inputs> <nb outputs>');
            term.newLine();
            term.write('  <what>    is either "button", "script", "text", "number" or a HTML tag.');
            term.newLine();
            term.write('  <content> is the content of the block (i.e. the button name, the');
            term.newLine();
            term.write('            script code, the text or number value, etc.).');
        } else {
            term.write('No help for "' + subject + '".');
        }
    };

    commands.addButton = commands.add.bind(null, 'html', 'button', 'go', 0, 1);
    commands.addScript = commands.add.bind(null, 'html', 'script', 'return in1 + 2;', 1, 1);
    commands.addText = commands.add.bind(null, 'html', 'span', 'empty', 1, 1);
    commands.addNumber = commands.add.bind(null, 'zed', 'number', '42', 1, 1);
    var bindKeysForMainMode = function () {
        Mousetrap.reset();
        Mousetrap.bind('k', commands.prev);
        Mousetrap.bind('j', commands.next);
        Mousetrap.bind('a n', commands.add.bind(null, 'New'));
        Mousetrap.bind('a h b', commands.addButton);
        Mousetrap.bind('a h s', commands.addScript);
        Mousetrap.bind('a h t', commands.addText);
        Mousetrap.bind('a h n', commands.addNumber);
        Mousetrap.bind('r', commands.remove);
        Mousetrap.bind('i', commands.inputs);
        Mousetrap.bind('o', commands.outputs);
        Mousetrap.bind('b', commands.block);
        Mousetrap.bind('c', commands.goToCommandLine);
        Mousetrap.bind('l', commands.link);
        Mousetrap.bind('g', commands.goToBlock);
        Mousetrap.bind('e', commands.edit);
        Mousetrap.bind('space', commands.fire);
    };

    commands.escape = function () {
        if (context === 'block') {
            var currentlyEditingElement = utils.dom.getSelectionStart();
            if (currentlyEditingElement !== null) {
                currentlyEditingElement.blur();
            }
            bindKeysForMainMode();
        }
    };

    var hideAllPorts = function () {
        var ports = document.querySelectorAll('z-port');
        [].forEach.call(ports, function (port) {
            port.hideKey();
        });
    };
    var firstPort;
    var selectPort = function (port) {
        if (firstPort === undefined) {
            firstPort = port;
        } else {
            if (port.connectable(port, firstPort)) {
                port.connect(port, firstPort);
                firstPort = undefined;
                hideAllPorts();
                bindKeysForMainMode();
            }
        }
    };

    var portToLinkTo;
    commands.link = function () {
        if (context === 'block') {
            firstPort = undefined;
            Mousetrap.reset();
            var ports = document.querySelectorAll('z-port');
            var index = 1;
            [].forEach.call(ports, function (port) {
                port.showKey();
                var key = port.querySelector('span.port-key').innerHTML;
                // Convert 'aae' into 'a a e'.
                key = key.split('').join(' ');
                Mousetrap.bind(key, selectPort.bind(null, port));
                index++;
            });
            Mousetrap.bind('esc', function () {
                bindKeysForMainMode();
                hideAllPorts();
            });
        } else {
            var port = document.querySelector('z-port.current');
            if (port !== null) {
                if (portToLinkTo === undefined) {
                    portToLinkTo = port;
                    portToLinkTo.classList.toggle('to-link-to');
                } else if (port.connectable(port, portToLinkTo)) {
                    port.connect(port, portToLinkTo);
                    portToLinkTo.classList.toggle('to-link-to');
                    portToLinkTo = undefined;
                } else {
                    portToLinkTo.classList.toggle('to-link-to');
                    portToLinkTo = port;
                    portToLinkTo.classList.toggle('to-link-to');
                }
            }
        }
    };

    var setCurrentBlockAndBackToMainMode = function (block) {
        setCurrentBlock(block);
        var blocks = document.querySelectorAll('z-block');
        [].forEach.call(blocks, function (block) {
            block.hideKey();
        });
        bindKeysForMainMode();
    };

    commands.goToBlock = function () {
        Mousetrap.reset();
        var blocks = document.querySelectorAll('z-block');
        var index = 0;
        [].forEach.call(blocks, function (block) {
            block.showKey();
            var key = block.querySelector('span.id').innerHTML;
            // Convert 'aae' into 'a a e'.
            key = key.split('').join(' ');
            Mousetrap.bind(key, setCurrentBlockAndBackToMainMode.bind(null, block));
            index++;
        });
        Mousetrap.bind('esc', bindKeysForMainMode);
    };

    // Set a new stopCallback for Moustrap to avoid stopping when we start
    // editing a contenteditable, so that we can use escape to leave editing.
    Mousetrap.stopCallback = function(e, element, combo) {
        // if the element has the class "mousetrap" then no need to stop
        if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
            return false;
        }

         // stop for input, select, and textarea
         return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA';
     };

    var blinkCursor = function () {
        var current = document.querySelector('z-block.current');
        if (current !== null) {
            current.classList.toggle('cursor-displayed');
        }
        window.setTimeout(blinkCursor, 1000);
    };
    blinkCursor();

    bindKeysForMainMode();
    goOutOfCommandLine();

})();
<commit_msg>minor<commit_after>/*eslint quotes: [2, "single"]*/

/*global document, window */

/*global utils */

/*global TermGlobals */
/*global termKey */
/*global Parser */
/*global Terminal */

/*global Mousetrap */

// TODO 0 move
var http = {};
http.get = function (url, success) {
  var request = new XMLHttpRequest();
  request.onload = function (e) {
    success(JSON.parse(request.responseText));
  };
  request.open("get", url, true);
  request.send();
};

(function(){
    'use strict';
    // Keyboard shortcuts.

    var setCurrentBlock = function (block) {
        var current = document.querySelector('z-block.current');
        block.classList.toggle('current');
        current.classList.toggle('current');
    };

    var setCurrentPort = function (port) {
        var current = document.querySelector('z-port.current');
        port.classList.toggle('current');
        current.classList.toggle('current');
    };

    var offsetCurrentBlock = function (offset) {
        var elements = document.querySelectorAll('z-block');
        var current = document.querySelector('z-block.current');
        for (var i = 0; i < elements.length; i++) {
            if (elements[i] === current) {
                var index = (elements.length + i + offset) % elements.length;
                setCurrentBlock(elements[index]);
            }
        }
    };
    window.setCurrentBlock = setCurrentBlock;

    // TODO 'context' or 'mode'?
    var context = 'block';
    var offsetCurrentPort = function (offset) {
        var elements = document.querySelectorAll('z-block.current-off-context * z-port.' + context);
        var current = document.querySelector('z-port.current');
        for (var i = 0; i < elements.length; i++) {
            if (elements[i] === current) {
                var index = (elements.length + i + offset) % elements.length;
                setCurrentPort(elements[index]);
            }
        }
    };

    window.commands = {};
    var commands = window.commands;
    var offsetCurrent = function (offset) {
        if (context === 'block') {
            offsetCurrentBlock(offset);
        } else if (context === 'input' || context === 'output') {
            offsetCurrentPort(offset);
        }
    };

    commands.prev = offsetCurrent.bind(null, -1);
    commands.next = offsetCurrent.bind(null, 1);

    commands.createBlockElement = function (content, nInputs, nOutputs) {
        var patch = document.querySelector('#patch');
        content = [
            '<z-port class="input"></z-port>'.repeat(nInputs),
            content,
            '<z-port class="output"></z-port>'.repeat(nOutputs)
        ].join('');
        var htmlString = '<z-block>' + content + '</z-block>';
        var fragment = utils.dom.createFragment(htmlString);
        var block = fragment.querySelector('z-block');

        var currentBlock = document.querySelector('z-block.current');
        var position = utils.dom.getPosition(currentBlock, currentBlock.parentNode);
        var top = position.y + currentBlock.getBoundingClientRect().height + 23;
        var left = position.x;
        block.style.top = top + 'px';
        block.style.left = left + 'px';

        setCurrentBlock(block);
        patch.appendChild(fragment);
    };

    commands.addBlock = function (type) {
        var args = arguments;
        var zeClass = '';
        if (args[1] === 'number') {
            type = 'html';
            args[1] = 'span';
            zeClass = 'zed-number';
        }
        if (type === 'html') {
            var tagName = args[1];
            var content = args[2];
            var newContent = '<' + tagName + ' class="ze-content ' + zeClass + '" contenteditable>' + content + '</' + tagName + '>';
            if (tagName === 'script') {
                newContent = '<script class="ze-content" type="application/x-prevent-script-execution-onload" style="display: block;" contenteditable oninput="compileScript(this)">' + content + '</script>';
            }
            if (tagName === 'button') {
                newContent = '<button onclick="sendEventToOutputPort(this)" class="ze-content" contenteditable>' + content + '</button>';
            }
            if (tagName[0] === '<') {
                // Actually tagName contains a HTML string.
                newContent = tagName;
            }
            args = Array.prototype.slice.call(args, 2);
            args[0] = newContent;
        }
        commands.createBlockElement.apply(null, args);
    };

    commands.add = function () {
        var current;
        if (context === 'block') {
            commands.addBlock.apply(null, arguments);
        } else if (context === 'input') {
            current = document.querySelector('z-block.current-off-context');
            current.addPort('<z-port class="input"></z-port>');
        } else if (context === 'output') {
            current = document.querySelector('z-block.current-off-context');
            current.addPort('<z-port class="output"></z-port>');
        }
    };

    commands.remove = function () {
        var selected = document.querySelector('.selected');
        if (selected !== null && selected.tagName === 'Z-LINK') {
            var link = selected;
            link.unconnect();
        } else if (context === 'block') {
            var block = document.querySelector('z-block.current');
            offsetCurrentBlock(1);
            block.unplug();
            block.parentNode.removeChild(block);
        } else if (context === 'input' || context === 'output') {
            var port = document.querySelector('z-port.current');
            offsetCurrentPort(1);
            port.unplug();
            port.parentNode.removeChild(port);
        }
    };

    var switchCurrentOnOffContext = function (elementTagName, onOrOff) {
        var className = 'current';
        if (onOrOff === 'on') {
            className += '-off-context';
        }
        var element = document.querySelector(elementTagName + '.' + className);
        element.classList.toggle('current-off-context');
        element.classList.toggle('current');
    };

    commands.port = function (inputOrOutput) {
        if (context !== 'block') {
            return;
        }
        try {
            switchCurrentOnOffContext('z-block.current * z-port.' + inputOrOutput, 'on');
        } catch (e) {
            var port = document.querySelector('z-block.current * z-port.' + inputOrOutput);
            if (port !== null) {
                port.classList.toggle('current');
            }
        }
        switchCurrentOnOffContext('z-block', 'off');
        context = inputOrOutput;
    };
    commands.inputs = commands.port.bind(null, 'input');
    commands.outputs = commands.port.bind(null, 'output');

    commands.block = function () {
        context = 'block';
        switchCurrentOnOffContext('z-block', 'on');
        try {
            switchCurrentOnOffContext('z-port.input', 'off');
        } catch(e) {}
        try {
            switchCurrentOnOffContext('z-port.output', 'off');
        } catch(e) {}
    };

    var goOutOfCommandLine = function () {
        TermGlobals.keylock = true;
        TermGlobals.activeTerm.cursorOff();
        bindKeysForMainMode();
        var termDiv = document.querySelector('#termDiv');
        termDiv.classList.toggle('focused');
    };

    var ctrlHandler = function () {
        if (this.inputChar === termKey.ESC) {
            goOutOfCommandLine();
        }
    };

    var termHandler = function () {
        this.newLine();
        var parser = new Parser();
        parser.parseLine(this);
        var commandName = this.argv[0];
        if (commands.hasOwnProperty(commandName)) {
            var args = this.argv.slice(1);
            try {
                commands[commandName].apply(null, args);
            } catch (e) {
                this.write(e.message);
            }
        } else {
            this.write('unknown command "' + commandName + '".');
        }
        this.prompt();
    };

    var initHandler = function () {
        this.prompt();
    };

    var term = new Terminal( {
        handler: termHandler,
        bgColor: '#f0f0f0',
        crsrBlinkMode: true,
        crsrBlockMode: false,
        rows: 10,
        frameWidth: 0,
        closeOnESC: false,
        ctrlHandler: ctrlHandler,
        initHandler: initHandler

    } );
    var res = term.open();

    commands.goToCommandLine = function () {
        TermGlobals.keylock = false;
        Mousetrap.reset();
        TermGlobals.activeTerm.cursorOn();
        var termDiv = document.querySelector('#termDiv');
        termDiv.classList.toggle('focused');
    };

    commands.editBlock = function (block) {
        Mousetrap.reset();
        Mousetrap.bind('esc', commands.escape);
        block.content.focus();
    };

    commands.edit = function () {
        if (context === 'block') {
            var block = document.querySelector('z-block.current');
            commands.editBlock(block);
            // Prevent default when this function is used with Moustrap.
            return false;
        }
    };

    commands.fire = function () {
        if (context === 'block') {
            var block = document.querySelector('z-block.current');
            var content = block.content;
            if (content.tagName === 'BUTTON') {
                sendEventToOutputPort(content);
            } else if (content.tagName === 'SCRIPT') {
                fireEvent2(block);
            }
        }
    };

    commands.help = function (subject) {
        if (subject === undefined) {
            term.write('Press Esc to leave the command line and go back to normal mode.');
            term.newLine();
            term.newLine();
            term.write('Commands: next, prev, remove and add.');
        } else if (subject === 'add') {
            term.write('Add a new block just below the current block.');
            term.newLine();
            term.newLine();
            term.write('add html <what> <content> <nb inputs> <nb outputs>');
            term.newLine();
            term.write('  <what>    is either "button", "script", "text", "number" or a HTML tag.');
            term.newLine();
            term.write('  <content> is the content of the block (i.e. the button name, the');
            term.newLine();
            term.write('            script code, the text or number value, etc.).');
        } else {
            term.write('No help for "' + subject + '".');
        }
    };

    commands.addButton = commands.add.bind(null, 'html', 'button', 'go', 0, 1);
    commands.addScript = commands.add.bind(null, 'html', 'script', 'return in1 + 2;', 1, 1);
    commands.addText = commands.add.bind(null, 'html', 'span', 'empty', 1, 1);
    commands.addNumber = commands.add.bind(null, 'zed', 'number', '42', 1, 1);
    var bindKeysForMainMode = function () {
        Mousetrap.reset();
        Mousetrap.bind('k', commands.prev);
        Mousetrap.bind('j', commands.next);
        Mousetrap.bind('a n', commands.add.bind(null, 'New'));
        Mousetrap.bind('a h b', commands.addButton);
        Mousetrap.bind('a h s', commands.addScript);
        Mousetrap.bind('a h t', commands.addText);
        Mousetrap.bind('a h n', commands.addNumber);
        Mousetrap.bind('r', commands.remove);
        Mousetrap.bind('i', commands.inputs);
        Mousetrap.bind('o', commands.outputs);
        Mousetrap.bind('b', commands.block);
        Mousetrap.bind('c', commands.goToCommandLine);
        Mousetrap.bind('l', commands.link);
        Mousetrap.bind('g', commands.goToBlock);
        Mousetrap.bind('e', commands.edit);
        Mousetrap.bind('space', commands.fire);
    };

    commands.escape = function () {
        if (context === 'block') {
            var currentlyEditingElement = utils.dom.getSelectionStart();
            if (currentlyEditingElement !== null) {
                currentlyEditingElement.blur();
            }
            bindKeysForMainMode();
        }
    };

    var hideAllPorts = function () {
        var ports = document.querySelectorAll('z-port');
        [].forEach.call(ports, function (port) {
            port.hideKey();
        });
    };
    var firstPort;
    var selectPort = function (port) {
        if (firstPort === undefined) {
            firstPort = port;
        } else {
            if (port.connectable(port, firstPort)) {
                port.connect(port, firstPort);
                firstPort = undefined;
                hideAllPorts();
                bindKeysForMainMode();
            }
        }
    };

    var portToLinkTo;
    commands.link = function () {
        if (context === 'block') {
            firstPort = undefined;
            Mousetrap.reset();
            var ports = document.querySelectorAll('z-port');
            var index = 1;
            [].forEach.call(ports, function (port) {
                port.showKey();
                var key = port.querySelector('span.port-key').innerHTML;
                // Convert 'aae' into 'a a e'.
                key = key.split('').join(' ');
                Mousetrap.bind(key, selectPort.bind(null, port));
                index++;
            });
            Mousetrap.bind('esc', function () {
                bindKeysForMainMode();
                hideAllPorts();
            });
        } else {
            var port = document.querySelector('z-port.current');
            if (port !== null) {
                if (portToLinkTo === undefined) {
                    portToLinkTo = port;
                    portToLinkTo.classList.toggle('to-link-to');
                } else if (port.connectable(port, portToLinkTo)) {
                    port.connect(port, portToLinkTo);
                    portToLinkTo.classList.toggle('to-link-to');
                    portToLinkTo = undefined;
                } else {
                    portToLinkTo.classList.toggle('to-link-to');
                    portToLinkTo = port;
                    portToLinkTo.classList.toggle('to-link-to');
                }
            }
        }
    };

    var setCurrentBlockAndBackToMainMode = function (block) {
        setCurrentBlock(block);
        var blocks = document.querySelectorAll('z-block');
        [].forEach.call(blocks, function (block) {
            block.hideKey();
        });
        bindKeysForMainMode();
    };

    commands.goToBlock = function () {
        Mousetrap.reset();
        var blocks = document.querySelectorAll('z-block');
        var index = 0;
        [].forEach.call(blocks, function (block) {
            block.showKey();
            var key = block.querySelector('span.id').innerHTML;
            // Convert 'aae' into 'a a e'.
            key = key.split('').join(' ');
            Mousetrap.bind(key, setCurrentBlockAndBackToMainMode.bind(null, block));
            index++;
        });
        Mousetrap.bind('esc', bindKeysForMainMode);
    };

    // Set a new stopCallback for Moustrap to avoid stopping when we start
    // editing a contenteditable, so that we can use escape to leave editing.
    Mousetrap.stopCallback = function(e, element, combo) {
        // if the element has the class "mousetrap" then no need to stop
        if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
            return false;
        }

         // stop for input, select, and textarea
         return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA';
     };

    var blinkCursor = function () {
        var current = document.querySelector('z-block.current');
        if (current !== null) {
            current.classList.toggle('cursor-displayed');
        }
        window.setTimeout(blinkCursor, 1000);
    };
    blinkCursor();

    bindKeysForMainMode();
    goOutOfCommandLine();

})();
<|endoftext|>


<commit_before>/* Profile chat-plugin
 * by jd, modified by panpawn
 */
var serverIp = '167.114.155.242';
var http = require('http');
var formatHex = '#000000'; //hex code for the formatting of the command
var geoip = require('geoip-ultralight');
geoip.startWatchingDataUpdate();

exports.commands = {
	profile: function(target, room, user) {
		if (!target) target = user.name;
		if (toId(target).length > 19) return this.sendReply("Usernames may not be more than 19 characters long.");
		if (toId(target).length < 1) return this.sendReply(target + " is not a valid username.");
		if (!this.canBroadcast()) return;

		var targetUser = Users.get(target);

		if (!targetUser) {
			var username = target;
			var userid = toId(target);
			var online = false;
			var avatar = (Config.customavatars[userid] ? "http://" + serverIp + ":" + Config.port + "/avatars/" + Config.customavatars[userid] : "http://play.pokemonshowdown.com/sprites/trainers/167.png");
		} else {
			var username = targetUser.name;
			var userid = targetUser.userid;
			var online = targetUser.connected;
			var avatar = (isNaN(targetUser.avatar) ? "http://" + serverIp + ":" + Config.port + "/avatars/" + targetUser.avatar : "http://play.pokemonshowdown.com/sprites/trainers/" + targetUser.avatar + ".png");
		}

    	if (Users.usergroups[userid]) {
			var userGroup = Users.usergroups[userid].substr(0,1);
			if (Config.groups[userGroup]) userGroup = Config.groups[userGroup].name;
		} else {
			var userGroup = 'Regular User';
		}

		var self = this;
		var bucks = economy.readMoney(userid)
		var options = {
			host: "pokemonshowdown.com",
			port: 80,
			path: "/users/" + userid
		};

		var content = "";
		var req = http.request(options, function(res) {

			res.setEncoding("utf8");
			res.on("data", function (chunk) {
				content += chunk;
			});
			res.on("end", function () {
				content = content.split("<em");
				if (content[1]) {
					content = content[1].split("
");
					if (content[0]) {
						content = content[0].split("");
						if (content[1]) {
							regdate = content[1].trim();
							showProfile();
						}
					}
				} else {
					regdate = '(Unregistered)';
					showProfile();
				}
			});
		});
		req.end();
		function getFlag (flagee) {
			if (!Users(flagee)) return false;
			if (Users(flagee)) {
				var geo = geoip.lookupCountry(Users(flagee).latestIp);
				if (!geo) {
					return false;
				} else {
					return ' ';
				}
			}
		}
		function showProfile() {
			var seenOutput = '';
			if (!Gold.seenData[userid]) seenOutput = "Never";
			var date = new Date(Gold.seenData[userid]);
			if (Gold.seenData[userid]) {
				seenOutput = date.toUTCString() + " ";
				var seconds = Math.floor(((Date.now() - Gold.seenData[userid]) / 1000));
				var minutes = Math.floor((seconds / 60));
				var hours = Math.floor((minutes / 60));
				var days = Math.floor((hours / 24));
				var secondsWord = (((seconds % 60) > 1 || (seconds % 60) == 0) ? 'seconds' : 'second');
				var minutesWord = (((minutes % 60) > 1 || (minutes % 60) == 0) ? 'minutes' : 'minute');
				var hoursWord = ((hours > 1 || hours == 0) ? 'hours' : 'hour');
				var daysWord = ((days === 1) ? 'day' : 'days');

				if (minutes < 1) {
					seenOutput += " (" + seconds + " " + secondsWord + " ago)";
				}
				if (minutes > 0 && minutes < 60) {
					seenOutput += " (" + minutes + " " + minutesWord + " ago)";
				}
				if (hours > 0 && days < 1) {
					seenOutput += " (" + hours + " " + hoursWord + " " + (minutes % 60) + " " + minutesWord + " ago)";
				}
				if (days > 0) {
					seenOutput += " (" + days + " " + daysWord + " ago)";
				}
			}

			var profile = '';
			profile += '';
			if (!getFlag(toId(username))) profile += ' Name: ' + Tools.escapeHTML(username) + '
';
			if (getFlag(toId(username))) profile += ' Name: ' + Tools.escapeHTML(username) + '' + getFlag(toId(username)) + '
';
			profile += ' Registered: ' + regdate + '
';
			if (!Gold.hasBadge(userid,'vip')) profile += ' Rank: ' + userGroup + '
';
			if (Gold.hasBadge(userid,'vip')) profile += ' Rank: ' + userGroup + ' (VIP User)
';
			if (bucks) profile += ' Bucks: ' + bucks + '
';
			if (online) profile += ' Last Online: Currently Online
';
			if (!online) profile += ' Last Online: ' + seenOutput + '
';
			profile += '
';
			self.sendReplyBox(profile);
			room.update();
		}
	}
};<commit_msg>Add 'last active' to /profile and begin to add status code<commit_after>/* Profile chat-plugin
 * by jd, modified by panpawn
 */
var serverIp = '167.114.155.242';
var http = require('http');
var formatHex = '#000000'; //hex code for the formatting of the command
var geoip = require('geoip-ultralight');
var moment = require('moment');
geoip.startWatchingDataUpdate();

exports.commands = {
	profile: function(target, room, user) {
		if (!target) target = user.name;
		if (toId(target).length > 19) return this.sendReply("Usernames may not be more than 19 characters long.");
		if (toId(target).length < 1) return this.sendReply(target + " is not a valid username.");
		if (!this.canBroadcast()) return;

		var targetUser = Users.get(target);

		if (!targetUser) {
			var username = target;
			var userid = toId(target);
			var online = false;
			var avatar = (Config.customavatars[userid] ? "http://" + serverIp + ":" + Config.port + "/avatars/" + Config.customavatars[userid] : "http://play.pokemonshowdown.com/sprites/trainers/167.png");
		} else {
			var username = targetUser.name;
			var userid = targetUser.userid;
			var online = targetUser.connected;
			var avatar = (isNaN(targetUser.avatar) ? "http://" + serverIp + ":" + Config.port + "/avatars/" + targetUser.avatar : "http://play.pokemonshowdown.com/sprites/trainers/" + targetUser.avatar + ".png");
		}

    	if (Users.usergroups[userid]) {
			var userGroup = Users.usergroups[userid].substr(0,1);
			if (Config.groups[userGroup]) userGroup = Config.groups[userGroup].name;
		} else {
			var userGroup = 'Regular User';
		}

		var self = this;
		var bucks = economy.readMoney(userid)
		var options = {
			host: "pokemonshowdown.com",
			port: 80,
			path: "/users/" + userid
		};

		var content = "";
		var req = http.request(options, function(res) {

			res.setEncoding("utf8");
			res.on("data", function (chunk) {
				content += chunk;
			});
			res.on("end", function () {
				content = content.split("<em");
				if (content[1]) {
					content = content[1].split("
");
					if (content[0]) {
						content = content[0].split("");
						if (content[1]) {
							regdate = content[1].trim();
							showProfile();
						}
					}
				} else {
					regdate = '(Unregistered)';
					showProfile();
				}
			});
		});
		req.end();
		function getFlag (flagee) {
			if (!Users(flagee)) return false;
			if (Users(flagee)) {
				var geo = geoip.lookupCountry(Users(flagee).latestIp);
				if (!geo) {
					return false;
				} else {
					return ' ';
				}
			}
		}
		/*
		function getStatus (user) {
			if (!Users(user)) return false;
			if (Users(user)) {
				var status = Users(users).status;
			}
			return status;
		}
		*/
		function lastActive (user) {
			if (!Users(user)) return false;
			var time = Users(user).lastMessageTime;
			if (time == 0) return "notalk";
			if (Users(user)) {
				var active = moment(time).fromNow();
			}
			return active;
		}
		function showProfile() {
			var seenOutput = '';
			if (!Gold.seenData[userid]) seenOutput = "Never";
			var date = new Date(Gold.seenData[userid]);
			if (Gold.seenData[userid]) {
				seenOutput = date.toUTCString() + " ";
				var seconds = Math.floor(((Date.now() - Gold.seenData[userid]) / 1000));
				var minutes = Math.floor((seconds / 60));
				var hours = Math.floor((minutes / 60));
				var days = Math.floor((hours / 24));
				var secondsWord = (((seconds % 60) > 1 || (seconds % 60) == 0) ? 'seconds' : 'second');
				var minutesWord = (((minutes % 60) > 1 || (minutes % 60) == 0) ? 'minutes' : 'minute');
				var hoursWord = ((hours > 1 || hours == 0) ? 'hours' : 'hour');
				var daysWord = ((days === 1) ? 'day' : 'days');

				if (minutes < 1) {
					seenOutput += " (" + seconds + " " + secondsWord + " ago)";
				}
				if (minutes > 0 && minutes < 60) {
					seenOutput += " (" + minutes + " " + minutesWord + " ago)";
				}
				if (hours > 0 && days < 1) {
					seenOutput += " (" + hours + " " + hoursWord + " " + (minutes % 60) + " " + minutesWord + " ago)";
				}
				if (days > 0) {
					seenOutput += " (" + days + " " + daysWord + " ago)";
				}
			}

			var profile = '';
			profile += '';
			if (!getFlag(toId(username))) profile += ' Name: ' + Tools.escapeHTML(username) + '
';
			if (getFlag(toId(username))) profile += ' Name: ' + Tools.escapeHTML(username) + '' + getFlag(toId(username)) + '
';
			profile += ' Registered: ' + regdate + '
';
			if (!Gold.hasBadge(userid,'vip')) profile += ' Rank: ' + userGroup + '
';
			if (Gold.hasBadge(userid,'vip')) profile += ' Rank: ' + userGroup + ' (VIP User)
';
			if (bucks) profile += ' Bucks: ' + bucks + '
';
			if (online && (lastActive(toId(username)) && lastActive(toId(username)) !== 'notalk')) profile += ' Last Active: ' + lastActive(toId(username)) + '
';
			if (online && lastActive(toId(username)) === 'notalk') profile += ' Last Online: Currently Online
';
			if (!online) profile += ' Last Online: ' + seenOutput + '
';
			profile += '
';
			self.sendReplyBox(profile);
			room.update();
		}
	},
	/*
	status: function(target, room, user) {
		if (!this.canTalk()) return;
		var status = Tools.escapeHTML(target);
		if (status.length > 75) return this.errorReply("Your status cannot be longer than 75 characters.");
		user.status = status;
		this.logModCommand(user.name + ' set their status to: ' + status);
	},
	clearstatus: function(target, room, user) {
		if (!this.can('pban')) return false;
		if (!Users(target)) return this.errorReply("User '" + target + "' not found.  Check spelling?");
		if (!Users(target).status) return this.errorReply("Users '" + target + "' does not have a status currently set to clear.");
		Users(target).status = false;
		this.logModCommand(user.name + ' has reset ' + target + '\'s status.');
	}
	*/
};<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : mapChartSpec.js
* Module : UnitTest
* Location : /test/businessTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-29   Filippo Rampado    Initial code
* =========================================================
*/

var MapChart = require('../../../lib/businessTier/graph/mapChart.js');
var assert = require('assert');

describe('MapChart', function() {
    var socketMock=function(){
        this.p1=null;
        this.p2=null;
        this._namespace='flow1';
        this.attachObject=function(p1, p2){
            this.p1=p1;
            this.p2=p2;
        };
        this.sendMessage=function(p1, p2){
            this.p1=p1;
            this.p2=p2;
        };
    };

    var socketMockHistory=function(){
        this.p1=[];
        this.p2=[];
        this._namespace='flow1';
        this.sendMessage=function(p1, p2){
            this.p1.push(p1);
            this.p2.push(p2);
        };
        this.attachObject=function(p1, p2){
            this.p1.push(p1);
            this.p2.push(p2);
        };
    };

    it('returns null when there are no params', function() {
        assert.strictEqual((new MapChart()).hasOwnProperty('_dataMapChart'), false);
    });

    it('returns null when there is no valid page in params', function() {
        assert.strictEqual((new MapChart(2, 3)).hasOwnProperty('_dataMapChart'), false);
    });

    it('returns null when there is no valid graphsocket in params', function() {
        assert.strictEqual((new MapChart(2, {_page:2}, 3)).hasOwnProperty('_dataMapChart'), false);
    });

    it('returns null when params are not valid', function() {
        assert.strictEqual((new MapChart(2, {_page:2}, new socketMock())).hasOwnProperty('_dataMapChart'), false);
    });

    it('calls the parent constructor with the params specified', function() {
        var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
        assert.strictEqual(mp._dataMapChart._ID, 'map1');
        assert.strictEqual(mp._graphSocket._namespace, 'flow1');
    });

    describe('#createMapChartFlow', function() {
        it ('returns 232 if are passed no valid params', function(){
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            assert.strictEqual(mp.createMapChartFlow(0), 232);
        });
        it ('adds and returns a mapChartFlow', function(){
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            assert.strictEqual(mp.createMapChartFlow({ID: 'flow1'}).hasOwnProperty('_dataMapChartFlow'), true);
            assert.strictEqual(mp._flows[0].hasOwnProperty('_dataMapChartFlow'), true);
        });

        it('adds and returns a mapChartFlow', function() {
            var mock = new socketMock();
            var mapChart=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            var lc=mapChart.createMapChartFlow({
                'ID':'flow1',
                'name': 'linea 22',
                'marker':{
                    'type': 'shape',
                    'shape': 'circle',
                    'icon': 'null',
                    'text': 'null',
                    'color' : '#000'
                },
                'trace':{
                    'type':'poly',
                    'coordinates': [[45.42946, 11.94090],[45.42941, 11.94081],[45.43054, 11.93937],[45.43131, 11.93773],[45.43268, 11.93539],[45.34719, 11.81996]],
                    'strokeColor': '#DC271C',
                    'fillColor': '#3a6d99'
                },
                'trailLength': 3,
                'latitudeKey': '1',
                'longitudeKey': '2',
                'objectKey': '0'
            });
            assert.strictEqual(lc.hasOwnProperty('_dataMapChartFlow'),true);
            assert.strictEqual(mock.p1,'insertFlow');
            assert.strictEqual(mock.p2.ID, 'flow1');
            assert.strictEqual(mock.p2.name, 'linea 22');
        });
    });
    describe('#getFlowByID', function() {
        it('returns 282 if there is no valid ID', function(){
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            assert.strictEqual(mp.getFlowByID(0), 282);
        });
        it('return 282 - no ID in flows', function() {
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            mp.createMapChartFlow({ID: 'flow1'}).hasOwnProperty('_dataMapChartFlow');
            assert.strictEqual(mp.getFlowByID('fl1'),282);
        });
        it('return correct flow', function() {
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            mp.createMapChartFlow({ID: 'flow1'});
            mp.createMapChartFlow({ID: 'flow2'});
            assert.strictEqual(mp.getFlowByID('flow2')._dataMapChartFlow._ID,'flow2');
        });
    });
    describe('#deleteFlow', function() {
        it('return 283 - ID is not a string', function() {
            var mock=new socketMock();
            var mp=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            mp.createLineChartFlow({ ID:'flow1', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            console.log('mp '+JSON.stringify(mp));
            console.log('mpmpmpmp '+JSON.stringify(mp.deleteFlow(34)));
            assert.strictEqual(mp.deleteFlow(34),283);
        });
        it('return 283 - no ID in flows', function() {
            var mock=new socketMock();
            var mp=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            mp.createLineChartFlow({ ID:'flow1', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            assert.strictEqual(mp.deleteFlow('flow123'),283);
        });
        it('return true - deleted flow', function() {
            var mock = new socketMock();
            var mp=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            mp.createLineChartFlow({ ID:'flow1', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            assert.strictEqual(mp.deleteFlow('flow1'),true);
            assert.strictEqual(mock.p1,'deleteFlow');
            assert.strictEqual(mock.p2.ID, 'flow1');
        });
    });
    describe('#deleteAllFlows', function() {
        it('deletes all flows and sends right message', function() {
            var mock = new socketMockHistory();
            var mp=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            mp.createLineChartFlow({ ID:'flow1', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            mp.createLineChartFlow({ ID:'flow2', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            mp.deleteAllFlows();
            assert.strictEqual(mock.p1[mock.p1.length-2],'deleteFlow');
            assert.deepEqual(mock.p2[mock.p2.length-2], {ID: 'flow1'});
            assert.strictEqual(mock.p1[mock.p1.length-1],'deleteFlow');
            assert.deepEqual(mock.p2[mock.p2.length-1], {ID: 'flow2'});
            assert.strictEqual(mp._flows.length,0);
        });
    });
});<commit_msg>fix test<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : mapChartSpec.js
* Module : UnitTest
* Location : /test/businessTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-29   Filippo Rampado    Initial code
* =========================================================
*/

var MapChart = require('../../../lib/businessTier/graph/mapChart.js');
var assert = require('assert');

describe('MapChart', function() {
    var socketMock=function(){
        this.p1=null;
        this.p2=null;
        this._namespace='flow1';
        this.attachObject=function(p1, p2){
            this.p1=p1;
            this.p2=p2;
        };
        this.sendMessage=function(p1, p2){
            this.p1=p1;
            this.p2=p2;
        };
    };

    var socketMockHistory=function(){
        this.p1=[];
        this.p2=[];
        this._namespace='flow1';
        this.sendMessage=function(p1, p2){
            this.p1.push(p1);
            this.p2.push(p2);
        };
        this.attachObject=function(p1, p2){
            this.p1.push(p1);
            this.p2.push(p2);
        };
    };

    it('returns null when there are no params', function() {
        assert.strictEqual((new MapChart()).hasOwnProperty('_dataMapChart'), false);
    });

    it('returns null when there is no valid page in params', function() {
        assert.strictEqual((new MapChart(2, 3)).hasOwnProperty('_dataMapChart'), false);
    });

    it('returns null when there is no valid graphsocket in params', function() {
        assert.strictEqual((new MapChart(2, {_page:2}, 3)).hasOwnProperty('_dataMapChart'), false);
    });

    it('returns null when params are not valid', function() {
        assert.strictEqual((new MapChart(2, {_page:2}, new socketMock())).hasOwnProperty('_dataMapChart'), false);
    });

    it('calls the parent constructor with the params specified', function() {
        var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
        assert.strictEqual(mp._dataMapChart._ID, 'map1');
        assert.strictEqual(mp._graphSocket._namespace, 'flow1');
    });

    describe('#createMapChartFlow', function() {
        it ('returns 232 if are passed no valid params', function(){
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            assert.strictEqual(mp.createMapChartFlow(0), 232);
        });
        it ('adds and returns a mapChartFlow', function(){
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            assert.strictEqual(mp.createMapChartFlow({ID: 'flow1'}).hasOwnProperty('_dataMapChartFlow'), true);
            assert.strictEqual(mp._flows[0].hasOwnProperty('_dataMapChartFlow'), true);
        });

        it('adds and returns a mapChartFlow', function() {
            var mock = new socketMock();
            var mapChart=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            var lc=mapChart.createMapChartFlow({
                'ID':'flow1',
                'name': 'linea 22',
                'marker':{
                    'type': 'shape',
                    'shape': 'circle',
                    'icon': 'null',
                    'text': 'null',
                    'color' : '#000'
                },
                'trace':{
                    'type':'poly',
                    'coordinates': [[45.42946, 11.94090],[45.42941, 11.94081],[45.43054, 11.93937],[45.43131, 11.93773],[45.43268, 11.93539],[45.34719, 11.81996]],
                    'strokeColor': '#DC271C',
                    'fillColor': '#3a6d99'
                },
                'trailLength': 3,
                'latitudeKey': '1',
                'longitudeKey': '2',
                'objectKey': '0'
            });
            assert.strictEqual(lc.hasOwnProperty('_dataMapChartFlow'),true);
            assert.strictEqual(mock.p1,'insertFlow');
            assert.strictEqual(mock.p2.ID, 'flow1');
            assert.strictEqual(mock.p2.name, 'linea 22');
        });
    });
    describe('#getFlowByID', function() {
        it('returns 282 if there is no valid ID', function(){
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            assert.strictEqual(mp.getFlowByID(0), 282);
        });
        it('return 282 - no ID in flows', function() {
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            mp.createMapChartFlow({ID: 'flow1'}).hasOwnProperty('_dataMapChartFlow');
            assert.strictEqual(mp.getFlowByID('fl1'),282);
        });
        it('return correct flow', function() {
            var mp=new MapChart({ID: 'map1'}, {_page:2}, new socketMock());
            mp.createMapChartFlow({ID: 'flow1'});
            mp.createMapChartFlow({ID: 'flow2'});
            assert.strictEqual(mp.getFlowByID('flow2')._dataMapChartFlow._ID,'flow2');
        });
    });
    describe('#deleteFlow', function() {
        it('return 283 - ID is not a string', function() {
            var mock=new socketMock();
            var mp=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            mp.createMapChartFlow({ ID:'flow1', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            console.log('mp '+JSON.stringify(mp));
            console.log('mpmpmpmp '+JSON.stringify(mp.deleteFlow(34)));
            assert.strictEqual(mp.deleteFlow(34),283);
        });
        it('return 283 - no ID in flows', function() {
            var mock=new socketMock();
            var mp=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            mp.createMapChartFlow({ ID:'flow1', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            assert.strictEqual(mp.deleteFlow('flow123'),283);
        });
        it('return true - deleted flow', function() {
            var mock = new socketMock();
            var mp=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            mp.createMapChartFlow({ ID:'flow1', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            assert.strictEqual(mp.deleteFlow('flow1'),true);
            assert.strictEqual(mock.p1,'deleteFlow');
            assert.strictEqual(mock.p2.ID, 'flow1');
        });
    });
    describe('#deleteAllFlows', function() {
        it('deletes all flows and sends right message', function() {
            var mock = new socketMockHistory();
            var mp=new MapChart({ID: 'dada'}, {_page: 'dssada'}, mock);
            mp.createMapChartFlow({ ID:'flow1', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            mp.createMapChartFlow({ ID:'flow2', name: 'linea 22', 'latitudeKey': '1', 'longitudeKey': '2', 'objectKey': '0'});
            mp.deleteAllFlows();
            assert.strictEqual(mock.p1[mock.p1.length-2],'deleteFlow');
            assert.deepEqual(mock.p2[mock.p2.length-2], {ID: 'flow1'});
            assert.strictEqual(mock.p1[mock.p1.length-1],'deleteFlow');
            assert.deepEqual(mock.p2[mock.p2.length-1], {ID: 'flow2'});
            assert.strictEqual(mp._flows.length,0);
        });
    });
});<|endoftext|>


<commit_before>exports.commands = {

        namecolors: function(target, room, user) {
                if (!this.canBroadcast()) return;
                this.sendReplyBox('Name Colors:
' +
                                  '
 Change your nickname color
 Use /name[color] - Change your nickname color' +
                                  '
 Available Colors: Rainbow, Blue, White, Black, Orange, Green, Red, Pink and Yellow
' +
                                  'By: Darkero'
                                                );
        },

        rainbow: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#ED1C24', '#F26522', '#F7941D', '#F0D200', '#8DC73F', '#39B54A', '#00A651', '#00A99D', '#00AEEF', '#0072BC', '#0054A6', '#2E3192', '#662D91', '#92278F', '#EC008C', '#ED145B'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        nameblue: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#0489B1'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        namewhite: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FFFFFF'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        nameblack: function (target, room, user){
		if (!this.can('hotpatch') && !user.vip && user.userid !== 'traineralain') return this.sendReply('/nameblack - Access denied.');
                var colors = ['#000000'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }

        },

        nameorange: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FF8000'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        namegreen: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#3ADF00'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        namered: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FF0000'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        namepink: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FF00FF'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');

        },

        namepurple: function (target, room, user){
		if (user.userid !== 'natm') return this.sendReply('/namepurple - Access denied.');
                var colors = ['#8000ff', '#39005e', '#c07bed'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }

        },

        nameyellow: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FFFF00'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

}
<commit_msg>Add in the custom color change commands.<commit_after>exports.commands = {

        namecolors: function(target, room, user) {
                if (!this.canBroadcast()) return;
                this.sendReplyBox('Name Colors:
' +
                                  '
 Change your nickname color
 Use /name[color] - Change your nickname color' +
                                  '
 Available Colors: Rainbow, Blue, White, Black, Orange, Green, Red, Pink and Yellow
' +
                                  'By: Darkero'
                                                );
        },

        rainbow: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#ED1C24', '#F26522', '#F7941D', '#F0D200', '#8DC73F', '#39B54A', '#00A651', '#00A99D', '#00AEEF', '#0072BC', '#0054A6', '#2E3192', '#662D91', '#92278F', '#EC008C', '#ED145B'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        nameblue: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#0489B1'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        namewhite: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FFFFFF'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        nameblack: function (target, room, user){
		if (!this.can('hotpatch') && !user.vip && user.userid !== 'traineralain') return this.sendReply('/nameblack - Access denied.');
                var colors = ['#000000'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }

        },

        nameorange: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FF8000'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        namegreen: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#3ADF00'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        namered: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FF0000'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

        namepink: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FF00FF'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');

        },

        namepurple: function (target, room, user){
		if (user.userid !== 'natm') return this.sendReply('/namepurple - Access denied.');
                var colors = ['#8000ff', '#39005e', '#c07bed'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }

        },

        auracolor: function (target, room, user){
		if (user.userid !== 'aurastormlucario') return this.errorReply('/auracolor - Access denied.');
                var colors = ['#007fff', '#1560bd'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
        },

        alaincolor: function (target, room, user){
		if (user.userid !== 'traineralain') return this.errorReply('/alaincolor - Access denied.');
                var colors = ['#00ffff'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }

        },

        nameyellow: function (target, room, user){
          if (user.can('hotpatch', null, room)) {
                var colors = ['#FFFF00'];
                if(!target) return this.sendReply('/rainbow message');
                        userColor = '',
                        currentDate = new Date(),
                        randomNumber = '';
                        for(var x = 0; x < user.name.length; x++){
                                randomNumber = Math.floor(Math.random() * colors.length);
                                if(user.name.substring(x, x + 1) !== undefined){
                                        userColor += '' + user.name.substring(x, x + 1) + '';
                                } else {
                                        userColor += ':';
                                }
                        }
                        if(target.indexOf('/me') > -1) {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + Tools.escapeHTML(target.substring(3, target.length)) + '');
                        } else {
                                room.add('|raw|' + user.group + '' + userColor + ': ' + target);
                        }
          }
          else return this.errorReply('You must be a Shadowfire DEV/Admin to use this command.');
        },

}
<|endoftext|>


<commit_before>steal('steal/generate',
	'steal/get',
	'steal/build',
	'steal/coffee',
	'steal/less',
	'steal/clean',
	'steal/parse',
	'steal/html/crawl')
.then('documentjs')
.then('./pages/init.js')
.then('jquery',
'jquery/controller',
	'jquery/controller/subscribe',
	'jquery/controller/history',
'jquery/view',
	'jquery/view/ejs',
	'jquery/view/jaml',
	'jquery/view/micro',
	'jquery/view/tmpl',
'jquery/model',
	'jquery/model/list',
		'jquery/model/list/cookie',
		'jquery/model/list/local',
	'jquery/model/backup',
	'jquery/model/validations',

'jquery/event/default',
'jquery/event/destroyed',
'jquery/event/drag',
	'jquery/event/drag/limit',
	'jquery/event/drag/scroll',
	'jquery/event/drag/step',
'jquery/event/drop',
'jquery/event/hover',
'jquery/event/key',
'jquery/event/pause',
'jquery/event/resize',
'jquery/event/swipe',
'jquery/event/selection',

'jquery/dom/compare',
'jquery/dom/closest',
'jquery/dom/within',
'jquery/dom/form_params',
'jquery/dom/dimensions',
'jquery/dom/fixture',
'jquery/dom/cookie',
'jquery/dom/selection'
)
// funcunit should always be included last because it puts jquery in noconflict mode
.then('funcunit')
.then(
"funcunit/pages/setup.js",
"funcunit/pages/writing.js",
"funcunit/pages/selenium.js",
"funcunit/pages/mastering.js",
"funcunit/pages/standalone.js",
"funcunit/pages/example.js"
)

<commit_msg>Added jquery/controller/view to docs<commit_after>steal('steal/generate',
	'steal/get',
	'steal/build',
	'steal/coffee',
	'steal/less',
	'steal/clean',
	'steal/parse',
	'steal/html/crawl'
)
.then('documentjs')
.then('./pages/init.js')
.then('jquery',
'jquery/controller',
'jquery/controller/view',
	'jquery/controller/subscribe',
	'jquery/controller/history',
'jquery/view',
	'jquery/view/ejs',
	'jquery/view/jaml',
	'jquery/view/micro',
	'jquery/view/tmpl',
'jquery/model',
	'jquery/model/list',
		'jquery/model/list/cookie',
		'jquery/model/list/local',
	'jquery/model/backup',
	'jquery/model/validations',

'jquery/event/default',
'jquery/event/destroyed',
'jquery/event/drag',
	'jquery/event/drag/limit',
	'jquery/event/drag/scroll',
	'jquery/event/drag/step',
'jquery/event/drop',
'jquery/event/hover',
'jquery/event/key',
'jquery/event/pause',
'jquery/event/resize',
'jquery/event/swipe',
'jquery/event/selection',

'jquery/dom/compare',
'jquery/dom/closest',
'jquery/dom/within',
'jquery/dom/form_params',
'jquery/dom/dimensions',
'jquery/dom/fixture',
'jquery/dom/cookie',
'jquery/dom/selection'
)
// funcunit should always be included last because it puts jquery in noconflict mode
.then('funcunit')
.then(
"funcunit/pages/setup.js",
"funcunit/pages/writing.js",
"funcunit/pages/selenium.js",
"funcunit/pages/mastering.js",
"funcunit/pages/standalone.js",
"funcunit/pages/example.js"
)

<|endoftext|>


<commit_before>import gql from 'graphql-tag';
import { c, t } from 'ttag';
import { useQuery } from '@apollo/react-hooks';
import { makeStyles } from '@material-ui/core/styles';
import { useRouter } from 'next/router';

import { ListPageCards, ArticleCard } from 'components/ListPageDisplays';
import { LoadMore } from 'components/ListPageControls';

import leftImage from './images/article-left.png';
import rightImage from './images/article-right.png';

const LIST_ARTICLES = gql`
  query GetArticlesList(
    $filter: ListArticleFilter
    $orderBy: [ListArticleOrderBy]
    $after: String
  ) {
    ListArticles(filter: $filter, orderBy: $orderBy, after: $after, first: 10) {
      edges {
        node {
          id
          ...ArticleCard
        }
        ...LoadMoreEdge
      }
    }
  }
  ${ArticleCard.fragments.ArticleCard}
  ${LoadMore.fragments.LoadMoreEdge}
`;

const useStyles = makeStyles(theme => ({
  root: {
    background: theme.palette.primary[200],
    padding: '60px 30px',
    overflow: 'hidden',

    [theme.breakpoints.down('sm')]: {
      padding: 0,
      background: theme.palette.background.default,
    },

    '& > h3': {
      width: '80%',
      maxWidth: 1200,
      fontSize: 48,
      fontWeight: 'bold',
      lineHeight: 1.45,
      margin: '0 auto 26px',

      [theme.breakpoints.only('md')]: {
        width: '100%',
        paddingLeft: 40,
      },

      [theme.breakpoints.down('sm')]: {
        fontSize: 24,
        fontWeight: 'normal',
        textAlign: 'center',
        width: 'unset',
        margin: '16px auto 4px',
      },
    },
  },
  articleContainer: {
    position: 'relative',
    width: '80%',
    maxWidth: 1200,
    height: 600,
    background: theme.palette.background.default,
    borderRadius: 8,
    padding: '15px 0 15px 15px',
    margin: '0 auto',

    [theme.breakpoints.down('md')]: {
      width: '100%',
    },

    [theme.breakpoints.down('sm')]: {
      width: '100%',
      orderRadius: 0,
      padding: 12,
    },
  },
  scrollbarWrapper: {
    width: '100%',
    height: '100%',
    overflow: 'auto',
  },
  leftImage: {
    position: 'absolute',
    left: -180,
    bottom: -100,

    [theme.breakpoints.down('md')]: {
      width: 295,
      left: -55,
      bottom: -75,
    },

    [theme.breakpoints.down('sm')]: {
      display: 'none',
    },
  },
  rightImage: {
    position: 'absolute',
    right: -160,
    top: -120,

    [theme.breakpoints.down('md')]: {
      width: 255,
      right: -30,
      top: -140,
    },

    [theme.breakpoints.down('sm')]: {
      display: 'none',
    },
  },
}));

const SectionArticles = () => {
  const classes = useStyles();
  const router = useRouter();

  const listQueryVars = {
    filter: {
      replyRequestCount: { GTE: 2 },
      hasArticleReplyWithMorePositiveFeedback: false,
    },
    orderBy: [{ lastRequestedAt: 'DESC' }],
  };

  const {
    loading,
    data: listArticlesData,
    error: listArticlesError,
  } = useQuery(LIST_ARTICLES, {
    variables: listQueryVars,
    notifyOnNetworkStatusChange: true, // Make loading true on `fetchMore`
  });

  // List data
  const articleEdges = listArticlesData?.ListArticles?.edges || [];

  return (

{c('landing page').t`Messages reported in Cofacts`}

          {loading && !articleEdges.length ? (
            t`Loading...`
          ) : listArticlesError ? (
            listArticlesError.toString()
          ) : (
            <>
              <ListPageCards>
                {articleEdges.map(({ node: article }) => (
                  <ArticleCard key={article.id} article={article} />
                ))}
              </ListPageCards>
              <LoadMore
                edges={articleEdges}
                loading={loading}
                onMoreRequest={() => {
                  router.push({
                    pathname: '/hoax-for-you',
                  });
                }}
              />
            </>
          )}

  );
};

export default SectionArticles;
<commit_msg>[LandingPage] hide scroll bar on windows<commit_after>import gql from 'graphql-tag';
import { c, t } from 'ttag';
import { useQuery } from '@apollo/react-hooks';
import { makeStyles } from '@material-ui/core/styles';
import { useRouter } from 'next/router';

import { ListPageCards, ArticleCard } from 'components/ListPageDisplays';
import { LoadMore } from 'components/ListPageControls';

import leftImage from './images/article-left.png';
import rightImage from './images/article-right.png';

const LIST_ARTICLES = gql`
  query GetArticlesList(
    $filter: ListArticleFilter
    $orderBy: [ListArticleOrderBy]
    $after: String
  ) {
    ListArticles(filter: $filter, orderBy: $orderBy, after: $after, first: 10) {
      edges {
        node {
          id
          ...ArticleCard
        }
        ...LoadMoreEdge
      }
    }
  }
  ${ArticleCard.fragments.ArticleCard}
  ${LoadMore.fragments.LoadMoreEdge}
`;

const useStyles = makeStyles(theme => ({
  root: {
    background: theme.palette.primary[200],
    padding: '60px 30px',
    overflow: 'hidden',

    [theme.breakpoints.down('sm')]: {
      padding: 0,
      background: theme.palette.background.default,
    },

    '& > h3': {
      width: '80%',
      maxWidth: 1200,
      fontSize: 48,
      fontWeight: 'bold',
      lineHeight: 1.45,
      margin: '0 auto 26px',

      [theme.breakpoints.only('md')]: {
        width: '100%',
        paddingLeft: 40,
      },

      [theme.breakpoints.down('sm')]: {
        fontSize: 24,
        fontWeight: 'normal',
        textAlign: 'center',
        width: 'unset',
        margin: '16px auto 4px',
      },
    },
  },
  articleContainer: {
    position: 'relative',
    width: '80%',
    maxWidth: 1200,
    height: 600,
    background: theme.palette.background.default,
    borderRadius: 8,
    padding: '0 15px',
    margin: '0 auto',

    [theme.breakpoints.down('md')]: {
      width: '100%',
    },

    [theme.breakpoints.down('sm')]: {
      width: '100%',
      orderRadius: 0,
      padding: 12,
    },
  },
  scrollbarWrapper: {
    width: '100%',
    height: '100%',
    padding: '15px 0',
    overflow: 'auto',
    msOverflowStyle: 'none' /* hide scrollbar on IE and Edge */,
    scrollbarWidth: 'none' /* hide scrollbar on Firefox */,

    '&::-webkit-scrollbar': {
      display: 'none',
    },
  },
  leftImage: {
    position: 'absolute',
    left: -180,
    bottom: -100,

    [theme.breakpoints.down('md')]: {
      width: 295,
      left: -55,
      bottom: -75,
    },

    [theme.breakpoints.down('sm')]: {
      display: 'none',
    },
  },
  rightImage: {
    position: 'absolute',
    right: -160,
    top: -120,

    [theme.breakpoints.down('md')]: {
      width: 255,
      right: -30,
      top: -140,
    },

    [theme.breakpoints.down('sm')]: {
      display: 'none',
    },
  },
}));

const SectionArticles = () => {
  const classes = useStyles();
  const router = useRouter();

  const listQueryVars = {
    filter: {
      replyRequestCount: { GTE: 2 },
      hasArticleReplyWithMorePositiveFeedback: false,
    },
    orderBy: [{ lastRequestedAt: 'DESC' }],
  };

  const {
    loading,
    data: listArticlesData,
    error: listArticlesError,
  } = useQuery(LIST_ARTICLES, {
    variables: listQueryVars,
    notifyOnNetworkStatusChange: true, // Make loading true on `fetchMore`
  });

  // List data
  const articleEdges = listArticlesData?.ListArticles?.edges || [];

  return (

{c('landing page').t`Messages reported in Cofacts`}

          {loading && !articleEdges.length ? (
            t`Loading...`
          ) : listArticlesError ? (
            listArticlesError.toString()
          ) : (
            <>
              <ListPageCards>
                {articleEdges.map(({ node: article }) => (
                  <ArticleCard key={article.id} article={article} />
                ))}
              </ListPageCards>
              <LoadMore
                edges={articleEdges}
                loading={loading}
                onMoreRequest={() => {
                  router.push({
                    pathname: '/hoax-for-you',
                  });
                }}
              />
            </>
          )}

  );
};

export default SectionArticles;
<|endoftext|>