<commit_before>var $ = function (selector, elem) {
    return (elem || document).querySelector(selector);
};
var $$ = function (selector, elem) {
    return (elem || document).querySelectorAll(selector);
};

var rtmlOperators = [
    "<", "<=", "<=>", ">", ">=", "ACCUMULATE", "ACTION", "AND", "APPEND",
    "AS-LIST", "AS-NUMBER", "AS-STRING", "AUCTIONURL", "BASKET",
    "BASKET-MODULE", "BLUE", "BODY", "CALL", "CAPS", "CENTER", "CMP", "COLOGO",
    "COLOR", "COMMENT", "CSS-WITH-LINK", "DIV", "ELEMENT", "ELEMENTS", "EQUALS",
    "EVEN", "FC-BAR", "FC-LOADER", "FIND-ALL", "FIND-ONE", "FONT", "FONT-WIDTH",
    "FOR", "FOR-EACH", "FOR-EACH-BUT", "FOR-EACH-OBJECT", "FORM", "FROM-HEX",
    "FUSE", "GET-ALL-PATHS-TO", "GET-PATH-TO", "GRAB", "GRAYSCALE", "GREEN",
    "HEAD", "HEIGHT", "HEX-ENCODE", "HRULE", "IF", "IMAGE", "IMAGE-REF", "IMG",
    "INDEXED-SORT", "INPUT", "INVENTORY-INFO", "ITEM", "ITEM-INVENTORY",
    "LABEL", "LENGTH", "LINEBREAK", "LINES", "LINK", "LOG", "LOWERCASE",
    "MAKE-LIST", "MAXIMUM", "MAXNUM", "META", "MINIMUM", "MINNUM", "MODULE",
    "MULTI", "NAMED-PROP", "NOBREAK", "NONEMPTY", "NOSCRIPT", "NOT", "NUMBER",
    "OBJID-FROM-STRING", "ONCE", "OR", "ORDER", "ORDER-FORM", "PARAGRAPH",
    "PARAGRAPHS", "PAT-GREP", "PAT-MATCH", "PAT-SUBST", "POSITION", "PRICE",
    "PROMO-CATEGORY", "PROMO-HOME", "PROMO-ITEM", "PROMO-ITEMPAGE", "RED",
    "RENDER", "RETURN-WITH", "REVERSE", "SCRIPT", "SEARCH-FORM", "SEGMENTS",
    "SELECT", "SHIM", "SHOPPING-BANNER", "SOCIAL-SHARE", "SORT", "SPAN",
    "STRCASECMP", "STRCMP", "STRING-APPEND", "STRING-TRIM", "STYLE",
    "SUPER-BAR", "SUPER-LOADER", "SWITCH", "TABLE", "TABLE-CELL", "TABLE-ROW",
    "TAG", "TAG-WHEN", "TEXT", "TEXT-STYLE", "TEXTAREA", "TITLE", "TO",
    "TO-HEX", "TOKENS", "TOPSEARCH", "VALUE", "WHEN", "WHOLE-CONTENTS", "WIDTH",
    "WITH-LINK", "WITH-OBJECT", "WITH=", "WORDBREAK", "YANK", "YFUNCTION"
];

var rtmlKeywords = [
    "nil", ":big", ":bottom", ":center", ":contents", ":download", ":email",
    ":empty", ":empty.", ":fixed", ":help", ":home", ":horizontal", ":icon",
    ":image", ":incised", ":index", ":info", ":info.", ":item.", ":left",
    ":link.", ":main.", ":mall", ":multi-line", ":next", ":no", ":norder.",
    ":normal", ":privacypolicy", ":privacypolicy.", ":quiet", ":raw-html.",
    ":register", ":request", ":right", ":section.", ":show-order", ":solid",
    ":search", ":search.", ":side-buttons", ":solid", ":t", ":text", ":top",
    ":top-buttons", ":two-line", ":up", ":yes", ":variable", ":vertical"
];

var lastButtonSelector = 'body > table:nth-child(1) > tbody > tr:nth-child(2) > td > center > table > tbody > tr > td:last-child';

var pageActions = [
    {
        name: 'Previous Link',
        keyCode: 106, /* j */
        keyCommand: function (el) {
            while ((el = el.nextSibling) && el.nodeType !== 9) {
                if (el.nodeType === 1 && el.nodeName == 'A' &&
                    el.getAttribute('title') == 'Select') {
                    el.focus();
                    break;
                }
            }
        }
    },
    {
        name: 'Next Link',
        keyCode: 107, /* k */
        keyCommand: function (el) {
            while ((el = el.previousSibling) && el.nodeType !== 9) {
                if (el.nodeType === 1 && el.nodeName == 'A' &&
                    el.getAttribute('title') == 'Select') {
                    el.focus();
                    break;
                }
            }
        }
    },
    {
        name: 'New',
        keyCode: 110 /* n */
    },
    {
        name: 'Edit',
        keyCode: 101 /* e */
    },
    {
        name: 'Copy',
        keyCode: 99 /* c */
    },
    {
        name: 'Cut',
        keyCode: 120 /* x */
    },
    {
        name: 'Replace',
        keyCode: 114 /* r */
    },
    {
        name: 'Paste Within',
        keyCode: 119 /* w */
    },
    {
        name: 'Paste After',
        keyCode: 118 /* v */
    },
    {
        name: 'Contract',
        keyCode: 45 /* - */
    },
    {
        name: 'Expand',
        keyCode: 61 /* = */
    },
    {
        name: 'Find',
        keyCode: 48 /* 0 */
    },
    {
        name: 'Contents',
        keyCode: 50 /* 2 */
    },
    {
        name: 'Variables',
        keyCode: 51 /* 3 */
    },
    {
        name: 'Files',
        keyCode: 52 /* 4 */
    },
    {
        name: 'Templates',
        keyCode: 53 /* 5 */
    },
    {
        name: 'Types',
        keyCode: 54 /* 6 */
    },
    {
        name: 'Database Upload',
        keyCode: 55 /* 7 */
    },
    {
        name: 'Config',
        keyCode: 56 /* 8 */
    },
    {
        name: 'Controls',
        keyCode: 57 /* 9 */
    },
    {
        name: 'Last Edit',
        keyCode: 49 /* 1 */
    },
];

var keyCommands = pageActions.reduce(function (obj, action) {
    if (action.keyCommand) {
        obj[action.keyCode] = action.keyCommand;
    } else {
        var targetEl = $('a[title="' + action.name + '"]');
        if (! targetEl) {
            targetEl = $(lastButtonSelector + ' > a');
            pageActions[pageActions.length - 1].name = targetEl.title;
        }
        obj[action.keyCode] = targetEl;
    }
    return obj;
}, {});

var findElementsWithText = function (els, text) {
    return [].filter.call(els, function (el) {
        return el.textContent.match(new RegExp(text));
    });
};

var isTemplatePage = function () {
    return !! $('img[alt="Delete Template"]');
};

var isTemplateListPage = function () {
    return !! findElementsWithText($$('b'), 'Built-In Templates').length;
};

var setupKeyCommands = function () {
    document.addEventListener('keypress', function (evt) {
        var command = keyCommands[evt.keyCode];

        if (! command || evt.ctrlKey) return;

        var elem;
        var titleElem;

        if (typeof command === 'function') {
            elem = document.activeElement;
            if (elem.toString() === '[object HTMLBodyElement]') {
                elem = $$('b')[1];
                if (! elem)
                    elem = $$('a[href^="javascript:document"]')[1];
            }
            command(elem);
        } else if (command.href) {
            window.location.href = command.href;
        }
    });
};

var setupStyle = function () {
    var elems = $$('a');

    var i = elems.length;
    var elem, text, j, action, tLink;

    while (i--) {
        elem = elems[i];
        text = elem.textContent;

        if (rtmlOperators.indexOf(text) > -1)
            elem.classList.add('yiyaye-operator');
        else if (rtmlKeywords.indexOf(text) > -1)
            elem.classList.add('yiyaye-keyword');

        if (text.search('@') > -1)
            elem.classList.add('yiyaye-prefix-a');
        else if (text.search(':') > -1)
            elem.classList.add('yiyaye-prefix-b');

        if (elem.href.search(/\?e=/) > -1) {
            elem.previousElementSibling.classList.add('yiyaye-template-link');
        }

        j = pageActions.length;
        while (j--) {
            action = pageActions[j];
            if (action.name === elem.title)
                elem.innerHTML = elem.title + ' (' +
                                 String.fromCharCode(action.keyCode) + ')';
        }
    }

    document.body.classList.add('yiyaye-template');
};

var setupFileUpload = function () {
    [].filter.call($$('form'), function (form) {
        return $('input[type="file"]', form);
    }).forEach(function (form) {
        var file = $('input[type="file"]');
        var text = $('input[type="text"]');
        file.addEventListener('change', function () {
            text.value = file.value.split('\\')[2];
        });
    });
};

var findWordPages = function () {
    var jobsToDo;

    var finish = function () {
        postMessage({finished: true});
        close();
    };

    var async = function (url, fn) {
        var request = new XMLHttpRequest();
        request.open('GET', url);

        request.onload = function () {
            if (request.status == 200)
                fn({success: true, response: request.responseText,
                    templateName: url.match(/\?e=(.+)/)[1]});
            else
                fn({success: false});

            if (--jobsToDo === 0)
                finish();
        };

        request.send();
    };

    var postBack = function (resp) {
        postMessage(resp);
    };

    onmessage = function(data) {
        var urls = JSON.parse(data.data);
        jobsToDo = urls.length;

        console.log(urls);

        for (var i = 0, l = urls.length; i < l; i++) {
            async(urls[i], postBack);
        }
    };
};

var templateRegExSearch = function (regexString, urls, oneFn, finalFn) {
    var workerBlob = new Blob(['(' + findWordPages + ')()'], {type: 'text/javascript'});

    var worker = new Worker(window.URL.createObjectURL(workerBlob));

    worker.onmessage = function (data) {
        data = data.data;
        if (data.success && data.response.match(new RegExp(regexString)))
            oneFn(data.templateName);
        if (data.finished)
            finalFn();
    };

    worker.postMessage(JSON.stringify(urls));
};

