<commit_before>var cache = false;
var log = new Log();
var engine = caramel.engine('handlebars', (function() {
    return {
        partials: function(Handlebars) {
            var theme = caramel.theme();
            var partials = function(file) {
                (function register(prefix, file) {
                    var i, length, name, files;
                    if (file.isDirectory()) {
                        files = file.listFiles();
                        length = files.length;
                        for (i = 0; i < length; i++) {
                            file = files[i];
                            register(prefix ? prefix + '.' + file.getName() : file.getName(), file);
                        }
                    } else {
                        name = file.getName();
                        if (name.substring(name.length - 4) !== '.hbs') {
                            return;
                        }
                        file.open('r');
                        Handlebars.registerPartial(prefix.substring(0, prefix.length - 4), file.readAll());
                        file.close();
                    }
                })('', file);
            };
            //TODO : we don't need to register all partials in the themes dir.
            //Rather register only not overridden partials
            partials(new File(theme.__proto__.resolve.call(theme, 'partials')));
            partials(new File(theme.resolve('partials')));
            Handlebars.registerHelper('dyn', function(options) {
                var asset = options.hash.asset,
                    resolve = function(path) {
                        var p,
                            publisher = require('/modules/publisher.js');
                        if (asset) {
                            p = publisher.ASSETS_EXT_PATH + asset + '/themes/' + theme.name + '/' + path;
                            if (new File(p).isExists()) {
                                return p;
                            }
                        }
                        return theme.__proto__.resolve.call(theme, path);
                    };
                partials(new File(resolve('partials')));
                return options.fn(this);
            });
            Handlebars.registerHelper('eachField', function(context, options) {
                var ret = '';
                for (var key in context) {
                    context[key].label = context[key].name.label ? context[key].name.label : context[key].name.name;
                    ret += options.fn(context[key]);
                }
                return ret;
            });
            var renderOptionsTextPreview = function(field) {
                var value;
                var values = field.value;
                var output = '';
                for (var index in values) {
                    value = values[index];
                    var delimter = value.indexOf(':')
                    var option = value.substring(0, delimter);
                    var text = value.substring(delimter + 1, value.length);
                    output += '
' + option + '	' + text + '
';
                }
                return output;
            };
            var getHeadings = function(table) {
                return (table.subheading) ? table.subheading[0].heading : [];
            };
            var getNumOfRows = function(table) {
                for (var key in table.fields) {
                    return table.fields[key].value.length;
                }
                return 0;
            };
            var getFieldCount = function(table) {
                var count = 0;
                for (var key in table.fields) {
                    count++;
                }
                return count;
            };
            var getFirstField = function(table) {
                for (var key in table.fields) {
                    return table.fields[key];
                }
                return null;
            };
            var renderHeadingFieldPreview = function(table) {
                var fields = table.fields;
                var columns = table.columns;
                var index = 0;
                var out = '
';
                for (var key in fields) {
                    if ((index % 3) == 0) {
                        index = 0;
                        out += '

';
                    }
                    out += '' + (fields[key].value || ' ') + '	';
                    index++;
                }
                return out;
            };
            Handlebars.registerHelper('renderUnboundTablePreview', function(table) {
                //Get the number of rows in the table
                var rowCount = getNumOfRows(table);
                var fields = table.fields;
                var out = '';
                for (var index = 0; index < rowCount; index++) {
                    out += '
';
                    for (var key in fields) {
                        var value = fields[key].value[index] ? fields[key].value : ' ';
                        out += '' + value + '	';
                    }
                    out += '
';
                }
                return new Handlebars.SafeString(out);
            });
            Handlebars.registerHelper('renderHeadingTablePreview', function(table) {
                var fieldCount = getFieldCount(table);
                var firstField = getFirstField(table);
                //Determine if there is only one field and it is an option text
                if ((fieldCount == 1) && (firstField.type == 'option-text')) {
                    return new Handlebars.SafeString(renderOptionsTextPreview(firstField));
                } else {
                    return new Handlebars.SafeString(renderHeadingFieldPreview(table));
                }
            });
            Handlebars.registerHelper('renderTablePreview', function(table) {
                var headingPtr = Handlebars.compile('{{> heading_table .}}');
                var defaultPtr = Handlebars.compile('{{> default_table .}}');
                var unboundPtr = Handlebars.compile('{{> unbound_table .}}');
                var headings = getHeadings(table);
                //Check if the table is unbounded
                if ((table.maxoccurs) && (table.maxoccurs == 'unbounded')) {
                    if (headings.length > 0) {
                        table.subheading = table.subheading[0].heading;
                    }
                    return new Handlebars.SafeString(unboundPtr(table));
                }
                //Check if the table has headings
                if (headings.length > 0) {
                    table.subheading = table.subheading[0].heading;
                    return new Handlebars.SafeString(headingPtr(table));
                }
                //Check if the table is a normal table
                return new Handlebars.SafeString(defaultPtr(table));
            });
            var renderFieldLabel = function(field) {
                return '' + (field.name.label || field.name.name) + '';
            };
            var renderOptions = function(value, values) {
                var out = '<select>';
                if (value) {
                    out += '<option selected>' + value + '</option>';
                }
                for (var index in values) {
                    out += '<option>' + values[index].value + '</option>';
                }
                //Filter out the selected
                out + '</select>';
                return out;
            };
            var renderOptionsTextField = function(field) {
                var value;
                var values = field.value;
                var output = '';
                if (values) {
                    for (var index in values) {
                        value = values[index];
                        var delimter = value.indexOf(':')
                        var option = value.substring(0, delimter);
                        var text = value.substring(delimter + 1, value.length);
                        output += '
';
                        output += '' + renderOptions(option, field.values) + '	';
                        output += '<input type="text"' + text + ' />	';
                        output += '
';
                    }
                } else {
                    output += '
';
                    output += '' + renderOptions(option, field.values[0].value) + '	';
                    output += '<input type="text" />	';
                    output += '
';
                }
                return output;
            };
            var renderField = function(field) {
                var out = '';
                switch (field.type) {
                    case 'options':
                        out = '' + renderOptions(field.value, field.values[0].value) + '	';
                        break;
                    case 'text':
                        out = '<input type="text" >';
                        break;
                    case 'text-area':
                        out = '<input type="text-area">';
                        break;
                    default:
                        out = 'Normal Field' + field.type + '	';
                        break;
                }
                return out;
            };
            var renderEditableHeadingField = function(table) {
                var fields = table.fields;
                var columns = table.columns;
                var index = 0;
                var out = '
';
                for (var key in fields) {
                    if ((index % 3) == 0) {
                        index = 0;
                        out += '

';
                    }
                    out += renderField(fields[key]);
                    index++;
                }
                return out;
            };
            Handlebars.registerHelper('renderEditableFields', function(fields) {
                var out = '';
                var field;
                for (var key in fields) {
                    field = fields[key];
                    out += rendeLabel(field) + renderField(field);
                }
                return new Handlebars.SafeString(out);
            });
            Handlebars.registerHelper('renderEditableField', function(field) {
                var label = '' + renderFieldLabel(field) + '	';
                return new Handlebars.SafeString(label + renderField(field));
            });
            Handlebars.registerHelper('renderEditableHeadingTable', function(table) {
                var fieldCount = getFieldCount(table);
                var firstField = getFirstField(table);
                //Determine if there is only one field and it is an option text
                if ((fieldCount == 1) && (firstField.type == 'option-text')) {
                    return new Handlebars.SafeString(renderOptionsTextField(firstField));
                } else {
                    return new Handlebars.SafeString(renderEditableHeadingField(table));
                }
            });
            Handlebars.registerHelper('renderTable', function(table) {
                var headingPtr = Handlebars.compile('{{> editable_heading_table .}}');
                var defaultPtr = Handlebars.compile('{{> editable_default_table .}}');
                var unboundPtr = Handlebars.compile('{{> editable_unbound_table .}}');
                var headings = getHeadings(table);
                //Check if the table is unbounded
                if ((table.maxoccurs) && (table.maxoccurs == 'unbounded')) {
                    if (headings.length > 0) {
                        table.subheading = table.subheading[0].heading;
                    }
                    log.info('Rendering unbounded table');
                    return new Handlebars.SafeString(unboundPtr(table));
                }
                //Check if the table has headings
                if (headings.length > 0) {
                    table.subheading = table.subheading[0].heading;
                    return new Handlebars.SafeString(headingPtr(table));
                }
                //Check if the table is a normal table
                return new Handlebars.SafeString(defaultPtr(table));
            });
        },
        render: function(data, meta) {
            if (request.getParameter('debug') == '1') {
                response.addHeader("Content-Type", "application/json");
                print(stringify(data));
            } else {
                this.__proto__.render.call(this, data, meta);
            }
        },
        globals: function(data, meta) {
            var publisher = require('/modules/publisher.js'),
                user = require('store').server.current(meta.session);
            return 'var store = ' + stringify({
                user: user ? user.username : null
            });
        }
    };
}()));
var resolve = function(path) {
    var themeResolver = this.__proto__.resolve;
    var asset = require('rxt').asset;
    path = asset.resolve(request, path, this.name, this, themeResolver);
    /*var p,
        publisher = require('/modules/publisher.js'),
        asset = publisher.currentAsset();
    if (asset) {
        p = publisher.ASSETS_EXT_PATH + asset + '/themes/' + this.name + '/' + path;
        if (new File(p).isExists()) {
            return p;
        }
    }
    var actualPath=this.__proto__.resolve.call(this, path);
    log.info('Actual path: '+actualPath);*/
    return path;
};<commit_msg>Fixed an issue with the unbound fields not rendering values correctly<commit_after>var cache = false;
var log = new Log();
var engine = caramel.engine('handlebars', (function() {
    return {
        partials: function(Handlebars) {
            var theme = caramel.theme();
            var partials = function(file) {
                (function register(prefix, file) {
                    var i, length, name, files;
                    if (file.isDirectory()) {
                        files = file.listFiles();
                        length = files.length;
                        for (i = 0; i < length; i++) {
                            file = files[i];
                            register(prefix ? prefix + '.' + file.getName() : file.getName(), file);
                        }
                    } else {
                        name = file.getName();
                        if (name.substring(name.length - 4) !== '.hbs') {
                            return;
                        }
                        file.open('r');
                        Handlebars.registerPartial(prefix.substring(0, prefix.length - 4), file.readAll());
                        file.close();
                    }
                })('', file);
            };
            //TODO : we don't need to register all partials in the themes dir.
            //Rather register only not overridden partials
            partials(new File(theme.__proto__.resolve.call(theme, 'partials')));
            partials(new File(theme.resolve('partials')));
            Handlebars.registerHelper('dyn', function(options) {
                var asset = options.hash.asset,
                    resolve = function(path) {
                        var p,
                            publisher = require('/modules/publisher.js');
                        if (asset) {
                            p = publisher.ASSETS_EXT_PATH + asset + '/themes/' + theme.name + '/' + path;
                            if (new File(p).isExists()) {
                                return p;
                            }
                        }
                        return theme.__proto__.resolve.call(theme, path);
                    };
                partials(new File(resolve('partials')));
                return options.fn(this);
            });
            Handlebars.registerHelper('eachField', function(context, options) {
                var ret = '';
                for (var key in context) {
                    context[key].label = context[key].name.label ? context[key].name.label : context[key].name.name;
                    ret += options.fn(context[key]);
                }
                return ret;
            });
            var renderOptionsTextPreview = function(field) {
                var value;
                var values = field.value;
                var output = '';
                for (var index in values) {
                    value = values[index];
                    var delimter = value.indexOf(':')
                    var option = value.substring(0, delimter);
                    var text = value.substring(delimter + 1, value.length);
                    output += '
' + option + '	' + text + '
';
                }
                return output;
            };
            var getHeadings = function(table) {
                return (table.subheading) ? table.subheading[0].heading : [];
            };
            var getNumOfRows = function(table) {
                for (var key in table.fields) {
                    return table.fields[key].value.length;
                }
                return 0;
            };
            var getFieldCount = function(table) {
                var count = 0;
                for (var key in table.fields) {
                    count++;
                }
                return count;
            };
            var getFirstField = function(table) {
                for (var key in table.fields) {
                    return table.fields[key];
                }
                return null;
            };
            var renderHeadingFieldPreview = function(table) {
                var fields = table.fields;
                var columns = table.columns;
                var index = 0;
                var out = '
';
                for (var key in fields) {
                    if ((index % 3) == 0) {
                        index = 0;
                        out += '

';
                    }
                    out += '' + (fields[key].value || ' ') + '	';
                    index++;
                }
                return out;
            };
            Handlebars.registerHelper('renderUnboundTablePreview', function(table) {
                //Get the number of rows in the table
                var rowCount = getNumOfRows(table);
                var fields = table.fields;
                var out = '';
                for (var index = 0; index < rowCount; index++) {
                    out += '
';
                    for (var key in fields) {
                        var value = fields[key].value[index] ? fields[key].value[index] : ' ';
                        out += '' + value + '	';
                    }
                    out += '
';
                }
                return new Handlebars.SafeString(out);
            });
            Handlebars.registerHelper('renderHeadingTablePreview', function(table) {
                var fieldCount = getFieldCount(table);
                var firstField = getFirstField(table);
                //Determine if there is only one field and it is an option text
                if ((fieldCount == 1) && (firstField.type == 'option-text')) {
                    return new Handlebars.SafeString(renderOptionsTextPreview(firstField));
                } else {
                    return new Handlebars.SafeString(renderHeadingFieldPreview(table));
                }
            });
            Handlebars.registerHelper('renderTablePreview', function(table) {
                var headingPtr = Handlebars.compile('{{> heading_table .}}');
                var defaultPtr = Handlebars.compile('{{> default_table .}}');
                var unboundPtr = Handlebars.compile('{{> unbound_table .}}');
                var headings = getHeadings(table);
                //Check if the table is unbounded
                if ((table.maxoccurs) && (table.maxoccurs == 'unbounded')) {
                    if (headings.length > 0) {
                        table.subheading = table.subheading[0].heading;
                    }
                    return new Handlebars.SafeString(unboundPtr(table));
                }
                //Check if the table has headings
                if (headings.length > 0) {
                    table.subheading = table.subheading[0].heading;
                    return new Handlebars.SafeString(headingPtr(table));
                }
                //Check if the table is a normal table
                return new Handlebars.SafeString(defaultPtr(table));
            });
            var renderFieldLabel = function(field) {
                return '' + (field.name.label || field.name.name) + '';
            };
            var renderOptions = function(value, values) {
                var out = '<select>';
                if (value) {
                    out += '<option selected>' + value + '</option>';
                }
                for (var index in values) {
                    out += '<option>' + values[index].value + '</option>';
                }
                //Filter out the selected
                out + '</select>';
                return out;
            };
            var renderOptionsTextField = function(field) {
                var value;
                var values = field.value;
                var output = '';
                if (values) {
                    for (var index in values) {
                        value = values[index];
                        var delimter = value.indexOf(':')
                        var option = value.substring(0, delimter);
                        var text = value.substring(delimter + 1, value.length);
                        output += '
';
                        output += '' + renderOptions(option, field.values) + '	';
                        output += '<input type="text"' + text + ' />	';
                        output += '
';
                    }
                } else {
                    output += '
';
                    output += '' + renderOptions(option, field.values[0].value) + '	';
                    output += '<input type="text" />	';
                    output += '
';
                }
                return output;
            };
            var renderField = function(field) {
                var out = '';
                switch (field.type) {
                    case 'options':
                        out = '' + renderOptions(field.value, field.values[0].value) + '	';
                        break;
                    case 'text':
                        out = '<input type="text" >';
                        break;
                    case 'text-area':
                        out = '<input type="text-area">';
                        break;
                    default:
                        out = 'Normal Field' + field.type + '	';
                        break;
                }
                return out;
            };
            var renderEditableHeadingField = function(table) {
                var fields = table.fields;
                var columns = table.columns;
                var index = 0;
                var out = '
';
                for (var key in fields) {
                    if ((index % 3) == 0) {
                        index = 0;
                        out += '

';
                    }
                    out += renderField(fields[key]);
                    index++;
                }
                return out;
            };
            Handlebars.registerHelper('renderEditableFields', function(fields) {
                var out = '';
                var field;
                for (var key in fields) {
                    field = fields[key];
                    out += rendeLabel(field) + renderField(field);
                }
                return new Handlebars.SafeString(out);
            });
            Handlebars.registerHelper('renderEditableField', function(field) {
                var label = '' + renderFieldLabel(field) + '	';
                return new Handlebars.SafeString(label + renderField(field));
            });
            Handlebars.registerHelper('renderEditableHeadingTable', function(table) {
                var fieldCount = getFieldCount(table);
                var firstField = getFirstField(table);
                //Determine if there is only one field and it is an option text
                if ((fieldCount == 1) && (firstField.type == 'option-text')) {
                    return new Handlebars.SafeString(renderOptionsTextField(firstField));
                } else {
                    return new Handlebars.SafeString(renderEditableHeadingField(table));
                }
            });
            Handlebars.registerHelper('renderTable', function(table) {
                var headingPtr = Handlebars.compile('{{> editable_heading_table .}}');
                var defaultPtr = Handlebars.compile('{{> editable_default_table .}}');
                var unboundPtr = Handlebars.compile('{{> editable_unbound_table .}}');
                var headings = getHeadings(table);
                //Check if the table is unbounded
                if ((table.maxoccurs) && (table.maxoccurs == 'unbounded')) {
                    if (headings.length > 0) {
                        table.subheading = table.subheading[0].heading;
                    }
                    log.info('Rendering unbounded table');
                    return new Handlebars.SafeString(unboundPtr(table));
                }
                //Check if the table has headings
                if (headings.length > 0) {
                    table.subheading = table.subheading[0].heading;
                    return new Handlebars.SafeString(headingPtr(table));
                }
                //Check if the table is a normal table
                return new Handlebars.SafeString(defaultPtr(table));
            });
        },
        render: function(data, meta) {
            if (request.getParameter('debug') == '1') {
                response.addHeader("Content-Type", "application/json");
                print(stringify(data));
            } else {
                this.__proto__.render.call(this, data, meta);
            }
        },
        globals: function(data, meta) {
            var publisher = require('/modules/publisher.js'),
                user = require('store').server.current(meta.session);
            return 'var store = ' + stringify({
                user: user ? user.username : null
            });
        }
    };
}()));
var resolve = function(path) {
    var themeResolver = this.__proto__.resolve;
    var asset = require('rxt').asset;
    path = asset.resolve(request, path, this.name, this, themeResolver);
    /*var p,
        publisher = require('/modules/publisher.js'),
        asset = publisher.currentAsset();
    if (asset) {
        p = publisher.ASSETS_EXT_PATH + asset + '/themes/' + this.name + '/' + path;
        if (new File(p).isExists()) {
            return p;
        }
    }
    var actualPath=this.__proto__.resolve.call(this, path);
    log.info('Actual path: '+actualPath);*/
    return path;
};<|endoftext|>


