<commit_before>{
  function loc() { return {start: { line: line(), column: column() } } }
  function range() { return [offset(), offset() + text().length]; }
  function listHelper(a,b,c) { return a == null ? [] : [a].concat(b.map(function(b) { return b[c || 2]; })); }
  function opt(name, def) { return name in options ? options[name] : def }

  function expandMultiStatements(list) {
    var out = [];
    for ( var i = 0; i < list.length; ++i ) {
        var value = list[i];
        if (value instanceof Array) out = out.concat(value);
        else out.push(value);
    }
    return out;
  }

  function wrapNode(obj, hasScope) {
    hasScope = !!hasScope
    obj.loc = loc();
    obj.range = range();
    obj.hasScope = hasScope;
    obj.text = text();
    return obj;
  }

  function eUntermIfEmpty(what, type, end, start) {
    if ( what.length == 0 ) return eUnterminated(type, end, start);
    return true;
  }

  function eUnterminated(type, end, start) {
    var xline = start !== undefined ? start.loc.start.line : (line());
    var xcol = start !== undefined ? start.loc.start.column : (column());

    eMsg("`" + (end || "end") + "` expected (to close " + type + " at " + xline + ":" + xcol + ") at " + line() +  ":" + column() );
    return true;
  }

  function eMsg(why) {
    if ( !opt("loose", false) ) error(why);
    errors.push({msg: why, loc: loc(), range: range()});
    return true;
  }

  var opPrecedence = {
    "^": 10,
    "not": 9,
    "*": 8, "/": 8,
    "+": 7, "-": 7,
    "..": 6,
    "<": 5, ">": 5, ">=": 5, "<=": 5, "==": 5, "~=": 5,
    "and": 4,
    "or": 3
  }

  function precedenceClimber(tokens, lhs, min) {
    while ( true ) {
        if ( tokens.length == 0 ) return lhs;
        var op = tokens[0];
        var prec = opPrecedence[op];
        if ( prec < min ) return lhs;
        tokens.shift();

        var rhs = tokens.shift();
        while ( true ) {
            var peek = tokens[0];
            if ( peek == null || opPrecedence[peek] <= prec ) break;
            rhs = precedenceClimber(tokens, rhs, opPrecedence[peek]);
        }

        lhs = bhelper.binaryExpression(op, lhs, rhs);
    }

  }

  var errors;

  function init() {
    errors = [];
  }

  var builder = {
    assignmentExpression: function(op, left, right) { return wrapNode({type: "AssignmentExpression", operator: op, left: left, right: right }); },
    binaryExpression: function(op, left, right) { return wrapNode({type: "BinaryExpression", operator: op, left: left, right: right }); },
    blockStatement: function(body) { return wrapNode({ type: "BlockStatement", body: body}); },
    callExpression: function(callee, args) { return wrapNode({ type: "CallExpression", callee: callee, arguments: args}); },
    emptyStatement: function() { return wrapNode({ type: "EmptyStatement" }); },
    functionDeclaration: function(name, args, body, isGenerator, isExpression) {
        return wrapNode({type: "FunctionDeclaration", id: name, params: args, body: body, generator: isGenerator, expression: isExpression });
    },
    memberExpression: function(obj, prop, isComputed) { return wrapNode({ type:"MemberExpression", object: obj, property: prop, computed: isComputed }); },
    variableDeclaration: function(kind, decls) { return { type: "VariableDeclaration", declarations: decls, kind: opt("forceVar", true) ? "var" : kind } },
    functionExpression: function(name, args, body) { return { type: "FunctionExpression", name: name, body: body, params: args } },
    returnStatement: function(arg) { return wrapNode({type: "ReturnStatement", argument: arg}); }
  };

  var i = function(n) { return { type: "Identifier", name: n}; }
  var tmpVarCtr = 0;

  function clone(obj) {
    return JSON.parse(JSON.stringify(obj));
  }

  function finalize(ast) {
    if ( opt("loose", false) ) ast.errors = errors;
    if ( opt("noSharedObjects", true) ) return clone(ast);
    return ast;
  }

  var bhelper = {
    blockStatement: function(body) {
        return builder.blockStatement(expandMultiStatements(body));
    },
    tempName: function() {
        return i("__lua$tmpvar$" + (++tmpVarCtr));
    },
    tempVar: function(exp) {
        return { type: "VariableDeclarator", id: bhelper.tempName(), init: exp };
    },
    assign: function(target, exp) {
        var out = builder.assignmentExpression("=", target, exp);
        if ( target.type == "MemberExpression" && opt("luaOperators", false) ) {
            var prop = target.property;
            if ( !target.computed ) prop = {"type": "Literal", "value": prop.name, loc: prop.loc, range: prop.range };

            var helper;
            var nue = bhelper.translateExpressionIfNeeded(target.object);

            if ( target.object.type == "Identifier" ) helper = target.object.name;

            if ( helper === undefined ) {
                nue = bhelper.luaOperator("indexAssign", nue, prop, exp);
            } else {
                nue = bhelper.luaOperator("indexAssign", nue, prop, exp, {type:"Literal", value: helper});
            }

            nue = {type: "ConditionalExpression",test: nue, consequent: exp, alternate: out};

            out = nue;
        }

        return {
            type: "ExpressionStatement",
            expression: out
        };
    },
    encloseDecls: function(body /*, decls...*/) {
        var decls = Array.prototype.slice.call(arguments, 1);
        return bhelper.encloseDeclsEx.apply(this, [body, opt("encloseWithFunctions", true) ].concat(decls));
    },
    encloseDeclsEx: function(body, enclose /*, decls...*/) {
        var decls = Array.prototype.slice.call(arguments, 2);
        var vals = [];
        var names = [];
        for ( var k in decls ) {
            var v = decls[k];
            vals.push(v.init);
            names.push(v.id);
        }

        if ( enclose ) {
            return {
                expression: builder.callExpression(
                    builder.functionExpression(null, names, bhelper.blockStatement(body)),
                    vals
                ),
                type: "ExpressionStatement"
            }
        } else {
            if ( decls.length < 1 ) return body;
            return bhelper.blockStatement([ builder.variableDeclaration("let", decls) ].concat(body));
        }
    },
    encloseDeclsUnpack: function(body, names, explist, force) {

        if ( force || opt("encloseWithFunctions", true) ) {
            return {
                expression: builder.callExpression(
                    builder.memberExpression(
                        builder.functionExpression(null, names, builder.blockStatement(body)),
                        i("apply")
                    ),
                    [{type: "Literal", value: null}, bhelper.luaOperatorA("expandReturnValues", explist)]
                ),
                type: "ExpressionStatement"
            }
        } else {
            var decls = [];
            for ( var idx in names ) {
                decls.push({
                    type: "VariableDeclarator",
                    id: names[idx],
                    init: idx.id
                });
            }
            return bhelper.blockStatement([
                builder.variableDeclaration("let", decls),
                bhelper.bulkAssign(names, explist)
                ].concat(body));
        }
    },
    bulkAssign: function(names, explist) {
        var temps = [];
        var body = [];
        for ( var i = 0; i < names.length; ++i ) {
            temps[i] = bhelper.tempName();
            body[i] = bhelper.assign(names[i], temps[i]);
        }

        var out = bhelper.encloseDeclsUnpack(body, temps, explist, true);
        return out;
    },
    luaOperator: function(op /*, args */) {
        var o = builder.callExpression(
            builder.memberExpression(i("__lua"), i(op)),
            Array.prototype.slice.call(arguments, 1)
        );
        o.internal = true;
        return o;
    },
    luaOperatorA: function(op, args) {
        var o = builder.callExpression(
            builder.memberExpression(i("__lua"), i(op)),
            args
        );
        o.internal = true;
        return o;
    },
    binaryExpression: function(op, a, b) {
        if ( opt("luaOperators", false) ) {
            var map = {"+": "add", "-": "sub", "*": "mul", "/": "div", "^": "pow", "%":"mod",
                "..": "concat", "==": "eq", "<": "lt", "<=": "lte", ">": "gt", ">=": "gte", "~=": "ne",
                "and": "andss", "or": "orss"
            };
            if ( op == "and" || op == "or" ) {
                b = bhelper.valueProvdier(b);
            }
            return bhelper.luaOperator(map[op], a, b);
        } else {

            if ( op == "~=" ) xop = "!=";
            else if ( op == ".." ) op = "+";
            else if ( op == "or" ) op = "||";
            else if ( op == "and" ) op = "&&";

            return builder.binaryExpression(op, a, b);
        }
    },
    callExpression: function(callee, args) {
        if ( opt("luaCalls", false) ) {
            var that = {"type": "ThisExpression" };
            if ( callee.type == "MemberExpression" ) that = {"type":"Literal", "value": null};
            var flags = 0;
            if ( callee.selfSuggar ) {
                flags = flags | 1;
            }

            if ( opt('decorateLuaObjects', false) ) {
                flags = flags | 2;
            }

            var flagso = {"type": "Literal", "value": flags};
            var helper = null;

            if ( callee.type == "Identifier" ) helper = callee.name;
            else if ( callee.type == "MemberExpression" && !callee.computed ) helper = callee.property.name;

            helper = {"type": "Literal", "value": helper};

            if ( callee.selfSuggar ) {
                if ( callee.object.type == "Identifier" ) {
                    //Dont bother making a function if we are just an identifer.
                    var rcallee = bhelper.translateExpressionIfNeeded(callee)
                    return bhelper.luaOperator.apply(bhelper, ["call", flagso , rcallee, callee.object, helper].concat(args));

                } else {
                    var tmp = bhelper.tempVar(bhelper.translateExpressionIfNeeded(callee.object));

                    var rexpr = builder.memberExpression(tmp.id, callee.property, callee.computed);
                    var rcallee = bhelper.translateExpressionIfNeeded(rexpr);
                    var expr = bhelper.luaOperator.apply(bhelper, ["call", flagso, rcallee, tmp.id, helper].concat(args));
                    return result = bhelper.encloseDeclsEx([
                        builder.returnStatement(
                            expr
                        )
                    ], true, tmp).expression;

                }
            } else {
                var rcallee = bhelper.translateExpressionIfNeeded(callee)
                if ( rcallee.type == "Identifier" && rcallee.name == "assert" ) {
                    args.push({type: "Literal", value: args[0].text || "?"})
                }
                return bhelper.luaOperator.apply(bhelper, ["call", flagso , rcallee, that, helper].concat(args));
            }
        } else {
            return builder.callExpression(callee, args);
        }
    },
    memberExpression: function(obj, prop, isComputed) {
        if ( opt("luaOperators", false) && !isComputed ) {
            var helper;
            if ( obj.type == "Identifier") helper = obj.name;

            if ( helper == undefined ) {
                return bhelper.luaOperator("index", obj, prop);
            } else {
                return bhelper.luaOperator("index", obj, prop, {type:"Literal", value: helper});
            }
        }
        return builder.memberExpression(obj, prop, isComputed);
    },
    translateExpressionIfNeeded: function(exp) {
        if ( !opt("luaOperators", false) ) return exp;
        if ( exp.type == "MemberExpression" ) {
            var prop = exp.property;
            if ( !exp.computed ) prop = {"type": "Literal", value: prop.name };
            var nu = bhelper.memberExpression(bhelper.translateExpressionIfNeeded(exp.object), prop, false);
            nu.origional = exp;
            nu.range = exp.range;
            nu.loc = exp.loc;
            return nu;
        }

        return exp;
    },
    injectRest: function(block, count) {
        block.unshift(builder.variableDeclaration("let", [
                {
                    type: "VariableDeclarator",
                    id: {type: "Identifier", name:"__lua$rest"},
                    init: bhelper.luaOperator("rest",
                        {type: "Identifier", name:"arguments"},
                        {type: "Literal", value:count}
                    )
                }
             ]));
    },
    valueProvdier: function(statement) {
        return builder.functionExpression(null, [], bhelper.blockStatement([
            builder.returnStatement(statement)
        ]));
    }
  }

}
<commit_msg>- In the case of a simple assignment, try to output a simpler AST.<commit_after>{
  function loc() { return {start: { line: line(), column: column() } } }
  function range() { return [offset(), offset() + text().length]; }
  function listHelper(a,b,c) { return a == null ? [] : [a].concat(b.map(function(b) { return b[c || 2]; })); }
  function opt(name, def) { return name in options ? options[name] : def }

  function expandMultiStatements(list) {
    var out = [];
    for ( var i = 0; i < list.length; ++i ) {
        var value = list[i];
        if (value instanceof Array) out = out.concat(value);
        else out.push(value);
    }
    return out;
  }

  function wrapNode(obj, hasScope) {
    hasScope = !!hasScope
    obj.loc = loc();
    obj.range = range();
    obj.hasScope = hasScope;
    obj.text = text();
    return obj;
  }

  function eUntermIfEmpty(what, type, end, start) {
    if ( what.length == 0 ) return eUnterminated(type, end, start);
    return true;
  }

  function eUnterminated(type, end, start) {
    var xline = start !== undefined ? start.loc.start.line : (line());
    var xcol = start !== undefined ? start.loc.start.column : (column());

    eMsg("`" + (end || "end") + "` expected (to close " + type + " at " + xline + ":" + xcol + ") at " + line() +  ":" + column() );
    return true;
  }

  function eMsg(why) {
    if ( !opt("loose", false) ) error(why);
    errors.push({msg: why, loc: loc(), range: range()});
    return true;
  }

  var opPrecedence = {
    "^": 10,
    "not": 9,
    "*": 8, "/": 8,
    "+": 7, "-": 7,
    "..": 6,
    "<": 5, ">": 5, ">=": 5, "<=": 5, "==": 5, "~=": 5,
    "and": 4,
    "or": 3
  }

  function precedenceClimber(tokens, lhs, min) {
    while ( true ) {
        if ( tokens.length == 0 ) return lhs;
        var op = tokens[0];
        var prec = opPrecedence[op];
        if ( prec < min ) return lhs;
        tokens.shift();

        var rhs = tokens.shift();
        while ( true ) {
            var peek = tokens[0];
            if ( peek == null || opPrecedence[peek] <= prec ) break;
            rhs = precedenceClimber(tokens, rhs, opPrecedence[peek]);
        }

        lhs = bhelper.binaryExpression(op, lhs, rhs);
    }

  }

  var errors;

  function init() {
    errors = [];
  }

  var builder = {
    assignmentExpression: function(op, left, right) { return wrapNode({type: "AssignmentExpression", operator: op, left: left, right: right }); },
    binaryExpression: function(op, left, right) { return wrapNode({type: "BinaryExpression", operator: op, left: left, right: right }); },
    blockStatement: function(body) { return wrapNode({ type: "BlockStatement", body: body}); },
    callExpression: function(callee, args) { return wrapNode({ type: "CallExpression", callee: callee, arguments: args}); },
    emptyStatement: function() { return wrapNode({ type: "EmptyStatement" }); },
    functionDeclaration: function(name, args, body, isGenerator, isExpression) {
        return wrapNode({type: "FunctionDeclaration", id: name, params: args, body: body, generator: isGenerator, expression: isExpression });
    },
    memberExpression: function(obj, prop, isComputed) { return wrapNode({ type:"MemberExpression", object: obj, property: prop, computed: isComputed }); },
    variableDeclaration: function(kind, decls) { return { type: "VariableDeclaration", declarations: decls, kind: opt("forceVar", true) ? "var" : kind } },
    functionExpression: function(name, args, body) { return { type: "FunctionExpression", name: name, body: body, params: args } },
    returnStatement: function(arg) { return wrapNode({type: "ReturnStatement", argument: arg}); }
  };

  var i = function(n) { return { type: "Identifier", name: n}; }
  var id = i;
  var tmpVarCtr = 0;

  function clone(obj) {
    return JSON.parse(JSON.stringify(obj));
  }

  function finalize(ast) {
    if ( opt("loose", false) ) ast.errors = errors;
    if ( opt("noSharedObjects", true) ) return clone(ast);
    return ast;
  }

  var bhelper = {
    blockStatement: function(body) {
        return builder.blockStatement(expandMultiStatements(body));
    },
    tempName: function() {
        return i("__lua$tmpvar$" + (++tmpVarCtr));
    },
    tempVar: function(exp) {
        return { type: "VariableDeclarator", id: bhelper.tempName(), init: exp };
    },
    assign: function(target, exp) {
        var out = builder.assignmentExpression("=", target, exp);
        if ( target.type == "MemberExpression" && opt("luaOperators", false) ) {
            var prop = target.property;
            if ( !target.computed ) prop = {"type": "Literal", "value": prop.name, loc: prop.loc, range: prop.range };

            var helper;
            var nue = bhelper.translateExpressionIfNeeded(target.object);

            if ( target.object.type == "Identifier" ) helper = target.object.name;

            if ( helper === undefined ) {
                nue = bhelper.luaOperator("indexAssign", nue, prop, exp);
            } else {
                nue = bhelper.luaOperator("indexAssign", nue, prop, exp, {type:"Literal", value: helper});
            }

            nue = {type: "ConditionalExpression",test: nue, consequent: exp, alternate: out};

            out = nue;
        }

        return {
            type: "ExpressionStatement",
            expression: out
        };
    },
    encloseDecls: function(body /*, decls...*/) {
        var decls = Array.prototype.slice.call(arguments, 1);
        return bhelper.encloseDeclsEx.apply(this, [body, opt("encloseWithFunctions", true) ].concat(decls));
    },
    encloseDeclsEx: function(body, enclose /*, decls...*/) {
        var decls = Array.prototype.slice.call(arguments, 2);
        var vals = [];
        var names = [];
        for ( var k in decls ) {
            var v = decls[k];
            vals.push(v.init);
            names.push(v.id);
        }

        if ( enclose ) {
            return {
                expression: builder.callExpression(
                    builder.functionExpression(null, names, bhelper.blockStatement(body)),
                    vals
                ),
                type: "ExpressionStatement"
            }
        } else {
            if ( decls.length < 1 ) return body;
            return bhelper.blockStatement([ builder.variableDeclaration("let", decls) ].concat(body));
        }
    },
    encloseDeclsUnpack: function(body, names, explist, force) {

        if ( force || opt("encloseWithFunctions", true) ) {
            return {
                expression: builder.callExpression(
                    builder.memberExpression(
                        builder.functionExpression(null, names, builder.blockStatement(body)),
                        i("apply")
                    ),
                    [{type: "Literal", value: null}, bhelper.luaOperatorA("expandReturnValues", explist)]
                ),
                type: "ExpressionStatement"
            }
        } else {
            var decls = [];
            for ( var idx in names ) {
                decls.push({
                    type: "VariableDeclarator",
                    id: names[idx],
                    init: idx.id
                });
            }
            return bhelper.blockStatement([
                builder.variableDeclaration("let", decls),
                bhelper.bulkAssign(names, explist)
                ].concat(body));
        }
    },
    bulkAssign: function(names, explist) {
        var temps = [];
        var body = [];
        for ( var i = 0; i < names.length; ++i ) {
            temps[i] = bhelper.tempName();
            body[i] = bhelper.assign(names[i], temps[i]);
        }

        if ( names.length > 1 ) {
            return bhelper.encloseDeclsUnpack(body, temps, explist, true);
        } else {
            var value = explist[0];
            if ( value.type == "CallExpression" ) value = builder.callExpression(builder.memberExpression(id("__lua"),id("oneValue")),[value]);
            return bhelper.assign(names[0], value);
        }

    },
    luaOperator: function(op /*, args */) {
        var o = builder.callExpression(
            builder.memberExpression(i("__lua"), i(op)),
            Array.prototype.slice.call(arguments, 1)
        );
        o.internal = true;
        return o;
    },
    luaOperatorA: function(op, args) {
        var o = builder.callExpression(
            builder.memberExpression(i("__lua"), i(op)),
            args
        );
        o.internal = true;
        return o;
    },
    binaryExpression: function(op, a, b) {
        if ( opt("luaOperators", false) ) {
            var map = {"+": "add", "-": "sub", "*": "mul", "/": "div", "^": "pow", "%":"mod",
                "..": "concat", "==": "eq", "<": "lt", "<=": "lte", ">": "gt", ">=": "gte", "~=": "ne",
                "and": "andss", "or": "orss"
            };
            if ( op == "and" || op == "or" ) {
                b = bhelper.valueProvdier(b);
            }
            return bhelper.luaOperator(map[op], a, b);
        } else {

            if ( op == "~=" ) xop = "!=";
            else if ( op == ".." ) op = "+";
            else if ( op == "or" ) op = "||";
            else if ( op == "and" ) op = "&&";

            return builder.binaryExpression(op, a, b);
        }
    },
    callExpression: function(callee, args) {
        if ( opt("luaCalls", false) ) {
            var that = {"type": "ThisExpression" };
            if ( callee.type == "MemberExpression" ) that = {"type":"Literal", "value": null};
            var flags = 0;
            if ( callee.selfSuggar ) {
                flags = flags | 1;
            }

            if ( opt('decorateLuaObjects', false) ) {
                flags = flags | 2;
            }

            var flagso = {"type": "Literal", "value": flags};
            var helper = null;

            if ( callee.type == "Identifier" ) helper = callee.name;
            else if ( callee.type == "MemberExpression" && !callee.computed ) helper = callee.property.name;

            helper = {"type": "Literal", "value": helper};

            if ( callee.selfSuggar ) {
                if ( callee.object.type == "Identifier" ) {
                    //Dont bother making a function if we are just an identifer.
                    var rcallee = bhelper.translateExpressionIfNeeded(callee)
                    return bhelper.luaOperator.apply(bhelper, ["call", flagso , rcallee, callee.object, helper].concat(args));

                } else {
                    var tmp = bhelper.tempVar(bhelper.translateExpressionIfNeeded(callee.object));

                    var rexpr = builder.memberExpression(tmp.id, callee.property, callee.computed);
                    var rcallee = bhelper.translateExpressionIfNeeded(rexpr);
                    var expr = bhelper.luaOperator.apply(bhelper, ["call", flagso, rcallee, tmp.id, helper].concat(args));
                    return result = bhelper.encloseDeclsEx([
                        builder.returnStatement(
                            expr
                        )
                    ], true, tmp).expression;

                }
            } else {
                var rcallee = bhelper.translateExpressionIfNeeded(callee)
                if ( rcallee.type == "Identifier" && rcallee.name == "assert" ) {
                    args.push({type: "Literal", value: args[0].text || "?"})
                }
                return bhelper.luaOperator.apply(bhelper, ["call", flagso , rcallee, that, helper].concat(args));
            }
        } else {
            return builder.callExpression(callee, args);
        }
    },
    memberExpression: function(obj, prop, isComputed) {
        if ( opt("luaOperators", false) && !isComputed ) {
            var helper;
            if ( obj.type == "Identifier") helper = obj.name;

            if ( helper == undefined ) {
                return bhelper.luaOperator("index", obj, prop);
            } else {
                return bhelper.luaOperator("index", obj, prop, {type:"Literal", value: helper});
            }
        }
        return builder.memberExpression(obj, prop, isComputed);
    },
    translateExpressionIfNeeded: function(exp) {
        if ( !opt("luaOperators", false) ) return exp;
        if ( exp.type == "MemberExpression" ) {
            var prop = exp.property;
            if ( !exp.computed ) prop = {"type": "Literal", value: prop.name };
            var nu = bhelper.memberExpression(bhelper.translateExpressionIfNeeded(exp.object), prop, false);
            nu.origional = exp;
            nu.range = exp.range;
            nu.loc = exp.loc;
            return nu;
        }

        return exp;
    },
    injectRest: function(block, count) {
        block.unshift(builder.variableDeclaration("let", [
                {
                    type: "VariableDeclarator",
                    id: {type: "Identifier", name:"__lua$rest"},
                    init: bhelper.luaOperator("rest",
                        {type: "Identifier", name:"arguments"},
                        {type: "Literal", value:count}
                    )
                }
             ]));
    },
    valueProvdier: function(statement) {
        return builder.functionExpression(null, [], bhelper.blockStatement([
            builder.returnStatement(statement)
        ]));
    }
  }

}
<|endoftext|>