var setupTemplateRegExSearch = function () {
    var target = findElementsWithText($$('b'), 'Built-In Templates')[0];
    while ((target = target.parentNode).nodeName != 'TABLE') {
        // safety in case we don't find a table
        if (target.nodeName == 'BODY') return;
    }

    var anchors = $$('a', target.childNodes[0].childNodes[1].childNodes[1]);
    var templateURLs = [].map.call(anchors, function (a) { return a.href; });

    var input = document.createElement('input');
    var label = document.createElement('label');
    label.appendChild(document.createTextNode('Search Templates (regex): '));
    label.appendChild(input);

    var button = document.createElement('button');
    button.textContent = 'Search';

    var spinner = document.createElement('img');
    spinner.src = 'http://www.ajaxload.info/cache/FF/FF/FF/00/00/00/38-0.gif';
    spinner.style.display = 'none';

    button.addEventListener('click', function () {
        if (input.value === '') return;

        spinner.style.display = 'inline';
        templateRegExSearch(input.value, templateURLs, function (templateName) {
            console.log('regex found in template ' + templateName);
            var el = [].filter.call(anchors, function (a) {
                return a.textContent == templateName;
            })[0];
            el.style.background = 'red';
            el.style.fontWeight = 'bold';
            el.style.color = 'white';
            el.style.padding = '1px';
        }, function () {
            spinner.style.display = 'none';
        });
    });

    var search = document.createElement('div');
    search.appendChild(label);
    search.appendChild(button);
    search.appendChild(spinner);

    target.parentNode.insertBefore(search, target);
};

(function () {
    if (isTemplatePage()) {
        setupKeyCommands();
        setupStyle();
    }
    if (isTemplateListPage()) {
        setupTemplateRegExSearch();
    }
    setupFileUpload();
})();
<commit_msg>Code reorg<commit_after>var $ = function (selector, elem) {
    return (elem || document).querySelector(selector);
};
var $$ = function (selector, elem) {
    return (elem || document).querySelectorAll(selector);
};

var rtmlOperators = [
    "<", "<=", "<=>", ">", ">=", "ACCUMULATE", "ACTION", "AND", "APPEND",
    "AS-LIST", "AS-NUMBER", "AS-STRING", "AUCTIONURL", "BASKET",
    "BASKET-MODULE", "BLUE", "BODY", "CALL", "CAPS", "CENTER", "CMP", "COLOGO",
    "COLOR", "COMMENT", "CSS-WITH-LINK", "DIV", "ELEMENT", "ELEMENTS", "EQUALS",
    "EVEN", "FC-BAR", "FC-LOADER", "FIND-ALL", "FIND-ONE", "FONT", "FONT-WIDTH",
    "FOR", "FOR-EACH", "FOR-EACH-BUT", "FOR-EACH-OBJECT", "FORM", "FROM-HEX",
    "FUSE", "GET-ALL-PATHS-TO", "GET-PATH-TO", "GRAB", "GRAYSCALE", "GREEN",
    "HEAD", "HEIGHT", "HEX-ENCODE", "HRULE", "IF", "IMAGE", "IMAGE-REF", "IMG",
    "INDEXED-SORT", "INPUT", "INVENTORY-INFO", "ITEM", "ITEM-INVENTORY",
    "LABEL", "LENGTH", "LINEBREAK", "LINES", "LINK", "LOG", "LOWERCASE",
    "MAKE-LIST", "MAXIMUM", "MAXNUM", "META", "MINIMUM", "MINNUM", "MODULE",
    "MULTI", "NAMED-PROP", "NOBREAK", "NONEMPTY", "NOSCRIPT", "NOT", "NUMBER",
    "OBJID-FROM-STRING", "ONCE", "OR", "ORDER", "ORDER-FORM", "PARAGRAPH",
    "PARAGRAPHS", "PAT-GREP", "PAT-MATCH", "PAT-SUBST", "POSITION", "PRICE",
    "PROMO-CATEGORY", "PROMO-HOME", "PROMO-ITEM", "PROMO-ITEMPAGE", "RED",
    "RENDER", "RETURN-WITH", "REVERSE", "SCRIPT", "SEARCH-FORM", "SEGMENTS",
    "SELECT", "SHIM", "SHOPPING-BANNER", "SOCIAL-SHARE", "SORT", "SPAN",
    "STRCASECMP", "STRCMP", "STRING-APPEND", "STRING-TRIM", "STYLE",
    "SUPER-BAR", "SUPER-LOADER", "SWITCH", "TABLE", "TABLE-CELL", "TABLE-ROW",
    "TAG", "TAG-WHEN", "TEXT", "TEXT-STYLE", "TEXTAREA", "TITLE", "TO",
    "TO-HEX", "TOKENS", "TOPSEARCH", "VALUE", "WHEN", "WHOLE-CONTENTS", "WIDTH",
    "WITH-LINK", "WITH-OBJECT", "WITH=", "WORDBREAK", "YANK", "YFUNCTION"
];

var rtmlKeywords = [
    "nil", ":big", ":bottom", ":center", ":contents", ":download", ":email",
    ":empty", ":empty.", ":fixed", ":help", ":home", ":horizontal", ":icon",
    ":image", ":incised", ":index", ":info", ":info.", ":item.", ":left",
    ":link.", ":main.", ":mall", ":multi-line", ":next", ":no", ":norder.",
    ":normal", ":privacypolicy", ":privacypolicy.", ":quiet", ":raw-html.",
    ":register", ":request", ":right", ":section.", ":show-order", ":solid",
    ":search", ":search.", ":side-buttons", ":solid", ":t", ":text", ":top",
    ":top-buttons", ":two-line", ":up", ":yes", ":variable", ":vertical"
];

var lastButtonSelector = 'body > table:nth-child(1) > tbody > tr:nth-child(2) > td > center > table > tbody > tr > td:last-child';

var pageActions = [
    {
        name: 'Previous Link',
        keyCode: 106, /* j */
        keyCommand: function (el) {
            while ((el = el.nextSibling) && el.nodeType !== 9) {
                if (el.nodeType === 1 && el.nodeName == 'A' &&
                    el.getAttribute('title') == 'Select') {
                    el.focus();
                    break;
                }
            }
        }
    },
    {
        name: 'Next Link',
        keyCode: 107, /* k */
        keyCommand: function (el) {
            while ((el = el.previousSibling) && el.nodeType !== 9) {
                if (el.nodeType === 1 && el.nodeName == 'A' &&
                    el.getAttribute('title') == 'Select') {
                    el.focus();
                    break;
                }
            }
        }
    },
    {
        name: 'New',
        keyCode: 110 /* n */
    },
    {
        name: 'Edit',
        keyCode: 101 /* e */
    },
    {
        name: 'Copy',
        keyCode: 99 /* c */
    },
    {
        name: 'Cut',
        keyCode: 120 /* x */
    },
    {
        name: 'Replace',
        keyCode: 114 /* r */
    },
    {
        name: 'Paste Within',
        keyCode: 119 /* w */
    },
    {
        name: 'Paste After',
        keyCode: 118 /* v */
    },
    {
        name: 'Contract',
        keyCode: 45 /* - */
    },
    {
        name: 'Expand',
        keyCode: 61 /* = */
    },
    {
        name: 'Find',
        keyCode: 48 /* 0 */
    },
    {
        name: 'Contents',
        keyCode: 50 /* 2 */
    },
    {
        name: 'Variables',
        keyCode: 51 /* 3 */
    },
    {
        name: 'Files',
        keyCode: 52 /* 4 */
    },
    {
        name: 'Templates',
        keyCode: 53 /* 5 */
    },
    {
        name: 'Types',
        keyCode: 54 /* 6 */
    },
    {
        name: 'Database Upload',
        keyCode: 55 /* 7 */
    },
    {
        name: 'Config',
        keyCode: 56 /* 8 */
    },
    {
        name: 'Controls',
        keyCode: 57 /* 9 */
    },
    {
        name: 'Last Edit',
        keyCode: 49 /* 1 */
    }
];

var keyCommands = pageActions.reduce(function (obj, action) {
    if (action.keyCommand) {
        obj[action.keyCode] = action.keyCommand;
    } else {
        var targetEl = $('a[title="' + action.name + '"]');
        if (! targetEl) {
            targetEl = $(lastButtonSelector + ' > a');
            pageActions[pageActions.length - 1].name = targetEl.title;
        }
        obj[action.keyCode] = targetEl;
    }
    return obj;
}, {});

var findElementsWithText = function (els, text) {
    return [].filter.call(els, function (el) {
        return el.textContent.match(new RegExp(text));
    });
};

var isTemplatePage = function () {
    return !! $('img[alt="Delete Template"]');
};

var isTemplateListPage = function () {
    return !! findElementsWithText($$('b'), 'Built-In Templates').length;
};

var setupKeyCommands = function () {
    document.addEventListener('keypress', function (evt) {
        var command = keyCommands[evt.keyCode];

        if (! command || evt.ctrlKey) return;

        var elem;
        var titleElem;

        if (typeof command === 'function') {
            elem = document.activeElement;
            if (elem.toString() === '[object HTMLBodyElement]') {
                elem = $$('b')[1];
                if (! elem)
                    elem = $$('a[href^="javascript:document"]')[1];
            }
            command(elem);
        } else if (command.href) {
            window.location.href = command.href;
        }
    });
};

var setupTemplateStyle = function () {
    var elems = $$('a');

    var i = elems.length;
    var elem, text, j, action, tLink;

    while (i--) {
        elem = elems[i];
        text = elem.textContent;

        if (rtmlOperators.indexOf(text) > -1)
            elem.classList.add('yiyaye-operator');
        else if (rtmlKeywords.indexOf(text) > -1)
            elem.classList.add('yiyaye-keyword');

        if (text.search('@') > -1)
            elem.classList.add('yiyaye-prefix-a');
        else if (text.search(':') > -1)
            elem.classList.add('yiyaye-prefix-b');

        if (elem.href.search(/\?e=/) > -1) {
            elem.previousElementSibling.classList.add('yiyaye-template-link');
        }
    }

    document.body.classList.add('yiyaye-template');
};

var setupOtherStyle = function () {
    var elems = $$('a');

    var i = elems.length;
    var elem, text, j, action, tLink;

    while (i--) {
        elem = elems[i];
        j = pageActions.length;
        while (j--) {
            action = pageActions[j];
            if (action.name === elem.title)
                elem.innerHTML = elem.title + ' (' +
                                 String.fromCharCode(action.keyCode) + ')';
        }
    }
};

