<commit_before>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

 define([
    'angular',
    './module'
],
function(angular) {
    'use strict';
    /**
     * Name of the scope variable where the freetype data will be stored.
     */
    const SCOPE_FREETYPEDATA = 'freetypeData'
    /**
     * Generation of new index.
     */
    var index = 0;
    function getNewIndex(string) {
        index = index + 1;
        return string + '__' + index;
    }
    /**
     * Makes the form text input with angular model freetypeData.name.
     * also add the attributes from the tag, needed in case of classes or styles.
     */
    function makeAngularAttr(name, attr) {
        attr = attr || '';
        // remove any trailing `/` character from attr.
        // the trailing character is composed.
        if (attr.substr(attr.length - 1, 1) === '/') {
            attr = attr.substr(0, attr.length - 1);
        }
        if (name.substr(0, 1) === '$') {
            return '"' + name.substr(1).replace('[]', '[0]') + '" ' + attr;
        } else {
            return '"' + SCOPE_FREETYPEDATA + '.' + name.replace('[]', '[0]') + '" ' + attr;
        }
    }
    /**
    * Sets and gets the obj from path.
    *    this is needed to create the vectors in the angular scope.
    */
    function path2obj(obj, path, value) {
        if (path.substr(0, 1) === '$') {
            return;
        }
        var parts, part, vector;
        if (angular.isString(path)) {
            parts = path.split(/\./);
            for (var i = 0, variable = obj; i< parts.length; i++){
                if (parts[i].indexOf('[') !== -1) {
                    vector = parts[i].match(/([^\]]*)\[([^\]]*)]/);
                    if (parseInt(vector[2], 10) == vector[2]) {
                        vector[2] = parseInt(vector[2], 10);
                    }
                    part = {};
                    // if the array is already set, just use that.
                    if (angular.isArray(variable[vector[1]])){
                        // is the array is set but not that index, make it.
                        if (angular.isDefined(variable[vector[1]][vector[2]])) {
                            variable = variable[vector[1]][vector[2]]
                        } else {
                            variable[vector[1]][vector[2]] = part
                            variable = part;
                        }
                    } else {
                        variable[vector[1]] = [];
                        variable[vector[1]][vector[2]] = part
                        variable = part;
                    }
                } else {
                    // if the object is already set, just use that.
                    if (angular.isDefined(variable[parts[i]])) {
                        variable = variable[parts[i]];
                        if (i === parts.length - 1) {
                            return variable;
                        }
                    } else if (i === parts.length - 1){
                        variable[parts[i]] = value || '';
                    } else {
                        variable[parts[i]] = {};
                        variable = variable[parts[i]];
                    }
                }
            }
        }
    }
    /**
    * Create a list of paths from `obj` parameter and return it in the
    * `ret` parameter
    */
    function obj2path(ret, obj, path) {
        ret = ret || {};
        var gotopath, path;
        angular.forEach(obj, function(value, key) {
            if (angular.isArray(value)) {
                for (var i = 0; i< value.length; i++) {
                    gotopath = path? path + '.' + key + '[' + i + ']' : key + '[' + i + ']';
                    obj2path(ret, value[i], gotopath);
                }
            } else if (angular.isObject(value)) {
                gotopath = path? path + '.' + key : key;
                obj2path(ret, value, gotopath);
            } else {
                gotopath = path? path + '.' + key : key;
                ret[gotopath] = value;
            }
        });
    }
    /**
     * Inject `class` in the class attributes string.
     */
    function injectClass(attr, cls) {
        if (attr.indexOf('class') > -1) {
            return attr.replace(/class\w*=\w*("|')?([^\"\']+)("|')/, 'class="' + cls + ' $2"');
        } else {
            attr += 'class="' + cls + '" ';
            return attr;
        }
    }

    angular.module('liveblog.edit')
    .factory('freetypeService', ['$q', function ($q) {
        return {
            /**
            * transformation method from dorla sign template to angular template
            * also requires `scope` object so that the proper object with the data is set.
            *     this is special case for vector array.
            */
            transform: function(template, scope) {
                if (!angular.isObject(scope[SCOPE_FREETYPEDATA])) {
                    scope[SCOPE_FREETYPEDATA] = {};
                }
                // transform collection mechaism for `scorers` or for dinamical lists.
                template = template.replace(/\
]*)\>(.*?)\<\/li\>/g, function(all, attr, repeater) {
                    var iteratorName = getNewIndex('iterator');
                    var parts, vector = '';
                    repeater = repeater.replace(/\$([\$a-z0-9_.\[\]]+)/gi, function(all, path) {
                        path2obj(scope[SCOPE_FREETYPEDATA], path);
                        parts = path.split(/[\d*]/);
                        if (parts.length === 2 && parts[1] != '') {
                            vector = parts[0].substr(0, parts[0].length - 1);
                            return '$$' + iteratorName + '.' + parts[1].substr(2);
                        } else {
                            return all;
                        }
                    });
                    return '
' +
                            repeater + '<freetype-collection-remove index="$index" vector="' + SCOPE_FREETYPEDATA + '.' + vector + '"/>' +
                            '

<freetype-collection-add vector="' + SCOPE_FREETYPEDATA + '.' + vector + '"/>
';
                });
                // transform dollar variables in the attributes of `name` or `text` in any standalone tag .
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name;
                    attr = attr.replace(/(name|text)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        // remove the dollar variable from the attributes.
                        return '';
                    });
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name);
                        return '<input ng-model=' + makeAngularAttr(name, attr) + '/>';
                    }
                    return all;
                });
                // transform dollar variables in content of any start to end tag.
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>(.*?)<\/\1>?/gi, function(all, tag, attr, content) {
                    var name, parts;
                    content = content.replace(/^\s+|\s+$/g, '');
                    parts = content.match(/^\$([\$a-z0-9]+)/gi);
                    // content should be only the variable name
                    if (parts && parts[0].length === content.length) {
                        name = content.substr(1);
                    }
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name);
                        return '<input ng-model=' + makeAngularAttr(name, attr) + '/>';
                    }
                    return all;
                });
                // transform dollar variables in the attributes of `image` in any standalone tag .
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name;
                    attr = attr.replace(/(image|graphic|rendition)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        // remove the dollar variable from the attributes.
                        return '';
                    });
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name + '.picture_url');
                        return '<freetype-image image=' + makeAngularAttr(name, attr) + '></freetype-image>';
                    }
                    return all;
                });
                // transform dollar variables in the attributes of `link` in any standalone tag .
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name;
                    attr = attr.replace(/(link|url)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        // remove the dollar variable from the attributes.
                        return '';
                    });
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name);
                        return '<freetype-link link=' + makeAngularAttr(name, attr) + '></freetype-link>';
                    }
                    return all;
                });
                // transform dollar variables in the attributes of `embed` in any standalone tag .
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name;
                    attr = attr.replace(/(embed|html)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        // remove the dollar variable from the avem o problema, attributes.
                        return '';
                    });
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name);
                        return '<freetype-embed embed=' + makeAngularAttr(name, attr) + '></freetype-embed>';
                    }
                    return all;
                });
                return template;

            },
            htmlContent: function(template, data) {
                var paths = {},
                    path,
                    wrapBefore = '',
                    wrapAfter = '';
                obj2path(paths, data);
                template = template.replace(/\
]*)\>(.*?)\<\/li\>/g, function(all, attr, repeater) {
                    var vector, vectorPath, parts, templ = '', emptyVars = true;
                    repeater = repeater.replace(/\$([\$a-z0-9_.\[\]]+)/gi, function(all, path) {
                        parts = path.split(/[\d*]/);
                        if (parts.length === 2 && parts[1] != '') {
                            vectorPath = parts[0].substr(0, parts[0].length - 1);
                            return all;
                        } else {
                            return all;
                        }
                    });
                    if (vectorPath) {
                        vector = path2obj(data, vectorPath);
                        for (var i = 1; i< vector.length; i++) {
                            templ += '
' + repeater.replace('[]', '[0]').replace(/\$([\$a-z0-9_.\[\]]+)/gi, function(all) {
                                return all.replace('[]', '[0]').replace('[0]', '[' + i  + ']');
                            }) + '
';
                        }
                        repeater.replace('[]', '[0]').replace(/\$([\$a-z0-9_.\[\]]+)/gi, function(all, name) {
                            if (vector[0][name.replace(vectorPath + '[0].', '')]) {
                                emptyVars = false;
                            } else {
                                emptyVars = emptyVars && true;
                            }
                        });
                        if (emptyVars) {
                            return '';
                        } else {
                            return all.replace('[]', '[0]') + templ;
                        }
                    }
                    return all.replace('[]', '[0]');
                });
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name, type;
                    // transform `name` and `text` variables.
                    attr = attr.replace(/(name|text)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        type = 'text';
                        // remove the dollar variable from the attributes.
                        return '';
                    });

                    attr = attr.replace(/(image|graphic|rendition)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname + '.picture_url';
                        type = 'image';
                        // remove the dollar variable from the attributes.
                        return '';
                    });

                    attr = attr.replace(/(wrap-link)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        type = 'wrap-link';
                        // remove the dollar variable from the attributes.
                        return '';
                    });

                    attr = attr.replace(/(embed)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        type = 'embed';
                        // remove the dollar variable from the attributes.
                        return '';
                    });

                    if (name || type) {
                        switch (type) {
                            case 'text':
                                if (paths[name]) {
                                    return '' + paths[name] + '';
                                } else {
                                   return '';
                                }
                                break;

                            case 'image':
                                if (paths[name]) {
                                    return ''
                                } else {
                                   return '';
                                }
                                break;

                            case 'embed':
                                if (paths[name]) {
                                    return paths[name]
                                } else {
                                   return '';
                                }
                                break;

                            case 'wrap-link':
                                if (paths[name]) {
                                    wrapBefore = '';
                                    wrapAfter = ''
                                }
                                return '';
                                break;
                        }
                    }
                    return all;
                });
                template = (function recursiveContent(template) {
                    template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>(.*?)<\/\1>?/gi, function(all, tag, attr, content) {
                        if (content) {
                            content = recursiveContent(content);
                        }
                        var name, type;
                        attr = attr.replace(/hide-render/gi, function(match, tag, quote, rname) {
                            type = 'hide-render';
                            // remove the dollar variable from the attributes.
                            return '';
                        });
                        if (name || type) {
                            switch (type) {
                                case 'text':
                                    if (paths[name]) {
                                        return '' + paths[name] + '';
                                    } else {
                                       return '';
                                    }
                                    break;
                                case 'hide-render': {
                                    return '';
                                    break;
                                }
                            }
                        }
                        return '<' + tag + attr + '>' + content + '</' + tag + '>';
                    });
                    return template;
                })(template);
                return wrapBefore + template + wrapAfter;
            }
        };
    }]);
});