<commit_before>'use strict';

function init() {
  // Initialise la listHON
  hon_listHON.init();
}
init();

function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this;
    var args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) {
        func.apply(context, args);
      }
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) {
      func.apply(context, args);
    }
  };
}

function checkHonCode(url) {
  hon_listHON.checkURL(hon_listHON.formatHREF(url)).then(function(code) {
    if (code) {
      chrome.browserAction.setIcon({path: 'images/icon-48.png'});
    } else {
      chrome.browserAction.setIcon({path: 'images/icon-invalid-48.png'});
    }
  });
}

chrome.tabs.onActivated.addListener(function(activeInfo) {
  chrome.tabs.get(activeInfo.tabId, function(tab) {
    checkHonCode(tab.url);
  });
});

chrome.webRequest.onCompleted.addListener(function() {
  chrome.tabs.query({active: true}, function(tabs) {
    checkHonCode(tabs[0].url);
  });
},{
  types: ['xmlhttprequest'],
  urls: ['<all_urls>'],
});

chrome.browserAction.onClicked.addListener(function(tab) {
  hon_listHON.checkURL(hon_listHON.formatHREF(tab.url)).then(function(code) {
    if (code) {
      var action_url = 'https://www.hon.ch/HONcode/Conduct.html?' +
        code;
      chrome.tabs.create({ url: action_url });
    }
  });
});