var setupFileUpload = function () {
    [].filter.call($$('form'), function (form) {
        return $('input[type="file"]', form);
    }).forEach(function (form) {
        var file = $('input[type="file"]');
        var text = $('input[type="text"]');
        file.addEventListener('change', function () {
            text.value = file.value.split('\\')[2];
        });
    });
};

var findWordPages = function () {
    var jobsToDo;

    var finish = function () {
        postMessage({finished: true});
        close();
    };

    var async = function (url, fn) {
        var request = new XMLHttpRequest();
        request.open('GET', url);

        request.onload = function () {
            if (request.status == 200)
                fn({success: true, response: request.responseText,
                    templateName: url.match(/\?e=(.+)/)[1]});
            else
                fn({success: false});

            if (--jobsToDo === 0)
                finish();
        };

        request.send();
    };

    var postBack = function (resp) {
        postMessage(resp);
    };

    onmessage = function(data) {
        var urls = JSON.parse(data.data);
        jobsToDo = urls.length;

        console.log(urls);

        for (var i = 0, l = urls.length; i < l; i++) {
            async(urls[i], postBack);
        }
    };
};

var templateRegExSearch = function (regexString, urls, oneFn, finalFn) {
    var workerBlob = new Blob(['(' + findWordPages + ')()'], {type: 'text/javascript'});

    var worker = new Worker(window.URL.createObjectURL(workerBlob));

    worker.onmessage = function (data) {
        data = data.data;
        if (data.success && data.response.match(new RegExp(regexString)))
            oneFn(data.templateName);
        if (data.finished)
            finalFn();
    };

    worker.postMessage(JSON.stringify(urls));
};

var setupTemplateRegExSearch = function () {
    var target = findElementsWithText($$('b'), 'Built-In Templates')[0];
    while ((target = target.parentNode).nodeName != 'TABLE') {
        // safety in case we don't find a table
        if (target.nodeName == 'BODY') return;
    }

    var anchors = $$('a', target.childNodes[0].childNodes[1].childNodes[1]);
    var templateURLs = [].map.call(anchors, function (a) { return a.href; });

    var input = document.createElement('input');
    var label = document.createElement('label');
    label.appendChild(document.createTextNode('Search Templates (regex): '));
    label.appendChild(input);

    var button = document.createElement('button');
    button.textContent = 'Search';

    var spinner = document.createElement('img');
    spinner.src = 'http://www.ajaxload.info/cache/FF/FF/FF/00/00/00/38-0.gif';
    spinner.style.display = 'none';

    button.addEventListener('click', function () {
        if (input.value === '') return;

        spinner.style.display = 'inline';
        templateRegExSearch(input.value, templateURLs, function (templateName) {
            console.log('regex found in template ' + templateName);
            var el = [].filter.call(anchors, function (a) {
                return a.textContent == templateName;
            })[0];
            el.style.background = 'red';
            el.style.fontWeight = 'bold';
            el.style.color = 'white';
            el.style.padding = '1px';
        }, function () {
            spinner.style.display = 'none';
        });
    });

    var search = document.createElement('div');
    search.appendChild(label);
    search.appendChild(button);
    search.appendChild(spinner);

    target.parentNode.insertBefore(search, target);
};

(function () {
    if (isTemplatePage()) {
        setupKeyCommands();
        setupTemplateStyle();
    } else if (isTemplateListPage()) {
        setupTemplateRegExSearch();
    }

    if ($('body').className.match(/sbs_body/))
        setupOtherStyle();
    setupFileUpload();
})();
<|endoftext|>


<commit_before>Context = {
    // The Option button
    option: document.getElementById('option'),

    init: function(winamp) {
        this.winamp = winamp;
        var self = this;

        document.onclick = function() {
            self.option.classList.remove('selected');
        };

        this.option.onclick = function(event) {
            self.option.classList.toggle('selected');
            event.stopPropagation();
        };

        var skinSelectNodes = document.getElementsByClassName('skin-select');
        for(var i = 0; i < skinSelectNodes.length; i++) {
            skinSelectNodes[i].onclick = function() {
                var skinFile = new MyFile();
                skinFile.setUrl(this.dataset.skinUrl);
                self.winamp.setSkin(skinFile);
            };
        }

        document.getElementById('context-play-file').onclick = function(event) {
            self.option.classList.remove('selected');
            self.winamp.openFileDialog();
        };
        document.getElementById('context-load-skin').onclick = function(event) {
            self.option.classList.remove('selected');
            self.winamp.openFileDialog();
        };
        document.getElementById('context-exit').onclick = function() {
            self.winamp.close();
        };
    }
};
<commit_msg>Abstract skin loading method<commit_after>Context = {
    // The Option button
    option: document.getElementById('option'),

    init: function(winamp) {
        this.winamp = winamp;
        var self = this;

        document.onclick = function() {
            self.option.classList.remove('selected');
        };

        this.option.onclick = function(event) {
            self.option.classList.toggle('selected');
            event.stopPropagation();
        };

        var skinSelectNodes = document.getElementsByClassName('skin-select');
        for(var i = 0; i < skinSelectNodes.length; i++) {
            skinSelectNodes[i].onclick = this._loadSkin;
        }

        document.getElementById('context-play-file').onclick = function(event) {
            self.option.classList.remove('selected');
            self.winamp.openFileDialog();
        };
        document.getElementById('context-load-skin').onclick = function(event) {
            self.option.classList.remove('selected');
            self.winamp.openFileDialog();
        };
        document.getElementById('context-exit').onclick = function() {
            self.winamp.close();
        };
    },

    _loadSkin: function() {
        var skinFile = new MyFile();
        skinFile.setUrl(this.dataset.skinUrl);
        self.winamp.setSkin(skinFile);
    }

};
<|endoftext|>


<commit_before>// Sortable decorator
// Allows a list to be reordered with drag-and-drop.
module.exports = function sortable(listEl, keypath, index) {
    var el;
    var startY;
    var startIndex, currentIndex;
    var origNextNode;
    var ractive = this;

    // find the element ancestor corresponding to an item in our list
    function findEl(child) {
        for (var el = child;
            el && el.parentNode != listEl;
            el = el.parentNode);
        return el;
    }

    function onDrag(e) {
        var height = el.clientHeight;

        // swap item down the list
        while (e.clientY - startY > height/2 && el.nextElementSibling) {
            startY += height;
            currentIndex++;
            var nextEl = el.nextElementSibling;
            if (nextEl.nextElementSibling) {
                listEl.insertBefore(el, nextEl.nextElementSibling);
            } else {
                listEl.appendChild(el);
            }
        }

        // swap item up the list
        while (e.clientY - startY < -height/2 &&
                el.previousElementSibling) {
            currentIndex--;
            startY -= height;
            listEl.insertBefore(el, el.previousElementSibling);
        }

        el.style.top = (e.clientY - startY) + 'px';
    }

    function onDragEnd(e) {
        document.removeEventListener('mousemove', onDrag, false);
        document.removeEventListener('mouseup', onDragEnd, false);
        onDrag(e);

        var itemEl = el;
        el.classList.remove('ui-sortable-helper');
        el.style.position = '';
        el.style.top = '';
        el.style.zIndex = '';
        listEl.style.overflow = '';
        el = null;

        if (currentIndex == startIndex) {
            // node did not move
            return;
        }

        // put element back in place
        if (origNextNode) {
            listEl.insertBefore(itemEl, origNextNode);
        } else {
            listEl.appendChild(itemEl);
        }

        // update model
        var arrayOrig = ractive.get(keypath);
        var array = arrayOrig.slice();
        var item = array[startIndex];
        if (!item) {
            console.error('Unable to find item', array, startIndex);
            return;
        }
        item.playlistPosition = currentIndex;
        // remove item from old position
        array.splice(startIndex, 1);
        // add item to array at new position
        array.splice(currentIndex, 0, item);

        array._dragging = true;
        //ractive.merge(keypath, array);
        /*
        arrayOrig.sort(function(a, b) {
            return array.indexOf(a) - array.indexOf(b);
        });
        */
        ractive.set(keypath, array);

        array._dragging = false;
    }

    function onMouseDown(e) {
        e.preventDefault();

        if (el) {
            // finish previous drag
            onDragEnd(e);
            return;
        }

        el = findEl(e.target);
        if (!el || !el._ractive || !el._ractive.index) {
            console.error('Unable to find list item');
            return;
        }

        el.classList.add('ui-sortable-helper');
        el.style.position = 'relative';
        el.style.zIndex = 10000;
        listEl.style.overflow = 'visible';
        origNextNode = el.nextElementSibling;
        startY = e.clientY;
        currentIndex = startIndex = el._ractive.index[index];

        document.addEventListener('mousemove', onDrag, false);
        document.addEventListener('mouseup', onDragEnd, false);
    }

    listEl.addEventListener('mousedown', onMouseDown, false);

    return {
        teardown: function() {
            listEl.removeEventListener('mousedown', onMouseDown, false);
        }
    };
};
<commit_msg>Ignore right click in playlist organizer<commit_after>// Sortable decorator
// Allows a list to be reordered with drag-and-drop.
module.exports = function sortable(listEl, keypath, index) {
    var el;
    var startY;
    var startIndex, currentIndex;
    var origNextNode;
    var ractive = this;

    // find the element ancestor corresponding to an item in our list
    function findEl(child) {
        for (var el = child;
            el && el.parentNode != listEl;
            el = el.parentNode);
        return el;
    }

    function onDrag(e) {
        var height = el.clientHeight;

        // swap item down the list
        while (e.clientY - startY > height/2 && el.nextElementSibling) {
            startY += height;
            currentIndex++;
            var nextEl = el.nextElementSibling;
            if (nextEl.nextElementSibling) {
                listEl.insertBefore(el, nextEl.nextElementSibling);
            } else {
                listEl.appendChild(el);
            }
        }

        // swap item up the list
        while (e.clientY - startY < -height/2 &&
                el.previousElementSibling) {
            currentIndex--;
            startY -= height;
            listEl.insertBefore(el, el.previousElementSibling);
        }

        el.style.top = (e.clientY - startY) + 'px';
    }

    function onDragEnd(e) {
        document.removeEventListener('mousemove', onDrag, false);
        document.removeEventListener('mouseup', onDragEnd, false);
        onDrag(e);

        var itemEl = el;
        el.classList.remove('ui-sortable-helper');
        el.style.position = '';
        el.style.top = '';
        el.style.zIndex = '';
        listEl.style.overflow = '';
        el = null;

        if (currentIndex == startIndex) {
            // node did not move
            return;
        }

        // put element back in place
        if (origNextNode) {
            listEl.insertBefore(itemEl, origNextNode);
        } else {
            listEl.appendChild(itemEl);
        }

        // update model
        var arrayOrig = ractive.get(keypath);
        var array = arrayOrig.slice();
        var item = array[startIndex];
        if (!item) {
            console.error('Unable to find item', array, startIndex);
            return;
        }
        item.playlistPosition = currentIndex;
        // remove item from old position
        array.splice(startIndex, 1);
        // add item to array at new position
        array.splice(currentIndex, 0, item);

        array._dragging = true;
        //ractive.merge(keypath, array);
        /*
        arrayOrig.sort(function(a, b) {
            return array.indexOf(a) - array.indexOf(b);
        });
        */
        ractive.set(keypath, array);

        array._dragging = false;
    }

    function onMouseDown(e) {
        if (e.button == 2) {
            // leave right click alone
            return;
        }

        e.preventDefault();

        if (el) {
            // finish previous drag
            onDragEnd(e);
            return;
        }

        el = findEl(e.target);
        if (!el || !el._ractive || !el._ractive.index) {
            console.error('Unable to find list item');
            return;
        }

        el.classList.add('ui-sortable-helper');
        el.style.position = 'relative';
        el.style.zIndex = 10000;
        listEl.style.overflow = 'visible';
        origNextNode = el.nextElementSibling;
        startY = e.clientY;
        currentIndex = startIndex = el._ractive.index[index];

        document.addEventListener('mousemove', onDrag, false);
        document.addEventListener('mouseup', onDragEnd, false);
    }

    listEl.addEventListener('mousedown', onMouseDown, false);

    return {
        teardown: function() {
            listEl.removeEventListener('mousedown', onMouseDown, false);
        }
    };
};
<|endoftext|>