<commit_before>'use strict';

var mwUtil = require('./mwUtil');
var P = require('bluebird');
var URI = require('hyperswitch').URI;

module.exports = function(hyper, req, next, options, specInfo) {
    var rp = req.params;
    var titleParamName = options.title ? options.title : 'title';
    var checkURIParts = [rp.domain, 'sys', 'page_revisions', 'restrictions', rp.title];
    if (rp.revision) {
        checkURIParts.push(rp.revision + '');
    }

    return P.join(
        next(hyper, req),
        hyper.get({ uri: new URI(checkURIParts) })
        .catch({ status: 404 }, function() {
            return null;
        })
    )
    .spread(function(content, restriction) {
        if (restriction || content.headers.location) {
            if (restriction && restriction.body) {
                var revInfo = mwUtil.parseETag(content.headers.etag);
                mwUtil.applyAccessChecks(restriction.body, revInfo.rev);
            }

            // Use redirect target from restrictions table or content response.
            var redirectTarget = restriction && restriction.body
                && restriction.body.redirect
                || content.headers.location;
            if (redirectTarget
                    && req.query.redirect !== false
                    && !mwUtil.isNoCacheRequest(req)) {
                var newParams = Object.assign({}, rp);
                newParams[titleParamName] = redirectTarget;
                var location = mwUtil.createRelativeTitleRedirect(specInfo.path,
                    req, {
                        newReqParams: newParams,
                        titleParamName: titleParamName,
                        dropPathAfterTitle: true,
                    });

                var contentPromise;
                if (options.attach_body_to_redirect) {
                    contentPromise = P.resolve(content);
                } else {
                    contentPromise = P.resolve({
                        headers: {
                            etag: content.headers.etag
                        }
                    });
                }
                return contentPromise.then(function(content) {
                    return {
                        status: 302,
                        headers: Object.assign(content.headers, {
                            location: location,
                            'cache-control': options.redirect_cache_control || 'no-cache'
                        }),
                        body: content.body
                    };
                });
            }
        }

        return content;
    });
};
<commit_msg>Added self-redirect check<commit_after>'use strict';