chrome.webRequest.onCompleted.addListener(debounce(function(details) {
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'bower_components/jquery/dist/jquery.min.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/tld.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/md5.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/hash.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/honcode.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/listHON.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(details.tabId, {
      file: 'scripts/contentscript.js',
      allFrames: true,
    });
  }, 1000), {
  urls: [
    '*://*.google.com/*',
    '*://*.google.ch/*',
    '*://*.google.fr/*',
    '*://*.google.co.uk/*',
    '*://*.google.it/*',
    '*://*.google.bg/*',
    '*://*.google.cz/*',
    '*://*.google.dk/*',
    '*://*.google.gr/*',
    '*://*.google.ee/*',
    '*://*.google.es/*',
    '*://*.google.hr/*',
    '*://*.google.lv/*',
    '*://*.google.lt/*',
    '*://*.google.hu/*',
    '*://*.google.com.mt/*',
    '*://*.google.nl/*',
    '*://*.google.pl/*',
    '*://*.google.pt/*',
    '*://*.google.ro/*',
    '*://*.google.si/*',
    '*://*.google.sk/*',
    '*://*.google.se/*',
    '*://*.bing.com/*',
    '*://*.bing.com/*',
    '*://*.search.yahoo.com/*',
    '*://*.wikipedia.org/*',
    '*://*.nlm.nih.gov/medlineplus/*',
  ],
  types: ['xmlhttprequest'],
});
<commit_msg>better event listener<commit_after>'use strict';

function init() {
  // Initialise la listHON
  hon_listHON.init();
}
init();

function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this;
    var args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) {
        func.apply(context, args);
      }
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) {
      func.apply(context, args);
    }
  };
}

function checkHonCode(url) {
  hon_listHON.checkURL(hon_listHON.formatHREF(url)).then(function(code) {
    if (code) {
      chrome.browserAction.setIcon({path: 'images/icon-48.png'});
    } else {
      chrome.browserAction.setIcon({path: 'images/icon-invalid-48.png'});
    }
  });
}

chrome.tabs.onActivated.addListener(function(activeInfo) {
  chrome.tabs.get(activeInfo.tabId, function(tab) {
    checkHonCode(tab.url);
  });
});

chrome.tabs.onUpdated.addListener(function() {
  chrome.tabs.query({active: true}, function(tabs) {
    checkHonCode(tabs[0].url);
  });
});

chrome.browserAction.onClicked.addListener(function(tab) {
  hon_listHON.checkURL(hon_listHON.formatHREF(tab.url)).then(function(code) {
    if (code) {
      var action_url = 'https://www.hon.ch/HONcode/Conduct.html?' +
        code;
      chrome.tabs.create({ url: action_url });
    }
  });
});

chrome.webRequest.onCompleted.addListener(debounce(function(details) {
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'bower_components/jquery/dist/jquery.min.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/tld.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/md5.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/hash.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/honcode.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/listHON.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(details.tabId, {
      file: 'scripts/contentscript.js',
      allFrames: true,
    });
  }, 1000), {
  urls: [
    '*://*.google.com/*',
    '*://*.google.ch/*',
    '*://*.google.fr/*',
    '*://*.google.co.uk/*',
    '*://*.google.it/*',
    '*://*.google.bg/*',
    '*://*.google.cz/*',
    '*://*.google.dk/*',
    '*://*.google.gr/*',
    '*://*.google.ee/*',
    '*://*.google.es/*',
    '*://*.google.hr/*',
    '*://*.google.lv/*',
    '*://*.google.lt/*',
    '*://*.google.hu/*',
    '*://*.google.com.mt/*',
    '*://*.google.nl/*',
    '*://*.google.pl/*',
    '*://*.google.pt/*',
    '*://*.google.ro/*',
    '*://*.google.si/*',
    '*://*.google.sk/*',
    '*://*.google.se/*',
    '*://*.bing.com/*',
    '*://*.bing.com/*',
    '*://*.search.yahoo.com/*',
    '*://*.wikipedia.org/*',
    '*://*.nlm.nih.gov/medlineplus/*',
  ],
  types: ['xmlhttprequest'],
});
<|endoftext|>


<commit_before>// Turn on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;

jasmine.DEFAULT_TIMEOUT_INTERVAL = 100;

// Cancel Karma's synchronous start,
// we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function () {
};

System.config({
    packages: {
        'angular2': {
            defaultExtension: false
        },
        'base/app': {
            defaultExtension: 'js'
        }
    }
});

// Import all the specs, execute their `main()` method and kick off Karma (Jasmine).
System.import('angular2/src/core/dom/browser_adapter').then(function (browser_adapter) {
    browser_adapter.BrowserDomAdapter.makeCurrent();
}).then(function () {
        return Promise.all(
            Object.keys(window.__karma__.files)
                .filter(onlySpecFiles)
                .map(function (path) {
                    return System.import(path).then(function(module) {
                        if (module.hasOwnProperty('main')) {
                            module.main();
                        } else {
                            throw new Error('Unit-test module ' + path + ' does not implement main() method.');
                        }
                    });
                })
        );
    })
    .then(function () {
        __karma__.start();
    }, function (error) {
        __karma__.error(error.stack || error);
    });

function onlySpecFiles(path) {
    return /_spec\.js$/.test(path);
}
<commit_msg>test: fixes unit-tests after upgrading Angular to 2.0.0-alpha.47<commit_after>// Turn on full stack traces in errors to help debugging
Error.stackTraceLimit = Infinity;