<commit_msg>fix: escape input text.<commit_after>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

 define([
    'angular',
    './module'
],
function(angular) {
    'use strict';
    /**
     * Name of the scope variable where the freetype data will be stored.
     */
    const SCOPE_FREETYPEDATA = 'freetypeData'
    /**
     * Generation of new index.
     */
    var index = 0;
    function getNewIndex(string) {
        index = index + 1;
        return string + '__' + index;
    }
    /**
     * Makes the form text input with angular model freetypeData.name.
     * also add the attributes from the tag, needed in case of classes or styles.
     */
    function makeAngularAttr(name, attr) {
        attr = attr || '';
        // remove any trailing `/` character from attr.
        // the trailing character is composed.
        if (attr.substr(attr.length - 1, 1) === '/') {
            attr = attr.substr(0, attr.length - 1);
        }
        if (name.substr(0, 1) === '$') {
            return '"' + name.substr(1).replace('[]', '[0]') + '" ' + attr;
        } else {
            return '"' + SCOPE_FREETYPEDATA + '.' + name.replace('[]', '[0]') + '" ' + attr;
        }
    }
    /**
    * Sets and gets the obj from path.
    *    this is needed to create the vectors in the angular scope.
    */
    function path2obj(obj, path, value) {
        if (path.substr(0, 1) === '$') {
            return;
        }
        var parts, part, vector;
        if (angular.isString(path)) {
            parts = path.split(/\./);
            for (var i = 0, variable = obj; i< parts.length; i++){
                if (parts[i].indexOf('[') !== -1) {
                    vector = parts[i].match(/([^\]]*)\[([^\]]*)]/);
                    if (parseInt(vector[2], 10) == vector[2]) {
                        vector[2] = parseInt(vector[2], 10);
                    }
                    part = {};
                    // if the array is already set, just use that.
                    if (angular.isArray(variable[vector[1]])){
                        // is the array is set but not that index, make it.
                        if (angular.isDefined(variable[vector[1]][vector[2]])) {
                            variable = variable[vector[1]][vector[2]]
                        } else {
                            variable[vector[1]][vector[2]] = part
                            variable = part;
                        }
                    } else {
                        variable[vector[1]] = [];
                        variable[vector[1]][vector[2]] = part
                        variable = part;
                    }
                } else {
                    // if the object is already set, just use that.
                    if (angular.isDefined(variable[parts[i]])) {
                        variable = variable[parts[i]];
                        if (i === parts.length - 1) {
                            return variable;
                        }
                    } else if (i === parts.length - 1){
                        variable[parts[i]] = value || '';
                    } else {
                        variable[parts[i]] = {};
                        variable = variable[parts[i]];
                    }
                }
            }
        }
    }
    /**
    * Create a list of paths from `obj` parameter and return it in the
    * `ret` parameter
    */
    function obj2path(ret, obj, path) {
        ret = ret || {};
        var gotopath, path;
        angular.forEach(obj, function(value, key) {
            if (angular.isArray(value)) {
                for (var i = 0; i< value.length; i++) {
                    gotopath = path? path + '.' + key + '[' + i + ']' : key + '[' + i + ']';
                    obj2path(ret, value[i], gotopath);
                }
            } else if (angular.isObject(value)) {
                gotopath = path? path + '.' + key : key;
                obj2path(ret, value, gotopath);
            } else {
                gotopath = path? path + '.' + key : key;
                ret[gotopath] = value;
            }
        });
    }
    /**
     * Inject `class` in the class attributes string.
     */
    function injectClass(attr, cls) {
        if (attr.indexOf('class') > -1) {
            return attr.replace(/class\w*=\w*("|')?([^\"\']+)("|')/, 'class="' + cls + ' $2"');
        } else {
            attr += 'class="' + cls + '" ';
            return attr;
        }
    }

    angular.module('liveblog.edit')
    .factory('freetypeService', ['$q', function ($q) {
        return {
            /**
            * transformation method from dorla sign template to angular template
            * also requires `scope` object so that the proper object with the data is set.
            *     this is special case for vector array.
            */
            transform: function(template, scope) {
                if (!angular.isObject(scope[SCOPE_FREETYPEDATA])) {
                    scope[SCOPE_FREETYPEDATA] = {};
                }
                // transform collection mechaism for `scorers` or for dinamical lists.
                template = template.replace(/\
]*)\>(.*?)\<\/li\>/g, function(all, attr, repeater) {
                    var iteratorName = getNewIndex('iterator');
                    var parts, vector = '';
                    repeater = repeater.replace(/\$([\$a-z0-9_.\[\]]+)/gi, function(all, path) {
                        path2obj(scope[SCOPE_FREETYPEDATA], path);
                        parts = path.split(/[\d*]/);
                        if (parts.length === 2 && parts[1] != '') {
                            vector = parts[0].substr(0, parts[0].length - 1);
                            return '$$' + iteratorName + '.' + parts[1].substr(2);
                        } else {
                            return all;
                        }
                    });
                    return '
' +
                            repeater + '<freetype-collection-remove index="$index" vector="' + SCOPE_FREETYPEDATA + '.' + vector + '"/>' +
                            '

<freetype-collection-add vector="' + SCOPE_FREETYPEDATA + '.' + vector + '"/>
';
                });
                // transform dollar variables in the attributes of `name` or `text` in any standalone tag .
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name;
                    attr = attr.replace(/(name|text)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        // remove the dollar variable from the attributes.
                        return '';
                    });
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name);
                        return '<input ng-model=' + makeAngularAttr(name, attr) + '/>';
                    }
                    return all;
                });
                // transform dollar variables in content of any start to end tag.
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>(.*?)<\/\1>?/gi, function(all, tag, attr, content) {
                    var name, parts;
                    content = content.replace(/^\s+|\s+$/g, '');
                    parts = content.match(/^\$([\$a-z0-9]+)/gi);
                    // content should be only the variable name
                    if (parts && parts[0].length === content.length) {
                        name = content.substr(1);
                    }
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name);
                        return '<input ng-model=' + makeAngularAttr(name, attr) + '/>';
                    }
                    return all;
                });
                // transform dollar variables in the attributes of `image` in any standalone tag .
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name;
                    attr = attr.replace(/(image|graphic|rendition)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        // remove the dollar variable from the attributes.
                        return '';
                    });
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name + '.picture_url');
                        return '<freetype-image image=' + makeAngularAttr(name, attr) + '></freetype-image>';
                    }
                    return all;
                });
                // transform dollar variables in the attributes of `link` in any standalone tag .
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name;
                    attr = attr.replace(/(link|url)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        // remove the dollar variable from the attributes.
                        return '';
                    });
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name);
                        return '<freetype-link link=' + makeAngularAttr(name, attr) + '></freetype-link>';
                    }
                    return all;
                });
                // transform dollar variables in the attributes of `embed` in any standalone tag .
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name;
                    attr = attr.replace(/(embed|html)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        // remove the dollar variable from the avem o problema, attributes.
                        return '';
                    });
                    if (name) {
                        path2obj(scope[SCOPE_FREETYPEDATA], name);
                        return '<freetype-embed embed=' + makeAngularAttr(name, attr) + '></freetype-embed>';
                    }
                    return all;
                });
                return template;

            },
            htmlContent: function(template, data) {
                var paths = {},
                    path,
                    wrapBefore = '',
                    wrapAfter = '';
                obj2path(paths, data);
                template = template.replace(/\
]*)\>(.*?)\<\/li\>/g, function(all, attr, repeater) {
                    var vector, vectorPath, parts, templ = '', emptyVars = true;
                    repeater = repeater.replace(/\$([\$a-z0-9_.\[\]]+)/gi, function(all, path) {
                        parts = path.split(/[\d*]/);
                        if (parts.length === 2 && parts[1] != '') {
                            vectorPath = parts[0].substr(0, parts[0].length - 1);
                            return all;
                        } else {
                            return all;
                        }
                    });
                    if (vectorPath) {
                        vector = path2obj(data, vectorPath);
                        for (var i = 1; i< vector.length; i++) {
                            templ += '
' + repeater.replace('[]', '[0]').replace(/\$([\$a-z0-9_.\[\]]+)/gi, function(all) {
                                return all.replace('[]', '[0]').replace('[0]', '[' + i  + ']');
                            }) + '
';
                        }
                        repeater.replace('[]', '[0]').replace(/\$([\$a-z0-9_.\[\]]+)/gi, function(all, name) {
                            if (vector[0][name.replace(vectorPath + '[0].', '')]) {
                                emptyVars = false;
                            } else {
                                emptyVars = emptyVars && true;
                            }
                        });
                        if (emptyVars) {
                            return '';
                        } else {
                            return all.replace('[]', '[0]') + templ;
                        }
                    }
                    return all.replace('[]', '[0]');
                });
                template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>/gi, function(all, tag, attr) {
                    var name, type;
                    // transform `name` and `text` variables.
                    attr = attr.replace(/(name|text)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        type = 'text';
                        // remove the dollar variable from the attributes.
                        return '';
                    });

                    attr = attr.replace(/(image|graphic|rendition)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname + '.picture_url';
                        type = 'image';
                        // remove the dollar variable from the attributes.
                        return '';
                    });

                    attr = attr.replace(/(wrap-link)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        type = 'wrap-link';
                        // remove the dollar variable from the attributes.
                        return '';
                    });

                    attr = attr.replace(/(embed)\w*=\w*("|')?\$([\$a-z0-9_.\[\]]+)("|')?/gi, function(match, tag, quote, rname) {
                        name = rname;
                        type = 'embed';
                        // remove the dollar variable from the attributes.
                        return '';
                    });

                    if (name || type) {
                        switch (type) {
                            case 'text':
                                if (paths[name]) {
                                    return '' + _.escape(paths[name]) + '';
                                } else {
                                   return '';
                                }
                                break;

                            case 'image':
                                if (paths[name]) {
                                    return ''
                                } else {
                                   return '';
                                }
                                break;

                            case 'embed':
                                if (paths[name]) {
                                    return paths[name]
                                } else {
                                   return '';
                                }
                                break;

                            case 'wrap-link':
                                if (paths[name]) {
                                    wrapBefore = '';
                                    wrapAfter = ''
                                }
                                return '';
                                break;
                        }
                    }
                    return all;
                });
                template = (function recursiveContent(template) {
                    template = template.replace(/<([a-z][a-z0-9]*)\b([^>]*)>(.*?)<\/\1>?/gi, function(all, tag, attr, content) {
                        if (content) {
                            content = recursiveContent(content);
                        }
                        var name, type;
                        attr = attr.replace(/hide-render/gi, function(match, tag, quote, rname) {
                            type = 'hide-render';
                            // remove the dollar variable from the attributes.
                            return '';
                        });
                        if (name || type) {
                            switch (type) {
                                case 'text':
                                    if (paths[name]) {
                                        return '' + paths[name] + '';
                                    } else {
                                       return '';
                                    }
                                    break;
                                case 'hide-render': {
                                    return '';
                                    break;
                                }
                            }
                        }
                        return '<' + tag + attr + '>' + content + '</' + tag + '>';
                    });
                    return template;
                })(template);
                return wrapBefore + template + wrapAfter;
            }
        };
    }]);
});