<commit_before>/*
 *  jQuery ZenPen
 *
 *  Copyright (c) 2013 Deux Huit Huit (http://www.deuxhuithuit.com/)
 *  Licensed under the MIT (https://github.com/DeuxHuitHuit/jQuery-zenpen/blob/master/LICENSE.txt)
 *  Based on the work of Tim Holman (https://github.com/tholman/zenpen)
 *  Licensed under the Apache License (https://github.com/tholman/zenpen/blob/master/licence.md)
 */

(function ($) {

	if (!!$.zenpen) {
		return;
	}

	var counter = 0;

	var log = !!window.console ? console.error || console.log : window.alert;

	var getSelection = function () {
		if (!!window.getSelection) {
			return window.getSelection();
		} else if (!!document.selection) {
			return document.selection;
		}
		log('No selection API found');
	};

	var focus = function (elem) {
		var range = document.createRange();
		var selection = getSelection();
		range.setStart(elem.get(0), 1);
		selection.removeAllRanges();
		selection.addRange(range);
	};

	var rehighlightLastSelection = function (lastRange) {
		if (!!lastRange) {
			var selection = getSelection();
			selection.removeAllRanges();
			selection.addRange( lastRange );
		}
	}

	var parseHtmlEntity = function (he) {
		return $('<div />').html(he).text();
	};

	var execCommandFactory = function () {
		var a = arguments;
		return function (btn, popup, lastSelection) {
			document.execCommand.apply(document, a);
		};
	};

	var createButtonFactory = function (cla, text, key) {
		return createButton = function () {
			var b = $('<button />').addClass(cla).text(text);
			if (!!key) {
				b.attr('data-key',key);
			}
			return b;
		};
	};

	var eachActions = function (actions, cb) {
		$.each(actions, function (i, a) {
			if (!!a) {
				var action = $.zenpen.actions[a];
				cb(action, i, a);
			} else {
				console.error('Action %s does not exists in `$.zenpen.actions`', a);
			}
		});
	};

	var createPopUp = function (actions) {
		var popup = $('<div />').addClass('zenpen-panel');
		var options = $('<div />').addClass('zenpen-options');
		eachActions(actions, function (action, i, a) {
			options.append(action.create());
		});
		return popup.append(options);
	};

	var zenpen = function (options) {
		return function init(index, elem) {
			elem = $(elem);

			var id = (++counter);
			var namespace = '.zenpen-' + id;
			var popup = createPopUp(options.actions);
			var popupOpts = popup.find('.zenpen-options');
			var wrap = $('<div />').addClass('zenpen-wrap');
			var scrollTimeout = 0;
			var lastSelection;
			var lastMovePos = {x:0,y:0};

			var checkTextHighlighting = function (e) {
				var t = $(e.target);
				var selection = getSelection();
				var selectedText = selection.toString();

				console.log(t, selection.isCollapsed, selectedText, selection);

				if ( t.is('input, textarea, button, *[contenteditable="true"]') ) {

					//currentNodeList = findNodes( selection.focusNode );
					updateBubbleStates();
				}

				// Check selections exist
				else if ( selection.isCollapsed || !selectedText) {

					onSelectorBlur();
				}

				// Text is selected
				else if ( !selection.isCollapsed && !!selectedText) {

					lastMovePos.x = e.clientX;
					lastMovePos.y = e.clientY;

					//currentNodeList = findNodes( selection.focusNode );

					// Find if highlighting is in the editable area
					//if ( hasNode( currentNodeList, "ARTICLE") ) {
						updateBubbleStates();
						updateBubblePosition();

						// Show the ui bubble
						//textOptions.className = "text-options active";
						popup.addClass('active');
					//}

					// preverse selection object
					lastSelection = selection;
				}

			};

			var updateBubblePosition = function () {
				var selection = getSelection();
				var range = selection.getRangeAt(0);
				var boundary = range.getBoundingClientRect();

				popup.css({
					top: boundary.top - popupOpts.height()*1.4,// - 5 + window.pageYOffset + "px",
					left: lastMovePos.x - popupOpts.width()/2 //(boundary.left)// + boundary.right)/2 + "px"
				});
			};

			var updateBubbleStates = function () {
				if (!lastSelection) {
					return;
				}
				eachActions(options.actions, function (action, i, a) {
					var btn = popupOpts.find('*[data-key="'+a+'"]');
					var fx = action.validNode($(lastSelection.focusNode)) ? 'addClass' : 'removeClass';
					btn[fx]('active');
				});
			};

			var onSelectorBlur = function () {

				if (popup.hasClass('active') && !popup.hasClass('fade')) {

					popup.removeClass('active').addClass('fade');

					setTimeout( function() {

						popup.removeClass('fade');

					}, 260 );
				}
			};

			elem.wrap(wrap);
			elem.after(popup);
			elem.attr('data-zenpen', id);

			elem
				.on('keyup' + namespace, checkTextHighlighting)
				//.on('mousedown' + namespace, checkTextHighlighting)
				//.on('selectstart'+ namespace, checkTextHighlighting)
				//.on('selectionchange'+ namespace, checkTextHighlighting)
				.on('mouseup' + namespace, checkTextHighlighting);

			wrap.on('scroll' + namespace, function() {
				if ( !!scrollTimeout ) {
					clearTimeout(scrollTimeout);
					scrollTimeout = 0;
				}
				scrollTimeout = setTimeout(updateBubblePosition, 100);
			});

			popup.on('click' + namespace, '*[data-key]', function () {
				var t = $(this);
				var key = t.attr('data-key');
				var action = $.zenpen.actions[key];
				if (!!action) {
					action.exec(t, popup, lastSelection);
					updateBubbleStates();
				}
			});

			popup.on('update' + namespace, updateBubbleStates);

			focus(elem);
		};
	};

	$.fn.zenpen = function (options) {
		options = $.extend(true, {}, $.zenpen.defaults, options);

		if (!$.isArray(options.actions)) {
			options.actions = options.actions.split(',');
		}

		var t = $(this);

		return t.each(zenpen(options));
	};

	$.zenpen = function (target) {
		target = target || $.zenpen.defaults.autoLoadSelector;
		target = $(target);
		target.zenpen();
	};

	$.zenpen.actions = {
		bold: {
			validNode: function (node) {
				return !!node.closest('b, strong').length;
			},
			create: createButtonFactory('bold', 'b', 'bold'),
			exec: execCommandFactory('bold', false )
		},
		italic: {
			validNode: function (node) {
				return !!node.closest('i, em').length;
			},
			create: createButtonFactory('italic', 'i', 'italic'),
			exec: execCommandFactory('italic', false )
		},
		url: {
			validNode: function (node) {
				return !!node.closest('a').length;
			},
			create: function () {
				var btn = createButtonFactory('url useicons', parseHtmlEntity(''), 'url')();
				var input = $('<input />').addClass('url-input')
					.attr('type','text')
					.attr('placeholder','Type or Paste URL here');

				var self = this;

				var realExec = function () {
					var url = input.val();

					rehighlightLastSelection(self._options.range);

					// Unlink any current links
					document.execCommand( 'unlink', false );

					if (!!url) {

						// Insert HTTP if it doesn't exist.
						if ( !url.match("^(http|https|ftp|ftps|sftp)://")
						  && !url.match("^(mailto|tel|fax|skype|irc):")
						  && !url.match("^/")  ) {
							url = "http://" + url;
						}

						document.execCommand( 'createLink', false, url );

						input.val(''); // creates a blur

						self._options.popup.trigger('update');
					}
				};

				input.keyup(function (e) {
					if (e.which === 13) {
						realExec();
					} else if (e.which === 27) {
						self.exec(self._options.btn, self._options.popup);
					}
				});

				input.blur(function (e) {
					self.exec(self._options.btn, self._options.popup);
				});

				return btn.add(input);
			},
			exec: function ( btn, popup, lastSelection ) {
				var opts = popup.find('.zenpen-options');
				var has = opts.hasClass('url-mode');
				var fx = has ? 'removeClass' : 'addClass';
				opts[fx]('url-mode');

				// save options
				if (!!lastSelection) {
					this._options = {
						btn: btn,
						popup: popup,
						range: lastSelection.getRangeAt(0)
					};
				}

				if (!has) {
					setTimeout(function () {
						popup.find('input.url-input').focus();
					}, 50);
				}
			}
		},
		quote: {
			validNode: function (node) {
				return !!node.closest('blockquote').length;
			},
			create: createButtonFactory('quote', parseHtmlEntity('”'), 'quote'),
			exec: function (btn, popup, lastSelection ) {

				if ( this.validNode($(lastSelection.focusNode)) ) {
					document.execCommand( 'formatBlock', false, 'p' );
					document.execCommand( 'outdent' );
				} else {
					document.execCommand( 'formatBlock', false, 'blockquote' );
				}
			}
		}
	};

	$.zenpen.defaults = {
		autoLoad: true,
		autoLoadSelector: '*[contenteditable="true"]',
		actions: 'url,bold,italic,quote',
	};

	var autoLoad = function () {
		if (!!$.zenpen.defaults.autoLoad) {
			$.zenpen();
		}
		if (!document.execCommand) {
			log('Your browser does not support `document.execCommand`');
		}
		if (!getSelection()) {
			log('Your browser does not support text selection');
		}
	};

	var resize = function () {
		// TODO
	};

	$(autoLoad);

	$(window).resize(resize);

})(jQuery);<commit_msg>Getting rid of the parseHtmlEntity func<commit_after>/*
 *  jQuery ZenPen
 *
 *  Copyright (c) 2013 Deux Huit Huit (http://www.deuxhuithuit.com/)
 *  Licensed under the MIT (https://github.com/DeuxHuitHuit/jQuery-zenpen/blob/master/LICENSE.txt)
 *  Based on the work of Tim Holman (https://github.com/tholman/zenpen)
 *  Licensed under the Apache License (https://github.com/tholman/zenpen/blob/master/licence.md)
 */