jasmine.DEFAULT_TIMEOUT_INTERVAL = 100;

// Cancel Karma's synchronous start,
// we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function () {
};

System.config({
    packages: {
        'angular2': {
            defaultExtension: false
        },
        'base/app': {
            defaultExtension: 'js'
        }
    }
});

// Import all the specs, execute their `main()` method and kick off Karma (Jasmine).
System.import('angular2/platform/browser').then(function (browser) {
    browser.BrowserDomAdapter.makeCurrent();
}).then(function () {
        return Promise.all(
            Object.keys(window.__karma__.files)
                .filter(onlySpecFiles)
                .map(function (path) {
                    return System.import(path).then(function(module) {
                        if (module.hasOwnProperty('main')) {
                            module.main();
                        } else {
                            throw new Error('Unit-test module ' + path + ' does not implement main() method.');
                        }
                    });
                })
        );
    })
    .then(function () {
        __karma__.start();
    }, function (error) {
        __karma__.error(error.stack || error);
    });

function onlySpecFiles(path) {
    return /_spec\.js$/.test(path);
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { FormGroup, Checkbox, Glyphicon } from 'react-bootstrap'

const propTypes = {
  phenotypes      : PropTypes.array,
  togglePhenotype : PropTypes.func,
  removePhenotype : PropTypes.func
}

class SelectedPhenotypes extends Component {
  render () {
    const { phenotypes, togglePhenotype, removePhenotype } = this.props
    return

      Selected phenotypes:
      <form>
        <FormGroup>
          {phenotypes.map((pheno, index) => <Checkbox inline checked={pheno.active}
            onClick={() => togglePhenotype(index)}>
            {pheno.value.name}
            <Glyphicon glyph='remove' onClick={() => removePhenotype(index)} />
          </Checkbox>)}
        </FormGroup>
      </form>

  }
}

SelectedPhenotypes.propTypes = propTypes
export default SelectedPhenotypes
<commit_msg>Fix warning: checkbox without onChange attribute<commit_after>import React, { Component, PropTypes } from 'react'
import { FormGroup, Checkbox, Glyphicon } from 'react-bootstrap'

const propTypes = {
  phenotypes      : PropTypes.array,
  togglePhenotype : PropTypes.func,
  removePhenotype : PropTypes.func
}

class SelectedPhenotypes extends Component {
  render () {
    const { phenotypes, togglePhenotype, removePhenotype } = this.props
    return

      Selected phenotypes:
      <form>
        <FormGroup>
          {phenotypes.map((pheno, index) => <Checkbox key={index} inline checked={pheno.active}
            onChange={() => togglePhenotype(index)}>
            {pheno.value.name}
            <Glyphicon glyph='remove' onClick={() => removePhenotype(index)} />
          </Checkbox>)}
        </FormGroup>
      </form>

  }
}

SelectedPhenotypes.propTypes = propTypes
export default SelectedPhenotypes
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { validate } from 'parameter-validator';
import { color1 } from '../../style-variables';
import { MusicNoteEventType } from 'react-native-voxophone-engine';
import delay from '../../utils/delay';
import Ring from '../music-note-meter-ring';

const NUMBER_OF_RINGS = 8;
const NOTE_ON_TRANSITION_MILLISECONDS = 40;
const NOTE_OFF_TRANSITION_MILLISECONDS = 100;
const TOTAL_HUE_LIGHTNESS_CHANGE = 0.5;
const RANDOM_COLORS_ENABLED = true;

const meterCenterDiameter = 140;

const styles = StyleSheet.create({

    musicNoteMeter: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        // backgroundColor: 'green',
        // borderRadius: 170
    },
    meterCenter: {
        flexGrow: 0,
        flexShrink: 0,
        flexBasis: 'auto',
        height: meterCenterDiameter,
        width: meterCenterDiameter,
        borderRadius: meterCenterDiameter / 2,
        backgroundColor: 'white',
        alignItems: 'center',
        justifyContent: 'center',
    },
    meterCenterText: {
        color: color1,
        fontSize: 72,
        fontWeight: 'bold'
    }
});

/**
* Illustrates the volume envelope of a note played using concentric circles and
* displays the name of the note being played (e.g. "C#").
*/
export default class MusicNoteMeter extends Component {

    constructor(props) {

        super(props);
        validate(props.dependencies, [ 'logger', 'voxophone' ], this, { addPrefix: '_' });
        this._voxophone.addMusicNoteListener(this._handleMusicNoteEvent.bind(this));
        this.state = { note: '' };

        // return this._createAndConfigureRings()
        // .then(rings => {
        //     this._rings = rings;
        //     this._noteOff();
        // });
    }

    render() {
        return (
            <View style={styles.musicNoteMeter}>

                {this._renderRings(NUMBER_OF_RINGS, this.props.diameter, meterCenterDiameter,
                    <View style={styles.meterCenter}>
                        <Text style={styles.meterCenterText}>C#</Text>
                    </View>
                )}
            </View>
        );
    }

    _renderRings(numberOfRingsLeft, diameter, centerDiameter, center) {

        let distanceToCenter = diameter - centerDiameter,
            ringThickness = Math.floor(distanceToCenter / numberOfRingsLeft),
            nextRingDiameter = diameter - ringThickness;

        return (
            <Ring backgroundColor={this._getRandomColor()} diameter={diameter}>
                {--numberOfRingsLeft > 0 ? this._renderRings(numberOfRingsLeft, nextRingDiameter, centerDiameter, center) : center}
            </Ring>
        );
    }

    _handleMusicNoteEvent(event) {

        if (event.type === MusicNoteEventType.NOTE_ON) {

            this.setState({ note: event.note });
            // this._noteOn(event.note);
        } else {
            // this._noteOff();
        }
    }

    /* eslint-disable */

    /**
    * Illustrates that a given note has been played
    *
    * @param {string} note - e.g. 'C#'
    */
    _noteOn(note) {

        let delayPerRing = NOTE_ON_TRANSITION_MILLISECONDS / this._rings.length;
        let promisedDisplayUpdate = Promise.resolve().then(() => this.set('note', note));

        // Sequentially render each ring, adding a delay between each to stretch it out to the desired time.
        return this._rings.reduce((promise, ring) => {
            return promise
            .then(() => this._setRingVisibility(ring, true))
            .then(() => delay(delayPerRing));
        }, promisedDisplayUpdate);
    }

    /**
    * Updates the display when a note has stopped being played.
    */
    _noteOff() {

        let reversedRings = [ ...this._rings ].reverse();
        let delayPerRing = NOTE_OFF_TRANSITION_MILLISECONDS / this._rings.length;

        // Sequentially erase each ring, adding a delay between each to stretch it out to the desired time.
        return reversedRings.reduce((promise, ring) => {
            return promise
            .then(() => this._setRingVisibility(ring, false))
            .then(() => delay(delayPerRing));
        }, Promise.resolve());
    }

    /**
    * Draws or hides the given ring.
    *
    * @param {ui/View} ring
    * @param {boolean} isVisible
    */
    _setRingVisibility(ring, isVisible) {

        ring.backgroundColor = isVisible ? this._getColorForRing(ring) : this.view.page.backgroundColor;
    }

    /**
    * Creates and hooks up the ring-shaped views arranged in concentric circles that are used in the UI.
    *
    * @returns {Promise.<Array.<View>>} - Array where each item is a View that is a ring in the music note meter's UI.
    *                                     The rings go from the center to the circumference as the index increases.
    */
    _createAndConfigureRings() {

        return this._getOuterRing()
        .then(outerRing => {

            let center = this.view.getViewById('meter-center');
            this.view.removeChild(center);

            let radiusLengthToDivide = outerRing.borderRadius - center.borderRadius;
            let radiusStepSize = radiusLengthToDivide / NUMBER_OF_RINGS;

            let numberOfRingsToCreate = NUMBER_OF_RINGS - 1; // Subtract one, since the outer ring already exists.
            let rings = this._createRings(center, numberOfRingsToCreate, radiusStepSize);
            rings.push(outerRing);

            // Link the rings together in a parent-child hierarchy.
            this._linkRingsTogether(rings);
            rings[0].addChild(center);

            this._setRingColors(rings);
            return rings;
        })
        .catch(error => this._logger.error(`An error occurred during ring creation.`, { error }));
    }

    /**
    * @param   {ui/View}        centerRing     - The initial, center ring on which the size of the other rings will be based.
    * @param   {int}            numberOfRings  - Total number of rings to render
    * @param   {int}            radiusStepSize - The distance in pixels between the border of a ring and the border of the ring
    *                                            immediately outside of it.
    * @returns {Array.<ui/View}
    */
    _createRings(centerRing, numberOfRings, radiusStepSize) {

        let previousRing = centerRing,
            rings = [];

        for (let i = 0; i < numberOfRings; i++) {

            let radius = previousRing.borderRadius + radiusStepSize;
            let ring = this._createRing(radius);
            rings.push(ring);
            previousRing = ring;
        }
        return rings;
    }

    _createRing(radius) {

        let ring = new FlexboxLayout();
        ring.height = ring.width = radius * 2;
        ring.borderRadius = radius;
        ring.alignItems = AlignItems.CENTER;
        ring.justifyContent = JustifyContent.CENTER;
        FlexboxLayout.setFlexGrow(ring, 0);
        FlexboxLayout.setFlexShrink(ring, 0);
        return ring;
    }

    /**
    * Gets a reference to the existing view which will serve as the outermost ring and
    * then configures and returns it.
    *
    * @returns {Promise.<ui/View>}
    */
    _getOuterRing() {

        return Promise.resolve()
        .then(() => {

            let outerRing = this.view;
            let outerRingSize = outerRing.getActualSize();
            let outerRingRadius = Math.min(outerRingSize.height, outerRingSize.width) / 2;

            if (outerRingRadius === 0) {
                // The view hasn't been fully initialized. Let's try again in 1 millisecond.
                return delay(1).then(() => this._getOuterRing());
            }
            // Set the height and width equal to each other, because this view is initially just a rectangle.
            outerRing.height = this.view.width = outerRingRadius * 2;
            outerRing.borderRadius = outerRingRadius;
            return outerRing;
        });
    }

    _getRandomColor() {

        let num = Math.floor(Math.random() * 0xFFFFFF);
        let hex = num.toString(16).padStart(6, '0');
        return '#' + hex;
    }