<|endoftext|>


<commit_before>/*
Copyright (C) 2012 Alexander Murashkin, Neil Redman <http://gsd.uwaterloo.ca>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

function Goals(host, settings)
{
    this.id = "mdGoals";

    this.settings = settings;
    this.title = this.settings.title;

    this.width = this.settings.layout.width;
    this.height = this.settings.layout.height;
    this.posx = this.settings.layout.posx;
    this.posy = this.settings.layout.posy;

    this.host = host;
    this.goals = null;

    this.host.loaded();
}

Goals.method("onDataLoaded", function(data){
//    alert(data.claferXML);
    this.processor = new ClaferProcessor(data.claferXML);
    this.goals = this.processor.getGoals();
    this.ranges = [];
});

Goals.method("drag", function(ev)
{
    var data = ev.target.id + "|" + ev.target.className;
	ev.dataTransfer.setData("Text", data);
});

Goals.method("onRendered", function()
{
    if (this.goals && this.goals.length > 0)
    {
        var sid = "#goals a[draggable=true]";
        var dragElements = $(sid);

        for (var i = 0; i < dragElements.length; i++)
        {
            $(sid)[i].ondragstart = this.drag.bind(this);

            //add handler for range box
            var that = this;
            $('#' + this.goals[i].label + 'max').keyup(function(){
                that.filterByGoals($(this).attr("id").substring(0, $(this).attr("id").length - 3));
            });
            $('#' + this.goals[i].label + 'min').keyup(function(){
                that.filterByGoals($(this).attr("id").substring(0, $(this).attr("id").length - 3));
            });
        }

    }
});

Goals.method("getContent", function()
{
	var td;

	var table = $('

').addClass('goals');

	for (var i = 0; i < this.goals.length; i++)
	{
        var filteredTitle = this.goals[i].label.replaceAll(".", "-");
        //optimization direction
		var row = $('

').addClass('bar');
		td = $('	').addClass('td_operation');
		td.html(this.goals[i].operation);
		row.append(td);

        //goal title/draggable
		td = $('	').addClass('td_argument');
		var span = $('');
        span.html(this.goals[i].label);
		td.append(span);
        row.append(td);

        //range input
        td = $('	').addClass('td_argument');
        //(2nd input added to keep form from submitting on hitting enter)
        var input = $('<input type="text" class="text_input" id="' + this.goals[i].arg + 'min" placeholder="min" style="width: 40px">..<input type="text" class="text_input" id="' + this.goals[i].arg + 'max" placeholder="max" style="width: 40px">');
		td.append(input);
        row.append(td);

        //place row
		$(table).append(row);

        this.ranges.push({
            goal: this.goals[i].arg,
            //placeholder values
            min: -10000000,
            max: 10000000
        });
	}

    return $('

').append(table);
});

//get ranges to set landing zone else get minimum/maximum values for the ranges. After that filter
Goals.method("filterByGoals", function(input)
{
    alert(input);
    for (var x = 0; x<=this.ranges.length; x++){
        if (input == this.ranges[x].goal){
            break;
        } else if (x == this.ranges.length){
            return;
        }
    }
    var min = $("#" + input + "min").val();
    var max = $("#" + input + "max").val();
    if (jQuery.isNumeric( min ))
        this.ranges[x].min = min;
    else
        this.ranges[x].min = parseInt($("#" + input + "min").attr("placeholder"));

    if (jQuery.isNumeric( max ))
        this.ranges[x].max = max;
    else
        this.ranges[x].max = parseInt($("#" + input + "max").attr("placeholder"));

    this.settings.onFilterByGoals(this);
});

Goals.method("getInitContent", function()
{
	return '';
});

<commit_msg>Fixed filtering by goals<commit_after>/*
Copyright (C) 2012 Alexander Murashkin, Neil Redman <http://gsd.uwaterloo.ca>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

function Goals(host, settings)
{
    this.id = "mdGoals";

    this.settings = settings;
    this.title = this.settings.title;

    this.width = this.settings.layout.width;
    this.height = this.settings.layout.height;
    this.posx = this.settings.layout.posx;
    this.posy = this.settings.layout.posy;

    this.host = host;
    this.goals = null;

    this.host.loaded();
}

Goals.method("onDataLoaded", function(data){
//    alert(data.claferXML);
    this.processor = new ClaferProcessor(data.claferXML);
    this.goals = this.processor.getGoals();
    this.ranges = [];
});

Goals.method("drag", function(ev)
{
    var data = ev.target.id + "|" + ev.target.className;
	ev.dataTransfer.setData("Text", data);
});

Goals.method("onRendered", function()
{
    if (this.goals && this.goals.length > 0)
    {
        var sid = "#goals a[draggable=true]";
        var dragElements = $(sid);

        for (var i = 0; i < dragElements.length; i++)
        {
            $(sid)[i].ondragstart = this.drag.bind(this);

            //add handler for range box
            var that = this;
            $('#' + this.goals[i].arg + 'max').keyup(function(){
                that.filterByGoals($(this).attr("id").substring(0, $(this).attr("id").length - 3));
            });
            $('#' + this.goals[i].arg + 'min').keyup(function(){
                that.filterByGoals($(this).attr("id").substring(0, $(this).attr("id").length - 3));
            });
        }

    }
});

Goals.method("getContent", function()
{
	var td;

	var table = $('

').addClass('goals');

	for (var i = 0; i < this.goals.length; i++)
	{
        var filteredTitle = this.goals[i].label.replaceAll(".", "-");
        //optimization direction
		var row = $('

').addClass('bar');
		td = $('	').addClass('td_operation');
		td.html(this.goals[i].operation);
		row.append(td);

        //goal title/draggable
		td = $('	').addClass('td_argument');
		var span = $('');
        span.html(this.goals[i].label);
		td.append(span);
        row.append(td);

        //range input
        td = $('	').addClass('td_argument');
        //(2nd input added to keep form from submitting on hitting enter)
        var input = $('<input type="text" class="text_input" id="' + this.goals[i].arg + 'min" placeholder="min" style="width: 40px">..<input type="text" class="text_input" id="' + this.goals[i].arg + 'max" placeholder="max" style="width: 40px">');
		td.append(input);
        row.append(td);

        //place row
		$(table).append(row);

        this.ranges.push({
            goal: this.goals[i].arg,
            //placeholder values
            min: -10000000,
            max: 10000000
        });
	}

    return $('

').append(table);
});

//get ranges to set landing zone else get minimum/maximum values for the ranges. After that filter
Goals.method("filterByGoals", function(input)
{
    for (var x = 0; x<=this.ranges.length; x++){
        if (input == this.ranges[x].goal){
            break;
        } else if (x == this.ranges.length){
            return;
        }
    }

    var min = $("#" + input + "min").val();
    var max = $("#" + input + "max").val();
    if (jQuery.isNumeric( min ))
        this.ranges[x].min = min;
    else
        this.ranges[x].min = parseInt($("#" + input + "min").attr("placeholder"));

    if (jQuery.isNumeric( max ))
        this.ranges[x].max = max;
    else
        this.ranges[x].max = parseInt($("#" + input + "max").attr("placeholder"));

    this.settings.onFilterByGoals(this);
});

Goals.method("getInitContent", function()
{
	return '';
});

<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/components/Index'

import Doc from '@/components/Doc/Doc'
import Installation from '@/components/Doc/Installation'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Index',
      component: Index
    },
    {
      path: '/Doc/:id',
      component: Doc,
      children: [
        {path: 'Installation', component: Installation}
      ]
    }
  ]
})
<commit_msg>Doc Subroutes<commit_after>import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/components/Index'

import Doc from '@/components/Doc/Doc'
import Installation from '@/components/Doc/Installation'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Index',
      component: Index
    },
    {
      path: '/Doc',
      component: Doc,
      children: [
        {
          path: 'Installation',
          component: Installation,
          name: 'Doc/Installation'
        }
      ]
    }
  ]
})
<|endoftext|>


<commit_before>/*globals define, WebGMEGlobal, alert, _*/

