<commit_before>// ==UserScript==
// @name         O Antagonista - Speed Reading
// @namespace    http://oantagonista.com/speedread
// @version      0.9.0
// @description  Fast reading of the micro blog!
// @author       ViZeke
// @match        https://www.oantagonista.com/
// @match        http://www.oantagonista.com/
// @match        https://www.oantagonista.com/pagina/*
// @match        http://www.oantagonista.com/pagina/*
// @grant        none
// @require      https://code.jquery.com/jquery-2.1.4.min.js
// ==/UserScript==

(function($) {
    'use strict';

    /**
     * http://www.openjs.com/scripts/events/keyboard_shortcuts/
     * Version : 2.01.B
     * By Binny V A
     * License : BSD
     */
    let shortcut = {
        'all_shortcuts': {}, //All the shortcuts are stored in this array
        'add': function(shortcut_combination, callback, opt) {
            //Provide a set of default options
            let default_options = {
                'type': 'keydown',
                'propagate': false,
                'disable_in_input': false,
                'target': document,
                'keycode': false
            };
            if (!opt) opt = default_options;
            else {
                for (var dfo in default_options) {
                    if (typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
                }
            }

            var ele = opt.target;
            if (typeof opt.target == 'string') ele = document.getElementById(opt.target);
            var ths = this;
            shortcut_combination = shortcut_combination.toLowerCase();

            //The function to be called at keypress
            let func = function(e) {
                let code;
                e = e || window.event;

                if (opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
                    var element;
                    if (e.target) element = e.target;
                    else if (e.srcElement) element = e.srcElement;
                    if (element.nodeType == 3) element = element.parentNode;

                    if (element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
                }

                //Find Which key is pressed
                if (e.keyCode) code = e.keyCode;
                else if (e.which) code = e.which;
                var character = String.fromCharCode(code).toLowerCase();

                if (code == 188) character = ","; //If the user presses , when the type is onkeydown
                if (code == 190) character = "."; //If the user presses , when the type is onkeydown

                var keys = shortcut_combination.split("+");
                //Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
                var kp = 0;

                //Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
                var shift_nums = {
                    "`": "~",
                    "1": "!",
                    "2": "@",
                    "3": "#",
                    "4": "$",
                    "5": "%",
                    "6": "^",
                    "7": "&",
                    "8": "*",
                    "9": "(",
                    "0": ")",
                    "-": "_",
                    "=": "+",
                    ";": ":",
                    "'": "\"",
                    ",": "<",
                    ".": ">",
                    "/": "?",
                    "\\": "|"
                };
                //Special Keys - and their codes
                var special_keys = {
                    'esc': 27,
                    'escape': 27,
                    'tab': 9,
                    'space': 32,
                    'return': 13,
                    'enter': 13,
                    'backspace': 8,

                    'scrolllock': 145,
                    'scroll_lock': 145,
                    'scroll': 145,
                    'capslock': 20,
                    'caps_lock': 20,
                    'caps': 20,
                    'numlock': 144,
                    'num_lock': 144,
                    'num': 144,

                    'pause': 19,
                    'break': 19,

                    'insert': 45,
                    'home': 36,
                    'delete': 46,
                    'end': 35,

                    'pageup': 33,
                    'page_up': 33,
                    'pu': 33,

                    'pagedown': 34,
                    'page_down': 34,
                    'pd': 34,

                    'left': 37,
                    'up': 38,
                    'right': 39,
                    'down': 40,

                    'f1': 112,
                    'f2': 113,
                    'f3': 114,
                    'f4': 115,
                    'f5': 116,
                    'f6': 117,
                    'f7': 118,
                    'f8': 119,
                    'f9': 120,
                    'f10': 121,
                    'f11': 122,
                    'f12': 123
                };

                var modifiers = {
                    shift: {
                        wanted: false,
                        pressed: false
                    },
                    ctrl: {
                        wanted: false,
                        pressed: false
                    },
                    alt: {
                        wanted: false,
                        pressed: false
                    },
                    meta: {
                        wanted: false,
                        pressed: false
                    } //Meta is Mac specific
                };

                if (e.ctrlKey) modifiers.ctrl.pressed = true;
                if (e.shiftKey) modifiers.shift.pressed = true;
                if (e.altKey) modifiers.alt.pressed = true;
                if (e.metaKey) modifiers.meta.pressed = true;

                for (let i = 0; i < keys.length; i++) {
                    let k = keys[i];
                    //Modifiers
                    if (k == 'ctrl' || k == 'control') {
                        kp++;
                        modifiers.ctrl.wanted = true;

                    } else if (k == 'shift') {
                        kp++;
                        modifiers.shift.wanted = true;

                    } else if (k == 'alt') {
                        kp++;
                        modifiers.alt.wanted = true;
                    } else if (k == 'meta') {
                        kp++;
                        modifiers.meta.wanted = true;
                    } else if (k.length > 1) { //If it is a special key
                        if (special_keys[k] == code) kp++;

                    } else if (opt['keycode']) {
                        if (opt['keycode'] == code) kp++;

                    } else { //The special keys did not match
                        if (character == k) kp++;
                        else {
                            if (shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
                                character = shift_nums[character];
                                if (character == k) kp++;
                            }
                        }
                    }
                }

                if (kp == keys.length &&
                    modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
                    modifiers.shift.pressed == modifiers.shift.wanted &&
                    modifiers.alt.pressed == modifiers.alt.wanted &&
                    modifiers.meta.pressed == modifiers.meta.wanted) {
                    callback(e);

                    if (!opt['propagate']) { //Stop the event
                        //e.cancelBubble is supported by IE - this will kill the bubbling process.
                        e.cancelBubble = true;
                        e.returnValue = false;

                        //e.stopPropagation works in Firefox.
                        if (e.stopPropagation) {
                            e.stopPropagation();
                            e.preventDefault();
                        }
                        return false;
                    }
                }
            };
            this.all_shortcuts[shortcut_combination] = {
                'callback': func,
                'target': ele,
                'event': opt['type']
            };
            //Attach the function with the event
            if (ele.addEventListener) ele.addEventListener(opt['type'], func, false);
            else if (ele.attachEvent) ele.attachEvent('on' + opt['type'], func);
            else ele['on' + opt['type']] = func;
        },

        //Remove the shortcut - just specify the shortcut and I will remove the binding
        'remove': function(shortcut_combination) {
            shortcut_combination = shortcut_combination.toLowerCase();
            var binding = this.all_shortcuts[shortcut_combination];
            delete(this.all_shortcuts[shortcut_combination]);
            if (!binding) return;
            var type = binding.event;
            var ele = binding.target;
            var callback = binding.callback;

            if (ele.detachEvent) ele.detachEvent('on' + type, callback);
            else if (ele.removeEventListener) ele.removeEventListener(type, callback, false);
            else ele['on' + type] = false;
        }
    };

    let addGlobalStyle = (css) => {
        var head, style;
        head = document.getElementsByTagName('head')[0];
        if (!head) { return; }
        style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = css;
        head.appendChild(style);
    };

    function procArticles($articles){
        $articles.each( (i, itemPost) => {
            let url = $(itemPost).first().find('.article_link').first().attr('href');

            if(document.location.href.indexOf('https') === -1){
                url = url.replace('https://', 'http://');
            }

            $.get(url).success( response => {

                let $content = $(response).find('article.post .entry-content > p');

                console.log($content);

                $(itemPost).attr('processed', 1);
                $(itemPost).find('p').remove();
                $(itemPost).find('.readmore').parent().remove();
                $(itemPost).find('iframe').remove();
                $(itemPost).find('.article_link').append($content);
            });
        });
    }

    let cleanAds = () => {
        $('div.banner').remove();
        $('aside').remove();
        $('ins').remove();
        $('div.ob-widget').remove();
        $('#div-gpt-leaderboard').remove();
        $('.banners_content_home').remove();
        $('article.post.sponsorship').remove();
    };

    let procArticle = true;
    let procClean = true;

    $(document).scroll( () => {
        if ( procArticle ){
            setTimeout( () => {
                procArticles($('article.post[processed!=1]'));
                procArticle = true;
            }, 1000);
        }
        if ( procClean ){
            setTimeout( () => {
                cleanAds();
                procClean = true;
            }, 2000);
        }
        procArticle = false;
        procClean = false;
    });

    function goToNextPost(){
        console.log('j');
        let headerHeight = 109;
        let scrollTop = $(document).scrollTop() + headerHeight;

        let $articles = $("article.post");
        for(let i = 0; i < $articles.length; i++) {
            let $item = $($articles[i]);
            let itemTop = parseInt($item.position().top);
            if( scrollTop < itemTop - 1 ){
                $(document).scrollTop( itemTop - headerHeight );
                break;
            }
        }
    }

    //Init
    //Configurando Atalhos
    shortcut.add( "j", function () {
        goToNextPost();
        return false;
    });

    addGlobalStyle('#boxpost article.post { width: auto !important; }');
    addGlobalStyle('article.post.first-post { margin-top: 25px; }');
    addGlobalStyle('#player-ao-vivo.playerfixo { margin: 0 780px; width: auto !important; min-height: 300px; min-width: 31%; }');
    addGlobalStyle('.page .container > div { width: 100%; }');

    cleanAds();
    procArticles($('article.post[processed!=1]'));
})(jQuery);

//Init on global context
$(document).ready( () => {
    //specific site function in case of overlay adds
    if (dclk_hide_overlay) {
        dclk_hide_overlay();
    }
});<commit_msg>version bump<commit_after>// ==UserScript==
// @name         O Antagonista - Speed Reading
// @namespace    http://oantagonista.com/speedread
// @version      0.9.1
// @description  Fast reading of the micro blog!
// @author       ViZeke
// @match        https://www.oantagonista.com/
// @match        http://www.oantagonista.com/
// @match        https://www.oantagonista.com/pagina/*
// @match        http://www.oantagonista.com/pagina/*
// @grant        none
// @require      https://code.jquery.com/jquery-2.1.4.min.js
// ==/UserScript==

(function($) {
    'use strict';

    /**
     * http://www.openjs.com/scripts/events/keyboard_shortcuts/
     * Version : 2.01.B
     * By Binny V A
     * License : BSD
     */
    let shortcut = {
        'all_shortcuts': {}, //All the shortcuts are stored in this array
        'add': function(shortcut_combination, callback, opt) {
            //Provide a set of default options
            let default_options = {
                'type': 'keydown',
                'propagate': false,
                'disable_in_input': false,
                'target': document,
                'keycode': false
            };
            if (!opt) opt = default_options;
            else {
                for (var dfo in default_options) {
                    if (typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
                }
            }

            var ele = opt.target;
            if (typeof opt.target == 'string') ele = document.getElementById(opt.target);
            var ths = this;
            shortcut_combination = shortcut_combination.toLowerCase();

            //The function to be called at keypress
            let func = function(e) {
                let code;
                e = e || window.event;

                if (opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
                    var element;
                    if (e.target) element = e.target;
                    else if (e.srcElement) element = e.srcElement;
                    if (element.nodeType == 3) element = element.parentNode;

                    if (element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
                }

                //Find Which key is pressed
                if (e.keyCode) code = e.keyCode;
                else if (e.which) code = e.which;
                var character = String.fromCharCode(code).toLowerCase();

                if (code == 188) character = ","; //If the user presses , when the type is onkeydown
                if (code == 190) character = "."; //If the user presses , when the type is onkeydown

                var keys = shortcut_combination.split("+");
                //Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
                var kp = 0;

                //Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
                var shift_nums = {
                    "`": "~",
                    "1": "!",
                    "2": "@",
                    "3": "#",
                    "4": "$",
                    "5": "%",
                    "6": "^",
                    "7": "&",
                    "8": "*",
                    "9": "(",
                    "0": ")",
                    "-": "_",
                    "=": "+",
                    ";": ":",
                    "'": "\"",
                    ",": "<",
                    ".": ">",
                    "/": "?",
                    "\\": "|"
                };
                //Special Keys - and their codes
                var special_keys = {
                    'esc': 27,
                    'escape': 27,
                    'tab': 9,
                    'space': 32,
                    'return': 13,
                    'enter': 13,
                    'backspace': 8,

                    'scrolllock': 145,
                    'scroll_lock': 145,
                    'scroll': 145,
                    'capslock': 20,
                    'caps_lock': 20,
                    'caps': 20,
                    'numlock': 144,
                    'num_lock': 144,
                    'num': 144,

                    'pause': 19,
                    'break': 19,

                    'insert': 45,
                    'home': 36,
                    'delete': 46,
                    'end': 35,

                    'pageup': 33,
                    'page_up': 33,
                    'pu': 33,

                    'pagedown': 34,
                    'page_down': 34,
                    'pd': 34,

                    'left': 37,
                    'up': 38,
                    'right': 39,
                    'down': 40,

                    'f1': 112,
                    'f2': 113,
                    'f3': 114,
                    'f4': 115,
                    'f5': 116,
                    'f6': 117,
                    'f7': 118,
                    'f8': 119,
                    'f9': 120,
                    'f10': 121,
                    'f11': 122,
                    'f12': 123
                };

                var modifiers = {
                    shift: {
                        wanted: false,
                        pressed: false
                    },
                    ctrl: {
                        wanted: false,
                        pressed: false
                    },
                    alt: {
                        wanted: false,
                        pressed: false
                    },
                    meta: {
                        wanted: false,
                        pressed: false
                    } //Meta is Mac specific
                };

                if (e.ctrlKey) modifiers.ctrl.pressed = true;
                if (e.shiftKey) modifiers.shift.pressed = true;
                if (e.altKey) modifiers.alt.pressed = true;
                if (e.metaKey) modifiers.meta.pressed = true;

                for (let i = 0; i < keys.length; i++) {
                    let k = keys[i];
                    //Modifiers
                    if (k == 'ctrl' || k == 'control') {
                        kp++;
                        modifiers.ctrl.wanted = true;

                    } else if (k == 'shift') {
                        kp++;
                        modifiers.shift.wanted = true;

                    } else if (k == 'alt') {
                        kp++;
                        modifiers.alt.wanted = true;
                    } else if (k == 'meta') {
                        kp++;
                        modifiers.meta.wanted = true;
                    } else if (k.length > 1) { //If it is a special key
                        if (special_keys[k] == code) kp++;

                    } else if (opt['keycode']) {
                        if (opt['keycode'] == code) kp++;

                    } else { //The special keys did not match
                        if (character == k) kp++;
                        else {
                            if (shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
                                character = shift_nums[character];
                                if (character == k) kp++;
                            }
                        }
                    }
                }

                if (kp == keys.length &&
                    modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
                    modifiers.shift.pressed == modifiers.shift.wanted &&
                    modifiers.alt.pressed == modifiers.alt.wanted &&
                    modifiers.meta.pressed == modifiers.meta.wanted) {
                    callback(e);

                    if (!opt['propagate']) { //Stop the event
                        //e.cancelBubble is supported by IE - this will kill the bubbling process.
                        e.cancelBubble = true;
                        e.returnValue = false;

                        //e.stopPropagation works in Firefox.
                        if (e.stopPropagation) {
                            e.stopPropagation();
                            e.preventDefault();
                        }
                        return false;
                    }
                }
            };
            this.all_shortcuts[shortcut_combination] = {
                'callback': func,
                'target': ele,
                'event': opt['type']
            };
            //Attach the function with the event
            if (ele.addEventListener) ele.addEventListener(opt['type'], func, false);
            else if (ele.attachEvent) ele.attachEvent('on' + opt['type'], func);
            else ele['on' + opt['type']] = func;
        },

        //Remove the shortcut - just specify the shortcut and I will remove the binding
        'remove': function(shortcut_combination) {
            shortcut_combination = shortcut_combination.toLowerCase();
            var binding = this.all_shortcuts[shortcut_combination];
            delete(this.all_shortcuts[shortcut_combination]);
            if (!binding) return;
            var type = binding.event;
            var ele = binding.target;
            var callback = binding.callback;

            if (ele.detachEvent) ele.detachEvent('on' + type, callback);
            else if (ele.removeEventListener) ele.removeEventListener(type, callback, false);
            else ele['on' + type] = false;
        }
    };

    let addGlobalStyle = (css) => {
        var head, style;
        head = document.getElementsByTagName('head')[0];
        if (!head) { return; }
        style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = css;
        head.appendChild(style);
    };

    function procArticles($articles){
        $articles.each( (i, itemPost) => {
            let url = $(itemPost).first().find('.article_link').first().attr('href');

            if(document.location.href.indexOf('https') === -1){
                url = url.replace('https://', 'http://');
            }

            $.get(url).success( response => {

                let $content = $(response).find('article.post .entry-content > p');

                console.log($content);

                $(itemPost).attr('processed', 1);
                $(itemPost).find('p').remove();
                $(itemPost).find('.readmore').parent().remove();
                $(itemPost).find('iframe').remove();
                $(itemPost).find('.article_link').append($content);
            });
        });
    }

    let cleanAds = () => {
        $('div.banner').remove();
        $('aside').remove();
        $('ins').remove();
        $('div.ob-widget').remove();
        $('#div-gpt-leaderboard').remove();
        $('.banners_content_home').remove();
        $('article.post.sponsorship').remove();
    };

    let procArticle = true;
    let procClean = true;

    $(document).scroll( () => {
        if ( procArticle ){
            setTimeout( () => {
                procArticles($('article.post[processed!=1]'));
                procArticle = true;
            }, 1000);
        }
        if ( procClean ){
            setTimeout( () => {
                cleanAds();
                procClean = true;
            }, 2000);
        }
        procArticle = false;
        procClean = false;
    });

    function goToNextPost(){
        console.log('j');
        let headerHeight = 109;
        let scrollTop = $(document).scrollTop() + headerHeight;

        let $articles = $("article.post");
        for(let i = 0; i < $articles.length; i++) {
            let $item = $($articles[i]);
            let itemTop = parseInt($item.position().top);
            if( scrollTop < itemTop - 1 ){
                $(document).scrollTop( itemTop - headerHeight );
                break;
            }
        }
    }

    //Init
    //Configurando Atalhos
    shortcut.add( "j", function () {
        goToNextPost();
        return false;
    });

    addGlobalStyle('#boxpost article.post { width: auto !important; }');
    addGlobalStyle('article.post.first-post { margin-top: 25px; }');
    addGlobalStyle('#player-ao-vivo.playerfixo { margin: 0 780px; width: auto !important; min-height: 300px; min-width: 31%; }');
    addGlobalStyle('.page .container > div { width: 100%; }');

    cleanAds();
    procArticles($('article.post[processed!=1]'));
})(jQuery);

//Init on global context
$(document).ready( () => {
    //specific site function in case of overlay adds
    if (dclk_hide_overlay) {
        dclk_hide_overlay();
    }
});<|endoftext|>


<commit_before>//= require ./iterable/context

var
    Iterator;

(function ($module) {
    "use strict";

    Object.defineProperties($module, {
        Iterator: {
            value: {}
        }
    });

    Object.defineProperties(Iterator, {

        new: {
            value: function (enumerable) {
                var
                    self = Iterator,
                    i = 0,
                    keys = Object.keys(enumerable),
                    count = keys.length;

                if (!(this instanceof self.new)) {
                    return new self.new(enumerable);
                }

                // instance methods
                this.first = function () {
                    return enumerable[keys[0]];
                };

                this.current = function () {
                    return enumerable[keys[i]];
                };

                this.next = function () {
                    if (i < count) {
                        i += 1;
                        return enumerable[keys[i]];
                    }
                };

                this.done = function () {
                    if (i == count - 1) {
                        return true;
                    }

                    return false;
                };

                this.index = function () {
                    return i;
                };

                return this;

            }
        }

    });

})(window);
<commit_msg>fix iterator<commit_after>//= require ./iterable/context

var
    Iterator;

(function ($module) {
    "use strict";

    Object.defineProperties($module, {
        Iterator: {
            value: {}
        }
    });

    Object.defineProperties(Iterator, {

        new: {
            value: function (enumerable) {
                var
                    self = Iterator,
                    i = 0,
                    keys = Object.keys(enumerable),
                    count = keys.length;

                if (!(this instanceof self.new)) {
                    return new self.new(enumerable);
                }

                // iteration protocols
                // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

                // instance methods
                this.next = function () {
                    if (i < count) {
                        i += 1;
                        return enumerable[keys[i]];
                    }
                };

                this.first = function () {
                    return enumerable[keys[0]];
                };

                this.current = function () {
                    return enumerable[keys[i]];
                };

                this.index = function () {
                    return i;
                };

                this.done = function () {
                    if (i >= count - 1) {
                        return true;
                    }

                    return false;
                };

                return this;

            }
        }

    });

})(window);
<|endoftext|>


<commit_before>var
    $ = jQuery;

(function ($module) {
    "use strict";

    var setButtonsAction = function () {

        var
            btnClose = $("a.jtime-ui-modal-btn-close"),
            modal = $module.modal(),
            time;

        $(document).keydown(function (e) {
            if (e.keyCode === 27) {
                // modal.minimize();
            }
        });

        btnClose.click(function (e) {
            modal.close();
        });

    };

    $module.modal = function () {
        return {
            create: function (args) {
                var
                    body = $("body"),
                    wrapperModal,
                    modalMask,
                    modal,
                    header,
                    btnClose,
                    content,
                    observer;

                if ($(".jtime-ui-wrapper-modal").length < 1) {
                    wrapperModal = $("

")
                        .addClass("jtime-ui-wrapper-modal");
                    modalMask = $("

")
                        .addClass("jtime-ui-modal-mask basicss-fixed basicss-transparent");
                    modal = $("

").addClass("jtime-ui-modal basicss-hidden");
                    header = $("

").addClass("jtime-ui-modal-header");
                    btnClose = $("")
                        .addClass("jtime-ui-modal-btn-close button");
                    content = $("

").addClass("jtime-ui-modal-content");

                    body.append(wrapperModal);

                    wrapperModal
                        .append(modalMask)
                        .append(modal);

                    modal
                        .append(header)
                        .css({
                            "max-height": $(document).height(),
                            "max-width": $(window).width()
                        });

                    header.append(btnClose);
                    modal.append(content);

                    setButtonsAction();
                } else {
                    wrapperModal = $(".jtime-ui-wrapper-modal");
                    modal = wrapperModal.find(".jtime-ui-modal");
                    modalMask = wrapperModal.find(".jtime-ui-modal-mask");

                    wrapperModal.show();
                    modal.show();
                }

                modalMask
                    .replaceToggleClass("basicss-transparent",
                        "basicss-opacity-transition");

                // callback
                if (args.load) {
                    args.load(modal);
                }

                observer = new MutationObserver(function () {
                    modal.centralizeOn($(document));
                    modal.show();
                });
                observer.observe(content.get(0), {childList: true});
            },

            minimize: function () {
                var
                    wrapperModal = $(".jtime-ui-wrapper-modal"),
                    modalMask = wrapperModal.find(".jtime-ui-modal-mask"),
                    time = 0;

                $(".jtime-ui-modal").hide();

                modalMask.replaceToggleClass("basicss-transparent", "basicss-opacity-transition");

                time = parseFloat(
                    modalMask.css("transition-duration")
                ) * 1000;
                setTimeout(function () {
                    $(".jtime-ui-wrapper-modal").hide();
                }, time);
            },

            close: function () {
                var
                    wrapperModal = $(".jtime-ui-wrapper-modal"),
                    modalMask = wrapperModal.find(".jtime-ui-modal-mask"),
                    time = 0;

                $(".jtime-ui-modal").hide();

                modalMask.replaceToggleClass("basicss-transparent", "basicss-opacity-transition");

                time = parseFloat(
                    modalMask.css("transition-duration")
                ) * 1000;
                setTimeout(function () {
                    $(".jtime-ui-wrapper-modal").remove();
                }, time);
            }
        }

    };

})(jTime.ui);

//var maximizeModal = function () {
    //jtime-ui-wrapper-modal e modal ficam hide
    //trocar transparencia de wrapperModal
//};

// minimize = ->
  // atribuir classe
  // colocar left: 0; bottom: 0 e mostrar só o header

// afterLoad = (url, execute)->
//   $(".modal").load url, ->
//     $(this).find(".jtime-ui-modal-content").load url, ->
//       execute.each
          // ...
//<commit_msg>remove variável de fora do escopo de função anônima<commit_after>(function ($module) {
    "use strict";

    var
        $ = jQuery,
        setButtonsAction = function () {

            var
                btnClose = $("a.jtime-ui-modal-btn-close"),
                modal = $module.modal(),
                time;

            $(document).keydown(function (e) {
                if (e.keyCode === 27) {
                    // modal.minimize();
                }
            });

            btnClose.click(function (e) {
                modal.close();
            });

        };

    $module.modal = function () {
        return {
            create: function (args) {
                var
                    body = $("body"),
                    wrapperModal,
                    modalMask,
                    modal,
                    header,
                    btnClose,
                    content,
                    observer;

                if ($(".jtime-ui-wrapper-modal").length < 1) {
                    wrapperModal = $("

")
                        .addClass("jtime-ui-wrapper-modal");
                    modalMask = $("

")
                        .addClass("jtime-ui-modal-mask basicss-fixed basicss-transparent");
                    modal = $("

").addClass("jtime-ui-modal basicss-hidden");
                    header = $("

").addClass("jtime-ui-modal-header");
                    btnClose = $("")
                        .addClass("jtime-ui-modal-btn-close button");
                    content = $("

").addClass("jtime-ui-modal-content");

                    body.append(wrapperModal);

                    wrapperModal
                        .append(modalMask)
                        .append(modal);

                    modal
                        .append(header)
                        .css({
                            "max-height": $(document).height(),
                            "max-width": $(window).width()
                        });

                    header.append(btnClose);
                    modal.append(content);

                    setButtonsAction();
                } else {
                    wrapperModal = $(".jtime-ui-wrapper-modal");
                    modal = wrapperModal.find(".jtime-ui-modal");
                    modalMask = wrapperModal.find(".jtime-ui-modal-mask");

                    wrapperModal.show();
                    modal.show();
                }

                modalMask
                    .replaceToggleClass("basicss-transparent",
                        "basicss-opacity-transition");

                // callback
                if (args.load) {
                    args.load(modal);
                }

                observer = new MutationObserver(function () {
                    modal.centralizeOn($(document));
                    modal.show();
                });
                observer.observe(content.get(0), {childList: true});
            },

            minimize: function () {
                var
                    wrapperModal = $(".jtime-ui-wrapper-modal"),
                    modalMask = wrapperModal.find(".jtime-ui-modal-mask"),
                    time = 0;

                $(".jtime-ui-modal").hide();

                modalMask.replaceToggleClass("basicss-transparent", "basicss-opacity-transition");

                time = parseFloat(
                    modalMask.css("transition-duration")
                ) * 1000;
                setTimeout(function () {
                    $(".jtime-ui-wrapper-modal").hide();
                }, time);
            },

            close: function () {
                var
                    wrapperModal = $(".jtime-ui-wrapper-modal"),
                    modalMask = wrapperModal.find(".jtime-ui-modal-mask"),
                    time = 0;

                $(".jtime-ui-modal").hide();

                modalMask.replaceToggleClass("basicss-transparent", "basicss-opacity-transition");

                time = parseFloat(
                    modalMask.css("transition-duration")
                ) * 1000;
                setTimeout(function () {
                    $(".jtime-ui-wrapper-modal").remove();
                }, time);
            }
        }

    };

})(jTime.ui);

//var maximizeModal = function () {
    //jtime-ui-wrapper-modal e modal ficam hide
    //trocar transparencia de wrapperModal
//};

// minimize = ->
  // atribuir classe
  // colocar left: 0; bottom: 0 e mostrar só o header

// afterLoad = (url, execute)->
//   $(".modal").load url, ->
//     $(this).find(".jtime-ui-modal-content").load url, ->
//       execute.each
          // ...
//<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'

import { Row, Col, Button, ButtonGroup } from 'react-bootstrap'

import { setQueryParam } from '../../actions/form'
import ModeButton from './mode-button'
import { getModeIcon, isAccessMode, hasBike, isTransit, hasTransit, getTransitModes } from '../../util/itinerary'
import GeneralSettingsPanel from './general-settings-panel'

class SettingsSelectorPanel extends Component {
  static propTypes = {
    icons: PropTypes.object
  }

  constructor (props) {
    super(props)
    this.state = { activePanel: 'MODES' }
  }

  // Returns whether a particular mode or TNC agency is active
  _modeIsActive (mode) {
    const {companies, queryModes} = this.props
    if (mode.mode === 'CAR_HAIL') {
      return Boolean(companies && companies.includes(mode.company.toUpperCase()))
    }

    for (const m of queryModes) {
      if (m === mode.mode) return true
    }
    return false
  }

  _setSoloMode (mode) {
    // save current access/transit modes
    if (hasTransit(this.props.mode)) this._lastTransitMode = this.props.mode
    this.props.setQueryParam({ mode })
  }

  _setWalkOnly = () => { this._setSoloMode('WALK') }

  _setBikeOnly = () => { this._setSoloMode('BICYCLE') }

  _setOwnBike = () => {
    const nonBikeModes = this.props.queryModes.filter(m => !m.startsWith('BICYCLE'))
    this.props.setQueryParam({ mode: 'BICYCLE,' + nonBikeModes.join(',') })
  }

  _setRentedBike = () => {
    const nonBikeModes = this.props.queryModes.filter(m => !m.startsWith('BICYCLE'))
    this.props.setQueryParam({ mode: 'BICYCLE_RENT,' + nonBikeModes.join(',') })
  }

  _toggleTransitMode (mode) {
    const modeStr = mode.mode || mode
    let queryModes = this.props.queryModes.slice(0) // Clone the modes array

    // do not allow the last transit mode to be deselected
    const transitModes = queryModes.filter(m => isTransit(m))
    if (transitModes.length === 1 && transitModes[0] === modeStr) return

    // If mode is currently selected, deselect it
    if (queryModes.includes(modeStr)) {
      queryModes = queryModes.filter(m => m !== modeStr)
    // Or, if mode is currently not selected, select it
    } else if (!queryModes.includes(modeStr)) {
      queryModes.push(modeStr)
    }
    this.props.setQueryParam({ mode: queryModes.join(',') })
  }

  _setAccessMode = (mode) => {
    let queryModes = this.props.queryModes.slice(0) // Clone the modes array
    const modeStr = mode.mode || mode

    // Create object to contain multiple parameter updates if needed (i.e. 'mode', 'compainies')
    const queryParamUpdate = {}

    if (this._lastTransitMode) {
      // Restore previous transit selection, if present
      queryModes = this._lastTransitMode.split(',').filter(m => !isAccessMode(m))
      this._lastTransitMode = null
    } else {
      // Otherwise, retain any currently selected transit modes
      queryModes = queryModes.filter(m => !isAccessMode(m))
    }

    // If no transit modes selected, select all
    if (!queryModes || queryModes.length === 0) queryModes = getTransitModes(this.props.config)

    // Add the access mode
    queryModes.push(modeStr)

    // Do extra stuff if mode selected was a TNC
    queryParamUpdate.companies = modeStr === 'CAR_HAIL' ? mode.company.toUpperCase() : null

    queryParamUpdate.mode = queryModes.join(',')

    this.props.setQueryParam(queryParamUpdate)
  }

  render () {
    const { config, mode, icons, queryModes } = this.props

    const modeHasTransit = hasTransit(mode)

    // TODO: make configurable
    const { transitModes, accessModes, bicycleModes } = config.modes

    return (

          {/* Take Transit button */}
          <Row className='mode-group-row'>
            <Col xs={12}>
              <ModeButton
                enabled
                active={modeHasTransit && this._modeIsActive({ mode: 'WALK' })}
                icons={icons}
                mode={'TRANSIT'}
                height={54}
                label={'Take Transit'}
                inlineLabel
                onClick={() => this._setAccessMode('WALK')}
              />
            </Col>
          </Row>

          {/* transit access mode selector */}
          <Row className='mode-group-row'>
            {accessModes.map((mode, k) => {
              return <Col xs={4} key={k}>
                <ModeButton
                  enabled
                  active={modeHasTransit && this._modeIsActive(mode)}
                  icons={icons}
                  mode={mode}
                  height={46}
                  label={mode.label}
                  showPlusTransit
                  onClick={() => this._setAccessMode(mode)}
                />
              </Col>
            })}
          </Row>

          <Row className='mode-group-row'>
            <Col xs={2} />
            <Col xs={4}>
              <ModeButton
                enabled
                active={mode === 'WALK'}
                icons={icons}
                mode={'WALK'}
                height={36}
                label={'Walk Only'}
                inlineLabel
                onClick={this._setWalkOnly}
              />
            </Col>
            <Col xs={4}>
              <ModeButton
                enabled
                active={!modeHasTransit && hasBike(mode)}
                icons={icons}
                mode={'BICYCLE'}
                height={36}
                label={'Bike Only'}
                inlineLabel
                onClick={this._setBikeOnly}
              />
            </Col>
            <Col xs={2} />
          </Row>

          {/* Transit mode selector */}
          {/*<Row className='mode-group-row'>
            <Col xs={12}>

Filter Transit Modes

            </Col>
            <Col xs={12} style={{ textAlign: 'center' }}>
              {transitModes.map((mode, k) => {
                return (

                  <ModeButton
                    enabled={modeHasTransit}
                    active={this._modeIsActive(mode)}
                    icons={icons}
                    mode={mode}
                    label={mode.label}
                    showCheck
                    height={44}
                    onClick={() => this._toggleTransitMode(mode)}
                  />

)
              })}
            </Col>
          </Row>*/}

        {/* Travel Preferences */}
        <Row>
          <Col xs={12} className='general-settings-panel'>

Travel Preferences

            {/* The transit mode selected */}
            {hasTransit(mode) && (

Use

                {transitModes.map((mode, k) => {
                  let classNames = ['select-button']
                  if (this._modeIsActive(mode)) classNames.push('active')
                  return <Button key={mode.mode}
                    className={classNames.join(' ')}
                    style={{ marginTop: 3, marginBottom: 3, marginLeft: 0, marginRight: 5 }}
                    onClick={() => this._toggleTransitMode(mode)}
                  >

                      {getModeIcon(mode, icons)}

                    {mode.label}
                  </Button>
                })}

)}

            {/* The bike trip type selector */}
            {hasBike(mode) && !hasTransit(mode) && (

Use

                {bicycleModes.map((option, k) => {
                  let action = this._setOwnBike
                  if (option.mode === 'BICYCLE_RENT') action = this._setRentedBike
                  let classNames = ['select-button']
                  if (queryModes.includes(option.mode)) classNames.push('active')
                  // TODO: Handle different bikeshare networks
                  return (
                    <Button key={k}
                      className={classNames.join(' ')}
                      onClick={action}
                    >

                        {getModeIcon(option.mode, icons)}

                      {option.label}
                    </Button>
                  )
                })}

)}

            {/* Other general settings */}
            <GeneralSettingsPanel />
          </Col>
        </Row>

    )
  }
}

// connect to redux store

const mapStateToProps = (state, ownProps) => {
  const { companies, mode, routingType } = state.otp.currentQuery
  return {
    config: state.otp.config,
    mode,
    companies,
    modeGroups: state.otp.config.modeGroups,
    queryModes: !mode || mode.length === 0 ? [] : mode.split(','),
    routingType
  }
}

const mapDispatchToProps = { setQueryParam }

export default connect(mapStateToProps, mapDispatchToProps)(SettingsSelectorPanel)
<commit_msg>fix(mode-selector): fix hanging comma when setting bike mode<commit_after>import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'

import { Row, Col, Button, ButtonGroup } from 'react-bootstrap'

import { setQueryParam } from '../../actions/form'
import ModeButton from './mode-button'
import { getModeIcon, isAccessMode, hasBike, isTransit, hasTransit, getTransitModes } from '../../util/itinerary'
import GeneralSettingsPanel from './general-settings-panel'

class SettingsSelectorPanel extends Component {
  static propTypes = {
    icons: PropTypes.object
  }

  constructor (props) {
    super(props)
    this.state = { activePanel: 'MODES' }
  }

  // Returns whether a particular mode or TNC agency is active
  _modeIsActive (mode) {
    const {companies, queryModes} = this.props
    if (mode.mode === 'CAR_HAIL') {
      return Boolean(companies && companies.includes(mode.company.toUpperCase()))
    }

    for (const m of queryModes) {
      if (m === mode.mode) return true
    }
    return false
  }

  _setSoloMode (mode) {
    // save current access/transit modes
    if (hasTransit(this.props.mode)) this._lastTransitMode = this.props.mode
    this.props.setQueryParam({ mode })
  }

  _setWalkOnly = () => { this._setSoloMode('WALK') }

  _setBikeOnly = () => { this._setSoloMode('BICYCLE') }

  _addBikeModeToQueryModes = (bikeMode) => {
    const { queryModes, setQueryParam } = this.props
    const nonBikeModes = queryModes.filter(m => !m.startsWith('BICYCLE'))
    setQueryParam({ mode: [...nonBikeModes, bikeMode].join(',') })
  }

  _setOwnBike = () => this._addBikeModeToQueryModes('BICYCLE')

  _setRentedBike = () => this._addBikeModeToQueryModes('BICYCLE_RENT')

  _toggleTransitMode (mode) {
    const modeStr = mode.mode || mode
    let queryModes = this.props.queryModes.slice(0) // Clone the modes array

    // do not allow the last transit mode to be deselected
    const transitModes = queryModes.filter(m => isTransit(m))
    if (transitModes.length === 1 && transitModes[0] === modeStr) return

    // If mode is currently selected, deselect it
    if (queryModes.includes(modeStr)) {
      queryModes = queryModes.filter(m => m !== modeStr)
    // Or, if mode is currently not selected, select it
    } else if (!queryModes.includes(modeStr)) {
      queryModes.push(modeStr)
    }
    this.props.setQueryParam({ mode: queryModes.join(',') })
  }

  _setAccessMode = (mode) => {
    let queryModes = this.props.queryModes.slice(0) // Clone the modes array
    const modeStr = mode.mode || mode

    // Create object to contain multiple parameter updates if needed (i.e. 'mode', 'compainies')
    const queryParamUpdate = {}

    if (this._lastTransitMode) {
      // Restore previous transit selection, if present
      queryModes = this._lastTransitMode.split(',').filter(m => !isAccessMode(m))
      this._lastTransitMode = null
    } else {
      // Otherwise, retain any currently selected transit modes
      queryModes = queryModes.filter(m => !isAccessMode(m))
    }

    // If no transit modes selected, select all
    if (!queryModes || queryModes.length === 0) queryModes = getTransitModes(this.props.config)

    // Add the access mode
    queryModes.push(modeStr)

    // Do extra stuff if mode selected was a TNC
    queryParamUpdate.companies = modeStr === 'CAR_HAIL' ? mode.company.toUpperCase() : null

    queryParamUpdate.mode = queryModes.join(',')

    this.props.setQueryParam(queryParamUpdate)
  }

  render () {
    const { config, mode, icons, queryModes } = this.props

    const modeHasTransit = hasTransit(mode)

    // TODO: make configurable
    const { transitModes, accessModes, bicycleModes } = config.modes

    return (

          {/* Take Transit button */}
          <Row className='mode-group-row'>
            <Col xs={12}>
              <ModeButton
                enabled
                active={modeHasTransit && this._modeIsActive({ mode: 'WALK' })}
                icons={icons}
                mode={'TRANSIT'}
                height={54}
                label={'Take Transit'}
                inlineLabel
                onClick={() => this._setAccessMode('WALK')}
              />
            </Col>
          </Row>

          {/* transit access mode selector */}
          <Row className='mode-group-row'>
            {accessModes.map((mode, k) => {
              return <Col xs={4} key={k}>
                <ModeButton
                  enabled
                  active={modeHasTransit && this._modeIsActive(mode)}
                  icons={icons}
                  mode={mode}
                  height={46}
                  label={mode.label}
                  showPlusTransit
                  onClick={() => this._setAccessMode(mode)}
                />
              </Col>
            })}
          </Row>

          <Row className='mode-group-row'>
            <Col xs={2} />
            <Col xs={4}>
              <ModeButton
                enabled
                active={mode === 'WALK'}
                icons={icons}
                mode={'WALK'}
                height={36}
                label={'Walk Only'}
                inlineLabel
                onClick={this._setWalkOnly}
              />
            </Col>
            <Col xs={4}>
              <ModeButton
                enabled
                active={!modeHasTransit && hasBike(mode)}
                icons={icons}
                mode={'BICYCLE'}
                height={36}
                label={'Bike Only'}
                inlineLabel
                onClick={this._setBikeOnly}
              />
            </Col>
            <Col xs={2} />
          </Row>

          {/* Transit mode selector */}
          {/*<Row className='mode-group-row'>
            <Col xs={12}>

Filter Transit Modes

            </Col>
            <Col xs={12} style={{ textAlign: 'center' }}>
              {transitModes.map((mode, k) => {
                return (

                  <ModeButton
                    enabled={modeHasTransit}
                    active={this._modeIsActive(mode)}
                    icons={icons}
                    mode={mode}
                    label={mode.label}
                    showCheck
                    height={44}
                    onClick={() => this._toggleTransitMode(mode)}
                  />

)
              })}
            </Col>
          </Row>*/}

        {/* Travel Preferences */}
        <Row>
          <Col xs={12} className='general-settings-panel'>

Travel Preferences

            {/* The transit mode selected */}
            {hasTransit(mode) && (

Use

                {transitModes.map((mode, k) => {
                  let classNames = ['select-button']
                  if (this._modeIsActive(mode)) classNames.push('active')
                  return <Button key={mode.mode}
                    className={classNames.join(' ')}
                    style={{ marginTop: 3, marginBottom: 3, marginLeft: 0, marginRight: 5 }}
                    onClick={() => this._toggleTransitMode(mode)}
                  >

                      {getModeIcon(mode, icons)}

                    {mode.label}
                  </Button>
                })}

)}

            {/* The bike trip type selector */}
            {hasBike(mode) && !hasTransit(mode) && (

Use

                {bicycleModes.map((option, k) => {
                  let action = this._setOwnBike
                  if (option.mode === 'BICYCLE_RENT') action = this._setRentedBike
                  let classNames = ['select-button']
                  if (queryModes.includes(option.mode)) classNames.push('active')
                  // TODO: Handle different bikeshare networks
                  return (
                    <Button key={k}
                      className={classNames.join(' ')}
                      onClick={action}
                    >

                        {getModeIcon(option.mode, icons)}

                      {option.label}
                    </Button>
                  )
                })}

)}

            {/* Other general settings */}
            <GeneralSettingsPanel />
          </Col>
        </Row>

    )
  }
}

// connect to redux store

const mapStateToProps = (state, ownProps) => {
  const { companies, mode, routingType } = state.otp.currentQuery
  return {
    config: state.otp.config,
    mode,
    companies,
    modeGroups: state.otp.config.modeGroups,
    queryModes: !mode || mode.length === 0 ? [] : mode.split(','),
    routingType
  }
}

const mapDispatchToProps = { setQueryParam }

export default connect(mapStateToProps, mapDispatchToProps)(SettingsSelectorPanel)
<|endoftext|>


<commit_before>var Storage = function () {

	var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

	var name = 'threejs-editor';
	var version = 1;

	var database;

	return {

		init: function ( callback ) {

			var request = indexedDB.open( name, version );
			request.onupgradeneeded = function ( event ) {

				var db = event.target.result;

				if ( db.objectStoreNames.contains( 'states' ) === false ) {

					db.createObjectStore( 'states' );

				}

			};
			request.onsuccess = function ( event ) {

				database = event.target.result;

				callback();

			};
			request.onerror = function ( event ) {

				console.error( 'IndexedDB', event );

			};

		},

		get: function ( callback ) {

			var transaction = database.transaction( [ 'states' ], 'readwrite' );
			var objectStore = transaction.objectStore( 'states' );
			var request = objectStore.get( 0 );
			request.onsuccess = function ( event ) {

				callback( event.target.result );

			};

		},

		set: function ( data, callback ) {

			var start = performance.now();

			var transaction = database.transaction( [ 'states' ], 'readwrite' );
			var objectStore = transaction.objectStore( 'states' );
			var request = objectStore.put( data, 0 );
			request.onsuccess = function ( event ) {

				console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved state to IndexedDB in ' + ( performance.now() - start ).toFixed( 2 ) + 'ms.' );

			};

		},

		clear: function ( callback ) {

			var transaction = database.transaction( [ 'states' ], 'readwrite' );
			var objectStore = transaction.objectStore( 'states' );
			var request = objectStore.clear();
			request.onsuccess = function ( event ) {

				callback();

			};

		}

	}

};<commit_msg>Editor: Minor tweaks to indexedDB save time logging.<commit_after>var Storage = function () {

	var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

	var name = 'threejs-editor';
	var version = 1;

	var database;

	return {

		init: function ( callback ) {

			var request = indexedDB.open( name, version );
			request.onupgradeneeded = function ( event ) {

				var db = event.target.result;

				if ( db.objectStoreNames.contains( 'states' ) === false ) {

					db.createObjectStore( 'states' );

				}

			};
			request.onsuccess = function ( event ) {

				database = event.target.result;

				callback();

			};
			request.onerror = function ( event ) {

				console.error( 'IndexedDB', event );

			};

		},

		get: function ( callback ) {

			var transaction = database.transaction( [ 'states' ], 'readwrite' );
			var objectStore = transaction.objectStore( 'states' );
			var request = objectStore.get( 0 );
			request.onsuccess = function ( event ) {

				callback( event.target.result );

			};

		},

		set: function ( data, callback ) {

			var start = performance.now();

			var transaction = database.transaction( [ 'states' ], 'readwrite' );
			var objectStore = transaction.objectStore( 'states' );
			var request = objectStore.put( data, 0 );
			request.onsuccess = function ( event ) {

				console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved state to IndexedDB. ' + ( performance.now() - start ).toFixed( 2 ) + 'ms' );

			};

		},

		clear: function ( callback ) {

			var transaction = database.transaction( [ 'states' ], 'readwrite' );
			var objectStore = transaction.objectStore( 'states' );
			var request = objectStore.clear();
			request.onsuccess = function ( event ) {

				callback();

			};

		}

	}

};<|endoftext|>


<commit_before>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

/*
    This file contains all functionality pertaining to the mini map shown in the upper right corner in the editor
*/

var MiniMap;

(function()
{
    "use strict";

    var zoom = 1,
        // Show details? Set to false to speed up editor processing in large scenarios
        detailed = true;

    MiniMap =
    {
        zoom: zoom,
        detailed: detailed,
        initialise: initialise,
        attachScrollListener: attachScrollListener,
        update: update,
        activate: activate,
        deactivate: deactivate
    };

    // Turned on for this session? (based on e.g. browser)
    var enabled = true,
    // Allowed by the context? If not, hidden completely, including controls
    active = true,
    // Turned on by the user? If not, hidden, but controls are still visible
    shown = true;

    function initialise()
    {
        // Minimap does not work yet in firefox,
        // due to css zoom not being supported,
        // updateMinimap code needs to be rewritten for css translate: scale(v)
        // but this bugs out a lot of other css properties in the cloned main DOM
        // meanwhile the minimap is disabled for mozilla
        // minimap disabled in ie, until minimap displacement bug is fixed

        if (navigator.userAgent.match(/Chrome/i) || navigator.userAgent.match(/Opera/i) ||  navigator.userAgent.match(/Edge/i))
        {
            enabled = true;

            recallShown();
            if (!shown)
            {
                $("#minimap").hide();
                $("#enableMinimap").prop("checked", false);
            }

            $("#miniwrap").css("display","block");
            $("#minimap").css("width", "300px");
            $("#minimap").css("height", "300px");
            $("#minimap").css("overflow", "hidden");

            $("#minimap").on("click", function(e)
            {
                updateScrollPosition(e);
            });
            $("#mainCell #main").on("scroll", function()
            {
                update(false);
            });

            // Zoomed in scroll event listeners for minimap are created by attachScrollListener,
            // called by createEmptyTree()!

            // Listeners for minimap checkboxes
            $("#enableMinimap").on("click", function()
            {
                if (this.checked)
                {
                    setAndStoreShown(true);
                    showAnimated($("#minimap"));
                }
                else
                {
                    hideAnimated($("#minimap"));
                    setAndStoreShown(false);
                }
            });
            $("#simpleMinimap").on("click", function()
            {
                if (this.checked)
                {
                    detailed = false;
                    $("#scaledDiv").empty();
                    update(false);
                }
                else
                {
                    detailed = true;
                    update(true);
                }
            });
        }
        else
        {
            enabled = false;
            $("#miniwrap").css("display","none");
            console.log("It appears you're using Firefox or IE, minimap display:" + $("#miniwrap").css("display") + ". We recommend running this game in Chrome or Opera.");
        }
    }

    function attachScrollListener(treeDiv)
    {
        if (!enabled) return;

        treeDiv.on('scroll', function(e)
        {
            update(false);
        });
    }

    function updateScrollPosition(e)
    {
        var minimapSelectorX = e.pageX - $("#minimap").offset().left - $("#minimapSelector").width() / 2;
        var minimapSelectorY = e.pageY - $("#minimap").offset().top - $("#minimapSelector").height() / 2;

        //Limit the minimum/maximum positions of the selector
        var maxX = $("#minimap").width() - $("#minimapSelector").width();
        var maxY = $("#minimap").height() - $("#minimapSelector").height();
        if(minimapSelectorX < 0) minimapSelectorX = 0;
        if(minimapSelectorY < 0) minimapSelectorY = 0;
        if(minimapSelectorX > maxX) minimapSelectorX = maxX;
        if(minimapSelectorY > maxY) minimapSelectorY = maxY;

        $("#minimapSelector").css("top", minimapSelectorY+"px");
        $("#minimapSelector").css("left", minimapSelectorX+"px");

        minimapSelectorX /= zoom;
        minimapSelectorY /= zoom;

        if(!Zoom.isZoomed())   //Nothing is zoomed
        {
            $("#mainCell > #main").scrollLeft(minimapSelectorX);
            $("#mainCell > #main").scrollTop(minimapSelectorY);
        }
        else
        {
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollLeft(minimapSelectorX);
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollTop(minimapSelectorY);
        }

        update(false);
    }

    //Scale the minimap according to the main div dimensions
    //and optionally refresh the background by cloning the main div
    ///refresh boolean to effect a new clone of the main div and its children
    function update(refresh)
    {
        if (!(enabled && active && shown)) return;

        var realWidth, realHeight;
        var viewportWidth, viewportHeight, viewportX, viewportY, zoomFactor;

        var main = $("#mainCell > #main");

        if (!Zoom.isZoomed())   //Nothing is zoomed
        {
            realWidth = main[0].scrollWidth;
            realHeight = main[0].scrollHeight;
            viewportX = main.scrollLeft();
            viewportY = main.scrollTop();
        }
        else
        {
            var treeDiv = $("#mainCell .treeContainer.zoom > .treeDiv");
            realWidth = treeDiv[0].scrollWidth;
            realHeight = treeDiv[0].scrollHeight + $("#mainCell .subjectDiv")[0].scrollHeight;
            viewportX = treeDiv.scrollLeft();
            viewportY = treeDiv.scrollTop() + $("#mainCell .subjectDiv")[0].scrollHeight;
        }
        viewportWidth = main.width();
        viewportHeight = main.height();

        $("#scaledDiv").css("width", realWidth+"px");
        $("#scaledDiv").css("height", realHeight+"px");
        $("#minimap").css("height", $("#sidebar").height()-25+"px");

        //Show a cloned and scaled down version of the main div in the minimap if detailedMinimap is set to true
        if (detailed && refresh)
        {
            $("#scaledDiv").empty();
            main.clone().appendTo($("#scaledDiv"));
            $("#scaledDiv #gridIndicator").remove();
            //Rename cloned div ids!
            $("#scaledDiv > #main").attr("id","miniMain");
            //Remove inappropriate subjects from minimap
            if(Zoom.isZoomed())
                $("#scaledDiv .treeContainer").not(".zoom").remove();
        }

        //Standard width/height for minimap container
        var width = 300;
        var height = 300;

        var widthFactor = width/realWidth;
        var heightFactor = height/realHeight;

        zoomFactor = widthFactor;
        //minimap gets taller than the allowed screenheight
        if (zoomFactor * realHeight > $("#sidebar").height())
        {
            zoomFactor = $("#sidebar").height()/(realHeight+realHeight*0.1);
        }

        $("#minimap").css("width", realWidth * zoomFactor + "px");
        $("#minimap").css("height", realHeight * zoomFactor + "px");

        if (detailed && refresh)
        {
            $("#scaledDiv *").css("overflow", "hidden");

            $("#scaledDiv .treeContainer.zoom").css("left", 0 + "px");
            $("#scaledDiv .treeContainer.zoom").css("top", 0 + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("height", realHeight + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("width", realWidth + "px");

            $("#scaledDiv *").off();
        }

        $("#scaledDiv").css("zoom", zoomFactor+"");
        // css zoom code needs to be rewritten for css translate: scale(v)
        // but this bugs out a lot of other css properties in the cloned main DOM:
        //$("#scaledDiv #main").css("-moz-transform:", "scale("zoomFactor+")");

        //Scale and reposition the minimap selector
        $("#minimapSelector").css({
            width: viewportWidth * zoomFactor + "px",
            height: viewportHeight * zoomFactor + "px",
            top: viewportY * zoomFactor + "px",
            left: viewportX * zoomFactor + "px"
        });

        zoom = zoomFactor;
    }

    function recallShown()
    {
        var recalledShown = localStorage.getItem('MiniMap.shown');
        if (recalledShown !== null) shown = Boolean(JSON.parse(recalledShown));
    }

    function setAndStoreShown(newShown)
    {
        shown = Boolean(newShown);
        try
        {
            localStorage.setItem('MiniMap.shown', JSON.stringify(shown));
        }
        catch (e)
        {
            // storage is an enhancement, so ignore failure
        }
    }

    function showAnimated(element)
    {
        // slide Down with animation stopper
        var autoHeight = element.css('height', 'auto').height();
        element.height(0).show().stop(true,false).animate({height: autoHeight}, 400);
    }

    function hideAnimated(element)
    {
        // slide Up with animation stopper
        element.stop(true,false).animate({height: 0}, 400,
            'swing', function(){ element.hide(); });
    }

    function activate()
    {
        if (!enabled) return;

        if (!active) showAnimated($("#miniwrap"));
        active = true;
        update(true);
    }

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

        if (active) hideAnimated($("#miniwrap"));
        active = false;
    }
})();
<commit_msg>Switched MiniMap from zoom to scale transform, enabled it everywhere<commit_after>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

/*
    This file contains all functionality pertaining to the mini map shown in the upper right corner in the editor
*/

var MiniMap;

(function()
{
    "use strict";

    var zoom = 1,
        // Show details? Set to false to speed up editor processing in large scenarios
        detailed = true;

    MiniMap =
    {
        zoom: zoom,
        detailed: detailed,
        initialise: initialise,
        attachScrollListener: attachScrollListener,
        update: update,
        activate: activate,
        deactivate: deactivate
    };

    // Turned on for this session? (based on e.g. browser)
    var enabled = true,
    // Allowed by the context? If not, hidden completely, including controls
    active = true,
    // Turned on by the user? If not, hidden, but controls are still visible
    shown = true;

    function initialise()
    {
        recallShown();
        if (!shown)
        {
            $("#minimap").hide();
            $("#enableMinimap").prop("checked", false);
        }

        $("#miniwrap").css("display","block");
        $("#minimap").css("width", "300px");
        $("#minimap").css("height", "300px");
        $("#minimap").css("overflow", "hidden");

        $("#minimap").on("click", function(e)
        {
            updateScrollPosition(e);
        });
        $("#mainCell #main").on("scroll", function()
        {
            update(false);
        });

        // Zoomed in scroll event listeners for minimap are created by attachScrollListener,
        // called by createEmptyTree()!

        // Listeners for minimap checkboxes
        $("#enableMinimap").on("click", function()
        {
            if (this.checked)
            {
                setAndStoreShown(true);
                showAnimated($("#minimap"));
            }
            else
            {
                hideAnimated($("#minimap"));
                setAndStoreShown(false);
            }
        });
        $("#simpleMinimap").on("click", function()
        {
            if (this.checked)
            {
                detailed = false;
                $("#scaledDiv").empty();
                update(false);
            }
            else
            {
                detailed = true;
                update(true);
            }
        });
    }

    function attachScrollListener(treeDiv)
    {
        if (!enabled) return;

        treeDiv.on('scroll', function(e)
        {
            update(false);
        });
    }

    function updateScrollPosition(e)
    {
        var minimapSelectorX = e.pageX - $("#minimap").offset().left - $("#minimapSelector").width() / 2;
        var minimapSelectorY = e.pageY - $("#minimap").offset().top - $("#minimapSelector").height() / 2;

        //Limit the minimum/maximum positions of the selector
        var maxX = $("#minimap").width() - $("#minimapSelector").width();
        var maxY = $("#minimap").height() - $("#minimapSelector").height();
        if(minimapSelectorX < 0) minimapSelectorX = 0;
        if(minimapSelectorY < 0) minimapSelectorY = 0;
        if(minimapSelectorX > maxX) minimapSelectorX = maxX;
        if(minimapSelectorY > maxY) minimapSelectorY = maxY;

        $("#minimapSelector").css("top", minimapSelectorY+"px");
        $("#minimapSelector").css("left", minimapSelectorX+"px");

        minimapSelectorX /= zoom;
        minimapSelectorY /= zoom;

        if(!Zoom.isZoomed())   //Nothing is zoomed
        {
            $("#mainCell > #main").scrollLeft(minimapSelectorX);
            $("#mainCell > #main").scrollTop(minimapSelectorY);
        }
        else
        {
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollLeft(minimapSelectorX);
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollTop(minimapSelectorY);
        }

        update(false);
    }

    //Scale the minimap according to the main div dimensions
    //and optionally refresh the background by cloning the main div
    ///refresh boolean to effect a new clone of the main div and its children
    function update(refresh)
    {
        if (!(enabled && active && shown)) return;

        var realWidth, realHeight;
        var viewportWidth, viewportHeight, viewportX, viewportY, zoomFactor;

        var main = $("#mainCell > #main");

        if (!Zoom.isZoomed())   //Nothing is zoomed
        {
            realWidth = main[0].scrollWidth;
            realHeight = main[0].scrollHeight;
            viewportX = main.scrollLeft();
            viewportY = main.scrollTop();
        }
        else
        {
            var treeDiv = $("#mainCell .treeContainer.zoom > .treeDiv");
            realWidth = treeDiv[0].scrollWidth;
            realHeight = treeDiv[0].scrollHeight + $("#mainCell .subjectDiv")[0].scrollHeight;
            viewportX = treeDiv.scrollLeft();
            viewportY = treeDiv.scrollTop() + $("#mainCell .subjectDiv")[0].scrollHeight;
        }
        viewportWidth = main.width();
        viewportHeight = main.height();

        $("#scaledDiv").css("width", realWidth+"px");
        $("#scaledDiv").css("height", realHeight+"px");
        $("#minimap").css("height", $("#sidebar").height()-25+"px");

        //Show a cloned and scaled down version of the main div in the minimap if detailedMinimap is set to true
        if (detailed && refresh)
        {
            $("#scaledDiv").empty();
            main.clone().appendTo($("#scaledDiv"));
            $("#scaledDiv #gridIndicator").remove();
            //Rename cloned div ids!
            $("#scaledDiv > #main").attr("id","miniMain");
            //Remove inappropriate subjects from minimap
            if(Zoom.isZoomed())
                $("#scaledDiv .treeContainer").not(".zoom").remove();
            $("#scaledDiv *").off();
        }

        //Standard width/height for minimap container
        var width = 300;
        var height = 300;

        var widthFactor = width/realWidth;
        var heightFactor = height/realHeight;

        zoomFactor = widthFactor;
        //minimap gets taller than the allowed screenheight
        if (zoomFactor * realHeight > $("#sidebar").height())
        {
            zoomFactor = $("#sidebar").height()/(realHeight+realHeight*0.1);
        }

        var minimapSize = {
            width: realWidth * zoomFactor + "px",
            height: realHeight * zoomFactor + "px"
        };
        $("#minimap").css(minimapSize);
        $("#minimap").data("savedSize", minimapSize);

        if (detailed && refresh)
        {
            $("#scaledDiv .treeContainer.zoom").css("left", 0 + "px");
            $("#scaledDiv .treeContainer.zoom").css("top", 0 + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("height", realHeight + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("width", realWidth + "px");
        }

        $("#scaledDiv").css({
            transform: "scale(" + zoomFactor + ")",
            transformOrigin: "top left"
        });

        //Scale and reposition the minimap selector
        $("#minimapSelector").css({
            width: viewportWidth * zoomFactor + "px",
            height: viewportHeight * zoomFactor + "px",
            top: viewportY * zoomFactor + "px",
            left: viewportX * zoomFactor + "px"
        });

        zoom = zoomFactor;
    }

    function recallShown()
    {
        var recalledShown = localStorage.getItem('MiniMap.shown');
        if (recalledShown !== null) shown = Boolean(JSON.parse(recalledShown));
    }

    function setAndStoreShown(newShown)
    {
        shown = Boolean(newShown);
        try
        {
            localStorage.setItem('MiniMap.shown', JSON.stringify(shown));
        }
        catch (e)
        {
            // storage is an enhancement, so ignore failure
        }
    }

    function showAnimated(element)
    {
        // slide Down with animation stopper
        var savedSize = element.data('savedSize');
        var finalHeight = savedSize ? savedSize.height : element.css('height', 'auto').height();
        element.height(0).show().stop(true,false).animate({height: finalHeight}, 400);
    }

    function hideAnimated(element)
    {
        // slide Up with animation stopper
        element.stop(true,false).animate({height: 0}, 400,
            'swing', function(){ element.hide(); });
    }

    function activate()
    {
        if (!enabled) return;

        if (!active) showAnimated($("#miniwrap"));
        active = true;
        update(true);
    }

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

        if (active) hideAnimated($("#miniwrap"));
        active = false;
    }
})();
<|endoftext|>


<commit_before>// @ts-check

const { updateRepo } = require("@artsy/update-repo")
const { execSync } = require("child_process")
const path = require("path")
const { buildSchema, introspectionQuery, graphqlSync } = require("graphql")
const { readFileSync, writeFileSync } = require("fs")

/**
 * @param {string} repo - Name of artsy repo to update
 * @param {string} [dest=data/schema.graphql] - Path to schema file in target repo
 */
async function updateSchemaFile(repo, dest = "data/schema.graphql") {
  await updateRepo({
    repo: {
      owner: "artsy",
      repo,
    },
    branch: "update-schema",
    title: "Update metaphysics schema",
    targetBranch: "master",
    commitMessage: "Update metaphysics schema",
    body:
      "Greetings human :robot: this PR was automatically created as part of metaphysics' deploy process.",
    assignees: ["artsyit"],
    labels: ["Merge On Green"],
    update: (repoDir) => {
      const repoDest = path.join(repoDir, dest)
      execSync("yarn install --ignore-engines", { cwd: repoDir })
      if (dest.endsWith(".json")) {
        const sdl = readFileSync("_schemaV2.graphql", "utf8").toString()
        const schema = buildSchema(sdl, { commentDescriptions: true })
        const gql = graphqlSync(schema, introspectionQuery)
        writeFileSync(repoDest, JSON.stringify(gql, null, 2))
      } else {
        execSync(`cp _schemaV2.graphql '${repoDest}'`)
        execSync("./node_modules/.bin/relay-compiler", { cwd: repoDir })
      }
      execSync(`./node_modules/.bin/prettier --write ${dest}`, {
        cwd: repoDir,
      })
    },
  })
}

async function main() {
  try {
    console.log("∙ Dumping staging schema")

    execSync("yarn dump:staging")

    await updateSchemaFile("eigen")
    await updateSchemaFile("force")
    await updateSchemaFile("volt", "vendor/graphql/schema/metaphysics.json")
  } catch (error) {
    console.error(error)
    process.exit(1)
  }
}

main()
<commit_msg>Update Pulse's schema automatically too (#2669)<commit_after>// @ts-check

const { updateRepo } = require("@artsy/update-repo")
const { execSync } = require("child_process")
const path = require("path")
const { buildSchema, introspectionQuery, graphqlSync } = require("graphql")
const { readFileSync, writeFileSync } = require("fs")

/**
 * @param {string} repo - Name of artsy repo to update
 * @param {string} [dest=data/schema.graphql] - Path to schema file in target repo
 */
async function updateSchemaFile(repo, dest = "data/schema.graphql") {
  await updateRepo({
    repo: {
      owner: "artsy",
      repo,
    },
    branch: "update-schema",
    title: "Update metaphysics schema",
    targetBranch: "master",
    commitMessage: "Update metaphysics schema",
    body:
      "Greetings human :robot: this PR was automatically created as part of metaphysics' deploy process.",
    assignees: ["artsyit"],
    labels: ["Merge On Green"],
    update: (repoDir) => {
      const repoDest = path.join(repoDir, dest)
      execSync("yarn install --ignore-engines", { cwd: repoDir })
      if (dest.endsWith(".json")) {
        const sdl = readFileSync("_schemaV2.graphql", "utf8").toString()
        const schema = buildSchema(sdl, { commentDescriptions: true })
        const gql = graphqlSync(schema, introspectionQuery)
        writeFileSync(repoDest, JSON.stringify(gql, null, 2))
      } else {
        execSync(`cp _schemaV2.graphql '${repoDest}'`)
        execSync("./node_modules/.bin/relay-compiler", { cwd: repoDir })
      }
      execSync(
        `[ ! -f ./node_modules/.bin/prettier ] || ./node_modules/.bin/prettier --write ${dest}`,
        {
          cwd: repoDir,
        }
      )
    },
  })
}

async function main() {
  try {
    console.log("∙ Dumping staging schema")

    execSync("yarn dump:staging")

    await updateSchemaFile("eigen")
    await updateSchemaFile("force")
    await updateSchemaFile("volt", "vendor/graphql/schema/metaphysics.json")
    await updateSchemaFile("pulse", "vendor/graphql/schema/metaphysics.json")
  } catch (error) {
    console.error(error)
    process.exit(1)
  }
}

main()
<|endoftext|>


<commit_before>module.exports = function(self,deps){
    var preprocessProperties = self.require('lib/properties');
    var getAppScheme = self.require('lib/getAppScheme');
    var compareDescriptors = self.require('lib/difference');
    var g = require('grunt');
    var Sync = require('sql-ddl-sync').Sync;
    var Q = require('q');
    var _ = require('underscore');
    var currentState;
    var appState;
    var dbg = true;
    var MState;
    var flagFirst = true;
    var diff;
    var mjcDir;
    var magic = {id: null, run: null};

    return {
        init : function(mDir, dbPath){
           mjcDir = mDir;
           var prms = self.require('lib/migrationState').init(dbPath).then(function(State){
               MState = State;
               return State.lastState();
           }).then(function(last){
               if(last.getId()) flagFirst = false;
               currentState = last;
               if(currentState.err){
                   if(dbg) console.log(currentState.err);
                   return Q.reject(new Error("Migration module: Errors in last migration state."));
               }
               return Q();
           }).then(function(){
               return MState.createState().then(function(stt){
                   appState = stt;
                   appState.setScheme(getAppScheme());
               });
           }).then(function(){
               diff = compareDescriptors(currentState.scheme, appState.scheme);
               m.diff = diff;
               if(diff.need){
                   if(flagFirst) {
                       if(dbg) console.log("First migration - magic function not need.");
                       return Q();
                   }
                   if(!currentState.isSynced()){
                       magic.id = currentState.magicId;
                   } else {
                       magic.id = currentState.getId();
                   }

                   var mjcPath = mjcDir+magic.id+".js";
                   var txt = "module.exports = {\n"+
                   "function(models) {\n"+
                   "}\n"+
                   "};\n";
                   if (!g.file.exists(mjcPath)){
                       g.file.write(mjcPath, txt);
                       if(dbg) console.log("Magic file created: "+ mjcPath);
                   } else {
                       if(dbg) console.log("Magic file already exists: " + mjcPath);
                   }
                   magic.run = require(mjcPath);

               } else {
                   if(dbg) console.log("Nothing to sync.");
                   return Q(new Error("Nothing to sync."));
               }
               return Q();
           });
           return prms;
        },
        run: function(){
            if(!diff.need){
                if(dbg) console.log("Nothing to sync");
                return Q();
            }
            if(!flagFirst && !magic.run ){
                if(dbg) console.log("no magic function");
                return Q().reject(new Error("no magic function"));
            }
            var prms = Q();
            var syncingState;
            if(currentState.isSynced()){
                prms = MState.createState().then(function(stt){
                    syncingState = stt;
                    syncingState.setScheme(currentState.getScheme());
                    syncingState.downStateId = currentState.getId();
                });
            } else {
                syncingState = currentState;
            }

            prms = prms.then(function(){ // ddl sync app models;
                if(dbg) console.log("ddl sync added app models ... ");
                if(_.keys(diff.ddlSyncAdd).length == 0 ){
                    if(dbg) console.log("no models to ddl-sync.");
                    return Q();
                }
                return syncingState.ddlSync(diff.ddlSyncAdd).then(function(){
                    return deps.config.reloadScope();
                });
            }).then(function(){ // orm sync app models;
                if(dbg) console.log("orm sync app models ... ");
                if(_.keys(diff.modelSync).length == 0 ) {
                    if(dbg) console.log("no models to sync.");
                    return Q();
                }
                function one(name){
                    var df = Q.defer();
                    m.app.models[mdl].sync(function(err){ //TODO
                        if(err) df.reject(err);
                        if(dbg) console.log("Model "+mdl+" synced.");
                        df.resolve();
                    });
                    return df.promise;
                }
                var _p = Q();
                for (var db in diff.modelSync){
                    var dsc = diff.modelSync[db];
                    for(var mdl in dsc){
                        _p = _p.then(function(){
                            return one(mdl);
                        }).then(function(){
                            var _dsc = {};
                            _dsc[mdl] = dsc[mdl];
                            syncingState.changeDescriptor(db, _dsc);
                            return Q();
                        });
                    }
                    _p = _p.then(function(){
                        return syncingState.save();
                    });
                }
                return _p;
            }).then(function(){ // magic
                if(flagFirst) return Q();
                if(dbg) console.log("Magic ... ");
                if(magic.run) return magic.run();
                else return Q(new Error("No magic function"));
            }).then(function(){
                if(dbg) console.log("ddl sync removed app models ... ");
                if(_.keys(diff.ddlSyncRm).length == 0){
                    if(dbg) console.log("no models to remove.");
                    return Q();
                }
                return syncingState.ddlSync(diff.ddlSyncRm);
            });
            return prms;
        }
    };
};<commit_msg>reject in orm sync one model<commit_after>module.exports = function(self,deps){
    var preprocessProperties = self.require('lib/properties');
    var getAppScheme = self.require('lib/getAppScheme');
    var compareDescriptors = self.require('lib/difference');
    var g = require('grunt');
    var Sync = require('sql-ddl-sync').Sync;
    var Q = require('q');
    var _ = require('underscore');
    var currentState;
    var appState;
    var dbg = true;
    var MState;
    var flagFirst = true;
    var diff;
    var mjcDir;
    var magic = {id: null, run: null};

    return {
        init : function(mDir, dbPath){
           mjcDir = mDir;
           var prms = self.require('lib/migrationState').init(dbPath).then(function(State){
               MState = State;
               return State.lastState();
           }).then(function(last){
               if(last.getId()) flagFirst = false;
               currentState = last;
               if(currentState.err){
                   if(dbg) console.log(currentState.err);
                   return Q.reject(new Error("Migration module: Errors in last migration state."));
               }
               return Q();
           }).then(function(){
               return MState.createState().then(function(stt){
                   appState = stt;
                   appState.setScheme(getAppScheme());
               });
           }).then(function(){
               diff = compareDescriptors(currentState.scheme, appState.scheme);
               m.diff = diff;
               if(diff.need){
                   if(flagFirst) {
                       if(dbg) console.log("First migration - magic function not need.");
                       return Q();
                   }
                   if(!currentState.isSynced()){
                       magic.id = currentState.magicId;
                   } else {
                       magic.id = currentState.getId();
                   }

                   var mjcPath = mjcDir+magic.id+".js";
                   var txt = "module.exports = {\n"+
                   "function(models) {\n"+
                   "}\n"+
                   "};\n";
                   if (!g.file.exists(mjcPath)){
                       g.file.write(mjcPath, txt);
                       if(dbg) console.log("Magic file created: "+ mjcPath);
                   } else {
                       if(dbg) console.log("Magic file already exists: " + mjcPath);
                   }
                   magic.run = require(mjcPath);

               } else {
                   if(dbg) console.log("Nothing to sync.");
                   return Q(new Error("Nothing to sync."));
               }
               return Q();
           });
           return prms;
        },
        run: function(){
            if(!diff.need){
                if(dbg) console.log("Nothing to sync");
                return Q();
            }
            if(!flagFirst && !magic.run ){
                if(dbg) console.log("no magic function");
                return Q().reject(new Error("no magic function"));
            }
            var prms = Q();
            var syncingState;
            if(currentState.isSynced()){
                prms = MState.createState().then(function(stt){
                    syncingState = stt;
                    syncingState.setScheme(currentState.getScheme());
                    syncingState.downStateId = currentState.getId();
                });
            } else {
                syncingState = currentState;
            }

            prms = prms.then(function(){ // ddl sync app models;
                if(dbg) console.log("ddl sync added app models ... ");
                if(_.keys(diff.ddlSyncAdd).length == 0 ){
                    if(dbg) console.log("no models to ddl-sync.");
                    return Q();
                }
                return syncingState.ddlSync(diff.ddlSyncAdd).then(function(){
                    return deps.config.reloadScope();
                });
            }).then(function(){ // orm sync app models;
                if(dbg) console.log("orm sync app models ... ");
                if(_.keys(diff.modelSync).length == 0 ) {
                    if(dbg) console.log("no models to sync.");
                    return Q();
                }
                function one(name){
                    var df = Q.defer();
                    m.app.models[mdl].sync(function(err){ //TODO
                        if(dbg) console.log("Syncing: "+mdl);
                        if(err) df.reject(err);
                        if(dbg) console.log("Model "+mdl+" synced.");
                        df.resolve();
                    });
                    return df.promise;
                }
                var _p = Q();
                for (var db in diff.modelSync){
                    var dsc = diff.modelSync[db];
                    for(var mdl in dsc){
                        _p = _p.then(function(){
                            return one(mdl);
                        }).then(function(){
                            var _dsc = {};
                            _dsc[mdl] = dsc[mdl];
                            syncingState.changeDescriptor(db, _dsc);
                            return Q();
                        });
                    }
                    _p = _p.then(function(){
                        return syncingState.save();
                    });
                }
                return _p;
            }).then(function(){ // magic
                if(flagFirst) return Q();
                if(dbg) console.log("Magic ... ");
                if(magic.run) return magic.run();
                else return Q(new Error("No magic function"));
            }).then(function(){
                if(dbg) console.log("ddl sync removed app models ... ");
                if(_.keys(diff.ddlSyncRm).length == 0){
                    if(dbg) console.log("no models to remove.");
                    return Q();
                }
                return syncingState.ddlSync(diff.ddlSyncRm);
            });
            return prms;
        }
    };
};<|endoftext|>


<commit_before>module.exports = function(grunt) {

  grunt.registerTask('default', [
    'jshint:gruntfile'
  ]);

 grunt.registerTask('dev', 'Run website locally and start watch process (living document).', function() {

    grunt.task.run([
      'clean:dev',
      'init_env:dev',
      'icons2fonts:dev',
      'less:dev',
      'copy:images_dev',
      'copy:css_dev',
      'build_content:dev',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('dist', 'Build the website ready for production', function() {

    grunt.task.run([
      'clean:dist',
      'init_env:dist',
      'icons2fonts:dist',
      'less:dist',
      'copy:css_dist',
      //'cssmin:dist',
      'imagemin:dist',
      'svgmin:dist',
      'build_content:dist'
    ]);

  });

};<commit_msg>Added browserify task to the dev task startup<commit_after>module.exports = function(grunt) {

  grunt.registerTask('default', [
    'jshint:gruntfile'
  ]);

 grunt.registerTask('dev', 'Run website locally and start watch process (living document).', function() {

    grunt.task.run([
      'clean:dev',
      'init_env:dev',
      'icons2fonts:dev',
      'browserify:frontend',
      'less:dev',
      'copy:images_dev',
      'copy:css_dev',
      'build_content:dev',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('dist', 'Build the website ready for production', function() {

    grunt.task.run([
      'clean:dist',
      'init_env:dist',
      'icons2fonts:dist',
      'less:dist',
      'copy:css_dist',
      //'cssmin:dist',
      'imagemin:dist',
      'svgmin:dist',
      'build_content:dist'
    ]);

  });

};
<|endoftext|>