    _linkRingsTogether(rings) {

        rings.forEach((ring, index) => {
            let parentRing = rings[index + 1];

            if (parentRing) {
                parentRing.addChild(ring);
            }
        });
    }

    _setRingColors(rings) {

        rings.forEach((ring, index) => {
            ring.backgroundColor = this._getColorForRingIndex(index);
        });
    }

    _getColorForRing(ring) {

        let ringIndex = this._rings.indexOf(ring);
        return this._getColorForRingIndex(ringIndex);
    }

    _getColorForRingIndex(ringIndex) {

        if (RANDOM_COLORS_ENABLED) {
            return this._getRandomColor();
        }

        let lightnessStepSize = TOTAL_HUE_LIGHTNESS_CHANGE / NUMBER_OF_RINGS;
        let rootColor = '#ff871e';
        let { r, g, b } = ColorEditor(rootColor).darken(ringIndex * lightnessStepSize).rgb().object();
        return new Color(255, r, g, b);
    }
}
<commit_msg>I now have the music note meter's animation working so that it blinks.<commit_after>import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import _ from 'lodash';
import { validate } from 'parameter-validator';
import { color1 } from '../../style-variables';
import { MusicNoteEventType } from 'react-native-voxophone-engine';
import delay from '../../utils/delay';
import Ring from '../music-note-meter-ring';

const NUMBER_OF_RINGS = 8;
const NOTE_ON_TRANSITION_MILLISECONDS = 40;
const NOTE_OFF_TRANSITION_MILLISECONDS = 100;
const TOTAL_HUE_LIGHTNESS_CHANGE = 0.5;
const RANDOM_COLORS_ENABLED = true;

const meterCenterDiameter = 140;

const styles = StyleSheet.create({

    musicNoteMeter: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        // backgroundColor: 'green',
        // borderRadius: 170
    },
    meterCenter: {
        flexGrow: 0,
        flexShrink: 0,
        flexBasis: 'auto',
        height: meterCenterDiameter,
        width: meterCenterDiameter,
        borderRadius: meterCenterDiameter / 2,
        backgroundColor: 'white',
        alignItems: 'center',
        justifyContent: 'center',
    },
    meterCenterText: {
        color: color1,
        fontSize: 72,
        fontWeight: 'bold'
    }
});

/**
* Illustrates the volume envelope of a note played using concentric circles and
* displays the name of the note being played (e.g. "C#").
*/
export default class MusicNoteMeter extends Component {

    constructor(props) {

        super(props);
        validate(props.dependencies, [ 'logger', 'voxophone' ], this, { addPrefix: '_' });
        this._voxophone.addMusicNoteListener(this._handleMusicNoteEvent.bind(this));

        this.state = {
            note: '',
            rings: _.range(NUMBER_OF_RINGS).map(() => ({ isVisible: false, color: 'white' }))
        };

        this._blink();
    }

    render() {
        return (
            <View style={styles.musicNoteMeter}>

                {this._renderRings(this.state.rings, this.props.diameter, meterCenterDiameter,
                    <View style={styles.meterCenter}>
                        <Text style={styles.meterCenterText}>C#</Text>
                    </View>
                )}
            </View>
        );
    }

    _renderRings(rings, diameter, centerDiameter, center) {

        let distanceToCenter = diameter - centerDiameter,
            ringThickness = Math.floor(distanceToCenter / rings.length),
            nextRingDiameter = diameter - ringThickness,
            ring = rings[0],
            color = ring.isVisible ? ring.color : 'white';

        return (
            <Ring backgroundColor={color} diameter={diameter}>
                {rings.length > 1 ? this._renderRings(rings.slice(1), nextRingDiameter, centerDiameter, center) : center}
            </Ring>
        );
    }

    _blink() {

        return delay(2000)
        .then(() => {

            this._noteIsOn = !this._noteIsOn;
            return this._noteIsOn ? this._noteOn('C#') : this._noteOff();
        })
        .then(() => this._blink());
    }

    _handleMusicNoteEvent(event) {

        if (event.type === MusicNoteEventType.NOTE_ON) {

            this.setState({ note: event.note });
            // this._noteOn(event.note);
        } else {
            // this._noteOff();
        }
    }

    /* eslint-disable */

    /**
    * Illustrates that a given note has been played
    *
    * @param {string} note - e.g. 'C#'
    */
    _noteOn(note) {

        let reversedRings = [ ...this.state.rings ].reverse();
        let delayPerRing = NOTE_ON_TRANSITION_MILLISECONDS / this.state.rings.length;
        let promisedDisplayUpdate = Promise.resolve().then(() => this.setState({ note }));

        // Sequentially render each ring, adding a delay between each to stretch it out to the desired time.
        return reversedRings.reduce((promise, ring) => {
            return promise
            .then(() => {
                ring.color = this._getRandomColor();
                ring.isVisible = true;
                this.setState({
                    rings: this.state.rings
                });
                return delay(delayPerRing)
            });
        }, promisedDisplayUpdate);
    }

    /**
    * Updates the display when a note has stopped being played.
    */
    _noteOff() {

        let delayPerRing = NOTE_OFF_TRANSITION_MILLISECONDS / this.state.rings.length;

        // Sequentially erase each ring, adding a delay between each to stretch it out to the desired time.
        return this.state.rings.reduce((promise, ring) => {
            return promise
            .then(() => {
                ring.isVisible = false;
                this.setState({
                    rings: this.state.rings
                });
                return delay(delayPerRing);
            });
        }, Promise.resolve());
    }

    /**
    * Creates and hooks up the ring-shaped views arranged in concentric circles that are used in the UI.
    *
    * @returns {Promise.<Array.<View>>} - Array where each item is a View that is a ring in the music note meter's UI.
    *                                     The rings go from the center to the circumference as the index increases.
    */
    _createAndConfigureRings() {

        return this._getOuterRing()
        .then(outerRing => {

            let center = this.view.getViewById('meter-center');
            this.view.removeChild(center);

            let radiusLengthToDivide = outerRing.borderRadius - center.borderRadius;
            let radiusStepSize = radiusLengthToDivide / NUMBER_OF_RINGS;

            let numberOfRingsToCreate = NUMBER_OF_RINGS - 1; // Subtract one, since the outer ring already exists.
            let rings = this._createRings(center, numberOfRingsToCreate, radiusStepSize);
            rings.push(outerRing);

            // Link the rings together in a parent-child hierarchy.
            this._linkRingsTogether(rings);
            rings[0].addChild(center);

            this._setRingColors(rings);
            return rings;
        })
        .catch(error => this._logger.error(`An error occurred during ring creation.`, { error }));
    }

    /**
    * @param   {ui/View}        centerRing     - The initial, center ring on which the size of the other rings will be based.
    * @param   {int}            numberOfRings  - Total number of rings to render
    * @param   {int}            radiusStepSize - The distance in pixels between the border of a ring and the border of the ring
    *                                            immediately outside of it.
    * @returns {Array.<ui/View}
    */
    _createRings(centerRing, numberOfRings, radiusStepSize) {

        let previousRing = centerRing,
            rings = [];

        for (let i = 0; i < numberOfRings; i++) {

            let radius = previousRing.borderRadius + radiusStepSize;
            let ring = this._createRing(radius);
            rings.push(ring);
            previousRing = ring;
        }
        return rings;
    }

    _createRing(radius) {

        let ring = new FlexboxLayout();
        ring.height = ring.width = radius * 2;
        ring.borderRadius = radius;
        ring.alignItems = AlignItems.CENTER;
        ring.justifyContent = JustifyContent.CENTER;
        FlexboxLayout.setFlexGrow(ring, 0);
        FlexboxLayout.setFlexShrink(ring, 0);
        return ring;
    }

    /**
    * Gets a reference to the existing view which will serve as the outermost ring and
    * then configures and returns it.
    *
    * @returns {Promise.<ui/View>}
    */
    _getOuterRing() {

        return Promise.resolve()
        .then(() => {

            let outerRing = this.view;
            let outerRingSize = outerRing.getActualSize();
            let outerRingRadius = Math.min(outerRingSize.height, outerRingSize.width) / 2;

            if (outerRingRadius === 0) {
                // The view hasn't been fully initialized. Let's try again in 1 millisecond.
                return delay(1).then(() => this._getOuterRing());
            }
            // Set the height and width equal to each other, because this view is initially just a rectangle.
            outerRing.height = this.view.width = outerRingRadius * 2;
            outerRing.borderRadius = outerRingRadius;
            return outerRing;
        });
    }

    _getRandomColor() {

        let num = Math.floor(Math.random() * 0xFFFFFF);
        let hex = num.toString(16).padStart(6, '0');
        return '#' + hex;
    }

    _linkRingsTogether(rings) {

        rings.forEach((ring, index) => {
            let parentRing = rings[index + 1];

            if (parentRing) {
                parentRing.addChild(ring);
            }
        });
    }

    _setRingColors(rings) {

        rings.forEach((ring, index) => {
            ring.backgroundColor = this._getColorForRingIndex(index);
        });
    }

    _getColorForRing(ring) {

        let ringIndex = this._rings.indexOf(ring);
        return this._getColorForRingIndex(ringIndex);
    }

    _getColorForRingIndex(ringIndex) {

        if (RANDOM_COLORS_ENABLED) {
            return this._getRandomColor();
        }

        let lightnessStepSize = TOTAL_HUE_LIGHTNESS_CHANGE / NUMBER_OF_RINGS;
        let rootColor = '#ff871e';
        let { r, g, b } = ColorEditor(rootColor).darken(ringIndex * lightnessStepSize).rgb().object();
        return new Color(255, r, g, b);
    }
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from '../styles';
import { capitalize } from '../utils/helpers';

export const styles = theme => {
  const light = theme.palette.type === 'light';
  const align = theme.direction === 'rtl' ? 'right' : 'left';

  return {
    /* Styles applied to the root element. */
    root: {
      position: 'absolute',
      bottom: 0,
      right: 0,
      top: -5,
      left: 0,
      margin: 0,
      padding: 0,
      pointerEvents: 'none',
      borderRadius: theme.shape.borderRadius,
      borderStyle: 'solid',
      borderWidth: 1,
      borderColor: light ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)',
      // Match the Input Label
      transition: theme.transitions.create([`padding-${align}`, 'border-color', 'border-width'], {
        duration: theme.transitions.duration.shorter,
        easing: theme.transitions.easing.easeOut,
      }),
    },
    /* Styles applied to the legend element. */
    legend: {
      textAlign: 'left',
      padding: 0,
      lineHeight: '10px',
      transition: theme.transitions.create('width', {
        duration: theme.transitions.duration.shorter,
        easing: theme.transitions.easing.easeOut,
      }),
      // Firefox workaround. Firefox will only obscure the
      // rendered height of the legend and, unlike other browsers,
      // will not push fieldset contents.
      '@supports (-moz-appearance:none)': {
        height: 2,
      },
    },
  };
};