(function ($) {

	if (!!$.zenpen) {
		return;
	}

	var counter = 0;

	var log = !!window.console ? console.error || console.log : window.alert;

	var getSelection = function () {
		if (!!window.getSelection) {
			return window.getSelection();
		} else if (!!document.selection) {
			return document.selection;
		}
		log('No selection API found');
	};

	var focus = function (elem) {
		var range = document.createRange();
		var selection = getSelection();
		range.setStart(elem.get(0), 1);
		selection.removeAllRanges();
		selection.addRange(range);
	};

	var rehighlightLastSelection = function (lastRange) {
		if (!!lastRange) {
			var selection = getSelection();
			selection.removeAllRanges();
			selection.addRange( lastRange );
		}
	}

	var execCommandFactory = function () {
		var a = arguments;
		return function (btn, popup, lastSelection) {
			document.execCommand.apply(document, a);
		};
	};

	var createButtonFactory = function (cla, text, key) {
		return createButton = function () {
			var b = $('<button />').addClass(cla).html(text);
			if (!!key) {
				b.attr('data-key',key);
			}
			return b;
		};
	};

	var eachActions = function (actions, cb) {
		$.each(actions, function (i, a) {
			if (!!a) {
				var action = $.zenpen.actions[a];
				cb(action, i, a);
			} else {
				console.error('Action %s does not exists in `$.zenpen.actions`', a);
			}
		});
	};

	var createPopUp = function (actions) {
		var popup = $('<div />').addClass('zenpen-panel');
		var options = $('<div />').addClass('zenpen-options');
		eachActions(actions, function (action, i, a) {
			options.append(action.create());
		});
		return popup.append(options);
	};

	var zenpen = function (options) {
		return function init(index, elem) {
			elem = $(elem);

			var id = (++counter);
			var namespace = '.zenpen-' + id;
			var popup = createPopUp(options.actions);
			var popupOpts = popup.find('.zenpen-options');
			var wrap = $('<div />').addClass('zenpen-wrap');
			var scrollTimeout = 0;
			var lastSelection;
			var lastMovePos = {x:0,y:0};

			var checkTextHighlighting = function (e) {
				var t = $(e.target);
				var selection = getSelection();
				var selectedText = selection.toString();

				console.log(t, selection.isCollapsed, selectedText, selection);

				if ( t.is('input, textarea, button, *[contenteditable="true"]') ) {

					//currentNodeList = findNodes( selection.focusNode );
					updateBubbleStates();
				}

				// Check selections exist
				else if ( selection.isCollapsed || !selectedText) {

					onSelectorBlur();
				}

				// Text is selected
				else if ( !selection.isCollapsed && !!selectedText) {

					lastMovePos.x = e.clientX;
					lastMovePos.y = e.clientY;

					//currentNodeList = findNodes( selection.focusNode );

					// Find if highlighting is in the editable area
					//if ( hasNode( currentNodeList, "ARTICLE") ) {
						updateBubbleStates();
						updateBubblePosition();

						// Show the ui bubble
						//textOptions.className = "text-options active";
						popup.addClass('active');
					//}

					// preverse selection object
					lastSelection = selection;
				}

			};

			var updateBubblePosition = function () {
				var selection = getSelection();
				var range = selection.getRangeAt(0);
				var boundary = range.getBoundingClientRect();

				popup.css({
					top: boundary.top - popupOpts.height()*1.4,// - 5 + window.pageYOffset + "px",
					left: lastMovePos.x - popupOpts.width()/2 //(boundary.left)// + boundary.right)/2 + "px"
				});
			};

			var updateBubbleStates = function () {
				if (!lastSelection) {
					return;
				}
				eachActions(options.actions, function (action, i, a) {
					var btn = popupOpts.find('*[data-key="'+a+'"]');
					var fx = action.validNode($(lastSelection.focusNode)) ? 'addClass' : 'removeClass';
					btn[fx]('active');
				});
			};

			var onSelectorBlur = function () {

				if (popup.hasClass('active') && !popup.hasClass('fade')) {

					popup.removeClass('active').addClass('fade');

					setTimeout( function() {

						popup.removeClass('fade');

					}, 260 );
				}
			};

			elem.wrap(wrap);
			elem.after(popup);
			elem.attr('data-zenpen', id);

			elem
				.on('keyup' + namespace, checkTextHighlighting)
				//.on('mousedown' + namespace, checkTextHighlighting)
				//.on('selectstart'+ namespace, checkTextHighlighting)
				//.on('selectionchange'+ namespace, checkTextHighlighting)
				.on('mouseup' + namespace, checkTextHighlighting);

			wrap.on('scroll' + namespace, function() {
				if ( !!scrollTimeout ) {
					clearTimeout(scrollTimeout);
					scrollTimeout = 0;
				}
				scrollTimeout = setTimeout(updateBubblePosition, 100);
			});

			popup.on('click' + namespace, '*[data-key]', function () {
				var t = $(this);
				var key = t.attr('data-key');
				var action = $.zenpen.actions[key];
				if (!!action) {
					action.exec(t, popup, lastSelection);
					updateBubbleStates();
				}
			});

			popup.on('update' + namespace, updateBubbleStates);

			focus(elem);
		};
	};

	$.fn.zenpen = function (options) {
		options = $.extend(true, {}, $.zenpen.defaults, options);

		if (!$.isArray(options.actions)) {
			options.actions = options.actions.split(',');
		}

		var t = $(this);

		return t.each(zenpen(options));
	};

	$.zenpen = function (target) {
		target = target || $.zenpen.defaults.autoLoadSelector;
		target = $(target);
		target.zenpen();
	};

	$.zenpen.actions = {
		bold: {
			validNode: function (node) {
				return !!node.closest('b, strong').length;
			},
			create: createButtonFactory('bold', 'b', 'bold'),
			exec: execCommandFactory('bold', false )
		},
		italic: {
			validNode: function (node) {
				return !!node.closest('i, em').length;
			},
			create: createButtonFactory('italic', 'i', 'italic'),
			exec: execCommandFactory('italic', false )
		},
		url: {
			validNode: function (node) {
				return !!node.closest('a').length;
			},
			create: function () {
				var btn = createButtonFactory('url useicons', '', 'url')();
				var input = $('<input />').addClass('url-input')
					.attr('type','text')
					.attr('placeholder','Type or Paste URL here');

				var self = this;

				var realExec = function () {
					var url = input.val();

					rehighlightLastSelection(self._options.range);

					// Unlink any current links
					document.execCommand( 'unlink', false );

					if (!!url) {

						// Insert HTTP if it doesn't exist.
						if ( !url.match("^(http|https|ftp|ftps|sftp)://")
						  && !url.match("^(mailto|tel|fax|skype|irc):")
						  && !url.match("^/")  ) {
							url = "http://" + url;
						}

						document.execCommand( 'createLink', false, url );

						input.val(''); // creates a blur

						self._options.popup.trigger('update');
					}
				};

				input.keyup(function (e) {
					if (e.which === 13) {
						realExec();
					} else if (e.which === 27) {
						self.exec(self._options.btn, self._options.popup);
					}
				});

				input.blur(function (e) {
					self.exec(self._options.btn, self._options.popup);
				});

				return btn.add(input);
			},
			exec: function ( btn, popup, lastSelection ) {
				var opts = popup.find('.zenpen-options');
				var has = opts.hasClass('url-mode');
				var fx = has ? 'removeClass' : 'addClass';
				opts[fx]('url-mode');

				// save options
				if (!!lastSelection) {
					this._options = {
						btn: btn,
						popup: popup,
						range: lastSelection.getRangeAt(0)
					};
				}

				if (!has) {
					setTimeout(function () {
						popup.find('input.url-input').focus();
					}, 50);
				}
			}
		},
		quote: {
			validNode: function (node) {
				return !!node.closest('blockquote').length;
			},
			create: createButtonFactory('quote', '”', 'quote'),
			exec: function (btn, popup, lastSelection ) {

				if ( this.validNode($(lastSelection.focusNode)) ) {
					document.execCommand( 'formatBlock', false, 'p' );
					document.execCommand( 'outdent' );
				} else {
					document.execCommand( 'formatBlock', false, 'blockquote' );
				}
			}
		}
	};

	$.zenpen.defaults = {
		autoLoad: true,
		autoLoadSelector: '*[contenteditable="true"]',
		actions: 'url,bold,italic,quote',
	};

	var autoLoad = function () {
		if (!!$.zenpen.defaults.autoLoad) {
			$.zenpen();
		}
		if (!document.execCommand) {
			log('Your browser does not support `document.execCommand`');
		}
		if (!getSelection()) {
			log('Your browser does not support text selection');
		}
	};

	var resize = function () {
		// TODO
	};

	$(autoLoad);

	$(window).resize(resize);

})(jQuery);<|endoftext|>