/**
 * @author rkereskenyi / https://github.com/rkereskenyi
 * @author nabana / https://github.com/nabana
 */

define([
    'js/Controls/PropertyGrid/PropertyGridWidgetManager',
    'text!./templates/PluginConfigDialog.html',
    'css!./styles/PluginConfigDialog.css'],
    function (
        PropertyGridWidgetManager,
        pluginConfigDialogTemplate) {

    "use strict";

    var PluginConfigDialog,
        PLUGIN_DATA_KEY = 'plugin',
        ATTRIBUTE_DATA_KEY = 'attribute';

    PluginConfigDialog = function () {
        this._propertyGridWidgetManager = new PropertyGridWidgetManager();
        this._propertyGridWidgetManager.registerWidgetForType('boolean', 'iCheckBox');
    };

    PluginConfigDialog.prototype.show = function (pluginConfigs, fnCallback) {
        var self = this;

        this._fnCallback = fnCallback;

        this._initDialog(pluginConfigs);

        this._dialog.on('hidden', function () {
            self._dialog.remove();
            self._dialog.empty();
            self._dialog = undefined;

            if (self._fnCallback && self._updatedConfig) {
                self._fnCallback(self._updatedConfig);
            }
        });

        this._dialog.on('shown', function () {
            self._dialog.find('input').first().focus();
        });

        this._dialog.modal('show');
    };

    PluginConfigDialog.prototype._closeAndSave = function () {
        var invalids = this._dialog.find('input:invalid');
        if (invalids.length === 0) {
            this._updatedConfig = this._readConfig();
            this._dialog.modal('hide');
        } else {
            $(invalids[0]).focus();
        }
    };

    var PLUGIN_CONFIG_SECTION_BASE = $('
<fieldset><legend></legend>

<fieldset>
');
    PluginConfigDialog.prototype._initDialog = function (pluginConfigs) {
        var self = this;
        var pluginSectionEl;

        this._dialog = $(pluginConfigDialogTemplate);

        this._btnSave = this._dialog.find('.btn-save');

        this._divContainer = this._dialog.find('.modal-body');

        this._widgets = {};

        this._btnSave.on('click', function (event) {
            self._closeAndSave();
            event.stopPropagation();
            event.preventDefault();
        });

        for (var p in pluginConfigs) {
            if (pluginConfigs.hasOwnProperty(p)) {
                pluginSectionEl = PLUGIN_CONFIG_SECTION_BASE.clone();
                pluginSectionEl.data(PLUGIN_DATA_KEY, p);
                pluginSectionEl.find('legend').text('Plugin: ' + p);
                this._divContainer.append(pluginSectionEl);
                this._generatePluginSection(p, pluginConfigs[p], pluginSectionEl.find('.form-horizontal'));
            }
        }

        //save&run on CTRL + Enter
        this._dialog.on('keydown.PluginConfigDialog', function (e) {
            if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) {
                e.stopPropagation();
                e.preventDefault();
                self._closeAndSave();
            }
        });
    };

    var ENTRY_BASE = $('
NAME

');
    var DESCRIPTION_BASE = $('

');
    PluginConfigDialog.prototype._generatePluginSection = function (pluginName, pluginConfig, containerEl) {
        var len = pluginConfig.length,
            i,
            el,
            pluginConfigEntry,
            widget,
            descEl;

        this._widgets[pluginName] = {};
        for (i = 0; i < len; i += 1) {
            pluginConfigEntry = pluginConfig[i];
            descEl = undefined;

            widget = this._propertyGridWidgetManager.getWidgetForProperty(pluginConfigEntry);
            this._widgets[pluginName][pluginConfigEntry.name] = widget;

            el = ENTRY_BASE.clone();
            el.data(ATTRIBUTE_DATA_KEY, pluginConfigEntry.name);
            el.find('.controls').append(widget.el);

            el.find('label.control-label').text(pluginConfigEntry.displayName);

            if (pluginConfigEntry.description && pluginConfigEntry.description !== '') {
                descEl = descEl || DESCRIPTION_BASE.clone();
                descEl.text(pluginConfigEntry.description);
            }

            if (pluginConfigEntry.minValue !== undefined &&
                pluginConfigEntry.minValue !== null &&
                pluginConfigEntry.minValue !== '') {
                descEl = descEl || DESCRIPTION_BASE.clone();
                descEl.append(' The minimum value is: ' + pluginConfigEntry.minValue + '.');
            }

            if (pluginConfigEntry.maxValue !== undefined &&
                pluginConfigEntry.maxValue !== null &&
                pluginConfigEntry.maxValue !== '') {
                descEl = descEl || DESCRIPTION_BASE.clone();
                descEl.append(' The maximum value is: ' + pluginConfigEntry.maxValue + '.');
            }

            if (descEl) {
                el.append(descEl);
            }

            containerEl.append(el);
        }
    };

    PluginConfigDialog.prototype._readConfig = function () {
        var newConfig = {},
            plugin,
            attrName;

        for (plugin in this._widgets) {
            if (this._widgets.hasOwnProperty(plugin)) {
                for (attrName in this._widgets[plugin]) {
                    if (this._widgets[plugin].hasOwnProperty(attrName)) {
                        newConfig[plugin] = newConfig[plugin] || {};
                        newConfig[plugin][attrName] = this._widgets[plugin][attrName].getValue();
                    }
                }
            }
        }

        return newConfig;
    };

    return PluginConfigDialog;
});<commit_msg>Update dialog form layout (still not good...)<commit_after>/*globals define, WebGMEGlobal, alert, _*/

/**
 * @author rkereskenyi / https://github.com/rkereskenyi
 * @author nabana / https://github.com/nabana
 */

define([
    'js/Controls/PropertyGrid/PropertyGridWidgetManager',
    'text!./templates/PluginConfigDialog.html',
    'css!./styles/PluginConfigDialog.css'],
    function (
        PropertyGridWidgetManager,
        pluginConfigDialogTemplate) {

    "use strict";

    var PluginConfigDialog,
        PLUGIN_DATA_KEY = 'plugin',
        ATTRIBUTE_DATA_KEY = 'attribute';

    PluginConfigDialog = function () {
        this._propertyGridWidgetManager = new PropertyGridWidgetManager();
        this._propertyGridWidgetManager.registerWidgetForType('boolean', 'iCheckBox');
    };

    PluginConfigDialog.prototype.show = function (pluginConfigs, fnCallback) {
        var self = this;

        this._fnCallback = fnCallback;

        this._initDialog(pluginConfigs);

        this._dialog.on('hidden', function () {
            self._dialog.remove();
            self._dialog.empty();
            self._dialog = undefined;

            if (self._fnCallback && self._updatedConfig) {
                self._fnCallback(self._updatedConfig);
            }
        });

        this._dialog.on('shown', function () {
            self._dialog.find('input').first().focus();
        });

        this._dialog.modal('show');
    };

    PluginConfigDialog.prototype._closeAndSave = function () {
        var invalids = this._dialog.find('input:invalid');
        if (invalids.length === 0) {
            this._updatedConfig = this._readConfig();
            this._dialog.modal('hide');
        } else {
            $(invalids[0]).focus();
        }
    };

    var PLUGIN_CONFIG_SECTION_BASE = $('
<fieldset><legend></legend><form class="form-horizontal" role="form"></form><fieldset>
');
    PluginConfigDialog.prototype._initDialog = function (pluginConfigs) {
        var self = this;
        var pluginSectionEl;

        this._dialog = $(pluginConfigDialogTemplate);

        this._btnSave = this._dialog.find('.btn-save');

        this._divContainer = this._dialog.find('.modal-body');

        this._widgets = {};

        this._btnSave.on('click', function (event) {
            self._closeAndSave();
            event.stopPropagation();
            event.preventDefault();
        });

        for (var p in pluginConfigs) {
            if (pluginConfigs.hasOwnProperty(p)) {
                pluginSectionEl = PLUGIN_CONFIG_SECTION_BASE.clone();
                pluginSectionEl.data(PLUGIN_DATA_KEY, p);
                pluginSectionEl.find('legend').text('Plugin: ' + p);
                this._divContainer.append(pluginSectionEl);
                this._generatePluginSection(p, pluginConfigs[p], pluginSectionEl.find('.form-horizontal'));
            }
        }

        //save&run on CTRL + Enter
        this._dialog.on('keydown.PluginConfigDialog', function (e) {
            if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) {
                e.stopPropagation();
                e.preventDefault();
                self._closeAndSave();
            }
        });
    };

    var ENTRY_BASE = $('
NAME

');
    var DESCRIPTION_BASE = $('

');
    PluginConfigDialog.prototype._generatePluginSection = function (pluginName, pluginConfig, containerEl) {
        var len = pluginConfig.length,
            i,
            el,
            pluginConfigEntry,
            widget,
            descEl;

        this._widgets[pluginName] = {};
        for (i = 0; i < len; i += 1) {
            pluginConfigEntry = pluginConfig[i];
            descEl = undefined;

            widget = this._propertyGridWidgetManager.getWidgetForProperty(pluginConfigEntry);
            this._widgets[pluginName][pluginConfigEntry.name] = widget;

            el = ENTRY_BASE.clone();
            el.data(ATTRIBUTE_DATA_KEY, pluginConfigEntry.name);
            el.find('.controls').append(widget.el);

            el.find('label.control-label').text(pluginConfigEntry.displayName);

            if (pluginConfigEntry.description && pluginConfigEntry.description !== '') {
                descEl = descEl || DESCRIPTION_BASE.clone();
                descEl.text(pluginConfigEntry.description);
            }

            if (pluginConfigEntry.minValue !== undefined &&
                pluginConfigEntry.minValue !== null &&
                pluginConfigEntry.minValue !== '') {
                descEl = descEl || DESCRIPTION_BASE.clone();
                descEl.append(' The minimum value is: ' + pluginConfigEntry.minValue + '.');
            }

            if (pluginConfigEntry.maxValue !== undefined &&
                pluginConfigEntry.maxValue !== null &&
                pluginConfigEntry.maxValue !== '') {
                descEl = descEl || DESCRIPTION_BASE.clone();
                descEl.append(' The maximum value is: ' + pluginConfigEntry.maxValue + '.');
            }

            if (descEl) {
                el.append(descEl);
            }

            containerEl.append(el);
        }
    };

    PluginConfigDialog.prototype._readConfig = function () {
        var newConfig = {},
            plugin,
            attrName;

        for (plugin in this._widgets) {
            if (this._widgets.hasOwnProperty(plugin)) {
                for (attrName in this._widgets[plugin]) {
                    if (this._widgets[plugin].hasOwnProperty(attrName)) {
                        newConfig[plugin] = newConfig[plugin] || {};
                        newConfig[plugin][attrName] = this._widgets[plugin][attrName].getValue();
                    }
                }
            }
        }

        return newConfig;
    };

    return PluginConfigDialog;
});<|endoftext|>


<commit_before>import Path from 'path'
import getDepsType from './helpers/get-deps-type'

export default (app, manifest, brains) => {
  app.get('/:user/:repo/:ref?/status.svg', (req, res) => {
    sendStatusBadge(req, res, {extension: 'svg'})
  })

  app.get('/:user/:repo/:ref?/status.png', (req, res) => {
    sendStatusBadge(req, res, {extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/status@2x.png', (req, res) => {
    sendStatusBadge(req, res, {retina: true, extension: 'png'})
  })

  /* dev */

  app.get('/:user/:repo/:ref?/dev-status.svg', (req, res) => {
    sendStatusBadge(req, res, {dev: true, extension: 'svg'})
  })

  app.get('/:user/:repo/:ref?/dev-status.png', (req, res) => {
    sendStatusBadge(req, res, {dev: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/dev-status@2x.png', (req, res) => {
    sendStatusBadge(req, res, {dev: true, retina: true, extension: 'png'})
  })

  /* peer */

  app.get('/:user/:repo/:ref?/peer-status.png', (req, res) => {
    sendStatusBadge(req, res, {peer: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/peer-status@2x.png', (req, res) => {
    sendStatusBadge(req, res, {peer: true, retina: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/peer-status.svg', (req, res) => {
    sendStatusBadge(req, res, {peer: true, extension: 'svg'})
  })

  /* optional */

  app.get('/:user/:repo/:ref?/optional-status.svg', (req, res) => {
    sendStatusBadge(req, res, {optional: true, extension: 'svg'})
  })

  app.get('/:user/:repo/:ref?/optional-status.png', (req, res) => {
    sendStatusBadge(req, res, {optional: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/optional-status@2x.png', (req, res) => {
    sendStatusBadge(req, res, {optional: true, retina: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?.svg', (req, res) => {
    sendStatusBadge(req, res, {extension: 'svg'})
  })

  app.get('/:user/:repo/:ref?@2x.png', (req, res) => {
    sendStatusBadge(req, res, {retina: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?.png', (req, res) => {
    sendStatusBadge(req, res, {extension: 'png'})
  })

  // Send the status badge for this user and repository
  function sendStatusBadge (req, res, opts) {
    opts = opts || {}

    const badgePathOpts = {
      type: getDepsType(opts),
      retina: opts.retina,
      style: req.query.style,
      extension: opts.extension
    }

    const sendFileCb = function (err) {
      if (err) {
        console.error('Failed to send status badge', err)
        if (err.code === 'ENOENT') return res.status(404).end()
        res.status(500).end()
      }
    }

    const sendFileOpts = {
      lastModified: false,
      etag: false,
      headers: {
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Expires': new Date().toUTCString()
      }
    }

    req.session.get('session/access-token', (err, authToken) => {
      if (err) {
        console.error('Failed to get session access token', err)
        return res.status(500).sendFile(getBadgePath('unknown', badgePathOpts), sendFileOpts, sendFileCb)
      }

      const { user, repo, ref } = req.params
      const path = req.query.path

      manifest.getManifest(user, repo, { path, ref, authToken }, (err, manifest) => {
        if (err) {
          console.error('Failed to get manifest', user, repo, path, ref, authToken, err)
          return res.status(404).sendFile(getBadgePath('unknown', badgePathOpts), sendFileOpts, sendFileCb)
        }

        brains.getInfo(manifest, opts, (err, info) => {
          if (err) {
            console.error('Failed to get info', manifest, opts, err)
            return res.status(500).sendFile(getBadgePath('unknown', badgePathOpts), sendFileOpts, sendFileCb)
          }

          res.sendFile(getBadgePath(info.status, badgePathOpts), sendFileOpts, sendFileCb)
        })
      })
    })
  }
}

function getBadgePath (status, opts) {
  opts = opts || {}

  const type = opts.type ? opts.type + '-' : ''
  const retina = opts.retina ? '@2x' : ''
  const extension = opts.extension === 'png' ? 'png' : 'svg'
  const style = extension === 'svg' && opts.style === 'flat-square' ? '-' + opts.style : ''

  return Path.resolve(Path.join(__dirname, '..', '..', 'public', 'img', 'status', type + status + retina + style + '.' + extension))
}
<commit_msg>Resolve badge path on startup<commit_after>import Path from 'path'
import getDepsType from './helpers/get-deps-type'

export default (app, manifest, brains) => {
  app.get('/:user/:repo/:ref?/status.svg', (req, res) => {
    sendStatusBadge(req, res, {extension: 'svg'})
  })

  app.get('/:user/:repo/:ref?/status.png', (req, res) => {
    sendStatusBadge(req, res, {extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/status@2x.png', (req, res) => {
    sendStatusBadge(req, res, {retina: true, extension: 'png'})
  })

  /* dev */

  app.get('/:user/:repo/:ref?/dev-status.svg', (req, res) => {
    sendStatusBadge(req, res, {dev: true, extension: 'svg'})
  })

  app.get('/:user/:repo/:ref?/dev-status.png', (req, res) => {
    sendStatusBadge(req, res, {dev: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/dev-status@2x.png', (req, res) => {
    sendStatusBadge(req, res, {dev: true, retina: true, extension: 'png'})
  })

  /* peer */

  app.get('/:user/:repo/:ref?/peer-status.png', (req, res) => {
    sendStatusBadge(req, res, {peer: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/peer-status@2x.png', (req, res) => {
    sendStatusBadge(req, res, {peer: true, retina: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/peer-status.svg', (req, res) => {
    sendStatusBadge(req, res, {peer: true, extension: 'svg'})
  })

  /* optional */

  app.get('/:user/:repo/:ref?/optional-status.svg', (req, res) => {
    sendStatusBadge(req, res, {optional: true, extension: 'svg'})
  })

  app.get('/:user/:repo/:ref?/optional-status.png', (req, res) => {
    sendStatusBadge(req, res, {optional: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?/optional-status@2x.png', (req, res) => {
    sendStatusBadge(req, res, {optional: true, retina: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?.svg', (req, res) => {
    sendStatusBadge(req, res, {extension: 'svg'})
  })

  app.get('/:user/:repo/:ref?@2x.png', (req, res) => {
    sendStatusBadge(req, res, {retina: true, extension: 'png'})
  })

  app.get('/:user/:repo/:ref?.png', (req, res) => {
    sendStatusBadge(req, res, {extension: 'png'})
  })

  // Send the status badge for this user and repository
  function sendStatusBadge (req, res, opts) {
    opts = opts || {}

    const badgePathOpts = {
      type: getDepsType(opts),
      retina: opts.retina,
      style: req.query.style,
      extension: opts.extension
    }

    const sendFileCb = function (err) {
      if (err) {
        console.error('Failed to send status badge', err)
        if (err.code === 'ENOENT') return res.status(404).end()
        res.status(500).end()
      }
    }

    const sendFileOpts = {
      lastModified: false,
      etag: false,
      headers: {
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Expires': new Date().toUTCString()
      }
    }

    req.session.get('session/access-token', (err, authToken) => {
      if (err) {
        console.error('Failed to get session access token', err)
        return res.status(500).sendFile(getBadgePath('unknown', badgePathOpts), sendFileOpts, sendFileCb)
      }

      const { user, repo, ref } = req.params
      const path = req.query.path

      manifest.getManifest(user, repo, { path, ref, authToken }, (err, manifest) => {
        if (err) {
          console.error('Failed to get manifest', user, repo, path, ref, authToken, err)
          return res.status(404).sendFile(getBadgePath('unknown', badgePathOpts), sendFileOpts, sendFileCb)
        }

        brains.getInfo(manifest, opts, (err, info) => {
          if (err) {
            console.error('Failed to get info', manifest, opts, err)
            return res.status(500).sendFile(getBadgePath('unknown', badgePathOpts), sendFileOpts, sendFileCb)
          }

          res.sendFile(getBadgePath(info.status, badgePathOpts), sendFileOpts, sendFileCb)
        })
      })
    })
  }
}

const badgePath = Path.resolve(__dirname, '..', '..', 'public', 'img', 'status')

function getBadgePath (status, opts) {
  opts = opts || {}

  const type = opts.type ? opts.type + '-' : ''
  const retina = opts.retina ? '@2x' : ''
  const extension = opts.extension === 'png' ? 'png' : 'svg'
  const style = extension === 'svg' && opts.style === 'flat-square' ? '-' + opts.style : ''

  return Path.join(badgePath, `${type}${status}${retina}${style}.${extension}`)
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { Container, Header, Card, Button, Divider } from 'semantic-ui-react';
import Listing from '../shared/Listing';
import { getUserListings, deleteListing } from '../../actions';
import { capitalize } from '../../helpers/capitalize';

class CustomerDashboard extends Component {
  constructor(props) {
    super(props);
    this.handleDelete = this.handleDelete.bind(this);
  }

  componentDidMount() {
    const { userId } = this.props;
    this.props.dispatch(getUserListings(userId));
  }

  handleDelete(listingId) {
    this.props.dispatch(deleteListing(this.props.userId, listingId));
  }

  convertTime(time) {
    return moment(time).fromNow();
  }

  render() {
    const { firstName, userListings, userId } = this.props;
    return (
      <Container textAlign="center">
        {`${capitalize(firstName)}'s Dashboard`}

Recent Listings

        <Divider />
        <Card.Group itemsPerRow={4} stackable>
          {userListings && userListings.map(listing =>
            <Listing
              key={listing.id}
              id={listing.id}
              title={listing.title}
              createdAt={this.convertTime(listing.createdAt)}
              body={listing.body}
              type={listing.type}
              onClick={this.onClick}
              handleDelete={this.handleDelete}
            />
          )}
        </Card.Group>
      </Container>
    );
  }
}

CustomerDashboard.propTypes = {
  firstName: React.PropTypes.string.isRequired,
};

const mapStateToProps = (state) => {
  const { first_name: firstName, id: userId } = state.auth.loggedInUser;
  const { userListings } = state.listing;

  return { firstName, userId, userListings };
};

export default connect(mapStateToProps)(CustomerDashboard);
<commit_msg>clean up style in CustomerDashboard.js<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { Container, Header, Card, Button, Divider } from 'semantic-ui-react';
import Listing from '../shared/Listing';
import { getUserListings, deleteListing } from '../../actions';
import { capitalize } from '../../helpers/capitalize';

class CustomerDashboard extends Component {
  constructor(props) {
    super(props);
    this.handleDelete = this.handleDelete.bind(this);
  }

  componentDidMount() {
    const { userId } = this.props;
    this.props.dispatch(getUserListings(userId));
  }

  handleDelete(listingId) {
    this.props.dispatch(deleteListing(this.props.userId, listingId));
  }

  convertTime(time) {
    return moment(time).fromNow();
  }

  render() {
    const { firstName, userListings } = this.props;
    return (
      <Container textAlign="center">
        {`${capitalize(firstName)}'s Dashboard`}

Recent Listings

        <Divider />
        <Card.Group itemsPerRow={4} stackable>
          {userListings && userListings.map(listing =>
            <Listing
              key={listing.id}
              id={listing.id}
              title={listing.title}
              createdAt={this.convertTime(listing.createdAt)}
              body={listing.body}
              type={listing.type}
              onClick={this.onClick}
              handleDelete={this.handleDelete}
            />
          )}
        </Card.Group>
      </Container>
    );
  }
}

CustomerDashboard.propTypes = {
  firstName: React.PropTypes.string.isRequired,
  userListings: React.PropTypes.array.isRequired,
  userId: React.PropTypes.string.isRequired,
};

const mapStateToProps = (state) => {
  const { first_name: firstName, id: userId } = state.auth.loggedInUser;
  const { userListings } = state.listing;

  return { firstName, userId, userListings };
};

export default connect(mapStateToProps)(CustomerDashboard);
<|endoftext|>


<commit_before>import router from '../router';
import playback from './playback';
import record from './record';
import notFound from './not-found';
import hud from '../hud';
import audio from '../audio';
import Room from '../room';

let current;

const routes = {
  '/record': record,
  '/:id?': playback,
  '/*': notFound,
};

router.on('navigate', () => {
  if (current) {
    audio.fadeOut();
    current.unmount();
    Room.reset();
    current = null;
  }
});

export default () => {
  Object
    .keys(routes)
    .forEach((url) => {
      router.get(url, (req, event) => {
        const route = routes[url];
        if (!route || event.parent()) return;
        route.mount(req);
        hud.update(route.hud);
        current = route;
      });
    });
};
<commit_msg>Always hide loader when changing routes<commit_after>import router from '../router';
import playback from './playback';
import record from './record';
import notFound from './not-found';
import hud from '../hud';
import audio from '../audio';
import Room from '../room';

let current;

const routes = {
  '/record': record,
  '/:id?': playback,
  '/*': notFound,
};

router.on('navigate', () => {
  if (current) {
    audio.fadeOut();
    current.unmount();
    Room.reset();
    current = null;
  }
});

export default () => {
  Object
    .keys(routes)
    .forEach((url) => {
      router.get(url, (req, event) => {
        const route = routes[url];
        if (!route || event.parent()) return;
        hud.hideLoader();
        route.mount(req);
        hud.update(route.hud);
        current = route;
      });
    });
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */

const co = require('co');
const phantom = require('phantom');
const Router = require('koa-router');

/**
 * Create router
 */

const router = new Router();

/**
 * Index page
 */

router.get('/', co.wrap(function* (ctx, next) {
  let ph, page, url = ctx.query.url;
  if (!url) {
    return ctx.body = {
      error: {
        message: 'url query param is required'
      }
    }
  }
  return phantom.create()
    .then(p => {
      ph = p;
      return ph.createPage();
    })
    .then(p => {
      page = p;
      return page.open(url);
    })
    .then(status => {
      if (status === 'success') {
        return page.renderBase64('PNG');
      }
      return null;
    })
    .then(base64 => {
      ctx.type = 'html';
      ctx.body = `<img src="data:image/gif;base64,${base64}">`
      page.close();
      ph.exit();
    });
}));

/**
 * Healthcheck
 */

router.get('/ping', co.wrap(function* (ctx, next) {
  ctx.body = {
    message: 'pong'
  };
}));

/**
 * Expose `router`
 */

module.exports = router;
<commit_msg>convert promise to generator<commit_after>'use strict';

/**
 * Module dependencies
 */

const co = require('co');
const phantom = require('phantom');
const Router = require('koa-router');

/**
 * Create router
 */

const router = new Router();

/**
 * Index page
 */

router.get('/', co.wrap(function* (ctx, next) {
  const url = ctx.query.url;
  if (!url) {
    return ctx.body = {
      error: {
        message: 'url query param is required'
      }
    }
  }

  const ph = yield phantom.create();
  const page = yield ph.createPage();
  const status = yield page.open(url);

  let result = null;
  if (status === 'success') {
    result = yield page.renderBase64('JPG');
  }

  ctx.type = 'html';
  ctx.body = `<img src="data:image/gif;base64,${result}">`
  page.close();
  ph.exit();
}));

/**
 * Healthcheck
 */

router.get('/ping', co.wrap(function* (ctx, next) {
  ctx.body = {
    message: 'pong'
  };
}));

/**
 * Expose `router`
 */

module.exports = router;
<|endoftext|>


<commit_before>/**
 * Shared DSL statements that are useful to all scenarios.
 */

 /**
 * Usage:
 *    wait() waits until you call resume() in the console
 */
angular.scenario.dsl('wait', function() {
  return function() {
    return this.addFuture('waiting for you to resume', function(done) {
      this.emit('InteractiveWait', this.spec, this.step);
      this.$window.resume = function() { done(); };
    });
  };
});

/**
 * Usage:
 *    pause(seconds) pauses the test for specified number of seconds
 */
angular.scenario.dsl('pause', function() {
  return function(time) {
    return this.addFuture('pause for ' + time + ' seconds', function(done) {
      this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000);
    });
  };
});

/**
 * Usage:
 *    browser().navigateTo(url) Loads the url into the frame
 *    browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to
 *    browser().reload() refresh the page (reload the same URL)
 *    browser().location().href() the full URL of the page
 *    browser().location().hash() the full hash in the url
 *    browser().location().path() the full path in the url
 *    browser().location().hashSearch() the hashSearch Object from angular
 *    browser().location().hashPath() the hashPath string from angular
 */
angular.scenario.dsl('browser', function() {
  var chain = {};

  chain.navigateTo = function(url, delegate) {
    var application = this.application;
    return this.addFuture("browser navigate to '" + url + "'", function(done) {
      if (delegate) {
        url = delegate.call(this, url);
      }
      application.navigateTo(url, function() {
        done(null, url);
      }, done);
    });
  };

  chain.reload = function() {
    var application = this.application;
    return this.addFutureAction('browser reload', function($window, $document, done) {
      var href = $window.location.href;
      application.navigateTo(href, function() {
        done(null, href);
      }, done);
    });
  };

  chain.location = function() {
    var api = {};

    api.href = function() {
      return this.addFutureAction('browser url', function($window, $document, done) {
        done(null, $window.location.href);
      });
    };

    api.hash = function() {
      return this.addFutureAction('browser url hash', function($window, $document, done) {
        done(null, $window.location.hash.replace('#', ''));
      });
    };

    api.path = function() {
      return this.addFutureAction('browser url path', function($window, $document, done) {
        done(null, $window.location.pathname);
      });
    };

    api.search = function() {
      return this.addFutureAction('browser url search', function($window, $document, done) {
        done(null, $window.angular.scope().$location.search);
      });
    };

    api.hashSearch = function() {
      return this.addFutureAction('browser url hash search', function($window, $document, done) {
        done(null, $window.angular.scope().$location.hashSearch);
      });
    };

    api.hashPath = function() {
      return this.addFutureAction('browser url hash path', function($window, $document, done) {
        done(null, $window.angular.scope().$location.hashPath);
      });
    };

    return api;
  };

  return function(time) {
    return chain;
  };
});

/**
 * Usage:
 *    expect(future).{matcher} where matcher is one of the matchers defined
 *    with angular.scenario.matcher
 *
 * ex. expect(binding("name")).toEqual("Elliott")
 */
angular.scenario.dsl('expect', function() {
  var chain = angular.extend({}, angular.scenario.matcher);

  chain.not = function() {
    this.inverse = true;
    return chain;
  };

  return function(future) {
    this.future = future;
    return chain;
  };
});

/**
 * Usage:
 *    using(selector, label) scopes the next DSL element selection
 *
 * ex.
 *   using('#foo', "'Foo' text field").input('bar')
 */
angular.scenario.dsl('using', function() {
  return function(selector, label) {
    this.selector = _jQuery.trim((this.selector||'') + ' ' + selector);
    if (angular.isString(label) && label.length) {
      this.label = label + ' ( ' + this.selector + ' )';
    } else {
      this.label = this.selector;
    }
    return this.dsl;
  };
});

/**
 * Usage:
 *    binding(name) returns the value of the first matching binding
 */
angular.scenario.dsl('binding', function() {
  return function(name) {
    return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) {
      var values = $document.elements().bindings(name);
      if (!values.length) {
        return done("Binding selector '" + name + "' did not match.");
      }
      done(null, values[0]);
    });
  };
});

/**
 * Usage:
 *    input(name).enter(value) enters value in input with specified name
 *    input(name).check() checks checkbox
 *    input(name).select(value) selects the readio button with specified name/value
 */
angular.scenario.dsl('input', function() {
  var chain = {};

  chain.enter = function(value) {
    return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) {
      var input = $document.elements(':input[name="$1"]', this.name);
      input.val(value);
      input.trigger('change');
      done();
    });
  };

  chain.check = function() {
    return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) {
      var input = $document.elements(':checkbox[name="$1"]', this.name);
      input.trigger('click');
      done();
    });
  };

  chain.select = function(value) {
    return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) {
      var input = $document.
        elements(':radio[name$="@$1"][value="$2"]', this.name, value);
      input.trigger('click');
      done();
    });
  };

  return function(name) {
    this.name = name;
    return chain;
  };
});

/**
 * Usage:
 *    repeater('#products table', 'Product List').count() number of rows
 *    repeater('#products table', 'Product List').row(1) all bindings in row as an array
 *    repeater('#products table', 'Product List').column('product.name') all values across all rows in an array
 */
angular.scenario.dsl('repeater', function() {
  var chain = {};

  chain.count = function() {
    return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) {
      try {
        done(null, $document.elements().length);
      } catch (e) {
        done(null, 0);
      }
    });
  };

  chain.column = function(binding) {
    return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) {
      done(null, $document.elements().bindings(binding));
    });
  };

  chain.row = function(index) {
    return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) {
      var values = [];
      var matches = $document.elements().slice(index, index + 1);
      if (!matches.length)
        return done('row ' + index + ' out of bounds');
      done(null, matches.bindings());
    });
  };

  return function(selector, label) {
    this.dsl.using(selector, label);
    return chain;
  };
});

/**
 * Usage:
 *    select(name).option('value') select one option
 *    select(name).options('value1', 'value2', ...) select options from a multi select
 */
angular.scenario.dsl('select', function() {
  var chain = {};

  chain.option = function(value) {
    return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) {
      var select = $document.elements('select[name="$1"]', this.name);
      select.val(value);
      select.trigger('change');
      done();
    });
  };

  chain.options = function() {
    var values = arguments;
    return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) {
      var select = $document.elements('select[multiple][name="$1"]', this.name);
      select.val(values);
      select.trigger('change');
      done();
    });
  };

  return function(name) {
    this.name = name;
    return chain;
  };
});

/**
 * Usage:
 *    element(selector, label).count() get the number of elements that match selector
 *    element(selector, label).click() clicks an element
 *    element(selector, label).query(fn) executes fn(selectedElements, done)
 *    element(selector, label).{method}() gets the value (as defined by jQuery, ex. val)
 *    element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val)
 *    element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr)
 *    element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr)
 */
angular.scenario.dsl('element', function() {
  var KEY_VALUE_METHODS = ['attr', 'css'];
  var VALUE_METHODS = [
    'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width',
    'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset'
  ];
  var chain = {};

  chain.count = function() {
    return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) {
      try {
        done(null, $document.elements().length);
      } catch (e) {
        done(null, 0);
      }
    });
  };

  chain.click = function() {
    return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) {
      var elements = $document.elements();
      var href = elements.attr('href');
      elements.trigger('click');
      if (href && elements[0].nodeName.toUpperCase() === 'A') {
        this.application.navigateTo(href, function() {
          done();
        }, done);
      } else {
        done();
      }
    });
  };

  chain.query = function(fn) {
    return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) {
      fn.call(this, $document.elements(), done);
    });
  };

  angular.forEach(KEY_VALUE_METHODS, function(methodName) {
    chain[methodName] = function(name, value) {
      var futureName = "element '" + this.label + "' get " + methodName + " '" + name + "'";
      if (angular.isDefined(value)) {
        futureName = "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'";
      }
      return this.addFutureAction(futureName, function($window, $document, done) {
        var element = $document.elements();
        done(null, element[methodName].call(element, name, value));
      });
    };
  });

  angular.forEach(VALUE_METHODS, function(methodName) {
    chain[methodName] = function(value) {
      var futureName = "element '" + this.label + "' " + methodName;
      if (angular.isDefined(value)) {
        futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'";
      }
      return this.addFutureAction(futureName, function($window, $document, done) {
        var element = $document.elements();
        done(null, element[methodName].call(element, value));
      });
    };
  });

  return function(selector, label) {
    this.dsl.using(selector, label);
    return chain;
  };
});
<commit_msg>fix e2e runner's browser.location methods<commit_after>/**
 * Shared DSL statements that are useful to all scenarios.
 */

 /**
 * Usage:
 *    wait() waits until you call resume() in the console
 */
angular.scenario.dsl('wait', function() {
  return function() {
    return this.addFuture('waiting for you to resume', function(done) {
      this.emit('InteractiveWait', this.spec, this.step);
      this.$window.resume = function() { done(); };
    });
  };
});

/**
 * Usage:
 *    pause(seconds) pauses the test for specified number of seconds
 */
angular.scenario.dsl('pause', function() {
  return function(time) {
    return this.addFuture('pause for ' + time + ' seconds', function(done) {
      this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000);
    });
  };
});

/**
 * Usage:
 *    browser().navigateTo(url) Loads the url into the frame
 *    browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to
 *    browser().reload() refresh the page (reload the same URL)
 *    browser().location().href() the full URL of the page
 *    browser().location().hash() the full hash in the url
 *    browser().location().path() the full path in the url
 *    browser().location().hashSearch() the hashSearch Object from angular
 *    browser().location().hashPath() the hashPath string from angular
 */
angular.scenario.dsl('browser', function() {
  var chain = {};

  chain.navigateTo = function(url, delegate) {
    var application = this.application;
    return this.addFuture("browser navigate to '" + url + "'", function(done) {
      if (delegate) {
        url = delegate.call(this, url);
      }
      application.navigateTo(url, function() {
        done(null, url);
      }, done);
    });
  };

  chain.reload = function() {
    var application = this.application;
    return this.addFutureAction('browser reload', function($window, $document, done) {
      var href = $window.location.href;
      application.navigateTo(href, function() {
        done(null, href);
      }, done);
    });
  };

  chain.location = function() {
    var api = {};

    api.href = function() {
      return this.addFutureAction('browser url', function($window, $document, done) {
        done(null, $window.location.href);
      });
    };

    api.hash = function() {
      return this.addFutureAction('browser url hash', function($window, $document, done) {
        done(null, $window.location.hash.replace('#', ''));
      });
    };

    api.path = function() {
      return this.addFutureAction('browser url path', function($window, $document, done) {
        done(null, $window.location.pathname);
      });
    };

    api.search = function() {
      return this.addFutureAction('browser url search', function($window, $document, done) {
        done(null, $window.angular.scope().$service('$location').search);
      });
    };

    api.hashSearch = function() {
      return this.addFutureAction('browser url hash search', function($window, $document, done) {
        done(null, $window.angular.scope().$service('$location').hashSearch);
      });
    };

    api.hashPath = function() {
      return this.addFutureAction('browser url hash path', function($window, $document, done) {
        done(null, $window.angular.scope().$service('$location').hashPath);
      });
    };

    return api;
  };

  return function(time) {
    return chain;
  };
});

/**
 * Usage:
 *    expect(future).{matcher} where matcher is one of the matchers defined
 *    with angular.scenario.matcher
 *
 * ex. expect(binding("name")).toEqual("Elliott")
 */
angular.scenario.dsl('expect', function() {
  var chain = angular.extend({}, angular.scenario.matcher);

  chain.not = function() {
    this.inverse = true;
    return chain;
  };

  return function(future) {
    this.future = future;
    return chain;
  };
});

/**
 * Usage:
 *    using(selector, label) scopes the next DSL element selection
 *
 * ex.
 *   using('#foo', "'Foo' text field").input('bar')
 */
angular.scenario.dsl('using', function() {
  return function(selector, label) {
    this.selector = _jQuery.trim((this.selector||'') + ' ' + selector);
    if (angular.isString(label) && label.length) {
      this.label = label + ' ( ' + this.selector + ' )';
    } else {
      this.label = this.selector;
    }
    return this.dsl;
  };
});

/**
 * Usage:
 *    binding(name) returns the value of the first matching binding
 */
angular.scenario.dsl('binding', function() {
  return function(name) {
    return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) {
      var values = $document.elements().bindings(name);
      if (!values.length) {
        return done("Binding selector '" + name + "' did not match.");
      }
      done(null, values[0]);
    });
  };
});

/**
 * Usage:
 *    input(name).enter(value) enters value in input with specified name
 *    input(name).check() checks checkbox
 *    input(name).select(value) selects the readio button with specified name/value
 */
angular.scenario.dsl('input', function() {
  var chain = {};

  chain.enter = function(value) {
    return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) {
      var input = $document.elements(':input[name="$1"]', this.name);
      input.val(value);
      input.trigger('change');
      done();
    });
  };

  chain.check = function() {
    return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) {
      var input = $document.elements(':checkbox[name="$1"]', this.name);
      input.trigger('click');
      done();
    });
  };

  chain.select = function(value) {
    return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) {
      var input = $document.
        elements(':radio[name$="@$1"][value="$2"]', this.name, value);
      input.trigger('click');
      done();
    });
  };

  return function(name) {
    this.name = name;
    return chain;
  };
});