/**
 * @ignore - internal component.
 */
function NotchedOutline(props) {
  const {
    children,
    classes,
    className,
    labelWidth: labelWidthProp,
    notched,
    style,
    theme,
    ...other
  } = props;

  const align = theme.direction === 'rtl' ? 'right' : 'left';
  const labelWidth = labelWidthProp > 0 ? labelWidthProp * 0.75 + 8 : 0;

  return (
    <fieldset
      aria-hidden
      style={{
        [`padding${capitalize(align)}`]: 8 + (notched ? 0 : labelWidth / 2),
        ...style,
      }}
      className={classNames(classes.root, className)}
      {...other}
    >
      <legend
        className={classes.legend}
        style={{
          // IE 11: fieldset with legend does not render
          // a border radius. This maintains consistency
          // by always having a legend rendered
          width: notched ? labelWidth : 0.01,
        }}
      >
        {/* Use the nominal use case of the legend, avoid rendering artefacts. */}
        {/* eslint-disable-next-line react/no-danger */}

      </legend>
    </fieldset>
  );
}

NotchedOutline.propTypes = {
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css-api) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The width of the legend.
   */
  labelWidth: PropTypes.number.isRequired,
  /**
   * If `true`, the outline is notched to accommodate the label.
   */
  notched: PropTypes.bool.isRequired,
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * @ignore
   */
  theme: PropTypes.object,
};

export default withStyles(styles, { name: 'MuiPrivateNotchedOutline', withTheme: true })(
  NotchedOutline,
);
<commit_msg>[OutlinedInput] Remove Firefox workaround (#13519)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from '../styles';
import { capitalize } from '../utils/helpers';

export const styles = theme => {
  const light = theme.palette.type === 'light';
  const align = theme.direction === 'rtl' ? 'right' : 'left';

  return {
    /* Styles applied to the root element. */
    root: {
      position: 'absolute',
      bottom: 0,
      right: 0,
      top: -5,
      left: 0,
      margin: 0,
      padding: 0,
      pointerEvents: 'none',
      borderRadius: theme.shape.borderRadius,
      borderStyle: 'solid',
      borderWidth: 1,
      borderColor: light ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)',
      // Match the Input Label
      transition: theme.transitions.create([`padding-${align}`, 'border-color', 'border-width'], {
        duration: theme.transitions.duration.shorter,
        easing: theme.transitions.easing.easeOut,
      }),
    },
    /* Styles applied to the legend element. */
    legend: {
      textAlign: 'left',
      padding: 0,
      lineHeight: '10px',
      transition: theme.transitions.create('width', {
        duration: theme.transitions.duration.shorter,
        easing: theme.transitions.easing.easeOut,
      }),
    },
  };
};

/**
 * @ignore - internal component.
 */
function NotchedOutline(props) {
  const {
    children,
    classes,
    className,
    labelWidth: labelWidthProp,
    notched,
    style,
    theme,
    ...other
  } = props;

  const align = theme.direction === 'rtl' ? 'right' : 'left';
  const labelWidth = labelWidthProp > 0 ? labelWidthProp * 0.75 + 8 : 0;

  return (
    <fieldset
      aria-hidden
      style={{
        [`padding${capitalize(align)}`]: 8 + (notched ? 0 : labelWidth / 2),
        ...style,
      }}
      className={classNames(classes.root, className)}
      {...other}
    >
      <legend
        className={classes.legend}
        style={{
          // IE 11: fieldset with legend does not render
          // a border radius. This maintains consistency
          // by always having a legend rendered
          width: notched ? labelWidth : 0.01,
        }}
      >
        {/* Use the nominal use case of the legend, avoid rendering artefacts. */}
        {/* eslint-disable-next-line react/no-danger */}

      </legend>
    </fieldset>
  );
}

NotchedOutline.propTypes = {
  /**
   * Override or extend the styles applied to the component.
   * See [CSS API](#css-api) below for more details.
   */
  classes: PropTypes.object,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The width of the legend.
   */
  labelWidth: PropTypes.number.isRequired,
  /**
   * If `true`, the outline is notched to accommodate the label.
   */
  notched: PropTypes.bool.isRequired,
  /**
   * @ignore
   */
  style: PropTypes.object,
  /**
   * @ignore
   */
  theme: PropTypes.object,
};

export default withStyles(styles, { name: 'MuiPrivateNotchedOutline', withTheme: true })(
  NotchedOutline,
);
<|endoftext|>


<commit_before>/* globals describe, it, expect, expectObservable, expectSubscriptions, cold, hot */
var Rx = require('../../dist/cjs/Rx');
var Observable = Rx.Observable;