<commit_before>var h = require('virtual-dom').h
var config = require('../config')

module.exports = Auth

function SignInButton (h) {
  var url = 'https://github.com/login/oauth/authorize?client_id=' + config.client_id + '&scope=repo&redirect_uri=' + config.redirect_uri

  return h('a.button.small', { href: url }, [
    h('i.fa.fa-github-square'),
    ' Sign in with GitHub'
  ])
}

function Profile (props) {
  var actions = props.actions
  var elements = []

  var options = {
    href: props.user.profile.html_url,
    target: '_blank'
  }

  elements.push(h('div.profile', [
    h('a', options, [
      h('img', { src: props.user.profile.avatar_url }),
      h('span', props.user.profile.name)
    ])
  ]))

  elements.push(h('a.sign-out', {
    href: '#',
    onclick: function (e) {
      e.preventDefault()
      actions.signOut(props.store)
      actions.setRoute('/')
    }
  }, 'sign out'))

  return elements
}

function Auth (props) {
  var children = []

  children.push(h('a.content-link', {
    href: '/about',
    target: '_blank'
  }, 'about'))

  children.push(h('a.content-link', {
    href: 'http://about.editdata.org',
    target: '_blank'
  }, 'docs'))

  children.push(h('a.content-link', {
    href: '/support',
    target: '_blank'
  }, 'support'))

  if (!props.user.profile) {
    children.push(SignInButton(h))
  } else if (props.user.profile) {
    children = children.concat(Profile(props))
  }

  return h('div.github-auth' + (props.user ? '.active' : ''), children)
}
<commit_msg>fix docs link<commit_after>var h = require('virtual-dom').h
var config = require('../config')

module.exports = Auth

function SignInButton (h) {
  var url = 'https://github.com/login/oauth/authorize?client_id=' + config.client_id + '&scope=repo&redirect_uri=' + config.redirect_uri

  return h('a.button.small', { href: url }, [
    h('i.fa.fa-github-square'),
    ' Sign in with GitHub'
  ])
}

function Profile (props) {
  var actions = props.actions
  var elements = []

  var options = {
    href: props.user.profile.html_url,
    target: '_blank'
  }

  elements.push(h('div.profile', [
    h('a', options, [
      h('img', { src: props.user.profile.avatar_url }),
      h('span', props.user.profile.name)
    ])
  ]))

  elements.push(h('a.sign-out', {
    href: '#',
    onclick: function (e) {
      e.preventDefault()
      actions.signOut(props.store)
      actions.setRoute('/')
    }
  }, 'sign out'))

  return elements
}

function Auth (props) {
  var children = []

  children.push(h('a.content-link', {
    href: '/about',
    target: '_blank'
  }, 'about'))

  children.push(h('a.content-link', {
    href: 'http://editdata.org',
    target: '_blank'
  }, 'docs'))

  children.push(h('a.content-link', {
    href: '/support',
    target: '_blank'
  }, 'support'))

  if (!props.user.profile) {
    children.push(SignInButton(h))
  } else if (props.user.profile) {
    children = children.concat(Profile(props))
  }

  return h('div.github-auth' + (props.user ? '.active' : ''), children)
}
<|endoftext|>


<commit_before>/**
 * Created by Scott on 2/25/2015.
 */