/**
 * Usage:
 *    repeater('#products table', 'Product List').count() number of rows
 *    repeater('#products table', 'Product List').row(1) all bindings in row as an array
 *    repeater('#products table', 'Product List').column('product.name') all values across all rows in an array
 */
angular.scenario.dsl('repeater', function() {
  var chain = {};

  chain.count = function() {
    return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) {
      try {
        done(null, $document.elements().length);
      } catch (e) {
        done(null, 0);
      }
    });
  };

  chain.column = function(binding) {
    return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) {
      done(null, $document.elements().bindings(binding));
    });
  };

  chain.row = function(index) {
    return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) {
      var values = [];
      var matches = $document.elements().slice(index, index + 1);
      if (!matches.length)
        return done('row ' + index + ' out of bounds');
      done(null, matches.bindings());
    });
  };

  return function(selector, label) {
    this.dsl.using(selector, label);
    return chain;
  };
});

/**
 * Usage:
 *    select(name).option('value') select one option
 *    select(name).options('value1', 'value2', ...) select options from a multi select
 */
angular.scenario.dsl('select', function() {
  var chain = {};

  chain.option = function(value) {
    return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) {
      var select = $document.elements('select[name="$1"]', this.name);
      select.val(value);
      select.trigger('change');
      done();
    });
  };

  chain.options = function() {
    var values = arguments;
    return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) {
      var select = $document.elements('select[multiple][name="$1"]', this.name);
      select.val(values);
      select.trigger('change');
      done();
    });
  };

  return function(name) {
    this.name = name;
    return chain;
  };
});