describe('Observable.prototype.skip()', function () {
  it('should skip values before a total', function () {
    var source = hot('--a--b--c--d--e--|');
    var subs =       '^                !';
    var expected =   '-----------d--e--|';

    expectObservable(source.skip(3)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should skip all values without error if total is more than actual number of values', function () {
    var source = hot('--a--b--c--d--e--|');
    var subs =       '^                !';
    var expected =   '-----------------|';

    expectObservable(source.skip(6)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should skip all values without error if total is same as actual number of values', function () {
    var source = hot('--a--b--c--d--e--|');
    var subs =       '^                !';
    var expected =   '-----------------|';

    expectObservable(source.skip(5)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should not skip if count is zero', function () {
    var source = hot('--a--b--c--d--e--|');
    var subs =       '^                !';
    var expected =   '--a--b--c--d--e--|';

    expectObservable(source.skip(0)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should allow unsubscribing explicitly and early', function () {
    var source = hot('--a--b--c--d--e--|');
    var unsub =      '          !       ';
    var subs =       '^         !       ';
    var expected =   '--------c--       ';

    expectObservable(source.skip(2), unsub).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should raise error if skip count is more than actual number of emits and source raises error', function () {
    var source = hot('--a--b--c--d--#');
    var subs =       '^             !';
    var expected =   '--------------#';

    expectObservable(source.skip(6)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should raise error if skip count is same as emits of source and source raises error', function () {
    var source = hot('--a--b--c--d--#');
    var subs =       '^             !';
    var expected =   '--------------#';

    expectObservable(source.skip(4)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should skip values before a total and raises error if source raises error', function () {
    var source = hot('--a--b--c--d--#');
    var subs =       '^             !';
    var expected =   '-----------d--#';

    expectObservable(source.skip(3)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should complete regardless of skip count if source is empty', function () {
    var e1 =  cold('|');
    var e1subs =   '(^!)';
    var expected = '|';

    expectObservable(e1.skip(3)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should not complete if source never completes without emit', function () {
    var e1 =   hot('-');
    var e1subs =   '^';
    var expected = '-';

    expectObservable(e1.skip(3)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should skip values before total and never completes if source emits and does not complete', function () {
    var e1 =   hot('--a--b--c-');
    var e1subs =   '^         ';
    var expected = '-----b--c-';

    expectObservable(e1.skip(1)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should skip all values and never completes if total is more than numbers of value and source does not complete', function () {
    var e1 =   hot('--a--b--c-');
    var e1subs =   '^         ';
    var expected = '----------';

    expectObservable(e1.skip(6)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should skip all values and never completes if total is same asnumbers of value and source does not complete', function () {
    var e1 =   hot('--a--b--c-');
    var e1subs =   '^         ';
    var expected = '----------';

    expectObservable(e1.skip(3)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should raise error if source throws', function () {
    var e1 =  cold('#');
    var e1subs =   '(^!)';
    var expected = '#';

    expectObservable(e1.skip(3)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });
});<commit_msg>test(skip): add test against breaking unsubscription chain<commit_after>/* globals describe, it, expect, expectObservable, expectSubscriptions, cold, hot */
var Rx = require('../../dist/cjs/Rx');
var Observable = Rx.Observable;

describe('Observable.prototype.skip()', function () {
  it('should skip values before a total', function () {
    var source = hot('--a--b--c--d--e--|');
    var subs =       '^                !';
    var expected =   '-----------d--e--|';

    expectObservable(source.skip(3)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should skip all values without error if total is more than actual number of values', function () {
    var source = hot('--a--b--c--d--e--|');
    var subs =       '^                !';
    var expected =   '-----------------|';

    expectObservable(source.skip(6)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should skip all values without error if total is same as actual number of values', function () {
    var source = hot('--a--b--c--d--e--|');
    var subs =       '^                !';
    var expected =   '-----------------|';

    expectObservable(source.skip(5)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should not skip if count is zero', function () {
    var source = hot('--a--b--c--d--e--|');
    var subs =       '^                !';
    var expected =   '--a--b--c--d--e--|';

    expectObservable(source.skip(0)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should allow unsubscribing explicitly and early', function () {
    var source = hot('--a--b--c--d--e--|');
    var unsub =      '          !       ';
    var subs =       '^         !       ';
    var expected =   '--------c--       ';

    expectObservable(source.skip(2), unsub).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should not break unsubscription chains when result is unsubscribed explicitly', function () {
    var source = hot('--a--b--c--d--e--|');
    var subs =       '^         !       ';
    var expected =   '--------c--       ';
    var unsub =      '          !       ';

    var result = source
      .mergeMap(function (x) { return Observable.of(x); })
      .skip(2)
      .mergeMap(function (x) { return Observable.of(x); });

    expectObservable(result, unsub).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should raise error if skip count is more than actual number of emits and source raises error', function () {
    var source = hot('--a--b--c--d--#');
    var subs =       '^             !';
    var expected =   '--------------#';

    expectObservable(source.skip(6)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should raise error if skip count is same as emits of source and source raises error', function () {
    var source = hot('--a--b--c--d--#');
    var subs =       '^             !';
    var expected =   '--------------#';

    expectObservable(source.skip(4)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should skip values before a total and raises error if source raises error', function () {
    var source = hot('--a--b--c--d--#');
    var subs =       '^             !';
    var expected =   '-----------d--#';

    expectObservable(source.skip(3)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should complete regardless of skip count if source is empty', function () {
    var e1 =  cold('|');
    var e1subs =   '(^!)';
    var expected = '|';

    expectObservable(e1.skip(3)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should not complete if source never completes without emit', function () {
    var e1 =   hot('-');
    var e1subs =   '^';
    var expected = '-';

    expectObservable(e1.skip(3)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should skip values before total and never completes if source emits and does not complete', function () {
    var e1 =   hot('--a--b--c-');
    var e1subs =   '^         ';
    var expected = '-----b--c-';

    expectObservable(e1.skip(1)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should skip all values and never completes if total is more than numbers of value and source does not complete', function () {
    var e1 =   hot('--a--b--c-');
    var e1subs =   '^         ';
    var expected = '----------';

    expectObservable(e1.skip(6)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should skip all values and never completes if total is same asnumbers of value and source does not complete', function () {
    var e1 =   hot('--a--b--c-');
    var e1subs =   '^         ';
    var expected = '----------';

    expectObservable(e1.skip(3)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should raise error if source throws', function () {
    var e1 =  cold('#');
    var e1subs =   '(^!)';
    var expected = '#';

    expectObservable(e1.skip(3)).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });
});<|endoftext|>


<commit_before>
/*!
 * ${copyright}
 */

sap.ui.define([
	"sap/ui/fl/Change"
], function (
	Change
) {
	"use strict";

	var CHANGES_NAMESPACE = "$sap.ui.fl.changes";

	/**
	 * Gets the $sap.ui.fl.changes section from the Manifest and returns it converted into sap.ui.fl.Change
	 * @param {sap.ui.core.Manifest} oManifest
	 * @returns Array<sap.ui.fl.Change> array of sap.ui.fl.Change
	 */
	function getDescriptorChanges(oManifest) {
		var aAppDescriptorChangesRaw = oManifest && oManifest.getEntry && oManifest.getEntry(CHANGES_NAMESPACE) && oManifest.getEntry(CHANGES_NAMESPACE).descriptor || [];
		return aAppDescriptorChangesRaw.map(function(oChange) {
			return new Change(oChange);
		});
	}

	var Applier = {
		/**
		 * Applies all descriptor changes to raw manifest.
		 *
		 * @param {object} oUpdatedManifest - Raw manifest provided by sap.ui.core.Component
		 * @param {Array<sap.ui.fl.Change>} aAppDescriptorChanges - Array of descriptor changes
		 * @param {object} mStrategy - Strategy for runtime or for buildtime merging
		 * @param {object} mStrategy.registry - Change handler registry
		 * @param {function} mStrategy.handleError - Error handling strategy
		 * @param {function} mStrategy.processTexts - Text postprocessing strategy
		 * @returns {Promise<object>} - Processed manifest with descriptor changes
		 */
		applyChanges: function (oUpdatedManifest, aAppDescriptorChanges, mStrategy) {
			return mStrategy.registry()
				.then(function (Registry) {
					var aChangeHandlerPromises = aAppDescriptorChanges.map(function (oChange) {
						return Registry[oChange.getChangeType()];
					});
					return Promise.all(aChangeHandlerPromises);
				})
				.then(function (aChangeHandlers) {
					aChangeHandlers.forEach(function (oChangeHandler, iIndex) {
						try {
							var oChange = aAppDescriptorChanges[iIndex];
							oUpdatedManifest = oChangeHandler.applyChange(oUpdatedManifest, oChange);
							if (!oChangeHandler.skipPostprocessing && oChange.getTexts()) {
								oUpdatedManifest = mStrategy.processTexts(oUpdatedManifest, oChange.getTexts());
							}
						} catch (oError) {
							mStrategy.handleError(oError);
						}
					});
					return oUpdatedManifest;
				});
		},

		/**
		 * Applies descriptor changes that can be found in the manifest under the section $sap.ui.fl.changes.
		 * @param {sap.ui.core.Manifest} oManifest
		 * @param {object} mStrategy - Strategy for runtime or for buildtime merging
		 * @param {object} mStrategy.registry - Change handler registry
		 * @param {function} mStrategy.handleError - Error handling strategy
		 * @param {function} mStrategy.processTexts - Text postprocessing strategy
		 * @returns Promise
		 */
		applyChangesIncludedInManifest: function(oManifest, mStrategy) {
			var aDescriptorChanges = getDescriptorChanges(oManifest);
			var oManifestJSON = oManifest.getJson();
			delete oManifestJSON[CHANGES_NAMESPACE];

			if (aDescriptorChanges.length > 0) {
				return this.applyChanges(oManifestJSON, aDescriptorChanges, mStrategy).then(function() {
					return;
				});
			}
			return Promise.resolve();
		}
	};

	return Applier;
});<commit_msg>[INTERNAL] sap.ui.fl - js doc fix for Applier<commit_after>
/*!
 * ${copyright}
 */

sap.ui.define([
	"sap/ui/fl/Change"
], function (
	Change
) {
	"use strict";

	var CHANGES_NAMESPACE = "$sap.ui.fl.changes";

	/**
	 * Gets the $sap.ui.fl.changes section from the Manifest and returns it converted into sap.ui.fl.Change
	 * @param {sap.ui.core.Manifest} oManifest - Manifest provided by sap.ui.core.Component
	 * @returns {sap.ui.fl.Change[]} Array of sap.ui.fl.Change
	 */
	function getDescriptorChanges(oManifest) {
		var aAppDescriptorChangesRaw = oManifest && oManifest.getEntry && oManifest.getEntry(CHANGES_NAMESPACE) && oManifest.getEntry(CHANGES_NAMESPACE).descriptor || [];
		return aAppDescriptorChangesRaw.map(function(oChange) {
			return new Change(oChange);
		});
	}

	var Applier = {
		/**
		 * Applies all descriptor changes to raw manifest.
		 *
		 * @param {object} oUpdatedManifest - Raw manifest provided by sap.ui.core.Component
		 * @param {Array<sap.ui.fl.Change>} aAppDescriptorChanges - Array of descriptor changes
		 * @param {object} mStrategy - Strategy for runtime or for buildtime merging
		 * @param {object} mStrategy.registry - Change handler registry
		 * @param {function} mStrategy.handleError - Error handling strategy
		 * @param {function} mStrategy.processTexts - Text postprocessing strategy
		 * @returns {Promise<object>} - Processed manifest with descriptor changes
		 */
		applyChanges: function (oUpdatedManifest, aAppDescriptorChanges, mStrategy) {
			return mStrategy.registry()
				.then(function (Registry) {
					var aChangeHandlerPromises = aAppDescriptorChanges.map(function (oChange) {
						return Registry[oChange.getChangeType()];
					});
					return Promise.all(aChangeHandlerPromises);
				})
				.then(function (aChangeHandlers) {
					aChangeHandlers.forEach(function (oChangeHandler, iIndex) {
						try {
							var oChange = aAppDescriptorChanges[iIndex];
							oUpdatedManifest = oChangeHandler.applyChange(oUpdatedManifest, oChange);
							if (!oChangeHandler.skipPostprocessing && oChange.getTexts()) {
								oUpdatedManifest = mStrategy.processTexts(oUpdatedManifest, oChange.getTexts());
							}
						} catch (oError) {
							mStrategy.handleError(oError);
						}
					});
					return oUpdatedManifest;
				});
		},

		/**
		 * Applies descriptor changes that can be found in the manifest under the section $sap.ui.fl.changes.
		 * @param {sap.ui.core.Manifest} oManifest - Manifest provided by sap.ui.core.Component
		 * @param {object} mStrategy - Strategy for runtime or for buildtime merging
		 * @param {object} mStrategy.registry - Change handler registry
		 * @param {function} mStrategy.handleError - Error handling strategy
		 * @param {function} mStrategy.processTexts - Text postprocessing strategy
		 * @returns Promise
		 */
		applyChangesIncludedInManifest: function(oManifest, mStrategy) {
			var aDescriptorChanges = getDescriptorChanges(oManifest);
			var oManifestJSON = oManifest.getJson();
			delete oManifestJSON[CHANGES_NAMESPACE];

			if (aDescriptorChanges.length > 0) {
				return this.applyChanges(oManifestJSON, aDescriptorChanges, mStrategy).then(function() {
					return;
				});
			}
			return Promise.resolve();
		}
	};

	return Applier;
});<|endoftext|>


<commit_before>		var currentTime = new Date();
		currentTime.setUTCMinutes(0, 0, 0);
		var endDate = new Date(currentTime.getTime());
		L.TimeDimension.Util.addTimeDuration(endDate, "P1D", true);

		var map = L.map('map', {
			center: [45.25, -73.6159],
			zoom: 9,
			timeDimension: true,
			timeDimensionControl: true,
			timeDimensionOptions: {
				timeInterval: currentTime.toISOString() + "/P1D",
				period: "PT1H",
				currentTime: currentTime.getTime(),
			},
			timeDimensionControlOptions: {
				styleNS: "leaflet-control-timecontrol",
				position: "bottomleft",
				autoPlay: false,
				loopButton: true,
				playerOptions: {
					buffer: 10,
					transitionTime: 250,
				},
				timeZones: ['Local'],
			},

		});

		var basemaps = {
			Google: L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}')
		};

		var temperatureLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'HRDPS.CONTINENTAL_TT',
			opacity: '0.5',
			attribution: 'Data Source: Environment and Climate Change Canada'
			});

		var windLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'HRDPS.CONTINENTAL_UU',
			//opacity: '0.9',
			transparent: true,
			format: 'image/png',
			attribution: 'Data Source: Environment and Climate Change Canada'
			});

		var precipLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'HRDPS.CONTINENTAL_PR',
			opacity: '0.6',
			transparent: true,
			format: 'image/png',
			attribution: 'Data Source: Environment and Climate Change Canada'
			});

		var dewpointLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'HRDPS.CONTINENTAL_TD',
			opacity: '0.75',
			transparent: true,
			format: 'image/png',
			attribution: 'Data Source: Environment and Climate Change Canada'
			});

		var radarLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'RADAR_RDBS',
			transparent: true,
			format: 'image/png'
			});

		var markers = [{
			name: 'Mas',
			position: [45.177046, -73.614294],
		}, {
			name: 'Leclair',
			position: [45.149207, -73.622507]
		}, {
			name: 'JML',
			position: [45.197038, -73.639380],
		}, {
			name: 'Village',
			position: [45.236798, -73.574530]
		}, {
			name: 'Hamelin',
			position: [45.230818, -73.55349],
		}];

	    var proxy = 'proxy.php';

		var hrrrTemperatureTimeLayer = L.timeDimension.layer.wms.timeseries(temperatureLayer, {
			//proxy: proxy,
			updateTimeDimension: true,
			updateTimeDimensionMode: "replace",
			requestTimeFromCapabilities: true
			markers: markers,
			name: "Surface Temperature",
			units: "\xBA C",
			//enableNewMarkers: true
		});

		var tdTemp = L.timeDimension.layer.wms(temperatureLayer, {
			wmsVersion: "1.3.0",
			proxy: proxy,
			markers: markers,
			name: "Surface Temperature",
			//units: "\xBA C",
		});

		var tdDew = L.timeDimension.layer.wms(dewpointLayer, {
			wmsVersion: "1.3.0",
			proxy: proxy,
		});

		var tdWind = L.timeDimension.layer.wms(windLayer, {
			wmsVersion: "1.3.0",
			proxy: proxy,
		});

		var tdPrecip = L.timeDimension.layer.wms(precipLayer, {
			wmsVersion: "1.3.0",
			proxy: proxy,
		});

		// add Temp Legend
		var legend1 = L.control({position: 'bottomright'});
		legend1.onAdd = function(map) {
			var src1 = "http://geo.weather.gc.ca/geomet?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=HRDPS.CONTINENTAL_TT&format=image/png&STYLE=TEMPSUMMER"
			var div = L.DomUtil.create('div', 'info legend');
			div.innerHTML +=
				'';
			return div;
		};

		// add Wind Legend
		var legend2 = L.control({position: 'bottomright'});
		legend2.onAdd = function(map) {
			var src2 = "http://geo.weather.gc.ca/geomet?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=HRDPS.CONTINENTAL_UU&format=image/png&STYLE=WINDARROWKMH"
			var div = L.DomUtil.create('div', 'info legend');
			div.innerHTML +=
				'';
			return div;
		};

		// add dewpoint Legend
		var legend3 = L.control({position: 'bottomright'});
		legend3.onAdd = function(map) {
			var src3 = "http://geo.weather.gc.ca/geomet?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=HRDPS.CONTINENTAL_TD&format=image/png&STYLE=DEWPOINT"
			var div = L.DomUtil.create('div', 'info legend');
			div.innerHTML +=
				'';
			return div;
		};

		// add Precip Legend
		var legend4 = L.control({position: 'bottomright'});
		legend4.onAdd = function(map) {
			var src4 = "http://geo.weather.gc.ca/geomet?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=HRDPS.CONTINENTAL_PR&format=image/png&STYLE=PRECIPMM"
			var div = L.DomUtil.create('div', 'info legend');
			div.innerHTML +=
				'';
			return div;
		};

		legend1.addTo(map);

		var envcan = {
			'Temperature': tdTemp,
			'Dewpoint': tdDew,
			'Cumulative Precipitation (mm)': tdPrecip,
			'Windspeed Arrows in km/h': tdWind,
		};

		L.control.layers(basemaps, envcan).addTo(map);

		envcan.Temperature.addTo(map);
		basemaps.Google.addTo(map);

		// Remove Legends
		map.on('overlayremove', function (eventLayer) {
			if (eventLayer.name === 'Temperature') {
				this.removeControl(legend1);
			} else if (eventLayer.name === 'Dewpoint') {
				this.removeControl(legend3);
			} else if (eventLayer.name === 'Windspeed Arrows in km/h') {
				this.removeControl(legend2);
			} else {
				this.removeControl(legend4);
			}
		});
		map.on('overlayadd', function (eventLayer) {
		// Add Legends
			if (eventLayer.name === 'Temperature') {
				legend1.addTo(this);
			} else if (eventLayer.name === 'Dewpoint') {
				legend3.addTo(this);
			} else if (eventLayer.name === 'Windspeed Arrows in km/h') {
				legend2.addTo(this);
			} else {
				legend4.addTo(this);
			}
		});
		<commit_msg>Remove proxy test<commit_after>		var currentTime = new Date();
		currentTime.setUTCMinutes(0, 0, 0);
		var endDate = new Date(currentTime.getTime());
		L.TimeDimension.Util.addTimeDuration(endDate, "P1D", true);

		var map = L.map('map', {
			center: [45.25, -73.6159],
			zoom: 9,
			timeDimension: true,
			timeDimensionControl: true,
			timeDimensionOptions: {
				timeInterval: currentTime.toISOString() + "/P1D",
				period: "PT1H",
				currentTime: currentTime.getTime(),
			},
			timeDimensionControlOptions: {
				styleNS: "leaflet-control-timecontrol",
				position: "bottomleft",
				autoPlay: false,
				loopButton: true,
				playerOptions: {
					buffer: 10,
					transitionTime: 250,
				},
				timeZones: ['Local'],
			},

		});

		var basemaps = {
			Google: L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}')
		};

		var temperatureLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'HRDPS.CONTINENTAL_TT',
			opacity: '0.5',
			attribution: 'Data Source: Environment and Climate Change Canada'
			});

		var windLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'HRDPS.CONTINENTAL_UU',
			//opacity: '0.9',
			transparent: true,
			format: 'image/png',
			attribution: 'Data Source: Environment and Climate Change Canada'
			});

		var precipLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'HRDPS.CONTINENTAL_PR',
			opacity: '0.6',
			transparent: true,
			format: 'image/png',
			attribution: 'Data Source: Environment and Climate Change Canada'
			});

		var dewpointLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'HRDPS.CONTINENTAL_TD',
			opacity: '0.75',
			transparent: true,
			format: 'image/png',
			attribution: 'Data Source: Environment and Climate Change Canada'
			});

		var radarLayer = L.tileLayer.wms('http://geo.weather.gc.ca/geomet/?lang=E&service=WMS&request=GetCapabilities', {
			layers: 'RADAR_RDBS',
			transparent: true,
			format: 'image/png'
			});

		var markers = [{
			name: 'Mas',
			position: [45.177046, -73.614294],
		}, {
			name: 'Leclair',
			position: [45.149207, -73.622507]
		}, {
			name: 'JML',
			position: [45.197038, -73.639380],
		}, {
			name: 'Village',
			position: [45.236798, -73.574530]
		}, {
			name: 'Hamelin',
			position: [45.230818, -73.55349],
		}];

	    var proxy = 'proxy.php';

		var hrrrTemperatureTimeLayer = L.timeDimension.layer.wms.timeseries(temperatureLayer, {
			updateTimeDimension: true,
			updateTimeDimensionMode: "replace",
			requestTimeFromCapabilities: true
			markers: markers,
			name: "Surface Temperature",
			units: "\xBA C",
			//enableNewMarkers: true
		});

		var tdTemp = L.timeDimension.layer.wms(temperatureLayer, {
			wmsVersion: "1.3.0",
			proxy: proxy,
			markers: markers,
			name: "Surface Temperature",
			//units: "\xBA C",
		});

		var tdDew = L.timeDimension.layer.wms(dewpointLayer, {
			wmsVersion: "1.3.0",
			proxy: proxy,
		});

		var tdWind = L.timeDimension.layer.wms(windLayer, {
			wmsVersion: "1.3.0",
			proxy: proxy,
		});

		var tdPrecip = L.timeDimension.layer.wms(precipLayer, {
			wmsVersion: "1.3.0",
			proxy: proxy,
		});

		// add Temp Legend
		var legend1 = L.control({position: 'bottomright'});
		legend1.onAdd = function(map) {
			var src1 = "http://geo.weather.gc.ca/geomet?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=HRDPS.CONTINENTAL_TT&format=image/png&STYLE=TEMPSUMMER"
			var div = L.DomUtil.create('div', 'info legend');
			div.innerHTML +=
				'';
			return div;
		};

		// add Wind Legend
		var legend2 = L.control({position: 'bottomright'});
		legend2.onAdd = function(map) {
			var src2 = "http://geo.weather.gc.ca/geomet?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=HRDPS.CONTINENTAL_UU&format=image/png&STYLE=WINDARROWKMH"
			var div = L.DomUtil.create('div', 'info legend');
			div.innerHTML +=
				'';
			return div;
		};

		// add dewpoint Legend
		var legend3 = L.control({position: 'bottomright'});
		legend3.onAdd = function(map) {
			var src3 = "http://geo.weather.gc.ca/geomet?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=HRDPS.CONTINENTAL_TD&format=image/png&STYLE=DEWPOINT"
			var div = L.DomUtil.create('div', 'info legend');
			div.innerHTML +=
				'';
			return div;
		};

		// add Precip Legend
		var legend4 = L.control({position: 'bottomright'});
		legend4.onAdd = function(map) {
			var src4 = "http://geo.weather.gc.ca/geomet?version=1.3.0&service=WMS&request=GetLegendGraphic&sld_version=1.1.0&layer=HRDPS.CONTINENTAL_PR&format=image/png&STYLE=PRECIPMM"
			var div = L.DomUtil.create('div', 'info legend');
			div.innerHTML +=
				'';
			return div;
		};

		legend1.addTo(map);

		var envcan = {
			'Temperature': tdTemp,
			'Dewpoint': tdDew,
			'Cumulative Precipitation (mm)': tdPrecip,
			'Windspeed Arrows in km/h': tdWind,
		};

		L.control.layers(basemaps, envcan).addTo(map);

		envcan.Temperature.addTo(map);
		basemaps.Google.addTo(map);

		// Remove Legends
		map.on('overlayremove', function (eventLayer) {
			if (eventLayer.name === 'Temperature') {
				this.removeControl(legend1);
			} else if (eventLayer.name === 'Dewpoint') {
				this.removeControl(legend3);
			} else if (eventLayer.name === 'Windspeed Arrows in km/h') {
				this.removeControl(legend2);
			} else {
				this.removeControl(legend4);
			}
		});
		map.on('overlayadd', function (eventLayer) {
		// Add Legends
			if (eventLayer.name === 'Temperature') {
				legend1.addTo(this);
			} else if (eventLayer.name === 'Dewpoint') {
				legend3.addTo(this);
			} else if (eventLayer.name === 'Windspeed Arrows in km/h') {
				legend2.addTo(this);
			} else {
				legend4.addTo(this);
			}
		});
		<|endoftext|>