var mwUtil = require('./mwUtil');
var P = require('bluebird');
var URI = require('hyperswitch').URI;

module.exports = function(hyper, req, next, options, specInfo) {
    var rp = req.params;
    var titleParamName = options.title ? options.title : 'title';
    var checkURIParts = [rp.domain, 'sys', 'page_revisions', 'restrictions', rp.title];
    if (rp.revision) {
        checkURIParts.push(rp.revision + '');
    }

    return P.join(
        next(hyper, req),
        hyper.get({ uri: new URI(checkURIParts) })
        .catch({ status: 404 }, function() {
            return null;
        })
    )
    .spread(function(content, restriction) {
        if (restriction || content.headers.location) {
            if (restriction && restriction.body) {
                var revInfo = mwUtil.parseETag(content.headers.etag);
                mwUtil.applyAccessChecks(restriction.body, revInfo.rev);
            }

            // Use redirect target from restrictions table or content response.
            var redirectTarget = restriction && restriction.body
                && restriction.body.redirect
                || content.headers.location;
            if (redirectTarget
                    && req.query.redirect !== false
                    && !mwUtil.isNoCacheRequest(req)) {
                var newParams = Object.assign({}, rp);
                newParams[titleParamName] = redirectTarget;
                var location = mwUtil.createRelativeTitleRedirect(specInfo.path,
                    req, {
                        newReqParams: newParams,
                        titleParamName: titleParamName,
                        dropPathAfterTitle: true,
                    });

                if (mwUtil.isSelfRedirect(req, location)) {
                    location = mwUtil.addQueryString(location, { redirect: false });
                }

                var contentPromise;
                if (options.attach_body_to_redirect) {
                    contentPromise = P.resolve(content);
                } else {
                    contentPromise = P.resolve({
                        headers: {
                            etag: content.headers.etag
                        }
                    });
                }
                return contentPromise.then(function(content) {
                    return {
                        status: 302,
                        headers: Object.assign(content.headers, {
                            location: location,
                            'cache-control': options.redirect_cache_control || 'no-cache'
                        }),
                        body: content.body
                    };
                });
            }
        }

        return content;
    });
};
<|endoftext|>


<commit_before>/*
 * This file is part of the GOsa project -  http://gosa-project.org
 *
 * Copyright:
 *    (C) 2010-2017 GONICUS GmbH, Germany, http://www.gonicus.de
 *
 * License:
 *    LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * See the LICENSE file in the project's top-level directory for details.
 */

/**
 * This extension provides the same functionality as the <BlockedBy> setting in the object definitions, but in can be used in the templates
 * directly to block widgets without modelPaths.
 */
qx.Class.define("gosa.engine.extensions.BlockedBy", {
  extend: qx.core.Object,

  implement : [gosa.engine.extensions.IExtension],

  members : {

    process : function(data, target, context) {
      var value = data.value;
      var modelPath = data.modelPath;
      var sourceWidget = context.getWidgetRegistry().getMap()[modelPath];
      if (!sourceWidget) {
        this.error("No widget found for modelPath '" + modelPath + "'.");
        return;
      }
      target.setVisibility(sourceWidget.getSingleValue() === value ? "excluded" : "visible");

      sourceWidget.addListener("changeValue", function(ev) {

        var v = gosa.ui.widgets.Widget.getSingleValue(ev.getData());
        console.log(v);
        console.log(value);
        target.setVisibility(v === value ? "excluded" : "visible");
      }, this);
    }
  },

  defer : function() {
    gosa.engine.ExtensionManager.getInstance().registerExtension("blockedBy", gosa.engine.extensions.BlockedBy);
  }
});
<commit_msg>fix initial check<commit_after>/*
 * This file is part of the GOsa project -  http://gosa-project.org
 *
 * Copyright:
 *    (C) 2010-2017 GONICUS GmbH, Germany, http://www.gonicus.de
 *
 * License:
 *    LGPL-2.1: http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * See the LICENSE file in the project's top-level directory for details.
 */

/**
 * This extension provides the same functionality as the <BlockedBy> setting in the object definitions, but in can be used in the templates
 * directly to block widgets without modelPaths.
 */
qx.Class.define("gosa.engine.extensions.BlockedBy", {
  extend: qx.core.Object,

  implement : [gosa.engine.extensions.IExtension],

  members : {

    process : function(data, target, context) {
      var value = data.value;
      var modelPath = data.modelPath;
      var sourceWidget = context.getWidgetRegistry().getMap()[modelPath];
      if (!sourceWidget) {
        this.error("No widget found for modelPath '" + modelPath + "'.");
        return;
      }
      sourceWidget.addListenerOnce("appear", function() {
        target.setVisibility(sourceWidget.getSingleValue() === value ? "excluded" : "visible");
      }, this);

      sourceWidget.addListener("changeValue", function(ev) {

        var v = gosa.ui.widgets.Widget.getSingleValue(ev.getData());
        console.log(v);
        console.log(value);
        target.setVisibility(v === value ? "excluded" : "visible");
      }, this);
    }
  },

  defer : function() {
    gosa.engine.ExtensionManager.getInstance().registerExtension("blockedBy", gosa.engine.extensions.BlockedBy);
  }
});
<|endoftext|>


<commit_before>// change it manually in browser console if you need logging
var LOGGING_ENABLED = false;

function getParameterByName(name, defaultValue) {
  if (defaultValue == null) {
    defaultValue = '';
  }
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
  var results = regex.exec(location.search);
  if (results === null) {
    return defaultValue;
  }
  return decodeURIComponent(results[1].replace(/\+/g, ' '));
}

function log(msg) {
  if (LOGGING_ENABLED) {
    console.log(msg);
  }
}

function DatasetSyncWrapper(id) {
  this.globalState = {};
  this.updateRuntimeDataSchedule = false;
  this.updateInterval = 500;

  this.loadConfiguration();

  $(id).attr('src', this.interactiveUrl);
  $(id).load(function() {
    this.registerPhones(id);
  }.bind(this));
}