/**
 * Usage:
 *    element(selector, label).count() get the number of elements that match selector
 *    element(selector, label).click() clicks an element
 *    element(selector, label).query(fn) executes fn(selectedElements, done)
 *    element(selector, label).{method}() gets the value (as defined by jQuery, ex. val)
 *    element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val)
 *    element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr)
 *    element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr)
 */
angular.scenario.dsl('element', function() {
  var KEY_VALUE_METHODS = ['attr', 'css'];
  var VALUE_METHODS = [
    'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width',
    'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset'
  ];
  var chain = {};

  chain.count = function() {
    return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) {
      try {
        done(null, $document.elements().length);
      } catch (e) {
        done(null, 0);
      }
    });
  };

  chain.click = function() {
    return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) {
      var elements = $document.elements();
      var href = elements.attr('href');
      elements.trigger('click');
      if (href && elements[0].nodeName.toUpperCase() === 'A') {
        this.application.navigateTo(href, function() {
          done();
        }, done);
      } else {
        done();
      }
    });
  };

  chain.query = function(fn) {
    return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) {
      fn.call(this, $document.elements(), done);
    });
  };

  angular.forEach(KEY_VALUE_METHODS, function(methodName) {
    chain[methodName] = function(name, value) {
      var futureName = "element '" + this.label + "' get " + methodName + " '" + name + "'";
      if (angular.isDefined(value)) {
        futureName = "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'";
      }
      return this.addFutureAction(futureName, function($window, $document, done) {
        var element = $document.elements();
        done(null, element[methodName].call(element, name, value));
      });
    };
  });

  angular.forEach(VALUE_METHODS, function(methodName) {
    chain[methodName] = function(value) {
      var futureName = "element '" + this.label + "' " + methodName;
      if (angular.isDefined(value)) {
        futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'";
      }
      return this.addFutureAction(futureName, function($window, $document, done) {
        var element = $document.elements();
        done(null, element[methodName].call(element, value));
      });
    };
  });

  return function(selector, label) {
    this.dsl.using(selector, label);
    return chain;
  };
});
<|endoftext|>