define(['testharness', '../lib/request', '../lib/SQLish'],
    function(harness, request, SQLish) {
        return {
            run: function () {
                "use strict";

                var db, table, query;

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    harness.assert_true(SQLish.getDB('Library') !== undefined);
                }, "CREATE DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = SQLish.dropDB('Library');
                    harness.assert_true(db && SQLish.getDB('Library') === undefined);
                }, "DROP DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    table = db.createTable('Books')('title');

                    harness.assert_true(table.hasOwnProperty('title'));
                    db = SQLish.dropDB('Library');
                }, "CREATE TABLE Books (title)");

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    db.createTable('Books')('title');
                    db.insertInto('Books')('title').values('Book of Foo');
                    query = db.select('title').from('Books')();

                    harness.assert_true(query[0].title === 'Book of Foo');
                    db = SQLish.dropDB('Library');
                }, "INSERT INTO Books (title) VALUES ('Book of Foo')");

                // setup for next test
                db = SQLish.createDB('Library');
                table = db.createTable('Books')('title');

                harness.test(function () {
                    var insertValues = db.insertInto('Books')('title').values('Alphabet Soup')('Aliens')('Baseball')('Bats')('Cats')('Soup for the Soul'),
                        testPassed = false,
                        titlesArray;

                    titlesArray = db.select('title').from('Books')();

                    testPassed = titlesArray.every(function (rowObj) {
                        var title = rowObj.title,
                            a = ['Alphabet Soup', 'Aliens', 'Baseball', 'Bats', 'Cats', 'Soup for the Soul'];

                        return title && a.indexOf(title) >= 0;
                    });

                    harness.assert_true(testPassed);
                    // do not tear down Library
                }, "INSERT INTO Books (title) VALUES ('Alphabet Soup'),('Aliens'),('Baseball'),('Bats'),('Cats'),('Soup for the Soul')");

                // next test uses prerequisites from previous test...
                harness.test(function () {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens');

                    harness.assert_true(query[0] && query[0].title === 'Aliens');
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title === 'Aliens'");

                // keep going...
                harness.test(function () {
                    var where,
                        returnSet,
                        passedTest = false;

                    query = db.select('title').from('Books');
                    where = query.where;

                    returnSet = where('title', 'like', 'soup');
                    passedTest = returnSet.length === 0;

                    if (passedTest) {
                        returnSet = where('title', 'like', '.*soup');
                        passedTest = returnSet[0].title === 'Alphabet Soup' && returnSet.length === 1;
                    }

                    if (passedTest) {
                        returnSet = where('title', 'like', 'ba.*');
                        passedTest = returnSet[0].title === 'Baseball' && returnSet[1].title === 'Bats' && returnSet.length === 2;
                    }

                    if (passedTest) {
                        returnSet = where('title', 'like', '.*ou.*ou.*');
                        passedTest = returnSet[0].title === 'Soup for the Soul' && returnSet.length === 1;
                    }

                    harness.assert_true(passedTest);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title LIKE %ou%ou%  => plus 3 more 'LIKE' tests");

                harness.test(function () {
                    var where = query.where,
                        returnSet,
                        passedTest = false;

                    returnSet = where('title', 'not like', '.*b.*');
                    passedTest = returnSet[0].title === 'Aliens' && returnSet[1].title === 'Cats' && returnSet[2].title === 'Soup for the Soul' && returnSet.length === 3;

                    harness.assert_true(passedTest);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title NOT LIKE %b%");
            }
        };
    }
);
<commit_msg>select all * test<commit_after>/**
 * Created by Scott on 2/25/2015.
 */
define(['testharness', '../lib/request', '../lib/SQLish'],
    function(harness, request, SQLish) {
        return {
            run: function () {
                "use strict";

                var db, table, query;

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    harness.assert_true(SQLish.getDB('Library') !== undefined);
                }, "CREATE DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = SQLish.dropDB('Library');
                    harness.assert_true(db && SQLish.getDB('Library') === undefined);
                }, "DROP DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    table = db.createTable('Books')('title');

                    harness.assert_true(table.hasOwnProperty('title'));
                    db = SQLish.dropDB('Library');
                }, "CREATE TABLE Books (title)");

                harness.test(function () {
                    db = SQLish.createDB('Library');
                    db.createTable('Books')('title');
                    db.insertInto('Books')('title').values('Book of Foo');
                    query = db.select('title').from('Books')();

                    harness.assert_true(query[0].title === 'Book of Foo');
                    db = SQLish.dropDB('Library');
                }, "INSERT INTO Books (title) VALUES ('Book of Foo')");

                // setup for next test
                db = SQLish.createDB('Library');
                table = db.createTable('Books')('title');

                harness.test(function () {
                    var insertValues = db.insertInto('Books')('title').values('Alphabet Soup')('Aliens')('Baseball')('Bats')('Cats')('Soup for the Soul'),
                        testPassed = false,
                        titlesArray;

                    titlesArray = db.select('title').from('Books')();

                    testPassed = titlesArray.every(function (rowObj) {
                        var title = rowObj.title,
                            a = ['Alphabet Soup', 'Aliens', 'Baseball', 'Bats', 'Cats', 'Soup for the Soul'];

                        return title && a.indexOf(title) >= 0;
                    });

                    harness.assert_true(testPassed);
                    // do not tear down Library
                }, "INSERT INTO Books (title) VALUES ('Alphabet Soup'),('Aliens'),('Baseball'),('Bats'),('Cats'),('Soup for the Soul')");

                // next test uses prerequisites from previous test...
                harness.test(function () {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens');

                    harness.assert_true(query[0] && query[0].title === 'Aliens');
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title === 'Aliens'");

                // keep going...
                harness.test(function () {
                    var where,
                        returnSet,
                        passedTest = false;

                    query = db.select('title').from('Books');
                    where = query.where;

                    returnSet = where('title', 'like', 'soup');
                    passedTest = returnSet.length === 0;

                    if (passedTest) {
                        returnSet = where('title', 'like', '.*soup');
                        passedTest = returnSet[0].title === 'Alphabet Soup' && returnSet.length === 1;
                    }

                    if (passedTest) {
                        returnSet = where('title', 'like', 'ba.*');
                        passedTest = returnSet[0].title === 'Baseball' && returnSet[1].title === 'Bats' && returnSet.length === 2;
                    }

                    if (passedTest) {
                        returnSet = where('title', 'like', '.*ou.*ou.*');
                        passedTest = returnSet[0].title === 'Soup for the Soul' && returnSet.length === 1;
                    }

                    harness.assert_true(passedTest);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title LIKE %ou%ou%  => plus 3 more 'LIKE' tests");

                harness.test(function () {
                    var where = query.where,
                        returnSet,
                        passedTest = false;

                    returnSet = where('title', 'not like', '.*b.*');
                    passedTest = returnSet[0].title === 'Aliens' && returnSet[1].title === 'Cats' && returnSet[2].title === 'Soup for the Soul' && returnSet.length === 3;

                    harness.assert_true(passedTest);
                    // do not tear down Library
                }, "SELECT title FROM Books WHERE title NOT LIKE %b%");

                harness.test(function () {
                    query = db.select('*').from('Books')();

                    harness.assert_true(query.length === 6);
                    // do not tear down Library
                }, "SELECT * FROM Books");
            }
        };
    }
);
<|endoftext|>


<commit_before>// ----------------------------------------------------------------------------
//
// browserid-verify.js - remote or local verification of a browserid assertion
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// ----------------------------------------------------------------------------

// core
var https = require('https');
var http  = require('http');
var querystring = require('querystring');
var url = require('url');

// ----------------------------------------------------------------------------

const VERIFIER_METHOD = 'POST';
const VERIFIER_URL    = 'https://verifier.login.persona.org/verify';

// ----------------------------------------------------------------------------

function browserIdVerify(opts) {
    // set some defaults
    opts      = opts      || {};
    opts.type = opts.type || 'remote';
    opts.url  = opts.url  || VERIFIER_URL;

    // firstly, parse the url
    var parsedUrl = url.parse(opts.url);

    // var httpPkg = opts.
    var protocol;
    if ( parsedUrl.protocol === 'https:' ) {
        protocol = https;
    }
    else if ( parsedUrl.protocol === 'http:' ) {
        protocol = http;
    }
    else {
        throw new Error("url protocol must be 'https:' or 'http:', not '" + parsedUrl.protocol + "'");
    }

    // return the remote verifier
    if ( opts.type === 'remote' ) {
        return function verifyRemotely(assertion, audience, callback) {
            if (typeof callback !== 'function') throw "missing required callback argument";

            if (typeof assertion !== 'string' ) {
                process.nextTick(function() {
                    callback('assertion should be a string');
                });
                return;
            }

            if (typeof audience !== 'string' ) {
                process.nextTick(function() {
                    callback('audience should be a string');
                });
                return;
            }

            // hit the remote verifier
            var reqOpts = {
                method   : VERIFIER_METHOD,
                hostname : parsedUrl.hostname,
                path     : parsedUrl.path,
                port     : parsedUrl.port,
            };

            if ( opts.agent ) {
                reqOpts.agent = opts.agent;
            }

            var req = protocol.request(reqOpts, function(resp) {
                // if the statusCode isn't what we expect, get out of here
                if ( resp.statusCode !== 200 ) {
                    return callback(new Error("Remote verifier returned a non-200 status code : " + resp.statusCode));
                }

                // collect up the returned body
                var body = "";

                resp
                    .on('data', function(chunk) {
                        body += chunk;
                    })
                    .on('end', function() {
                        var response;

                        // catch any errors when parsing the returned JSON
                        try {
                            response = JSON.parse(body);
                        } catch(e) {
                            return callback(new Error("Remote verifier did not return JSON."));
                        }

                        if ( !response ) {
                            return callback(new Error("Remote verifier did not return any data."));
                        }

                        // Here, we're passing back the entire reponse since it should be up to
                        // if they want to do anything with any of the other fields
                        // (e.g. issuer, expires, etc).
                        return callback(null, response.email, response);
                    })
                ;
            });

            req.setHeader('Content-Type', 'application/x-www-form-urlencoded');

            var data = querystring.stringify({
                assertion : assertion,
                audience  : audience,
            });

            req.setHeader('Content-Length', data.length);
            req.write(data);
            req.end();
        };
    }

    // return the local verifier
    if ( opts.type === 'local' ) {
        throw new Error("Program error: local verification is not yet implemented. Please use 'remote' verification.");
    }

    // don't know what this type is
    throw new Error('Unknown verifier type : ' + opts.type);
}

// ----------------------------------------------------------------------------
// export the creator function

module.exports = browserIdVerify;

// ----------------------------------------------------------------------------
<commit_msg>The opts.url is only used for remote verification<commit_after>// ----------------------------------------------------------------------------
//
// browserid-verify.js - remote or local verification of a browserid assertion
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// ----------------------------------------------------------------------------

// core
var https = require('https');
var http  = require('http');
var querystring = require('querystring');
var url = require('url');

// ----------------------------------------------------------------------------

const VERIFIER_METHOD = 'POST';
const VERIFIER_URL    = 'https://verifier.login.persona.org/verify';

// ----------------------------------------------------------------------------

function browserIdVerify(opts) {
    // set some defaults
    opts      = opts      || {};
    opts.type = opts.type || 'remote';
    opts.url  = opts.url  || VERIFIER_URL;

    // return the remote verifier
    if ( opts.type === 'remote' ) {

        // firstly, parse the url
        var parsedUrl = url.parse(opts.url);

        // var httpPkg = opts.
        var protocol;
        if ( parsedUrl.protocol === 'https:' ) {
            protocol = https;
        }
        else if ( parsedUrl.protocol === 'http:' ) {
            protocol = http;
        }
        else {
            throw new Error("url protocol must be 'https:' or 'http:', not '" + parsedUrl.protocol + "'");
        }

        return function verifyRemotely(assertion, audience, callback) {
            if (typeof callback !== 'function') throw "missing required callback argument";

            if (typeof assertion !== 'string' ) {
                process.nextTick(function() {
                    callback('assertion should be a string');
                });
                return;
            }

            if (typeof audience !== 'string' ) {
                process.nextTick(function() {
                    callback('audience should be a string');
                });
                return;
            }

            // hit the remote verifier
            var reqOpts = {
                method   : VERIFIER_METHOD,
                hostname : parsedUrl.hostname,
                path     : parsedUrl.path,
                port     : parsedUrl.port,
            };

            if ( opts.agent ) {
                reqOpts.agent = opts.agent;
            }

            var req = protocol.request(reqOpts, function(resp) {
                // if the statusCode isn't what we expect, get out of here
                if ( resp.statusCode !== 200 ) {
                    return callback(new Error("Remote verifier returned a non-200 status code : " + resp.statusCode));
                }

                // collect up the returned body
                var body = "";

                resp
                    .on('data', function(chunk) {
                        body += chunk;
                    })
                    .on('end', function() {
                        var response;

                        // catch any errors when parsing the returned JSON
                        try {
                            response = JSON.parse(body);
                        } catch(e) {
                            return callback(new Error("Remote verifier did not return JSON."));
                        }

                        if ( !response ) {
                            return callback(new Error("Remote verifier did not return any data."));
                        }

                        // Here, we're passing back the entire reponse since it should be up to
                        // if they want to do anything with any of the other fields
                        // (e.g. issuer, expires, etc).
                        return callback(null, response.email, response);
                    })
                ;
            });

            req.setHeader('Content-Type', 'application/x-www-form-urlencoded');

            var data = querystring.stringify({
                assertion : assertion,
                audience  : audience,
            });

            req.setHeader('Content-Length', data.length);
            req.write(data);
            req.end();
        };
    }

    // return the local verifier
    if ( opts.type === 'local' ) {
        throw new Error("Program error: local verification is not yet implemented. Please use 'remote' verification.");
    }

    // don't know what this type is
    throw new Error('Unknown verifier type : ' + opts.type);
}

// ----------------------------------------------------------------------------
// export the creator function

module.exports = browserIdVerify;

// ----------------------------------------------------------------------------
<|endoftext|>


<commit_before>var conjectures = [];

function guessIncidences(el) {
    if (guessIncidences.hasOwnProperty(el.kind))
        guessIncidences[el.kind](el);
}

guessIncidences.P = function(p) {
    csgeo.lines.forEach(function(l) {
        var conjecture = incidentPL(p, l);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
    csgeo.conics.forEach(function(c) {
        var conjecture = incidentPC(p, c);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

guessIncidences.L = function(l) {
    csgeo.points.forEach(function(p) {
        var conjecture = incidentPL(p, l);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

guessIncidences.S = guessIncidences.L;

guessIncidences.C = function(c) {
    csgeo.points.forEach(function(p) {
        var conjecture = incidentPC(p, c);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

function applyIncidence(a, b) {
    return function() {
        a.incidences.push(b.name);
        b.incidences.push(a.name);
    };
}

function incidentPL(p, l) {
    return {
        toString: function() {
            return "point " + p.name + " incident line " + l.name;
        },
        apply: applyIncidence(p, l),
        holds: function() {
            var pn = List.scaldiv(List.abs(p.homog), p.homog);
            var ln = List.scaldiv(List.abs(l.homog), l.homog);
            var prod = CSNumber.abs(List.scalproduct(pn, ln));
            return (prod.value.real < 0.0000000000001);
        }
    };
}

function incidentPC(p, c) {
    return {
        toString: function() {
            return "point " + p.name + " incident conic " + c.name;
        },
        apply: applyIncidence(p, c),
        holds: function() {
            var erg = General.mult(c.matrix, p.homog);
            erg = General.mult(p.homog, erg);
            erg = CSNumber.abs(erg);
            return (erg.value.real < 0.0000000000001);
        }
    };
}

function checkConjectures() {
    var debug = true;
    console.log(conjectures);
    if (conjectures.length === 0) return;
    //    debugger;
    backupGeo();
    // TODO: we need some randomized proving here:
    // move free elements and check conjectures a number of times.
    // For now assume that all conjectures could be verified.

    var ii, jj, kk;
    var free = csgeo.free;
    var newpos, el;
    var nummoves = 3;

    // debug code remove later
    var nconject = conjectures.length;
    csgeo.free.forEach(function(el) {
        jj = nummoves;
        while (jj--) {
            if (el.kind === "C") break; // no conic movement currently
            if (el.pinned) {
                if (debug) console.log("element ", el.name, "is pinned");
                break;
            }
            if (debug) console.log("prover: moving element", el.name);
            newpos = geoOps[el.type].getRandomMove(el);
            movepointscr(el, newpos, "homog");
            // check if conjecture still holds
            conjectures = conjectures.filter(function(con) {
                return con.holds();
            });
        }
    });
    if (debug) {
        console.log("dropped ", nconject - conjectures.length, " conjectures");
    }

    restoreGeo();

    for (var i = 0; i < conjectures.length; ++i) {
        conjectures[i].apply();
    }
    conjectures = [];
}
<commit_msg>more debug code<commit_after>var conjectures = [];

function guessIncidences(el) {
    if (guessIncidences.hasOwnProperty(el.kind))
        guessIncidences[el.kind](el);
}

guessIncidences.P = function(p) {
    csgeo.lines.forEach(function(l) {
        var conjecture = incidentPL(p, l);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
    csgeo.conics.forEach(function(c) {
        var conjecture = incidentPC(p, c);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

guessIncidences.L = function(l) {
    csgeo.points.forEach(function(p) {
        var conjecture = incidentPL(p, l);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

guessIncidences.S = guessIncidences.L;

guessIncidences.C = function(c) {
    csgeo.points.forEach(function(p) {
        var conjecture = incidentPC(p, c);
        if (conjecture.holds())
            conjectures.push(conjecture);
    });
};

function applyIncidence(a, b) {
    return function() {
        a.incidences.push(b.name);
        b.incidences.push(a.name);
    };
}

function incidentPL(p, l) {
    return {
        toString: function() {
            return "point " + p.name + " incident line " + l.name;
        },
        apply: applyIncidence(p, l),
        holds: function() {
            var pn = List.scaldiv(List.abs(p.homog), p.homog);
            var ln = List.scaldiv(List.abs(l.homog), l.homog);
            var prod = CSNumber.abs(List.scalproduct(pn, ln));
            return (prod.value.real < 0.0000000000001);
        }
    };
}

function incidentPC(p, c) {
    return {
        toString: function() {
            return "point " + p.name + " incident conic " + c.name;
        },
        apply: applyIncidence(p, c),
        holds: function() {
            var erg = General.mult(c.matrix, p.homog);
            erg = General.mult(p.homog, erg);
            erg = CSNumber.abs(erg);
            return (erg.value.real < 0.0000000000001);
        }
    };
}

function checkConjectures() {
    var debug = true;
    console.log(conjectures);
    if (conjectures.length === 0) return;
    //    debugger;
    backupGeo();
    // TODO: we need some randomized proving here:
    // move free elements and check conjectures a number of times.
    // For now assume that all conjectures could be verified.

    var ii, jj, kk;
    var free = csgeo.free;
    var newpos, el;
    var nummoves = 3;

    // debug code remove later
    var nconject = conjectures.length;
    csgeo.free.forEach(function(el) {
        jj = nummoves;
        while (jj--) {
            if (el.kind === "C") break; // no conic movement currently
            if (el.pinned) {
                if (debug) console.log("element ", el.name, "is pinned");
                break;
            }
            if (debug) console.log("prover: moving element", el.name);
            newpos = geoOps[el.type].getRandomMove(el);
            movepointscr(el, newpos, "homog");
            // check if conjecture still holds
            conjectures = conjectures.filter(function(con) {
                return con.holds();
            });
        }
    });
    if (debug) {
        console.log("dropped ", nconject - conjectures.length, " conjectures");
    }

    restoreGeo();

    for (var i = 0; i < conjectures.length; ++i) {
        conjectures[i].apply();
    }
    conjectures = [];
    if(debug){
    csgeo.gslp.forEach(function(el){
        console.log(el.name, el.incidences);
    }
    );
    }
}
<|endoftext|>


<commit_before>// this class is not really related to a sampleToc but can be used for any TOC

import API from 'src/util/api';
import Versioning from 'src/util/versioning';

let defaultOptions = {
  group: 'all',
  varName: 'sampleToc',
  viewName: 'sample_toc',
  filter: (entry) => entry.value.hidden === false,
  sort: (a, b) => {
    if (a.value.modificationDate > b.value.modificationDate) {
      return -1;
    } else if (a.value.modificationDate < b.value.modificationDate) {
      return 1;
    } else {
      return 0;
    }
  }
};

class SampleToc {
  /**
   * Create an object managing the Toc
   * @param {object} [options={}]
   * @param {object} [roc=undefined]
   * @param {string} [options.group='mine'] Group to retrieve products. mine, all of a specific group name
   * @param {string} [options.varName='sampleToc']
   * @param {string} [options.viewName='sample_toc']
   * @param {function} [options.sort] Callback, by default sort by reverse date
   * @param {function} [options.filter] Callback to filter the result
   */
  constructor(roc, options = {}) {
    this.roc = roc;
    this.options = Object.assign({}, defaultOptions, options);
  }

  setFilter(filter) {
    this.options.filter = filter;
    return this.refresh();
  }

  /**
   * Retrieve the sample_toc and put the result in `sampleToc` variable
   *
   */
  refresh(options = {}) {
    console.log('Refresh sampleToc');
    let { group, sort, filter, viewName } = Object.assign(
      {},
      this.options,
      options
    );
    let mine = 0;
    let groups = '';
    group = String(group);
    if (group === 'mine') {
      mine = 1;
    } else if (group !== 'all') {
      groups = group;
    }

    return this.roc
      .query(viewName, {
        groups,
        mine,
        sort,
        filter,
        varName: this.options.varName
      })
      .then((entries) => {
        if (this.options.callback) {
          entries.forEach(this.options.callback);
        }
        return entries;
      });
  }

  /**
   * Retrieve the allowed groups for the logged in user and create 'groupForm'
   * variable and 'groupFormSchema' (for onde module). It will keep in a cookie
   * the last selected group. Calling this method should reload automatically
   * @param {object} [options={}]
   * @param {string} [varName='groupForm'] contains the name of the variable containing the form value
   * @param {string} [schemaVarName='groupFormSchema'] contains the name of the variable containing the form schema
   * @param {string} [cookieName='eln-default-sample-group''] cookie name containing the last selected group
   * @param {string} [filter] filter applied on first refresh
   * @param {string} [autoRefresh=true] refresh least after initialization
   * @return {string} the form to select group}
   */
  async initializeGroupForm(options = {}) {
    const {
      schemaVarName = 'groupFormSchema',
      varName = 'groupForm',
      cookieName = 'eln-default-sample-group',
      filter,
      autoRefresh = true
    } = options;

    let groups = (await this.roc.getGroupMembership()).map((g) => g.name);
    var possibleGroups = ['all', 'mine'].concat(groups);
    var defaultGroup = localStorage.getItem(cookieName);
    if (possibleGroups.indexOf(defaultGroup) === -1) {
      defaultGroup = 'all';
    }
    var schema = {
      type: 'object',
      properties: {
        group: {
          type: 'string',
          enum: possibleGroups,
          default: defaultGroup,
          required: true
        }
      }
    };
    API.createData(schemaVarName, schema);

    let groupForm = await API.createData(varName, { group: defaultGroup });

    this.options.group = groupForm.group;
    if (autoRefresh) {
      await this.refresh(filter);
    }
    let mainData = Versioning.getData();
    mainData.onChange((evt) => {
      if (evt.jpath[0] === varName) {
        localStorage.setItem(cookieName, groupForm.group);
        this.options.group = String(groupForm.group);
      }
    });

    return groupForm;
  }
}

module.exports = SampleToc;
<commit_msg>feat(SampleToc): refresh list on groupName change<commit_after>// this class is not really related to a sampleToc but can be used for any TOC

import API from 'src/util/api';
import Versioning from 'src/util/versioning';

let defaultOptions = {
  group: 'all',
  varName: 'sampleToc',
  viewName: 'sample_toc',
  filter: (entry) => entry.value.hidden === false,
  sort: (a, b) => {
    if (a.value.modificationDate > b.value.modificationDate) {
      return -1;
    } else if (a.value.modificationDate < b.value.modificationDate) {
      return 1;
    } else {
      return 0;
    }
  }
};

class SampleToc {
  /**
   * Create an object managing the Toc
   * @param {object} [options={}]
   * @param {object} [roc=undefined]
   * @param {string} [options.group='mine'] Group to retrieve products. mine, all of a specific group name
   * @param {string} [options.varName='sampleToc']
   * @param {string} [options.viewName='sample_toc']
   * @param {function} [options.sort] Callback, by default sort by reverse date
   * @param {function} [options.filter] Callback to filter the result
   */
  constructor(roc, options = {}) {
    this.roc = roc;
    this.options = Object.assign({}, defaultOptions, options);
  }

  setFilter(filter) {
    this.options.filter = filter;
    return this.refresh();
  }

  /**
   * Retrieve the sample_toc and put the result in `sampleToc` variable
   *
   */
  refresh(options = {}) {
    console.log('Refresh sampleToc');
    let { group, sort, filter, viewName } = Object.assign(
      {},
      this.options,
      options
    );
    let mine = 0;
    let groups = '';
    group = String(group);
    if (group === 'mine') {
      mine = 1;
    } else if (group !== 'all') {
      groups = group;
    }

    return this.roc
      .query(viewName, {
        groups,
        mine,
        sort,
        filter,
        varName: this.options.varName
      })
      .then((entries) => {
        if (this.options.callback) {
          entries.forEach(this.options.callback);
        }
        return entries;
      });
  }

  /**
   * Retrieve the allowed groups for the logged in user and create 'groupForm'
   * variable and 'groupFormSchema' (for onde module). It will keep in a cookie
   * the last selected group. Calling this method should reload automatically
   * @param {object} [options={}]
   * @param {string} [varName='groupForm'] contains the name of the variable containing the form value
   * @param {string} [schemaVarName='groupFormSchema'] contains the name of the variable containing the form schema
   * @param {string} [cookieName='eln-default-sample-group''] cookie name containing the last selected group
   * @param {string} [filter] filter applied on first refresh
   * @param {string} [autoRefresh=true] refresh least after initialization
   * @return {string} the form to select group}
   */
  async initializeGroupForm(options = {}) {
    const {
      schemaVarName = 'groupFormSchema',
      varName = 'groupForm',
      cookieName = 'eln-default-sample-group',
      filter,
      autoRefresh = true
    } = options;

    let groups = (await this.roc.getGroupMembership()).map((g) => g.name);
    var possibleGroups = ['all', 'mine'].concat(groups);
    var defaultGroup = localStorage.getItem(cookieName);
    if (possibleGroups.indexOf(defaultGroup) === -1) {
      defaultGroup = 'all';
    }
    var schema = {
      type: 'object',
      properties: {
        group: {
          type: 'string',
          enum: possibleGroups,
          default: defaultGroup,
          required: true
        }
      }
    };
    API.createData(schemaVarName, schema);

    let groupForm = await API.createData(varName, { group: defaultGroup });

    this.options.group = groupForm.group;
    if (autoRefresh) {
      await this.refresh(filter);
    }
    let mainData = Versioning.getData();
    mainData.onChange((evt) => {
      if (evt.jpath[0] === varName) {
        localStorage.setItem(cookieName, groupForm.group);
        this.options.group = String(groupForm.group);
        this.refresh();
      }
    });

    return groupForm;
  }
}

module.exports = SampleToc;
<|endoftext|>