DatasetSyncWrapper.prototype.loadConfiguration = function() {
  this.datasetName = getParameterByName('datasetName', 'prediction-dataset');
  log('DatasetSyncWrapper: Using dataset ' + this.datasetName);
  this.globalStateKey = getParameterByName('globalStateKey', 'gstate-prediction-dataset');
  log('DatasetSyncWrapper: Global key ' + this.globalStateKey);
  this.interactiveUrl = getParameterByName('interactive', 'http://lab.concord.org/embeddable-dev.html#interactives/itsi/sensor/prediction-prediction.json');
  log('DatasetSyncWrapper: Interactive ' + this.interactiveUrl);
};

DatasetSyncWrapper.prototype.registerPhones = function(id) {
  if (this.interactivePhone) {
    this.interactivePhone.hangup();
    this.interactivePhone = null;
  }
  if (this.runtimePhone) {
    this.runtimePhone.hangup();
    this.runtimePhone = null;
  }
  this.interactivePhone = new iframePhone.ParentEndpoint($(id)[0], function() {
    this.interactivePhoneAnswered();
    log('Interactive Phone ready');
    this.runtimePhone = new iframePhone.getIFrameEndpoint();
    this.registerHandlers(this.runtimePhone, this.runtimeHandlers());
    log('Runtime Phone ready');
    this.runtimePhone.initialize();
  }.bind(this));
};

DatasetSyncWrapper.prototype.scheduleDataUpdate = function() {
  if (this.updateRuntimeDataSchedule) {
    clearTimeout(this.updateRuntimeDataSchedule);
  }
  var func = function() {
    this.interactivePhone.post('getDataset', this.datasetName);
    this.updateRuntimeDataSchedule = false;
  }.bind(this);
  this.updateRuntimeDataSchedule = setTimeout(func, this.updateInterval);
};

DatasetSyncWrapper.prototype.runtimeHandlers = function() {
  return {
    "loadInteractiveGlobal": function(data) {
      var myData;
      if (typeof data === 'string') {
        data = JSON.parse(data);
      }
      this.globalState = data;
      myData = this.globalState[this.globalStateKey];
      if (myData) {
        this.interactivePhone.post('sendDatasetEvent', {
          'eventName': 'dataReset',
          'datasetName': this.datasetName,
          'data': myData.value.initialData
        });
      }
    }.bind(this)
  };
};

DatasetSyncWrapper.prototype.interactiveHandlers = function() {
  var obj = {};
  obj[this.datasetName + '-sampleAdded'] = function() {
    this.scheduleDataUpdate();
  }.bind(this);
  obj[this.datasetName + '-sampleRemoved'] = function() {
    this.scheduleDataUpdate();
  }.bind(this);
  obj[this.datasetName + '-dataReset'] = function() {
    this.scheduleDataUpdate();
  }.bind(this);
  obj['dataset'] = function(data) {
    this.globalState[this.globalStateKey] = data;
    this.runtimePhone.post('interactiveStateGlobal', this.globalState);
  }.bind(this);
  return obj;
};

DatasetSyncWrapper.prototype.interactivePhoneAnswered = function() {
  if (this.alreadySetupInteractive) {
    log('DatasetSyncWrapper: interactive phone rang, and previously answerd');
  } else {
    log('DatasetSyncWrapper: interactive phone answered');
    this.alreadySetupInteractive = true;
    this.registerHandlers(this.interactivePhone, this.interactiveHandlers());
    'sampleAdded dataReset sampleRemoved'.split(/\s+/).forEach(function(evt) {
      this.interactivePhone.post('listenForDatasetEvent', {
        eventName: evt,
        datasetName: this.datasetName
      });
    }.bind(this));
  }
};

DatasetSyncWrapper.prototype.registerHandlers = function(phone, handlers) {
  function register(phone, message, response) {
    phone.addListener(message, function(data) {
      log('DatasetSyncWrapper: handling phone: ' + message);
      if (response) {
        response(data);
      } else {
        log('DatasetSyncWrapper: no response defined for ' + message);
      }
    });
  }
  for (var message in handlers) {
    var response = handlers[message];
    register(phone, message, response);
  }
};

window.DatasetSyncWrapper = DatasetSyncWrapper;
<commit_msg>Use HTTPS in default interactive URL<commit_after>// change it manually in browser console if you need logging
var LOGGING_ENABLED = false;

var DEF_DATASET_NAME = 'prediction-dataset';
var DEF_GLOBAL_STATE_KEY = 'gstate-prediction-dataset';
var DEF_INTERACTIVE_URL = 'https://lab.concord.org/embeddable-dev.html#interactives/itsi/sensor/prediction-prediction.json';

function getParameterByName(name, defaultValue) {
  if (defaultValue == null) {
    defaultValue = '';
  }
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
  var results = regex.exec(location.search);
  if (results === null) {
    return defaultValue;
  }
  return decodeURIComponent(results[1].replace(/\+/g, ' '));
}

function log(msg) {
  if (LOGGING_ENABLED) {
    console.log(msg);
  }
}

function DatasetSyncWrapper(id) {
  this.globalState = {};
  this.updateRuntimeDataSchedule = false;
  this.updateInterval = 500;

  this.loadConfiguration();

  $(id).attr('src', this.interactiveUrl);
  $(id).load(function() {
    this.registerPhones(id);
  }.bind(this));
}

DatasetSyncWrapper.prototype.loadConfiguration = function() {
  this.datasetName = getParameterByName('datasetName', DEF_DATASET_NAME);
  log('DatasetSyncWrapper: Using dataset ' + this.datasetName);
  this.globalStateKey = getParameterByName('globalStateKey', DEF_GLOBAL_STATE_KEY);
  log('DatasetSyncWrapper: Global key ' + this.globalStateKey);
  this.interactiveUrl = getParameterByName('interactive', DEF_INTERACTIVE_URL);
  log('DatasetSyncWrapper: Interactive ' + this.interactiveUrl);
};

DatasetSyncWrapper.prototype.registerPhones = function(id) {
  if (this.interactivePhone) {
    this.interactivePhone.hangup();
    this.interactivePhone = null;
  }
  if (this.runtimePhone) {
    this.runtimePhone.hangup();
    this.runtimePhone = null;
  }
  this.interactivePhone = new iframePhone.ParentEndpoint($(id)[0], function() {
    this.interactivePhoneAnswered();
    log('Interactive Phone ready');
    this.runtimePhone = new iframePhone.getIFrameEndpoint();
    this.registerHandlers(this.runtimePhone, this.runtimeHandlers());
    log('Runtime Phone ready');
    this.runtimePhone.initialize();
  }.bind(this));
};

DatasetSyncWrapper.prototype.scheduleDataUpdate = function() {
  if (this.updateRuntimeDataSchedule) {
    clearTimeout(this.updateRuntimeDataSchedule);
  }
  var func = function() {
    this.interactivePhone.post('getDataset', this.datasetName);
    this.updateRuntimeDataSchedule = false;
  }.bind(this);
  this.updateRuntimeDataSchedule = setTimeout(func, this.updateInterval);
};

DatasetSyncWrapper.prototype.runtimeHandlers = function() {
  return {
    "loadInteractiveGlobal": function(data) {
      var myData;
      if (typeof data === 'string') {
        data = JSON.parse(data);
      }
      this.globalState = data;
      myData = this.globalState[this.globalStateKey];
      if (myData) {
        this.interactivePhone.post('sendDatasetEvent', {
          'eventName': 'dataReset',
          'datasetName': this.datasetName,
          'data': myData.value.initialData
        });
      }
    }.bind(this)
  };
};

DatasetSyncWrapper.prototype.interactiveHandlers = function() {
  var obj = {};
  obj[this.datasetName + '-sampleAdded'] = function() {
    this.scheduleDataUpdate();
  }.bind(this);
  obj[this.datasetName + '-sampleRemoved'] = function() {
    this.scheduleDataUpdate();
  }.bind(this);
  obj[this.datasetName + '-dataReset'] = function() {
    this.scheduleDataUpdate();
  }.bind(this);
  obj['dataset'] = function(data) {
    this.globalState[this.globalStateKey] = data;
    this.runtimePhone.post('interactiveStateGlobal', this.globalState);
  }.bind(this);
  return obj;
};

DatasetSyncWrapper.prototype.interactivePhoneAnswered = function() {
  if (this.alreadySetupInteractive) {
    log('DatasetSyncWrapper: interactive phone rang, and previously answerd');
  } else {
    log('DatasetSyncWrapper: interactive phone answered');
    this.alreadySetupInteractive = true;
    this.registerHandlers(this.interactivePhone, this.interactiveHandlers());
    'sampleAdded dataReset sampleRemoved'.split(/\s+/).forEach(function(evt) {
      this.interactivePhone.post('listenForDatasetEvent', {
        eventName: evt,
        datasetName: this.datasetName
      });
    }.bind(this));
  }
};

DatasetSyncWrapper.prototype.registerHandlers = function(phone, handlers) {
  function register(phone, message, response) {
    phone.addListener(message, function(data) {
      log('DatasetSyncWrapper: handling phone: ' + message);
      if (response) {
        response(data);
      } else {
        log('DatasetSyncWrapper: no response defined for ' + message);
      }
    });
  }
  for (var message in handlers) {
    var response = handlers[message];
    register(phone, message, response);
  }
};

window.DatasetSyncWrapper = DatasetSyncWrapper;
<|endoftext|>


<commit_before>jasmine.getFixtures().fixturesPath = 'tests/fixtures';

describe('Herotabs', function() {

    describe('Setup', function() {
        var tabs, instance;

        describe('Object init', function() {
            beforeEach(function() {
                loadFixtures('basic.html');
                tabs = $('.tabs').herotabs({
                    interactEvent: 'hover',
                    css: {
                        navId: 'test'
                    }
                });
                instance = tabs.data('herotabs');
            });

            it('should expose the constructor', function() {
                expect(typeof $.fn.herotabs.Herotabs).toBe('function');
            });

            it('should create an instance in data storage', function() {
                expect(instance.constructor).toEqual($.fn.herotabs.Herotabs);
            });

            it('should expose default options', function() {
                expect(typeof $.fn.herotabs.defaults).toBe('object');
            });

            it('should allow user to override default options', function() {
                expect(instance.options.interactEvent).toBe('hover');
                expect(instance.options.css.navId).toBe('test');
                expect(instance.options.css.current).toBe('tab-current');
            });

            it('should set an active class', function() {
                expect(tabs).toHaveClass($.fn.herotabs.defaults.css.active);
            });
        });

        describe('checkUrlIsAnchor regex', function() {
            it('should match hrefs that are anchor links', function() {
                expect(instance._checkUrlIsAnchor('#href')).toBeTruthy();
                expect(instance._checkUrlIsAnchor('#href_foo')).toBeTruthy();
                expect(instance._checkUrlIsAnchor('#href-foo')).toBeTruthy();
                expect(instance._checkUrlIsAnchor('#hREffoo')).toBeTruthy();
                expect(instance._checkUrlIsAnchor('/#hREffoo')).toBeTruthy();

                expect(instance._checkUrlIsAnchor('http://google.com')).toBeFalsy();
                expect(instance._checkUrlIsAnchor('fooo')).toBeFalsy();
                expect(instance._checkUrlIsAnchor('')).toBeFalsy();
            });
        });
    });

    describe('Ready/Setup', function() {
        beforeEach(function() {
            loadFixtures('basic.html');
        });

        it('should allow a setup callback before any plugin init is done', function() {
            var context;
            var tabs = $('.tabs').herotabs({
                onSetup: function() {
                    expect(true).toBeTruthy();
                    context = this;
                }
            });
            expect(context).toEqual(tabs.data('herotabs'));
        });

        it('should allow a ready callback when the plugin has instantiated', function() {
            var context;
            var tabs = $('.tabs').herotabs({
                onReady: function() {
                    expect(true).toBeTruthy();
                    context = this;
                }
            });
            expect(context).toEqual(tabs.data('herotabs'));
        });
    });

    /**
     * Run the same tests against different HTML structures
     * ----------------------------------------------------
     */

    describe('Basic HTML', function() {
        testSuite('basic.html');
    });

    describe('Heavily nested HTML', function() {
        testSuite('nesting.html');
    });

    describe('Mixed HTML elements', function() {
        testSuite('mixed-elements.html');
    });

    function testSuite(fixture) {
        var tabs, nav, tabPanels, instance;

        beforeEach(function() {
            loadFixtures(fixture);
            tabs = $('.tabs').herotabs();
            nav = $('.js-nav');
            tabPanels = $('.js-tab');
            instance = tabs.data('herotabs');
        });

        describe('Initial nav state', function() {
            it('should set roles on the navigation', function() {
                expect(nav).toHaveAttr('role', 'tablist');
                expect(nav.find('.js-nav-item')).toHaveAttr('role', 'presentation');
                expect(nav.find('.js-nav-item a')).toHaveAttr('role', 'tab');
            });

            it('should generate ids on the nav links', function() {
                nav.find('a').each(function(index) {
                    expect($(this)).toHaveId($.fn.herotabs.defaults.css.navId + instance._instanceId + '-' + (index + 1));
                });
            });

            it('should set the first nav item to current by default', function() {
                expect(nav.find('.js-nav-item').eq(0)).toHaveClass($.fn.herotabs.defaults.css.navCurrent);
                expect(nav.find('a').eq(0)).toHaveAttr('aria-selected', 'true');
                expect(nav.find('a').eq(0)).toHaveAttr('tabindex', '0');

                expect(nav.find('.js-nav-item').slice(1)).not.toHaveClass($.fn.herotabs.defaults.css.navCurrent);
                expect(nav.find('a').slice(1)).toHaveAttr('tabindex', '-1');
                expect(nav.find('a').slice(1)).toHaveAttr('aria-selected', 'false');
            });
        });

        describe('Initial tab panel state', function() {
            it('should set roles on the tab panels', function() {
                expect(tabPanels).toHaveAttr('role', 'tabpanel');
            });

            it('should link tab panels to their nav item ids', function() {
                tabPanels.each(function(index) {
                    expect($(this)).toHaveAttr('aria-labelledby', $.fn.herotabs.defaults.css.navId + instance._instanceId + '-' + (index + 1));
                });
            });

            it('should set the first tab panel to current by default', function() {
                expect(tabPanels.eq(0)).toHaveClass($.fn.herotabs.defaults.css.current);
                expect(tabPanels.eq(0)).toHaveAttr('aria-hidden', 'false');
                expect(tabPanels.eq(0)).toHaveAttr('tabindex', '0');
                expect(tabPanels.eq(0)).toBeVisible();

                expect(tabPanels.slice(1)).toHaveAttr('aria-hidden', 'true');
                expect(tabPanels.slice(1)).toHaveAttr('tabindex', '-1');
                expect(tabPanels.slice(1)).toBeHidden();
            });

            it('should set correct tabindex to links within the tab panels', function() {
                expect(tabPanels.eq(0).find('a')).toHaveAttr('tabindex', '0');
                expect(tabPanels.slice(1).find('a')).toHaveAttr('tabindex', '-1');
            });
        });

        describe('Show tab', function() {
            it('should show the selected tab by using an index', function() {
                instance.showTab(1);

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show the selected tab by using an jQuery object of the element', function() {
                instance.showTab(tabPanels.eq(1));

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should do nothing if an index is greater than the total elements', function() {
                instance.showTab(5);

                expect(tabPanels.eq(0)).toBeVisible();
                expect(tabPanels.eq(0)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should return the instance', function() {
                var ret = instance.showTab(2);
                expect(ret.constructor).toEqual($.fn.herotabs.Herotabs);
            });
        });

        describe('Next tab', function() {
            it('should show the next tab', function() {
                instance.nextTab();

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show the first tab if the last one is already visible', function() {
                instance.showTab(2);
                instance.nextTab();

                expect(tabPanels.eq(2)).toBeHidden();
                expect(tabPanels.eq(2)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(0)).toBeVisible();
                expect(tabPanels.eq(0)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should return the instance', function() {
                var ret = instance.nextTab();
                expect(ret.constructor).toEqual($.fn.herotabs.Herotabs);
            });
        });

        describe('Previous tab', function() {
            it('should show the previous tab', function() {
                instance.prevTab();

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(2)).toBeVisible();
                expect(tabPanels.eq(2)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should return the instance', function() {
                var ret = instance.nextTab();
                expect(ret.constructor).toEqual($.fn.herotabs.Herotabs);
            });
        });

        describe('Timer', function() {
            beforeEach(function() {
                jasmine.clock().install();
            });

            afterEach(function() {
                jasmine.clock().uninstall();
            });

            it('should show the next tab after the delay', function() {
                tabs = $('.tabs').herotabs({
                    delay: 300
                });

                jasmine.clock().tick(301);

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show the previous tab if reverse is set', function() {
                tabs = $('.tabs').herotabs({
                    delay: 300,
                    reverse: true
                });

                jasmine.clock().tick(301);

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(2)).toBeVisible();
                expect(tabPanels.eq(2)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should allow the timer to be stopped', function() {
                tabs = $('.tabs').herotabs({
                    delay: 500
                });
                instance = tabs.data('herotabs');

                jasmine.clock().tick(300);
                instance.stop();

                expect(tabPanels.eq(0)).toBeVisible();
                expect(tabPanels.eq(0)).toHaveClass($.fn.herotabs.defaults.css.current);
            });
        });

        describe('Custom events', function() {
            it('should fire an event when a tab is shown', function() {
                spyOnEvent(tabs, 'herotabs.show');
                instance.showTab(1);
                expect('herotabs.show').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire an event when a tab is hidden', function() {
                spyOnEvent(tabs, 'herotabs.hide');
                instance.showTab(1);
                expect('herotabs.hide').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire an event when the next tab is shown', function() {
                spyOnEvent(tabs, 'herotabs.next');
                instance.nextTab();
                expect('herotabs.next').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire an event when the previous tab is shown', function() {
                spyOnEvent(tabs, 'herotabs.prev');
                instance.prevTab();
                expect('herotabs.prev').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire events when the start method is called', function() {
                spyOnEvent(tabs, 'herotabs.start');

                instance.options.delay = 200;
                instance.start();

                expect('herotabs.start').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire events when the stop method is called', function() {
                spyOnEvent(tabs, 'herotabs.stop');

                instance.options.delay = 200;
                instance.start();
                instance.stop();

                expect('herotabs.stop').toHaveBeenTriggeredOn(tabs);
            });

            it('should allow events to be fired manually', function() {
                spyOnEvent(tabs, 'herotabs.show');
                instance.triggerEvent('herotabs.show', 1);
                expect('herotabs.show').toHaveBeenTriggeredOn(tabs);
            });
        });

        describe('Browser events', function() {
            it('should change tab when a nav item is clicked', function() {
                var event = $.Event('click', {
                    target: nav.find('a').get(1)
                });
                nav.trigger(event);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            xit('should change tab when a nav item is hovered', function() {
                tabs = $('.tabs').herotabs({
                    interactEvent: 'hover'
                });
                var event = $.Event('mouseenter');
                event.target = nav.find('a')[1];
                nav.trigger(event);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            xit('should show next tab when the right arrow is pressed', function() {
                var event = $.Event('keydown');
                event.target = nav.find('a')[1];
                event.keyCode = 39;
                nav.trigger(event);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            xit('should show next tab when the down arrow is pressed', function() {
                var event = $.Event('keydown');
                event.target = nav.find('a')[1];
                event.keyCode = 40;
                nav.trigger(event);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            xit('should show previous tab when the left arrow is pressed', function() {
                var event = $.Event('keydown');
                event.target = nav.find('a')[1];
                event.keyCode = 37;
                nav.trigger(event);

                expect(tabPanels.eq(2)).toBeVisible();
                expect(tabPanels.eq(2)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            xit('should show previous tab when the up arrow is pressed', function() {
                var event = $.Event('keydown');
                event.target = nav.find('a')[1];
                event.keyCode = 38;
                nav.trigger(event);

                expect(tabPanels.eq(2)).toBeVisible();
                expect(tabPanels.eq(2)).toHaveClass($.fn.herotabs.defaults.css.current);
            });
        });
    }
});

<commit_msg>Pass event into trigger<commit_after>jasmine.getFixtures().fixturesPath = 'tests/fixtures';

describe('Herotabs', function() {

    describe('Setup', function() {
        var tabs, instance;

        describe('Object init', function() {
            beforeEach(function() {
                loadFixtures('basic.html');
                tabs = $('.tabs').herotabs({
                    interactEvent: 'hover',
                    css: {
                        navId: 'test'
                    }
                });
                instance = tabs.data('herotabs');
            });

            it('should expose the constructor', function() {
                expect(typeof $.fn.herotabs.Herotabs).toBe('function');
            });

            it('should create an instance in data storage', function() {
                expect(instance.constructor).toEqual($.fn.herotabs.Herotabs);
            });

            it('should expose default options', function() {
                expect(typeof $.fn.herotabs.defaults).toBe('object');
            });

            it('should allow user to override default options', function() {
                expect(instance.options.interactEvent).toBe('hover');
                expect(instance.options.css.navId).toBe('test');
                expect(instance.options.css.current).toBe('tab-current');
            });

            it('should set an active class', function() {
                expect(tabs).toHaveClass($.fn.herotabs.defaults.css.active);
            });
        });

        describe('checkUrlIsAnchor regex', function() {
            it('should match hrefs that are anchor links', function() {
                expect(instance._checkUrlIsAnchor('#href')).toBeTruthy();
                expect(instance._checkUrlIsAnchor('#href_foo')).toBeTruthy();
                expect(instance._checkUrlIsAnchor('#href-foo')).toBeTruthy();
                expect(instance._checkUrlIsAnchor('#hREffoo')).toBeTruthy();
                expect(instance._checkUrlIsAnchor('/#hREffoo')).toBeTruthy();

                expect(instance._checkUrlIsAnchor('http://google.com')).toBeFalsy();
                expect(instance._checkUrlIsAnchor('fooo')).toBeFalsy();
                expect(instance._checkUrlIsAnchor('')).toBeFalsy();
            });
        });
    });

    describe('Ready/Setup', function() {
        beforeEach(function() {
            loadFixtures('basic.html');
        });

        it('should allow a setup callback before any plugin init is done', function() {
            var context;
            var tabs = $('.tabs').herotabs({
                onSetup: function() {
                    expect(true).toBeTruthy();
                    context = this;
                }
            });
            expect(context).toEqual(tabs.data('herotabs'));
        });

        it('should allow a ready callback when the plugin has instantiated', function() {
            var context;
            var tabs = $('.tabs').herotabs({
                onReady: function() {
                    expect(true).toBeTruthy();
                    context = this;
                }
            });
            expect(context).toEqual(tabs.data('herotabs'));
        });
    });

    /**
     * Run the same tests against different HTML structures
     * ----------------------------------------------------
     */

    describe('Basic HTML', function() {
        testSuite('basic.html');
    });

    describe('Heavily nested HTML', function() {
        //testSuite('nesting.html');
    });

    describe('Mixed HTML elements', function() {
        //testSuite('mixed-elements.html');
    });

    function testSuite(fixture) {
        var tabs, nav, tabPanels, instance;

        beforeEach(function() {
            loadFixtures(fixture);
            tabs = $('.tabs').herotabs();
            nav = $('.js-nav');
            tabPanels = $('.js-tab');
            instance = tabs.data('herotabs');
        });

        describe('Initial nav state', function() {
            it('should set roles on the navigation', function() {
                expect(nav).toHaveAttr('role', 'tablist');
                expect(nav.find('.js-nav-item')).toHaveAttr('role', 'presentation');
                expect(nav.find('.js-nav-item a')).toHaveAttr('role', 'tab');
            });

            it('should generate ids on the nav links', function() {
                nav.find('a').each(function(index) {
                    expect($(this)).toHaveId($.fn.herotabs.defaults.css.navId + instance._instanceId + '-' + (index + 1));
                });
            });

            it('should set the first nav item to current by default', function() {
                expect(nav.find('.js-nav-item').eq(0)).toHaveClass($.fn.herotabs.defaults.css.navCurrent);
                expect(nav.find('a').eq(0)).toHaveAttr('aria-selected', 'true');
                expect(nav.find('a').eq(0)).toHaveAttr('tabindex', '0');

                expect(nav.find('.js-nav-item').slice(1)).not.toHaveClass($.fn.herotabs.defaults.css.navCurrent);
                expect(nav.find('a').slice(1)).toHaveAttr('tabindex', '-1');
                expect(nav.find('a').slice(1)).toHaveAttr('aria-selected', 'false');
            });
        });

        describe('Initial tab panel state', function() {
            it('should set roles on the tab panels', function() {
                expect(tabPanels).toHaveAttr('role', 'tabpanel');
            });

            it('should link tab panels to their nav item ids', function() {
                tabPanels.each(function(index) {
                    expect($(this)).toHaveAttr('aria-labelledby', $.fn.herotabs.defaults.css.navId + instance._instanceId + '-' + (index + 1));
                });
            });

            it('should set the first tab panel to current by default', function() {
                expect(tabPanels.eq(0)).toHaveClass($.fn.herotabs.defaults.css.current);
                expect(tabPanels.eq(0)).toHaveAttr('aria-hidden', 'false');
                expect(tabPanels.eq(0)).toHaveAttr('tabindex', '0');
                expect(tabPanels.eq(0)).toBeVisible();

                expect(tabPanels.slice(1)).toHaveAttr('aria-hidden', 'true');
                expect(tabPanels.slice(1)).toHaveAttr('tabindex', '-1');
                expect(tabPanels.slice(1)).toBeHidden();
            });

            it('should set correct tabindex to links within the tab panels', function() {
                expect(tabPanels.eq(0).find('a')).toHaveAttr('tabindex', '0');
                expect(tabPanels.slice(1).find('a')).toHaveAttr('tabindex', '-1');
            });
        });

        describe('Show tab', function() {
            it('should show the selected tab by using an index', function() {
                instance.showTab(1);

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show the selected tab by using an jQuery object of the element', function() {
                instance.showTab(tabPanels.eq(1));

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should do nothing if an index is greater than the total elements', function() {
                instance.showTab(5);

                expect(tabPanels.eq(0)).toBeVisible();
                expect(tabPanels.eq(0)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should return the instance', function() {
                var ret = instance.showTab(2);
                expect(ret.constructor).toEqual($.fn.herotabs.Herotabs);
            });
        });

        describe('Next tab', function() {
            it('should show the next tab', function() {
                instance.nextTab();

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show the first tab if the last one is already visible', function() {
                instance.showTab(2);
                instance.nextTab();

                expect(tabPanels.eq(2)).toBeHidden();
                expect(tabPanels.eq(2)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(0)).toBeVisible();
                expect(tabPanels.eq(0)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should return the instance', function() {
                var ret = instance.nextTab();
                expect(ret.constructor).toEqual($.fn.herotabs.Herotabs);
            });
        });

        describe('Previous tab', function() {
            it('should show the previous tab', function() {
                instance.prevTab();

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(2)).toBeVisible();
                expect(tabPanels.eq(2)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should return the instance', function() {
                var ret = instance.nextTab();
                expect(ret.constructor).toEqual($.fn.herotabs.Herotabs);
            });
        });

        describe('Timer', function() {
            beforeEach(function() {
                jasmine.clock().install();
            });

            afterEach(function() {
                jasmine.clock().uninstall();
            });

            it('should show the next tab after the delay', function() {
                tabs = $('.tabs').herotabs({
                    delay: 300
                });

                jasmine.clock().tick(301);

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show the previous tab if reverse is set', function() {
                tabs = $('.tabs').herotabs({
                    delay: 300,
                    reverse: true
                });

                jasmine.clock().tick(301);

                expect(tabPanels.eq(0)).toBeHidden();
                expect(tabPanels.eq(0)).not.toHaveClass($.fn.herotabs.defaults.css.current);

                expect(tabPanels.eq(2)).toBeVisible();
                expect(tabPanels.eq(2)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should allow the timer to be stopped', function() {
                tabs = $('.tabs').herotabs({
                    delay: 500
                });
                instance = tabs.data('herotabs');

                jasmine.clock().tick(300);
                instance.stop();

                expect(tabPanels.eq(0)).toBeVisible();
                expect(tabPanels.eq(0)).toHaveClass($.fn.herotabs.defaults.css.current);
            });
        });

        describe('Custom events', function() {
            it('should fire an event when a tab is shown', function() {
                spyOnEvent(tabs, 'herotabs.show');
                instance.showTab(1);
                expect('herotabs.show').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire an event when a tab is hidden', function() {
                spyOnEvent(tabs, 'herotabs.hide');
                instance.showTab(1);
                expect('herotabs.hide').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire an event when the next tab is shown', function() {
                spyOnEvent(tabs, 'herotabs.next');
                instance.nextTab();
                expect('herotabs.next').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire an event when the previous tab is shown', function() {
                spyOnEvent(tabs, 'herotabs.prev');
                instance.prevTab();
                expect('herotabs.prev').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire events when the start method is called', function() {
                spyOnEvent(tabs, 'herotabs.start');

                instance.options.delay = 200;
                instance.start();

                expect('herotabs.start').toHaveBeenTriggeredOn(tabs);
            });

            it('should fire events when the stop method is called', function() {
                spyOnEvent(tabs, 'herotabs.stop');

                instance.options.delay = 200;
                instance.start();
                instance.stop();

                expect('herotabs.stop').toHaveBeenTriggeredOn(tabs);
            });

            it('should allow events to be fired manually', function() {
                spyOnEvent(tabs, 'herotabs.show');
                instance.triggerEvent('herotabs.show', 1);
                expect('herotabs.show').toHaveBeenTriggeredOn(tabs);
            });
        });

        describe('Browser events', function() {
            it('should change tab when a nav item is clicked', function() {
                nav.trigger($.Event('click', {
                    target: nav.find('a').get(1)
                }));

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should change tab when a nav item is hovered', function() {
                tabs = $('.tabs').herotabs({
                    interactEvent: 'hover'
                });
                nav.trigger($.Event('mouseenter', {
                    target: nav.find('a')[1]
                }));

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show next tab when the right arrow is pressed', function() {
                nav.trigger($.Event('keydown', {
                    target: nav.find('a')[1],
                    keyCode: 39
                }));

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show next tab when the down arrow is pressed', function() {
                nav.trigger($.Event('keydown', {
                    target: nav.find('a')[1],
                    keyCode: 40
                }));

                expect(tabPanels.eq(1)).toBeVisible();
                expect(tabPanels.eq(1)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show previous tab when the left arrow is pressed', function() {
                nav.trigger($.Event('keydown', {
                    target: nav.find('a')[1],
                    keyCode: 37
                }));

                expect(tabPanels.eq(2)).toBeVisible();
                expect(tabPanels.eq(2)).toHaveClass($.fn.herotabs.defaults.css.current);
            });

            it('should show previous tab when the up arrow is pressed', function() {
                var event = $.Event('keydown', {
                    target: nav.find('a')[1],
                    keyCode: 38
                });
                nav.trigger(event);

                expect(tabPanels.eq(2)).toBeVisible();
                expect(tabPanels.eq(2)).toHaveClass($.fn.herotabs.defaults.css.current);
            });
        });
    }
});

<|endoftext|>


<commit_before>import variables from '../../../../../config/variables.js';

module.exports = [
  {
    featureType: 'administrative.neighborhood',
    stylers: [
      { visibility: 'off' }
    ]
  },
  {
    featureType: 'landscape.man_made',
    elementType: 'geometry',
    stylers: [
      { color: variables.$white }
    ]
  },
  {
    featureType: 'landscape.natural',
    elementType: 'geometry',
    stylers: [
      { color: variables.$greenMuted }
    ]
  },
  {
    featureType: 'landscape.natural',
    elementType: 'labels.text',
    stylers: [
      { color: variables.$greenMuted }
    ]
  },
  {
    featureType: 'poi',
    elementType: 'geometry',
    stylers: [
      { visibility: 'simplified' },
      { color: variables.$greenMuted }
    ]
  },
  {
    featureType: 'poi.government',
    elementType: 'geometry',
    stylers: [
      { color: variables.$white }
    ]
  },
  {
    featureType: 'poi.school',
    elementType: 'geometry',
    stylers: [
      { color: variables.$white }
    ]
  },
  {
    featureType: 'road.arterial',
    elementType: 'geometry',
    stylers: [
      { color : variables.$gray },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.arterial',
    elementType: 'labels.text',
    stylers: [
      { color : variables.$grayDark },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.highway',
    elementType: 'geometry',
    stylers: [
      { color : variables.$gray },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.highway',
    elementType: 'labels.text',
    stylers: [
      { color : variables.$grayDark },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.local',
    elementType: 'geometry',
    stylers: [
      { color : variables.$grayLight },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.local',
    elementType: 'labels',
    stylers: [
      { visibility: 'off' }
    ]
  },
  {
    featureType: 'water',
    elementType: 'geometry',
    stylers: [
      { color: variables.$blueLight }
    ]
  },
  {
    featureType: 'water',
    elementType: 'labels',
    stylers: [
      { color: variables.$blue }
    ]
  },
];
<commit_msg>Map style - changed color<commit_after>import variables from '../../../../../config/variables.js';

module.exports = [
  {
    featureType: 'administrative.neighborhood',
    stylers: [
      { visibility: 'off' }
    ]
  },
  {
    featureType: 'landscape.man_made',
    elementType: 'geometry',
    stylers: [
      { color: variables.$white }
    ]
  },
  {
    featureType: 'landscape.natural',
    elementType: 'geometry',
    stylers: [
      { color: variables.$greenMuted }
    ]
  },
  {
    featureType: 'landscape.natural',
    elementType: 'labels.text',
    stylers: [
      { color: variables.$greenMuted }
    ]
  },
  {
    featureType: 'poi',
    elementType: 'geometry',
    stylers: [
      { visibility: 'simplified' },
      { color: variables.$greenMuted }
    ]
  },
  {
    featureType: 'poi.government',
    elementType: 'geometry',
    stylers: [
      { color: variables.$white }
    ]
  },
  {
    featureType: 'poi.school',
    elementType: 'geometry',
    stylers: [
      { color: variables.$white }
    ]
  },
  {
    featureType: 'road.arterial',
    elementType: 'geometry',
    stylers: [
      { color : variables.$grayLight },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.arterial',
    elementType: 'labels.text',
    stylers: [
      { color : variables.$gray },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.highway',
    elementType: 'geometry',
    stylers: [
      { color : variables.$grayLight },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.highway',
    elementType: 'labels.text',
    stylers: [
      { color : variables.$gray },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.local',
    elementType: 'geometry',
    stylers: [
      { color : variables.$grayLightest },
      { visibility: 'simplified' }
    ]
  },
  {
    featureType: 'road.local',
    elementType: 'labels',
    stylers: [
      { visibility: 'off' }
    ]
  },
  {
    featureType: 'water',
    elementType: 'geometry',
    stylers: [
      { color: variables.$blueLight }
    ]
  },
  {
    featureType: 'water',
    elementType: 'labels',
    stylers: [
      { color: variables.$blue }
    ]
  },
];
<|endoftext|>


<commit_before>enyo.kind({
	name: "moon.sample.TimePickerSample",
	kind: "FittableRows",
	classes: "moon enyo-unselectable enyo-fit",
	components: [
		{kind: 'moon.Scroller', fit: true, components: [
			{classes: "moon-7h moon-vspacing-s", components: [
				{kind: "moon.DatePicker", name:"pickerDateLinked", noneText: "Pick a Date", content: "Linked Date", onChange: "dateChanged"},
				{kind: "moon.TimePicker", name:"pickerTimeLinked", noneText: "Pick a Time", content: "Linked Time", meridiemEnable: true, onChange: "timeChanged"},
				{kind: "moon.TimePicker", name: "pickerTime", noneText: "Pick a Time", content: "Time", meridiemEnable: true, onChange: "timeChanged"},
				{kind: "moon.Button", name: "buttonReset", content: "Reset Time", small: true, ontap: "resetTapped"},
				{kind: "moon.TimePicker", name:"pickerDisabled", meridiemEnable: true, disabled: true, noneText: "Disabled Time Picker", content: "Disabled Time"},
				{kind: "moon.ExpandablePicker", name: "pickerLocale", noneText: "No Locale Selected", content: "Choose Locale", onChange:"pickerHandler", components: [
					{content: "Use Default Locale", active: true},
					{content: 'jp-JP'},
					{content: 'en-US'},
					{content: 'ko-KR'},
					{content: "th-TH"},	//Thailand
					{content: 'en-CA'},
					{content: 'en-IE'},
					{content: 'en-GB'},
					{content: 'en-MX'},
					{content: 'de-DE'},
					{content: 'fr-FR'},
					{content: 'fr-CA'},
					{content: 'it-IT'},
					{content: 'es-ES'},
					{content: 'es-MX'},
					{content: 'es-US'}
				]}
			]}
		]},
		{kind: "moon.Divider", content:"Result"},
		{kind: "moon.BodyText", name: "result", content: "No change yet"}
	],
	bindings: [
		{from:".value", to:".$.pickerDateLinked.value", oneWay:false},
		{from:".value", to:".$.pickerTimeLinked.value", oneWay:false}
	],
	create: function(){
		this.inherited(arguments);
		if (!window.ilib) {
			this.$.pickerLocale.hide();
			this.log("iLib not present -- hiding locale picker");
		}
		this.set("value", new Date("Mar 09 2014 01:59"));
	},
	pickerHandler: function(inSender, inEvent){
		var opt = inEvent.selected.content,
			val = (opt == "Use Default Locale") ? null : opt;
		this.$.pickerDateLinked.setLocale(val);
		this.$.pickerTimeLinked.setLocale(val);
		this.$.pickerTime.setLocale(val);
		this.$.pickerDisabled.setLocale(val);
		this.$.result.setContent("locale changed to " + opt);
		return true;
	},
	timeChanged: function(inSender, inEvent) {
		if (this.$.result && inEvent.value){
			var timeArray = inEvent.value.toTimeString().split(":");
			this.$.result.setContent(inEvent.name + " changed to " + timeArray[0] + ":" + timeArray[1]);
		}
	},
	dateChanged: function(inSender, inEvent) {
		if (this.$.result && inEvent.value){
			this.$.result.setContent(inEvent.name + " changed to " + inEvent.value.toDateString());
		}
	},
	resetTapped: function(inSender, inEvent) {
		this.$.pickerTime.set("open", false);
		this.$.pickerTime.set("value", null);
		return true;
	}
});<commit_msg>ENYO-525 Modify sample to support  Arabic locale and RTL<commit_after>enyo.kind({
	name: "moon.sample.TimePickerSample",
	kind: "FittableRows",
	classes: "moon enyo-unselectable enyo-fit",
	components: [
		{kind: 'moon.Scroller', fit: true, components: [
			{classes: "moon-7h moon-vspacing-s", components: [
				{kind: "moon.DatePicker", name:"pickerDateLinked", noneText: "Pick a Date", content: "Linked Date", onChange: "dateChanged"},
				{kind: "moon.TimePicker", name:"pickerTimeLinked", noneText: "Pick a Time", content: "Linked Time", meridiemEnable: true, onChange: "timeChanged"},
				{kind: "moon.TimePicker", name: "pickerTime", noneText: "Pick a Time", content: "Time", meridiemEnable: true, onChange: "timeChanged"},
				{kind: "moon.Button", name: "buttonReset", content: "Reset Time", small: true, ontap: "resetTapped"},
				{kind: "moon.TimePicker", name:"pickerDisabled", meridiemEnable: true, disabled: true, noneText: "Disabled Time Picker", content: "Disabled Time"},
				{kind: "moon.ExpandablePicker", name: "pickerLocale", noneText: "No Locale Selected", content: "Choose Locale", onChange:"setLocale", components: [
					{content: "Use Default Locale", active: true},
					{content: 'jp-JP'},
					{content: 'fa-IR'},
					{content: 'ar-SA'},
					{content: 'ur-IN'},
					{content: 'en-US'},
					{content: 'ko-KR'},
					{content: "th-TH"},	//Thailand
					{content: 'en-CA'},
					{content: 'en-IE'},
					{content: 'en-GB'},
					{content: 'en-MX'},
					{content: 'de-DE'},
					{content: 'fr-FR'},
					{content: 'fr-CA'},
					{content: 'it-IT'},
					{content: 'es-ES'},
					{content: 'es-MX'},
					{content: 'es-US'}
				]}
			]}
		]},
		{kind: "moon.Divider", content:"Result"},
		{kind: "moon.BodyText", name: "result", content: "No change yet"}
	],
	bindings: [
		{from:".value", to:".$.pickerDateLinked.value", oneWay:false},
		{from:".value", to:".$.pickerTimeLinked.value", oneWay:false}
	],
	create: function(){
		this.inherited(arguments);
		if (!window.ilib) {
			this.$.pickerLocale.hide();
			this.log("iLib not present -- hiding locale picker");
		}
		this.set("value", new Date("Mar 09 2014 01:59"));
	},
	setLocale: function(inSender, inEvent){
		if (ilib) {
			var locale = inEvent.selected.content,
				val = (locale == "Use Default Locale") ? null : locale;
			ilib.setLocale(locale);
			this.$.pickerDateLinked.setLocale(val);
			this.$.pickerTimeLinked.setLocale(val);
			this.$.pickerTime.setLocale(val);
			this.$.pickerDisabled.setLocale(val);
			this.$.result.setContent("locale changed to " + locale);

			var li = new ilib.LocaleInfo(locale);
			var script = new ilib.ScriptInfo(li.getScript());

			if (script.getScriptDirection() === "rtl") {
				enyo.Control.prototype.rtl = true;
				enyo.dom.addBodyClass('enyo-locale-right-to-left');
			} else {
				enyo.Control.prototype.rtl = false;
				enyo.dom.removeClass(document.body, 'enyo-locale-right-to-left');
			}
		}
		return true;
	},
	timeChanged: function(inSender, inEvent) {
		if (this.$.result && inEvent.value){
			var timeArray = inEvent.value.toTimeString().split(":");
			this.$.result.setContent(inEvent.name + " changed to " + timeArray[0] + ":" + timeArray[1]);
		}
	},
	dateChanged: function(inSender, inEvent) {
		if (this.$.result && inEvent.value){
			this.$.result.setContent(inEvent.name + " changed to " + inEvent.value.toDateString());
		}
	},
	resetTapped: function(inSender, inEvent) {
		this.$.pickerTime.set("open", false);
		this.$.pickerTime.set("value", null);
		return true;
	}
});<|endoftext|>


<commit_before>/**
 * Created by alex on 01.08.2015.
 */

var paginator = require("paginator-express"),
    _ = require('lodash'),
    express = require('express');

var router = express.Router();

module.exports = function (model) {
    var ctrl = new Controller(model);
    return ctrl;
};

function Controller(model) {
    var controller = {
        list: paginator.controller(model.find()),
        create: function (req, res, next) {
            var m = new model(req.body);

            m.save()
                .then(function (result) {
                    res.status(201);
                    res.json(result);
                }, next)

        },
        read: function (req, res, next) {
            load(model, req.params.id || req.query.id)
                .then(function (result) {
                    res.status(200);
                    res.json(result)
                }, next)
        },
        update: function (req, res, next) {
            load(model, req.params.id || req.query.id)
                .then(function (result) {
                    _.assign(result, req.body);
                    return result.save();
                }, next)
                .then(function (result) {
                    res.status(203);
                    res.json(result)
                }, next)
        },
        delete: function (req, res, next) {
            load(model, req.params.id || req.query.id)
                .then(function (result) {
                    return result.remove();
                }, next)
                .then(function () {
                    res.status(203);
                    res.end();
                }, next)
        }
    };

    return controller;
}

function load(model, id) {
    return model.findOne({
        _id: id
    }).exec();
}<commit_msg>добавил переопредление/кастомное подключение действий в контроллер<commit_after>/**
 * Created by alex on 01.08.2015.
 */

var paginator = require("paginator-express"),
    _ = require('lodash'),
    express = require('express');

var router = express.Router();

module.exports = function (model, customActions) {
    var ctrl = new Controller(model);

    _.forOwn(customActions, function (action, name) {
        ctrl[name] = action;
    })

    return ctrl;
};

function Controller(model) {
    var controller = {
        list: paginator.controller(model.find()),
        create: function (req, res, next) {
            var m = new model(req.body);

            m.save()
                .then(function (result) {
                    res.status(201);
                    res.json(result);
                }, next)

        },
        read: function (req, res, next) {
            load(model, req.params.id || req.query.id)
                .then(function (result) {
                    res.status(200);
                    res.json(result)
                }, next)
        },
        update: function (req, res, next) {
            load(model, req.params.id || req.query.id)
                .then(function (result) {
                    _.assign(result, req.body);
                    return result.save();
                }, next)
                .then(function (result) {
                    res.status(203);
                    res.json(result)
                }, next)
        },
        delete: function (req, res, next) {
            load(model, req.params.id || req.query.id)
                .then(function (result) {
                    return result.remove();
                }, next)
                .then(function () {
                    res.status(203);
                    res.end();
                }, next)
        }
    };
    return controller;
}

function load(model, id) {
    return model.findOne({
        _id: id
    }).exec();
}<|endoftext|>