<commit_before>var roleManager = {};

function getFromId(server,id)
{
    var role = server.roles.find(function(x){return x.id==id});
    if(role !=undefined)
        return role;
    return undefined;
}

function getFromName(server,name)
{
    name = name.toLowerCase();
    var role = server.roles.find(function(x){return x.name.toLowerCase()==name});
    if(role !=undefined)
        return role;
    return undefined;
}

function assertServerExistance(server, data)//returns true if server existed in data and was the correct version prior to this call, otherwise ... false
{
    if(data[server.id] == undefined){
        data[server.id] = {selfroles:[],otherroles:[]};
        return false;
    }
    else{//if data is in old format
        if(!data[server.id].hasOwnProperty("selfroles")){
            data[server.id] = {selfroles:data[server.id],otherroles:[]};
            return false
        }
    }
    return true;

}

roleManager.iam = function(message, role, data)
{
    var server = message.server;
    role = getFromName(server,role);
    if(role == undefined)
        return false;
    if(data[server.id].selfroles.find(function(x){return x==role.id})!=undefined){
        message.author.addTo(role);
        var logChannel = server.channels.find(function(x){return x.name=="logs"});
        if(logChannel!=undefined)
            message.client.sendMessage(logChannel,`Assigned ${role.name} to ${message.author.username}#${message.author.discriminator} per that user's request.`,{"disableEveryone":true});
        return true;
    }else
        return false;
}

roleManager.iamnot = function(message,role,data)
{
    var server = message.server;
    role = getFromName(server,role);
    if(role == undefined)
        return {"value":false, "message":"No role like that exist."};
    if(data[server.id].selfroles.find(function(x){return x==role.id})!=undefined){
        if(message.author.hasRole(role)){
            message.author.removeFrom(role);
            var logChannel = server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`Removed ${role.name} from ${message.author.username}#${message.author.discriminator} per that user's request.`,{"disableEveryone":true});
            return {"value":true, "message":"Role succesfully removed!"};

        }else{
            return {"value":false, "message":"You don't have that role."};
        }
    }else
        return {"value":false, "message":"I have no role like that in the self assignable list."};
}

roleManager.theyam = function(message, role, target, data)
{
    var server = message.server;
    role = getFromName(server,role);
    if(role == undefined)
        return false;
    if(data[server.id].otherroles.find(function(x){return x==role.id})!=undefined){
       target.addTo(role);
        var logChannel = server.channels.find(function(x){return x.name=="logs"});
        if(logChannel!=undefined)
            message.client.sendMessage(logChannel,`Assigned ${role.name} to ${target.username}#${target.discriminator} per ${message.author.username}#${message.author.discriminator}'s request.`,{"disableEveryone":true});
        return true;
    }else
        return false;
}

roleManager.theyamnot = function(message,role,target,data)
{
    var server = message.server;
    role = getFromName(server,role);
    if(role == undefined)
        return {"value":false, "message":"No role like that exist."};
    if(data[server.id].otherroles.find(function(x){return x==role.id})!=undefined){
        if(target.hasRole(role)){
            target.removeFrom(role);
            var logChannel = server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`Removed ${role.name} from ${target.username}#${target.discriminator} per ${message.author.username}#${message.author.discriminator}'s request.`,{"disableEveryone":true});
            return {"value":true, "message":`Role succesfully removed from ${target.username}#${target.discriminator}!`};

        }else{
            return {"value":false, "message":"That person doesn't have that role."};
        }
    }else
        return {"value":false, "message":"I have no role like that in the assignable list."};
}

roleManager.whatami = function(message, user, data)
{
    var server = message.server;
    var output = "";
    if(user.id == message.author.id) output+="You have";
    else output+= user.name + " has";
    var output2 = " the following self assignable roles:\n";
    var roles = server.rolesOfUser(user);
    var count = 0;
    for(var a = 0; a<data[server.id].selfroles.length;a++){
        var role =roles.find(function(x){return x.id == data[server.id][a]})
        if(role !=undefined)
        {
            if(count !=0)output2+=",";
            output2+=` "${role.name}"`;
            count++;
        }
    }
    if(count==0)output+= " no self assignable roles."
    else output+=output2;
    return output;
}

roleManager.lsar = function(message, data)
{
    if(!assertServerExistance(message.server,data) || data[message.server.id].selfroles.length == 0)
    {
        return "I have no self assignable roles listed for this server.";
    }
    var output = "I have the following self assignable roles listed:\n";
    for(var a = 0; a < data[message.server.id].selfroles.length; a++){
        if(a!=0) output+=", ";
        var name = getFromId(message.server,data[message.server.id].selfroles[a])
        if(name !== undefined){
             name = name.name;
            if(name.includes(" ")) name = `"${name}"`;
            output+=name;
        }else{
            data[message.server.id].selfroles.splice(a,1);
            var logChannel = message.server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`When I was listing roles, I discovered a role was missing. Deleted it.`,{"disableEveryone":true});
        }
    }
    return output;
}

roleManager.loar = function(message, data)
{
    if(!assertServerExistance(message.server,data) || data[message.server.id].otherroles.length == 0)
    {
        return "I have no assignable roles listed for this server.";
    }
    var output = "I have the following assignable roles listed:\n";
    for(var a = 0; a < data[message.server.id].otherroles.length; a++){
        if(a!=0) output+=", ";
        var name = getFromId(message.server,data[message.server.id].otherroles[a])
        if(name !== undefined){
             name = name.name;
            if(name.includes(" ")) name = `"${name}"`;
            output+=name;
        }else{
            data[message.server.id].otherroles.splice(a,1);
            var logChannel = message.server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`When I was listing roles, I discovered a role was missing. Deleted it.`,{"disableEveryone":true});
        }
    }
    return output;
}

roleManager.asar = function(message,role,data)//we need permissions before adding this one.
{
    var server = message.server;
    role = getFromName(server,role);
    assertServerExistance(server,data)
    if(role==undefined)
        return "I have not found a role named that way."
    else{
        if(data[server.id].selfroles.find(function(x){return x == role.id})!=undefined)
            return "This role is already in my list!";
        data[server.id].selfroles.push(role.id);
        var logChannel = server.channels.find(function(x){return x.name=="logs"});
        if(logChannel!=undefined)
            message.client.sendMessage(logChannel,`${message.author.username}#${message.author.discriminator} added ${role.name} to the list of self assignable roles.`,{"disableEveryone":true});
        return `"${role.name}" added to the list of self assignable roles!`;
    }
}

roleManager.aoar = function(message,role,data)//we need permissions before adding this one.
{
    var server = message.server;
    role = getFromName(server,role);
    assertServerExistance(server,data)
    if(role==undefined)
        return "I have not found a role named that way."
    else{
        if(data[server.id].otherroles.find(function(x){return x == role.id})!=undefined)
            return "This role is already in my list!";
        data[server.id].otherroles.push(role.id);
        var logChannel = server.channels.find(function(x){return x.name=="logs"});
        if(logChannel!=undefined)
            message.client.sendMessage(logChannel,`${message.author.username}#${message.author.discriminator} added ${role.name} to the list of assignable roles.`,{"disableEveryone":true});
        return `"${role.name}" added to the list of assignable roles!`;
    }
}

roleManager.dsar = function(message, role, data)
{
    var server = message.server;
    role = getFromName(server,role)
    assertServerExistance(server,data)
    if(role==undefined)
        return "I have not found a role named that way."
    else{
        if(data[server.id].selfroles.find(function(x){return x == role.id})!=undefined){
            var index = -1;
            for(var a = 0; a<data[server.id].selfroles.length; a++)
            {
                if(data[server.id].selfroles[a] == role.id){
                    index = a;
                    break;
                }
            }
            data[server.id].selfroles.splice(index,1);
            var logChannel = server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`${message.author.username}#${message.author.discriminator} removed ${role.name} from the list of self assignable roles.`,{"disableEveryone":true});
            return `Deleted ${role.name} from self assignable list.`
        }
        return "I don't have a self assignable role named that way."
        }
}

roleManager.doar = function(message, role, data)
{
    var server = message.server;
    role = getFromName(server,role)
    assertServerExistance(server,data)
    if(role==undefined)
        return "I have not found a role named that way."
    else{
        if(data[server.id].otherroles.find(function(x){return x == role.id})!=undefined){
            var index = -1;
            for(var a = 0; a<data[server.id].otherroles.length; a++)
            {
                if(data[server.id].otherroles[a] == role.id){
                    index = a;
                    break;
                }
            }
            data[server.id].otherroles.splice(index,1);
            var logChannel = server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`${message.author.username}#${message.author.discriminator} removed ${role.name} from the list of assignable roles.`,{"disableEveryone":true});
            return `Deleted ${role.name} from assignable list.`
        }
        return "I don't have a mod assignable role named that way."
        }
}

module.exports = roleManager;<commit_msg>other assignable roles (oar) now also takes sar's<commit_after>var roleManager = {};

function getFromId(server,id)
{
    var role = server.roles.find(function(x){return x.id==id});
    if(role !=undefined)
        return role;
    return undefined;
}

function getFromName(server,name)
{
    name = name.toLowerCase();
    var role = server.roles.find(function(x){return x.name.toLowerCase()==name});
    if(role !=undefined)
        return role;
    return undefined;
}

function assertServerExistance(server, data)//returns true if server existed in data and was the correct version prior to this call, otherwise ... false
{
    if(data[server.id] == undefined){
        data[server.id] = {selfroles:[],otherroles:[]};
        return false;
    }
    else{//if data is in old format
        if(!data[server.id].hasOwnProperty("selfroles")){
            data[server.id] = {selfroles:data[server.id],otherroles:[]};
            return false
        }
    }
    return true;

}

roleManager.iam = function(message, role, data)
{
    var server = message.server;
    role = getFromName(server,role);
    if(role == undefined)
        return false;
    if(data[server.id].selfroles.find(function(x){return x==role.id})!=undefined){
        message.author.addTo(role);
        var logChannel = server.channels.find(function(x){return x.name=="logs"});
        if(logChannel!=undefined)
            message.client.sendMessage(logChannel,`Assigned ${role.name} to ${message.author.username}#${message.author.discriminator} per that user's request.`,{"disableEveryone":true});
        return true;
    }else
        return false;
}

roleManager.iamnot = function(message,role,data)
{
    var server = message.server;
    role = getFromName(server,role);
    if(role == undefined)
        return {"value":false, "message":"No role like that exist."};
    if(data[server.id].selfroles.find(function(x){return x==role.id})!=undefined){
        if(message.author.hasRole(role)){
            message.author.removeFrom(role);
            var logChannel = server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`Removed ${role.name} from ${message.author.username}#${message.author.discriminator} per that user's request.`,{"disableEveryone":true});
            return {"value":true, "message":"Role succesfully removed!"};

        }else{
            return {"value":false, "message":"You don't have that role."};
        }
    }else
        return {"value":false, "message":"I have no role like that in the self assignable list."};
}

roleManager.theyam = function(message, role, target, data)
{
    var server = message.server;
    role = getFromName(server,role);
    if(role == undefined)
        return false;
    if(data[server.id].otherroles.find(function(x){return x==role.id})!=undefined || data[server.id].selfroles.find(function(x){return x==role.id})!=undefined){
       target.addTo(role);
        var logChannel = server.channels.find(function(x){return x.name=="logs"});
        if(logChannel!=undefined)
            message.client.sendMessage(logChannel,`Assigned ${role.name} to ${target.username}#${target.discriminator} per ${message.author.username}#${message.author.discriminator}'s request.`,{"disableEveryone":true});
        return true;
    }else
        return false;
}

roleManager.theyamnot = function(message,role,target,data)
{
    var server = message.server;
    role = getFromName(server,role);
    if(role == undefined)
        return {"value":false, "message":"No role like that exist."};
    if(data[server.id].otherroles.find(function(x){return x==role.id})!=undefined || data[server.id].selfroles.find(function(x){return x==role.id})!=undefined){
        if(target.hasRole(role)){
            target.removeFrom(role);
            var logChannel = server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`Removed ${role.name} from ${target.username}#${target.discriminator} per ${message.author.username}#${message.author.discriminator}'s request.`,{"disableEveryone":true});
            return {"value":true, "message":`Role succesfully removed from ${target.username}#${target.discriminator}!`};

        }else{
            return {"value":false, "message":"That person doesn't have that role."};
        }
    }else
        return {"value":false, "message":"I have no role like that in the assignable list."};
}

roleManager.whatami = function(message, user, data)
{
    var server = message.server;
    var output = "";
    if(user.id == message.author.id) output+="You have";
    else output+= user.name + " has";
    var output2 = " the following self assignable roles:\n";
    var roles = server.rolesOfUser(user);
    var count = 0;
    for(var a = 0; a<data[server.id].selfroles.length;a++){
        var role =roles.find(function(x){return x.id == data[server.id][a]})
        if(role !=undefined)
        {
            if(count !=0)output2+=",";
            output2+=` "${role.name}"`;
            count++;
        }
    }
    if(count==0)output+= " no self assignable roles."
    else output+=output2;
    return output;
}

roleManager.lsar = function(message, data)
{
    if(!assertServerExistance(message.server,data) || data[message.server.id].selfroles.length == 0)
    {
        return "I have no self assignable roles listed for this server.";
    }
    var output = "I have the following self assignable roles listed:\n";
    for(var a = 0; a < data[message.server.id].selfroles.length; a++){
        if(a!=0) output+=", ";
        var name = getFromId(message.server,data[message.server.id].selfroles[a])
        if(name !== undefined){
             name = name.name;
            if(name.includes(" ")) name = `"${name}"`;
            output+=name;
        }else{
            data[message.server.id].selfroles.splice(a,1);
            var logChannel = message.server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`When I was listing roles, I discovered a role was missing. Deleted it.`,{"disableEveryone":true});
        }
    }
    return output;
}

roleManager.loar = function(message, data)
{
    if(!assertServerExistance(message.server,data) || data[message.server.id].otherroles.length == 0)
    {
        if(data[message.server.id].selfroles.length == 0)
            return "I have no assignable roles listed for this server.";
        else
            return "I have no assignable roles listed, but you could assign self-assignable roles."
    }
    var output = "I have the following assignable roles listed:\n";
    for(var a = 0; a < data[message.server.id].otherroles.length; a++){
        if(a!=0) output+=", ";
        var name = getFromId(message.server,data[message.server.id].otherroles[a])
        if(name !== undefined){
             name = name.name;
            if(name.includes(" ")) name = `"${name}"`;
            output+=name;
        }else{
            data[message.server.id].otherroles.splice(a,1);
            var logChannel = message.server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`When I was listing roles, I discovered a role was missing. Deleted it.`,{"disableEveryone":true});
        }
    }
    return output;
}

roleManager.asar = function(message,role,data)//we need permissions before adding this one.
{
    var server = message.server;
    role = getFromName(server,role);
    assertServerExistance(server,data)
    if(role==undefined)
        return "I have not found a role named that way."
    else{
        if(data[server.id].selfroles.find(function(x){return x == role.id})!=undefined)
            return "This role is already in my list!";
        data[server.id].selfroles.push(role.id);
        data[server.id].selfroles.sort((x,y) =>
            {
                let x_ = server.roles.find(function(z1){return z1.id == x});
                let y_ = server.roles.find(function(z2){return z2.id == y});
                return y_.position-x_.position ;
            })
        var logChannel = server.channels.find(function(x){return x.name=="logs"});
        if(logChannel!=undefined)
            message.client.sendMessage(logChannel,`${message.author.username}#${message.author.discriminator} added ${role.name} to the list of self assignable roles.`,{"disableEveryone":true});
        return `"${role.name}" added to the list of self assignable roles!`;
    }
}

roleManager.aoar = function(message,role,data)//we need permissions before adding this one.
{
    var server = message.server;
    role = getFromName(server,role);
    assertServerExistance(server,data)
    if(role==undefined)
        return "I have not found a role named that way."
    else{
        if(data[server.id].otherroles.find(function(x){return x == role.id})!=undefined)
            return "This role is already in my list!";
        data[server.id].otherroles.push(role.id);
        data[server.id].otherroles.sort((x,y) =>
            {
                let x_ = server.roles.find(function(z1){return z1.id == x});
                let y_ = server.roles.find(function(z2){return z2.id == y});
                return  y_.position-x_.position;
            })
        var logChannel = server.channels.find(function(x){return x.name=="logs"});
        if(logChannel!=undefined)
            message.client.sendMessage(logChannel,`${message.author.username}#${message.author.discriminator} added ${role.name} to the list of assignable roles.`,{"disableEveryone":true});
        return `"${role.name}" added to the list of assignable roles!`;
    }
}

roleManager.dsar = function(message, role, data)
{
    var server = message.server;
    role = getFromName(server,role)
    assertServerExistance(server,data)
    if(role==undefined)
        return "I have not found a role named that way."
    else{
        if(data[server.id].selfroles.find(function(x){return x == role.id})!=undefined){
            var index = -1;
            for(var a = 0; a<data[server.id].selfroles.length; a++)
            {
                if(data[server.id].selfroles[a] == role.id){
                    index = a;
                    break;
                }
            }
            data[server.id].selfroles.splice(index,1);
            var logChannel = server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`${message.author.username}#${message.author.discriminator} removed ${role.name} from the list of self assignable roles.`,{"disableEveryone":true});
            return `Deleted ${role.name} from self assignable list.`
        }
        return "I don't have a self assignable role named that way."
        }
}

roleManager.doar = function(message, role, data)
{
    var server = message.server;
    role = getFromName(server,role)
    assertServerExistance(server,data)
    if(role==undefined)
        return "I have not found a role named that way."
    else{
        if(data[server.id].otherroles.find(function(x){return x == role.id})!=undefined){
            var index = -1;
            for(var a = 0; a<data[server.id].otherroles.length; a++)
            {
                if(data[server.id].otherroles[a] == role.id){
                    index = a;
                    break;
                }
            }
            data[server.id].otherroles.splice(index,1);
            var logChannel = server.channels.find(function(x){return x.name=="logs"});
            if(logChannel!=undefined)
                message.client.sendMessage(logChannel,`${message.author.username}#${message.author.discriminator} removed ${role.name} from the list of assignable roles.`,{"disableEveryone":true});
            return `Deleted ${role.name} from assignable list.`
        }
        return "I don't have a mod assignable role named that way."
        }
}

module.exports = roleManager;<|endoftext|>


<commit_before>"use strict";

var util = require("substance-util");
var _ = require("underscore");
var DefaultConfiguration = require('./default');

var ElifeConfiguration = function() {

};

ElifeConfiguration.Prototype = function() {

  this.enhanceCover = function(state, node, element) {
    var dispChannel = element.querySelector("subj-group[subj-group-type=display-channel] subject").textContent;
    try {
      var category = element.querySelector("subj-group[subj-group-type=heading] subject").textContent;
    } catch(err) {
      var category = null;
    }

    node.breadcrumbs = [
      { name: "eLife", url: "http://elife.elifesciences.org/", image: "http://lens.elifesciences.org/lens-elife/styles/elife.png" },
      { name: dispChannel, url: "http://elife.elifesciences.org/category/"+dispChannel.replace(/ /g, '-').toLowerCase() },
    ];

    if (category) node.breadcrumbs.push( { name: category, url: "http://elife.elifesciences.org/category/"+category.replace(/ /g, '-').toLowerCase() } );
  };

  // Resolves figure url
  // --------
  //

  this.enhanceFigure = function(state, node, element) {
    var graphic = element.querySelector("graphic");
    var url = graphic.getAttribute("xlink:href");
    node.url = this.resolveURL(state, url);
  };

  this.enhanceVideo = function(state, node, element) {
    var el = element.querySelector("media") || element;
    var href = element.getAttribute("xlink:href").split(".");
    var name = href[0];

    node.url = "http://static.movie-usa.glencoesoftware.com/mp4/10.7554/"+name+".mp4";
    node.url_ogv = "http://static.movie-usa.glencoesoftware.com/ogv/10.7554/"+name+".ogv";
    node.url_webm = "http://static.movie-usa.glencoesoftware.com/webm/10.7554/"+name+".webm";
    node.poster = "http://static.movie-usa.glencoesoftware.com/jpg/10.7554/"+name+".jpg";
  };

  // Example url to JPG: http://cdn.elifesciences.org/elife-articles/00768/svg/elife00768f001.jpg
  this.resolveURL = function(state, url) {
    // Use absolute URL
    if (url.match(/http:\/\//)) return url;

    // Look up base url
    var baseURL = this.getBaseURL(state);

    if (baseURL) {
      return [baseURL, url].join('');
    } else {
      // Use special URL resolving for production articles
      return [
        "http://cdn.elifesciences.org/elife-articles/",
        state.doc.id,
        "/jpg/",
        url,
        ".jpg"
      ].join('');
    }

  };

  this.enhanceSupplement = function(state, node, element) {
    var baseURL = this.getBaseURL(state);
    if (baseURL) {
      return [baseURL, node.url].join('');
    } else {
      node.url = [
        "http://cdn.elifesciences.org/elife-articles/",
        state.doc.id,
        "/suppl/",
        node.url
      ].join('');
    }
  };

  this.extractPublicationInfo = function(converter, state, article) {
    var doc = state.doc;

    // var doc = state.doc;

    // Initialize the Article Info object
    var articleInfo = {
      "id": "articleinfo",
      "type": "paragraph",
      "children": []
    };
    var nodes = articleInfo.children;

    // Get the author's impact statement
    var meta = article.querySelectorAll("meta-value");
    var impact = meta[1];

    if (impact) {
      var h1 = {
        "type": "heading",
        "id": state.nextId("heading"),
        "level": 3,
        "content": "Impact",
      };
      doc.create(h1);
      nodes.push(h1.id);

      var par = converter.paragraphGroup(state, impact);
      nodes.push(par[0].id);
    }

    // Get reviewing editor
    // --------------

    var editor = article.querySelector("contrib[contrib-type=editor]");

    if (editor) {
      var name = converter.getName(editor.querySelector('name'));
      var inst = editor.querySelector("institution").textContent;
      var role = editor.querySelector("role").textContent;
      var country = editor.querySelector("country").textContent;

      var h1 = {
        "type": "heading",
        "id": state.nextId("heading"),
        "level": 3,
        "content": "Reviewing Editor"
      };

      doc.create(h1);
      nodes.push(h1.id);

      var t1 = {
        "type": "text",
        "id": state.nextId("text"),
        "content": [name, role, inst, country].join(", ")
      };

      doc.create(t1);
      nodes.push(t1.id);
    }

    // Get major datasets

    var datasets = article.querySelectorAll('sec');

    for (var i = 0;i <datasets.length;i++){
      var data = datasets[i];
      var type = data.getAttribute('sec-type');
      if (type === 'datasets') {
        var h1 = {
          "type" : "heading",
          "id" : state.nextId("heading"),
          "level" : 3,
          "content" : "Major Datasets"
        };
        doc.create(h1);
        nodes.push(h1.id);
        var ids = converter.datasets(state, util.dom.getChildren(data));
        for (var j=0;j < ids.length;j++) {
          if (ids[j]) {
            nodes.push(ids[j]);
          }
        }
      }
    }

    // Get acknowledgements

    var ack = article.querySelector("ack");
    if (ack) {
      var h1 = {
        "type" : "heading",
        "id" : state.nextId("heading"),
        "level" : 3,
        "content" : "Acknowledgements"
      };
      doc.create(h1);
      nodes.push(h1.id);
      var par = converter.bodyNodes(state, util.dom.getChildren(ack));
      nodes.push(par[0].id);
    }

    // Get copyright and license information
    var license = article.querySelector("permissions");
    if (license) {
      var h1 = {
        "type" : "heading",
        "id" : state.nextId("heading"),
        "level" : 3,
        "content" : "Copyright and License"
      };
      doc.create(h1);
      nodes.push(h1.id);

      var copyright = license.querySelector("copyright-statement");
      if (copyright) {
        var par = converter.paragraphGroup(state, copyright);
        var textid = par[0].children[0];
        doc.nodes[textid].content += ". ";
        nodes.push(par[0].id);
      }
      var lic = license.querySelector("license");
      var children = util.dom.getChildren(lic);
      for (var i = 0;i < children.length;i++) {
        var child = children[i];
        var type = util.dom.getNodeType(child);
        if (type === 'p' || type === 'license-p') {
          var par = converter.paragraphGroup(state, child);
          nodes.push(par[0].id)
        }
      }
    }

    doc.create(articleInfo);

    // ========================================

    var articleMeta = article.querySelector("article-meta");

    function _extractDate(dateEl) {
      if (!dateEl) return null;
      var day = dateEl.querySelector("day").textContent;
      var month = dateEl.querySelector("month").textContent;
      var year = dateEl.querySelector("year").textContent;
      return [year, month, day].join("-");
    }

    var pubDate = articleMeta.querySelector("pub-date");
    var receivedDate = articleMeta.querySelector("date[date-type=received]");
    var acceptedDate = articleMeta.querySelector("date[date-type=accepted]");

    // Extract keywords
    // ------------
    //
    // <kwd-group kwd-group-type="author-keywords">
    // <title>Author keywords</title>
    // <kwd>innate immunity</kwd>
    // <kwd>histones</kwd>
    // <kwd>lipid droplet</kwd>
    // <kwd>anti-bacterial</kwd>
    // </kwd-group>
    var keyWords = articleMeta.querySelectorAll("kwd-group[kwd-group-type=author-keywords] kwd");

    // Extract research organism
    // ------------
    //

    // <kwd-group kwd-group-type="research-organism">
    // <title>Research organism</title>
    // <kwd>B. subtilis</kwd>
    // <kwd>D. melanogaster</kwd>
    // <kwd>E. coli</kwd>
    // <kwd>Mouse</kwd>
    // </kwd-group>
    var organisms = articleMeta.querySelectorAll("kwd-group[kwd-group-type=research-organism] kwd");

    // Extract subjects
    // ------------
    //
    // <subj-group subj-group-type="heading">
    // <subject>Immunology</subject>
    // </subj-group>
    // <subj-group subj-group-type="heading">
    // <subject>Microbiology and infectious disease</subject>
    // </subj-group>

    var subjects = articleMeta.querySelectorAll("subj-group[subj-group-type=heading] subject");

    // Extract article_type
    // ---------------
    //
    // <subj-group subj-group-type="display-channel">
    // <subject>Research article</subject>
    // </subj-group>

    var articleType = articleMeta.querySelector("subj-group[subj-group-type=display-channel] subject");

    // Extract journal title
    // ---------------
    //

    var journalTitle = article.querySelector("journal-title");

    // <article-id pub-id-type="doi">10.7554/eLife.00003</article-id>
    var articleDOI = article.querySelector("article-id[pub-id-type=doi]");

    // Extract PDF link
    // ---------------
    //
    // <self-uri content-type="pdf" xlink:href="elife00007.pdf"/>

    var pdfURI = article.querySelector("self-uri[content-type=pdf]");

    var pdfLink = [
      "http://cdn.elifesciences.org/elife-articles/",
      state.doc.id,
      "/pdf/",
      pdfURI ? pdfURI.getAttribute("xlink:href") : "#"
    ].join('');

    // Related article if exists
    // -----------

    var relatedArticle = article.querySelector("related-article");

    // if (relatedArticle) relatedArticle = relatedArticle.getAttribute("xlink:href");

    // Create PublicationInfo node
    // ---------------

    var pubInfoNode = {
      "id": "publication_info",
      "type": "publication_info",
      "published_on": _extractDate(pubDate),
      "received_on": _extractDate(receivedDate),
      "accepted_on": _extractDate(acceptedDate),
      "keywords": _.pluck(keyWords, "textContent"),
      "research_organisms": _.pluck(organisms, "textContent"),
      "subjects": _.pluck(subjects, "textContent"),
      "article_type": articleType ? articleType.textContent : "",
      "journal": journalTitle ? journalTitle.textContent : "",
      "pdf_link": pdfLink,
      "related_article": relatedArticle ? ["http://dx.doi.org/", relatedArticle.getAttribute("xlink:href")].join("") : "",
      "xml_link": "https://s3.amazonaws.com/elife-cdn/elife-articles/"+state.doc.id+"/elife"+state.doc.id+".xml", // "http://mickey.com/mouse.xml",
      "json_link": "http://mickey.com/mouse.json",
      "doi": articleDOI ? ["http://dx.doi.org/", articleDOI.textContent].join("") : "",
      "article_info": articleInfo.id
    };

    doc.create(pubInfoNode);
    doc.show("info", pubInfoNode.id, 0);
  };

  // Add additional information to the info view
  // ---------
  //
  // Impact
  // Reviewing Editor
  // Major datasets
  // Acknowledgements
  // Copyright

  this.enhanceInfo = function(converter, state, article) {

    // doc.show("info", articleInfo.id);
  };

  // Add Decision letter and author response
  // ---------

  this.enhanceArticle = function(converter, state, article) {

    var nodes = [];

    // Decision letter (if available)
    // -----------

    var articleCommentary = article.querySelector("#SA1");
    if (articleCommentary) {

      var heading = {
        id: state.nextId("heading"),
        type: "heading",
        level: 1,
        content: "Article Commentary"
      };
      doc.create(heading);
      nodes.push(heading);

      var heading = {
        id: state.nextId("heading"),
        type: "heading",
        level: 2,
        content: "Decision letter"
      };
      doc.create(heading);
      nodes.push(heading);

      var body = articleCommentary.querySelector("body");
      nodes = nodes.concat(converter.bodyNodes(state, util.dom.getChildren(body)));
    }

    // Author response
    // -----------

    var authorResponse = article.querySelector("#SA2");
    if (authorResponse) {

      var heading = {
        id: state.nextId("heading"),
        type: "heading",
        level: 2,
        content: "Author response"
      };
      doc.create(heading);
      nodes.push(heading);

      var body = authorResponse.querySelector("body");
      nodes = nodes.concat(converter.bodyNodes(state, util.dom.getChildren(body)));
    }

    // Show them off
    // ----------

    if (nodes.length > 0) {
      converter.show(state, nodes);
    }

    this.enhanceInfo(converter, state, article);
  };
};

ElifeConfiguration.Prototype.prototype = DefaultConfiguration.prototype;
ElifeConfiguration.prototype = new ElifeConfiguration.Prototype();
ElifeConfiguration.prototype.constructor = ElifeConfiguration;

module.exports = ElifeConfiguration;
<commit_msg>Capture article relevant links<commit_after>"use strict";

var util = require("substance-util");
var _ = require("underscore");
var DefaultConfiguration = require('./default');

var ElifeConfiguration = function() {

};

ElifeConfiguration.Prototype = function() {

  this.enhanceCover = function(state, node, element) {
    var dispChannel = element.querySelector("subj-group[subj-group-type=display-channel] subject").textContent;
    try {
      var category = element.querySelector("subj-group[subj-group-type=heading] subject").textContent;
    } catch(err) {
      var category = null;
    }

    node.breadcrumbs = [
      { name: "eLife", url: "http://elife.elifesciences.org/", image: "http://lens.elifesciences.org/lens-elife/styles/elife.png" },
      { name: dispChannel, url: "http://elife.elifesciences.org/category/"+dispChannel.replace(/ /g, '-').toLowerCase() },
    ];

    if (category) node.breadcrumbs.push( { name: category, url: "http://elife.elifesciences.org/category/"+category.replace(/ /g, '-').toLowerCase() } );
  };

  // Resolves figure url
  // --------
  //

  this.enhanceFigure = function(state, node, element) {
    var graphic = element.querySelector("graphic");
    var url = graphic.getAttribute("xlink:href");
    node.url = this.resolveURL(state, url);
  };

  this.enhanceVideo = function(state, node, element) {
    var el = element.querySelector("media") || element;
    var href = element.getAttribute("xlink:href").split(".");
    var name = href[0];

    node.url = "http://static.movie-usa.glencoesoftware.com/mp4/10.7554/"+name+".mp4";
    node.url_ogv = "http://static.movie-usa.glencoesoftware.com/ogv/10.7554/"+name+".ogv";
    node.url_webm = "http://static.movie-usa.glencoesoftware.com/webm/10.7554/"+name+".webm";
    node.poster = "http://static.movie-usa.glencoesoftware.com/jpg/10.7554/"+name+".jpg";
  };

  // Example url to JPG: http://cdn.elifesciences.org/elife-articles/00768/svg/elife00768f001.jpg
  this.resolveURL = function(state, url) {
    // Use absolute URL
    if (url.match(/http:\/\//)) return url;

    // Look up base url
    var baseURL = this.getBaseURL(state);

    if (baseURL) {
      return [baseURL, url].join('');
    } else {
      // Use special URL resolving for production articles
      return [
        "http://cdn.elifesciences.org/elife-articles/",
        state.doc.id,
        "/jpg/",
        url,
        ".jpg"
      ].join('');
    }

  };

  this.enhanceSupplement = function(state, node, element) {
    var baseURL = this.getBaseURL(state);
    if (baseURL) {
      return [baseURL, node.url].join('');
    } else {
      node.url = [
        "http://cdn.elifesciences.org/elife-articles/",
        state.doc.id,
        "/suppl/",
        node.url
      ].join('');
    }
  };

  this.extractPublicationInfo = function(converter, state, article) {
    var doc = state.doc;

    // var doc = state.doc;

    // Initialize the Article Info object
    var articleInfo = {
      "id": "articleinfo",
      "type": "paragraph",
      "children": []
    };
    var nodes = articleInfo.children;

    // Get the author's impact statement
    var meta = article.querySelectorAll("meta-value");
    var impact = meta[1];

    if (impact) {
      var h1 = {
        "type": "heading",
        "id": state.nextId("heading"),
        "level": 3,
        "content": "Impact",
      };
      doc.create(h1);
      nodes.push(h1.id);

      var par = converter.paragraphGroup(state, impact);
      nodes.push(par[0].id);
    }

    // Get reviewing editor
    // --------------

    var editor = article.querySelector("contrib[contrib-type=editor]");

    if (editor) {
      var name = converter.getName(editor.querySelector('name'));
      var inst = editor.querySelector("institution").textContent;
      var role = editor.querySelector("role").textContent;
      var country = editor.querySelector("country").textContent;

      var h1 = {
        "type": "heading",
        "id": state.nextId("heading"),
        "level": 3,
        "content": "Reviewing Editor"
      };

      doc.create(h1);
      nodes.push(h1.id);

      var t1 = {
        "type": "text",
        "id": state.nextId("text"),
        "content": [name, role, inst, country].join(", ")
      };

      doc.create(t1);
      nodes.push(t1.id);
    }

    // Get major datasets

    var datasets = article.querySelectorAll('sec');

    for (var i = 0;i <datasets.length;i++){
      var data = datasets[i];
      var type = data.getAttribute('sec-type');
      if (type === 'datasets') {
        var h1 = {
          "type" : "heading",
          "id" : state.nextId("heading"),
          "level" : 3,
          "content" : "Major Datasets"
        };
        doc.create(h1);
        nodes.push(h1.id);
        var ids = converter.datasets(state, util.dom.getChildren(data));
        for (var j=0;j < ids.length;j++) {
          if (ids[j]) {
            nodes.push(ids[j]);
          }
        }
      }
    }

    // Get acknowledgements

    var ack = article.querySelector("ack");
    if (ack) {
      var h1 = {
        "type" : "heading",
        "id" : state.nextId("heading"),
        "level" : 3,
        "content" : "Acknowledgements"
      };
      doc.create(h1);
      nodes.push(h1.id);
      var par = converter.bodyNodes(state, util.dom.getChildren(ack));
      nodes.push(par[0].id);
    }

    // Get copyright and license information
    var license = article.querySelector("permissions");
    if (license) {
      var h1 = {
        "type" : "heading",
        "id" : state.nextId("heading"),
        "level" : 3,
        "content" : "Copyright and License"
      };
      doc.create(h1);
      nodes.push(h1.id);

      var copyright = license.querySelector("copyright-statement");
      if (copyright) {
        var par = converter.paragraphGroup(state, copyright);
        var textid = par[0].children[0];
        doc.nodes[textid].content += ". ";
        nodes.push(par[0].id);
      }
      var lic = license.querySelector("license");
      var children = util.dom.getChildren(lic);
      for (var i = 0;i < children.length;i++) {
        var child = children[i];
        var type = util.dom.getNodeType(child);
        if (type === 'p' || type === 'license-p') {
          var par = converter.paragraphGroup(state, child);
          nodes.push(par[0].id)
        }
      }
    }

    doc.create(articleInfo);

    // ========================================

    var articleMeta = article.querySelector("article-meta");

    function _extractDate(dateEl) {
      if (!dateEl) return null;
      var day = dateEl.querySelector("day").textContent;
      var month = dateEl.querySelector("month").textContent;
      var year = dateEl.querySelector("year").textContent;
      return [year, month, day].join("-");
    }

    var pubDate = articleMeta.querySelector("pub-date");
    var receivedDate = articleMeta.querySelector("date[date-type=received]");
    var acceptedDate = articleMeta.querySelector("date[date-type=accepted]");

    // Extract keywords
    // ------------
    //
    // <kwd-group kwd-group-type="author-keywords">
    // <title>Author keywords</title>
    // <kwd>innate immunity</kwd>
    // <kwd>histones</kwd>
    // <kwd>lipid droplet</kwd>
    // <kwd>anti-bacterial</kwd>
    // </kwd-group>
    var keyWords = articleMeta.querySelectorAll("kwd-group[kwd-group-type=author-keywords] kwd");

    // Extract research organism
    // ------------
    //

    // <kwd-group kwd-group-type="research-organism">
    // <title>Research organism</title>
    // <kwd>B. subtilis</kwd>
    // <kwd>D. melanogaster</kwd>
    // <kwd>E. coli</kwd>
    // <kwd>Mouse</kwd>
    // </kwd-group>
    var organisms = articleMeta.querySelectorAll("kwd-group[kwd-group-type=research-organism] kwd");

    // Extract subjects
    // ------------
    //
    // <subj-group subj-group-type="heading">
    // <subject>Immunology</subject>
    // </subj-group>
    // <subj-group subj-group-type="heading">
    // <subject>Microbiology and infectious disease</subject>
    // </subj-group>

    var subjects = articleMeta.querySelectorAll("subj-group[subj-group-type=heading] subject");

    // Extract article_type
    // ---------------
    //
    // <subj-group subj-group-type="display-channel">
    // <subject>Research article</subject>
    // </subj-group>

    var articleType = articleMeta.querySelector("subj-group[subj-group-type=display-channel] subject");

    // Extract journal title
    // ---------------
    //

    var journalTitle = article.querySelector("journal-title");

    // <article-id pub-id-type="doi">10.7554/eLife.00003</article-id>
    var articleDOI = article.querySelector("article-id[pub-id-type=doi]");

    // Extract PDF link
    // ---------------
    //
    // <self-uri content-type="pdf" xlink:href="elife00007.pdf"/>

    var pdfURI = article.querySelector("self-uri[content-type=pdf]");

    var pdfLink = [
      "http://cdn.elifesciences.org/elife-articles/",
      state.doc.id,
      "/pdf/",
      pdfURI ? pdfURI.getAttribute("xlink:href") : "#"
    ].join('');

    // Related article if exists
    // -----------

    var relatedArticle = article.querySelector("related-article");

    // Collect Links
    // ---------------

    var links = [];

    if (pdfLink) {
      links.push({
        url: pdfLink,
        name: "PDF",
        type: "pdf"
      });
    }

    links.push({
      url: "https://s3.amazonaws.com/elife-cdn/elife-articles/"+state.doc.id+"/elife"+state.doc.id+".xml",
      name: "Source XML",
      type: "xml"
    });

    // Create PublicationInfo node
    // ---------------

    var pubInfoNode = {
      "id": "publication_info",
      "type": "publication_info",
      "published_on": _extractDate(pubDate),
      "received_on": _extractDate(receivedDate),
      "accepted_on": _extractDate(acceptedDate),
      "keywords": _.pluck(keyWords, "textContent"),
      "research_organisms": _.pluck(organisms, "textContent"),
      "subjects": _.pluck(subjects, "textContent"),
      "article_type": articleType ? articleType.textContent : "",
      "journal": journalTitle ? journalTitle.textContent : "",
      // "pdf_link": pdfLink,
      "related_article": relatedArticle ? ["http://dx.doi.org/", relatedArticle.getAttribute("xlink:href")].join("") : "",
      // "xml_link": "https://s3.amazonaws.com/elife-cdn/elife-articles/"+state.doc.id+"/elife"+state.doc.id+".xml", // "http://mickey.com/mouse.xml",
      "json_link": "http://mickey.com/mouse.json",
      "doi": articleDOI ? ["http://dx.doi.org/", articleDOI.textContent].join("") : "",
      "article_info": articleInfo.id,
      "links": links
    };

    doc.create(pubInfoNode);
    doc.show("info", pubInfoNode.id, 0);
  };

  // Add additional information to the info view
  // ---------
  //
  // Impact
  // Reviewing Editor
  // Major datasets
  // Acknowledgements
  // Copyright

  this.enhanceInfo = function(converter, state, article) {

    // doc.show("info", articleInfo.id);
  };

  // Add Decision letter and author response
  // ---------

  this.enhanceArticle = function(converter, state, article) {

    var nodes = [];

    // Decision letter (if available)
    // -----------

    var articleCommentary = article.querySelector("#SA1");
    if (articleCommentary) {

      var heading = {
        id: state.nextId("heading"),
        type: "heading",
        level: 1,
        content: "Article Commentary"
      };
      doc.create(heading);
      nodes.push(heading);

      var heading = {
        id: state.nextId("heading"),
        type: "heading",
        level: 2,
        content: "Decision letter"
      };
      doc.create(heading);
      nodes.push(heading);

      var body = articleCommentary.querySelector("body");
      nodes = nodes.concat(converter.bodyNodes(state, util.dom.getChildren(body)));
    }

    // Author response
    // -----------

    var authorResponse = article.querySelector("#SA2");
    if (authorResponse) {

      var heading = {
        id: state.nextId("heading"),
        type: "heading",
        level: 2,
        content: "Author response"
      };
      doc.create(heading);
      nodes.push(heading);

      var body = authorResponse.querySelector("body");
      nodes = nodes.concat(converter.bodyNodes(state, util.dom.getChildren(body)));
    }

    // Show them off
    // ----------

    if (nodes.length > 0) {
      converter.show(state, nodes);
    }

    this.enhanceInfo(converter, state, article);
  };
};

ElifeConfiguration.Prototype.prototype = DefaultConfiguration.prototype;
ElifeConfiguration.prototype = new ElifeConfiguration.Prototype();
ElifeConfiguration.prototype.constructor = ElifeConfiguration;

module.exports = ElifeConfiguration;
<|endoftext|>


<commit_before>
import {Control} from './Control';
import {Map} from '../map/Map';
import * as DomUtil from '../dom/DomUtil';
import * as DomEvent from '../dom/DomEvent';

/*
 * @class Control.Zoom
 * @aka L.Control.Zoom
 * @inherits Control
 *
 * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.
 */

export var Zoom = Control.extend({
	// @section
	// @aka Control.Zoom options
	options: {
		position: 'topleft',

		// @option zoomInText: String = '+'
		// The text set on the 'zoom in' button.
		zoomInText: '+',

		// @option zoomInTitle: String = 'Zoom in'
		// The title set on the 'zoom in' button.
		zoomInTitle: 'Zoom in',

		// @option zoomOutText: String = '−'
		// The text set on the 'zoom out' button.
		zoomOutText: '−',

		// @option zoomOutTitle: String = 'Zoom out'
		// The title set on the 'zoom out' button.
		zoomOutTitle: 'Zoom out'
	},

	onAdd: function (map) {
		var zoomName = 'leaflet-control-zoom',
		    container = DomUtil.create('div', zoomName + ' leaflet-bar'),
		    options = this.options;

		this._zoomInButton  = this._createButton(options.zoomInText, options.zoomInTitle,
		        zoomName + '-in',  container, this._zoomIn);
		this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
		        zoomName + '-out', container, this._zoomOut);

		this._updateDisabled();
		map.on('zoomend zoomlevelschange', this._updateDisabled, this);

		return container;
	},

	onRemove: function (map) {
		map.off('zoomend zoomlevelschange', this._updateDisabled, this);
	},

	disable: function () {
		this._disabled = true;
		this._updateDisabled();
		return this;
	},

	enable: function () {
		this._disabled = false;
		this._updateDisabled();
		return this;
	},

	_zoomIn: function (e) {
		if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
			this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
		}
	},

	_zoomOut: function (e) {
		if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
			this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
		}
	},

	_createButton: function (html, title, className, container, fn) {
		var link = DomUtil.create('a', className, container);
		link.innerHTML = html;
		link.href = '#';
		link.title = title;

		/*
		 * Will force screen readers like VoiceOver to read this as "Zoom in - button"
		 */
		link.setAttribute('role', 'button');
		link.setAttribute('aria-label', title);

		DomEvent.disableClickPropagation(link);
		DomEvent.on(link, 'click', DomEvent.stop);
		DomEvent.on(link, 'click', fn, this);
		DomEvent.on(link, 'click', this._refocusOnMap, this);

		return link;
	},

	_updateDisabled: function () {
		var map = this._map,
		    className = 'leaflet-disabled';

		DomUtil.removeClass(this._zoomInButton, className);
		DomUtil.removeClass(this._zoomOutButton, className);
		this._zoomInButton.setAttribute('aria-disabled', 'false');
		this._zoomOutButton.setAttribute('aria-disabled', 'false');

		if (this._disabled || map._zoom === map.getMinZoom()) {
			DomUtil.addClass(this._zoomOutButton, className);
			this._zoomOutButton.setAttribute('aria-disabled', 'true');
		}
		if (this._disabled || map._zoom === map.getMaxZoom()) {
			DomUtil.addClass(this._zoomInButton, className);
			this._zoomInButton.setAttribute('aria-disabled', 'true');
		}
	}
});

// @namespace Map
// @section Control options
// @option zoomControl: Boolean = true
// Whether a [zoom control](#control-zoom) is added to the map by default.
Map.mergeOptions({
	zoomControl: true
});

Map.addInitHook(function () {
	if (this.options.zoomControl) {
		// @section Controls
		// @property zoomControl: Control.Zoom
		// The default zoom control (only available if the
		// [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
		this.zoomControl = new Zoom();
		this.addControl(this.zoomControl);
	}
});

// @namespace Control.Zoom
// @factory L.control.zoom(options: Control.Zoom options)
// Creates a zoom control
export var zoom = function (options) {
	return new Zoom(options);
};
<commit_msg>Add aria-hidden to the +/- characters of zoom controls (#7795)<commit_after>
import {Control} from './Control';
import {Map} from '../map/Map';
import * as DomUtil from '../dom/DomUtil';
import * as DomEvent from '../dom/DomEvent';

/*
 * @class Control.Zoom
 * @aka L.Control.Zoom
 * @inherits Control
 *
 * A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends `Control`.
 */

export var Zoom = Control.extend({
	// @section
	// @aka Control.Zoom options
	options: {
		position: 'topleft',

		// @option zoomInText: String = '+'
		// The text set on the 'zoom in' button.
		zoomInText: '+',

		// @option zoomInTitle: String = 'Zoom in'
		// The title set on the 'zoom in' button.
		zoomInTitle: 'Zoom in',

		// @option zoomOutText: String = '−'
		// The text set on the 'zoom out' button.
		zoomOutText: '−',

		// @option zoomOutTitle: String = 'Zoom out'
		// The title set on the 'zoom out' button.
		zoomOutTitle: 'Zoom out'
	},

	onAdd: function (map) {
		var zoomName = 'leaflet-control-zoom',
		    container = DomUtil.create('div', zoomName + ' leaflet-bar'),
		    options = this.options;

		this._zoomInButton  = this._createButton(options.zoomInText, options.zoomInTitle,
		        zoomName + '-in',  container, this._zoomIn);
		this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
		        zoomName + '-out', container, this._zoomOut);

		this._updateDisabled();
		map.on('zoomend zoomlevelschange', this._updateDisabled, this);

		return container;
	},

	onRemove: function (map) {
		map.off('zoomend zoomlevelschange', this._updateDisabled, this);
	},

	disable: function () {
		this._disabled = true;
		this._updateDisabled();
		return this;
	},

	enable: function () {
		this._disabled = false;
		this._updateDisabled();
		return this;
	},

	_zoomIn: function (e) {
		if (!this._disabled && this._map._zoom < this._map.getMaxZoom()) {
			this._map.zoomIn(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
		}
	},

	_zoomOut: function (e) {
		if (!this._disabled && this._map._zoom > this._map.getMinZoom()) {
			this._map.zoomOut(this._map.options.zoomDelta * (e.shiftKey ? 3 : 1));
		}
	},

	_createButton: function (html, title, className, container, fn) {
		var link = DomUtil.create('a', className, container);
		link.innerHTML = html;
		link.href = '#';
		link.title = title;

		/*
		 * Will force screen readers like VoiceOver to read this as "Zoom in - button"
		 */
		link.setAttribute('role', 'button');
		link.setAttribute('aria-label', title);

		DomEvent.disableClickPropagation(link);
		DomEvent.on(link, 'click', DomEvent.stop);
		DomEvent.on(link, 'click', fn, this);
		DomEvent.on(link, 'click', this._refocusOnMap, this);

		return link;
	},

	_updateDisabled: function () {
		var map = this._map,
		    className = 'leaflet-disabled';

		DomUtil.removeClass(this._zoomInButton, className);
		DomUtil.removeClass(this._zoomOutButton, className);
		this._zoomInButton.setAttribute('aria-disabled', 'false');
		this._zoomOutButton.setAttribute('aria-disabled', 'false');

		if (this._disabled || map._zoom === map.getMinZoom()) {
			DomUtil.addClass(this._zoomOutButton, className);
			this._zoomOutButton.setAttribute('aria-disabled', 'true');
		}
		if (this._disabled || map._zoom === map.getMaxZoom()) {
			DomUtil.addClass(this._zoomInButton, className);
			this._zoomInButton.setAttribute('aria-disabled', 'true');
		}
	}
});

// @namespace Map
// @section Control options
// @option zoomControl: Boolean = true
// Whether a [zoom control](#control-zoom) is added to the map by default.
Map.mergeOptions({
	zoomControl: true
});

Map.addInitHook(function () {
	if (this.options.zoomControl) {
		// @section Controls
		// @property zoomControl: Control.Zoom
		// The default zoom control (only available if the
		// [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map).
		this.zoomControl = new Zoom();
		this.addControl(this.zoomControl);
	}
});

// @namespace Control.Zoom
// @factory L.control.zoom(options: Control.Zoom options)
// Creates a zoom control
export var zoom = function (options) {
	return new Zoom(options);
};
<|endoftext|>


<commit_before>odoo.define('hr_attendance_management.attendance', function (require) {
"use strict";

    var core = require('web.core');

    var hr_attendance = require('hr_attendance.my_attendances');
    var greeting_message = require('hr_attendance.greeting_message');
    var Model = require('web.Model');
    var session = require('web.session');

    var QWeb = core.qweb;
    var _t = core._t;

    hr_attendance.include({
        start: function () {
            var self = this;
            var result = this._super();
            var hr_location = new Model('hr.attendance.location');
            self.hr_location = [];
            hr_location.call('search', [[]]).then(function (location_ids) {
                hr_location.call('read', [location_ids, ['name']]).then(function (result) {
                   self.hr_location = result;
                   self.$el.html(QWeb.render("HrAttendanceMyMainMenu", {widget: self}));
                });
            });
            var hr_employee = new Model('hr.employee');
            hr_employee.query(['attendance_state', 'name', 'extra_hours_formatted', 'today_hour_formatted', 'time_warning_balance', 'time_warning_today', 'extra_hours_today', 'work_location'])
                .filter([['user_id', '=', self.session.uid]])
                .all()
                .then(function (res) {
                    if (_.isEmpty(res) ) {
                        self.$('.o_hr_attendance_employee').append(_t("Error : Could not find employee linked to user"));
                        return;
                    }
                    self.employee = res[0];
                    self.$el.html(QWeb.render("HrAttendanceMyMainMenu", {widget: self}));

                    // auto-counter
                    $('#moment_pl').html(Date.now());
                    setInterval(function () {
                        if ($('#moment_pl').length) {
                            var moment_start = moment(new Date(parseInt($('#moment_pl').text())));
                            var diff_minutes = moment().diff(moment_start, 'minutes');

                            ['worked_today', 'balance_today'].forEach(
                                function (el) {
                                    var matches = $('#' + el + '_pl').text().match(/^-?(\d{2}):(\d{2})$/);

                                    if (matches != null && $('#state').text() == 'checked in') {
                                        var hours = parseInt(matches[1]);
                                        var minutes = parseInt(matches[2]);

                                        var total_minutes = (minutes + (hours * 60)) * (matches[0].substring(0, 1) === '-' ? -1 : 1);// eslint-disable-line no-extra-parens
                                        var negative = total_minutes + diff_minutes < 0;

                                        var new_total = Math.abs(total_minutes + diff_minutes);
                                        var new_hours = ('0' + Math.trunc(new_total / 60)).slice(-2); // eslint-disable-line no-extra-parens
                                        var new_minutes = ('0' + (new_total % 60)).slice(-2); // eslint-disable-line no-extra-parens

                                        $('#' + el).text((negative ? '-' : '') + new_hours + ':' + new_minutes);

                                        if (el != 'worked_today') {
                                            $('#' + el).parent().get(0).style.color = negative ? 'red' : 'green';
                                        }
                                    }
                                });
                        }
                    }, 20000);
                });

            return result;
        },
        update_attendance: function () {
            var loc_id = parseInt($('#location').val(), 10);
            session.user_context['default_location_id'] = loc_id;
            this._super();
        }
    });

    greeting_message.include({

        setAttendanceMessageTimeout: function(context) {
            return function() {
                setTimeout(function() {
                    context.do_action(context.next_action, {
                        clear_breadcrumbs: true
                    });
                }, 5000);
            }
        },

        welcome_message: function () {
            this._super();
            if (!this.attendance.due_hours && !this.attendance.check_out && this.attendance.total_attendance === 0 && !this.attendance.has_change_day_request) {
                // remove timeout that redirects to main page after 5 seconds
                clearTimeout(this.return_to_main_menu);
                window.attendance_message_timeout = this.setAttendanceMessageTimeout(this);
                window.add_timeout_button_event = function(className) {
                    $('.'+className).click(window.attendance_message_timeout);
                };
                this.do_action('hr_attendance_management.change_day_wizard');
            }
        }
    });
});
<commit_msg>FIX hr_attendance location javascript<commit_after>odoo.define('hr_attendance_management.attendance', function (require) {
"use strict";

    var core = require('web.core');

    var hr_attendance = require('hr_attendance.my_attendances');
    var greeting_message = require('hr_attendance.greeting_message');
    var Model = require('web.Model');
    var session = require('web.session');

    var QWeb = core.qweb;
    var _t = core._t;

    hr_attendance.include({
        start: function () {
            var self = this;
            self.hr_location = [];
            var result = this._super();
            var hr_location = new Model('hr.attendance.location');
            var hr_employee = new Model('hr.employee');
            hr_employee.query(['attendance_state', 'name', 'extra_hours_formatted', 'today_hour_formatted', 'time_warning_balance', 'time_warning_today', 'extra_hours_today', 'work_location'])
                .filter([['user_id', '=', self.session.uid]])
                .all()
                .then(function (res) {
                    if (_.isEmpty(res) ) {
                        self.$('.o_hr_attendance_employee').append(_t("Error : Could not find employee linked to user"));
                        return;
                    }
                    self.employee = res[0];
                    hr_location.call('search', [[]]).then(function (location_ids) {
                        hr_location.call('read', [location_ids, ['name']]).then(function (result) {
                           self.hr_location = result;
                           self.$el.html(QWeb.render("HrAttendanceMyMainMenu", {widget: self}));
                        });
                    });

                    // auto-counter
                    $('#moment_pl').html(Date.now());
                    setInterval(function () {
                        if ($('#moment_pl').length) {
                            var moment_start = moment(new Date(parseInt($('#moment_pl').text())));
                            var diff_minutes = moment().diff(moment_start, 'minutes');

                            ['worked_today', 'balance_today'].forEach(
                                function (el) {
                                    var matches = $('#' + el + '_pl').text().match(/^-?(\d{2}):(\d{2})$/);

                                    if (matches != null && $('#state').text() == 'checked in') {
                                        var hours = parseInt(matches[1]);
                                        var minutes = parseInt(matches[2]);

                                        var total_minutes = (minutes + (hours * 60)) * (matches[0].substring(0, 1) === '-' ? -1 : 1);// eslint-disable-line no-extra-parens
                                        var negative = total_minutes + diff_minutes < 0;

                                        var new_total = Math.abs(total_minutes + diff_minutes);
                                        var new_hours = ('0' + Math.trunc(new_total / 60)).slice(-2); // eslint-disable-line no-extra-parens
                                        var new_minutes = ('0' + (new_total % 60)).slice(-2); // eslint-disable-line no-extra-parens

                                        $('#' + el).text((negative ? '-' : '') + new_hours + ':' + new_minutes);

                                        if (el != 'worked_today') {
                                            $('#' + el).parent().get(0).style.color = negative ? 'red' : 'green';
                                        }
                                    }
                                });
                        }
                    }, 20000);
                });

            return result;
        },
        update_attendance: function () {
            var loc_id = parseInt($('#location').val(), 10);
            session.user_context['default_location_id'] = loc_id;
            this._super();
        }
    });

    greeting_message.include({

        setAttendanceMessageTimeout: function(context) {
            return function() {
                setTimeout(function() {
                    context.do_action(context.next_action, {
                        clear_breadcrumbs: true
                    });
                }, 5000);
            }
        },

        welcome_message: function () {
            this._super();
            if (!this.attendance.due_hours && !this.attendance.check_out && this.attendance.total_attendance === 0 && !this.attendance.has_change_day_request) {
                // remove timeout that redirects to main page after 5 seconds
                clearTimeout(this.return_to_main_menu);
                window.attendance_message_timeout = this.setAttendanceMessageTimeout(this);
                window.add_timeout_button_event = function(className) {
                    $('.'+className).click(window.attendance_message_timeout);
                };
                this.do_action('hr_attendance_management.change_day_wizard');
            }
        }
    });
});
<|endoftext|>


<commit_before>/* from wikipdia
DSCP value 	Hex value 	Decimal value 	Meaning
101 110 	0x2e 		46 				Expedited forwarding (EF)
000 000 	0x00 		0 				Best effort
001 010 	0x0a 		10 				AF11
001 100 	0x0c 		12 				AF12
001 110 	0x0e 		14 				AF13
010 010 	0x12 		18 				AF21
010 100 	0x14 		20 				AF22
010 110 	0x16 		22 				AF23
011 010 	0x1a 		26 				AF31
011 100 	0x1c 		28 				AF32
011 110 	0x1e 		30 				AF33
100 010 	0x22 		34 				AF41
100 100 	0x24 		36 				AF42
100 110 	0x26 		38 				AF43
*/

var dscp_labels = [
	"EF",
	"BE",
	"AF11",
	"AF12",
	"AF13",
	"AF21",
	"AF22",
	"AF23",
	"AF31",
	"AF32",
	"AF33",
	"AF41",
	"AF42",
	"AF43",
	"Other"
]

var dscp_label_colours = [
	'#005151',
	'#7f3333',
	'#51cccc',
	'#337f7f',
	'#33467f',
	'#8ecc51',
	'#597f33',
	'#51cc70',
	'#8e51cc',
	'#59337f',
	'#5170cc',
	'#ccad51',
	'#7f6c33',
	'#cc6c33',
	'#cc51ad',
]

function setupcharts()
{
	var charts = {}
	charts.eth1line = c3.generate({
		bindto: ".eth1-line",
		data: {
			columns: [
				['rx'].concat(new Array(100).fill(0)),
				['tx'].concat(new Array(100).fill(0)),
			]
		},
		point: {
			show: false
		},
		axis: {
			y: { show: false },
			x: { show: false }
		},
		legend: { hide: true },
		interaction: {enabled: false},
	});

	charts.eth1rxgauge = c3.generate({
		bindto: ".eth1-rx-gauge",
		data: {
		columns: [
			['rx', 30],
		],
		type : 'gauge',
		},
		gauge: {
			label: {
				format: formatbandwidth,
				show: false
			},
			max: 1000000,
		},
		color: {
			pattern: [ '#7887AB', '#4F628E', '#162955', '#061539'],
			threshold: {
				values: [30, 60, 90, 100]
			}
		}
	});

	charts.eth1txgauge = c3.generate({
		bindto: ".eth1-tx-gauge",
		data: {
			columns: [
				['tx', 30],
			],
			type : 'gauge',
		},
		gauge: {
			label: {
				format: formatbandwidth,
				show: false
			},
			max: 1000000,
		},
		color: {
			pattern: ['#88CC88', '#55AA55', '#116611', '#004400'],
			threshold: {
				values: [30, 60, 90, 100]
			}
		}
	});

	charts.eth2line = c3.generate({
		bindto: ".eth2-line",
		data: {
			columns: [
				['rx'].concat(new Array(100).fill(0)),
				['tx'].concat(new Array(100).fill(0)),
			]
		},
		point: {
			show: false
		},
		axis: {
			y: { show: false },
			x: { show: false }
		},
		legend: { hide: true },
		interaction: {enabled: false},
	});

	charts.eth2rxgauge = c3.generate({
		bindto: ".eth2-rx-gauge",
		data: {
			columns: [
				['rx', 30],
			],
			type : 'gauge',
		},
		gauge: {
			label: {
				format: formatbandwidth,
				show: false
			},
			max: 1000000,
		},
		color: {
			pattern: [ '#7887AB', '#4F628E', '#162955', '#061539'],
			threshold: {
				values: [30, 60, 90, 100]
			}
		}
	});

	charts.eth2txgauge = c3.generate({
		bindto: ".eth2-tx-gauge",
		data: {
			columns: [
				['tx', 30],
			],
			type : 'gauge',
		},
		gauge: {
			label: {
				format: formatbandwidth,
				show: false
			},
			max: 1000000,
		},
		color: {
			pattern: ['#88CC88', '#55AA55', '#116611', '#004400'],
			threshold: {
				values: [30, 60, 90, 100]
			}
		}
	});

	charts.dscpbar = c3.generate({
		bindto: ".dscp-bar",
		data: {
			columns: [
				['DSCP Values', 35, 40, 10, 1, 4, 0, 0, 5, 0, 0, 0, 0, 0, 5]
			],
			type: 'bar',
			color: function (color, d) { return dscp_label_colours[d.index]; }
		},
		bar: {
			width: 50 // this makes bar width 100px
		},
		size: {
			height: 200,
			width: 1000
		},
		axis: {
			x: {
				type: 'category',
				categories: dscp_labels
			}
		},
		interaction: {enabled: false},
	});

	return charts;
}

function formatbandwidth(bytes, ratio)
{
	bits = bytes * 8

	if(bits > (1024 * 1024)) {
		return Math.floor(bits/ (1024*1024)) + ' Mb/s'
	} else if(bits > 1024) {
		return Math.floor(bits/ (1024)) + ' Kb/s'
	}
	return Math.floor(bits) + ' b/s'
}

var ws;

function init()
{
	var charts = setupcharts();

	websocketuri= "ws://" + window.location.hostname + ":8080/ifstatus";

	ws = new WebSocket(websocketuri, "SUPERNET");
	ws.onopen = function (event) {
		console.log("ws connected");
	};

	ws.onmessage = function (event) {
		netdata = JSON.parse(event.data)

		if(!netdata['interfaces'] ||!netdata['interfaces'].length)
			return;

		eth1 = netdata['interfaces'][1]
		eth2 = netdata['interfaces'][2]

		dscp = netdata['dscp']

		charts.eth1line.load({
			columns: [
				['rx'].concat(netdata[eth1]["rx"]),
				['tx'].concat(netdata[eth1]["tx"])
			]
		});

		charts.eth1rxgauge .load({
			columns: [
				['rx'].concat(netdata[eth1]["rx"].slice(-1)[0]),
			]
		});

		charts.eth1txgauge .load({
			columns: [
				['tx'].concat(netdata[eth1]["tx"].slice(-1)[0]),
			]
		});

		charts.eth2line.load({
			columns: [
				['rx'].concat(netdata[eth2]["rx"]),
				['tx'].concat(netdata[eth2]["tx"])
			]
		});

		charts.eth2rxgauge .load({
			columns: [
				['rx'].concat(netdata[eth2]["rx"].slice(-1)[0]),
			]
		});

		charts.eth2txgauge .load({
			columns: [
				['tx'].concat(netdata[eth2]["tx"].slice(-1)[0]),
			]
		});

		charts.dscpbar.load({
			columns: [
				['DSCP Values'].concat(dscp)
			]
		});
	}
}
<commit_msg>Initialise with the current number of bar entries<commit_after>/* from wikipdia
DSCP value 	Hex value 	Decimal value 	Meaning
101 110 	0x2e 		46 				Expedited forwarding (EF)
000 000 	0x00 		0 				Best effort
001 010 	0x0a 		10 				AF11
001 100 	0x0c 		12 				AF12
001 110 	0x0e 		14 				AF13
010 010 	0x12 		18 				AF21
010 100 	0x14 		20 				AF22
010 110 	0x16 		22 				AF23
011 010 	0x1a 		26 				AF31
011 100 	0x1c 		28 				AF32
011 110 	0x1e 		30 				AF33
100 010 	0x22 		34 				AF41
100 100 	0x24 		36 				AF42
100 110 	0x26 		38 				AF43
*/

var dscp_labels = [
	"EF",
	"BE",
	"AF11",
	"AF12",
	"AF13",
	"AF21",
	"AF22",
	"AF23",
	"AF31",
	"AF32",
	"AF33",
	"AF41",
	"AF42",
	"AF43",
	"Other"
]

var dscp_label_colours = [
	'#005151',
	'#7f3333',
	'#51cccc',
	'#337f7f',
	'#33467f',
	'#8ecc51',
	'#597f33',
	'#51cc70',
	'#8e51cc',
	'#59337f',
	'#5170cc',
	'#ccad51',
	'#7f6c33',
	'#cc6c33',
	'#cc51ad',
]

function setupcharts()
{
	var charts = {}
	charts.eth1line = c3.generate({
		bindto: ".eth1-line",
		data: {
			columns: [
				['rx'].concat(new Array(100).fill(0)),
				['tx'].concat(new Array(100).fill(0)),
			]
		},
		point: {
			show: false
		},
		axis: {
			y: { show: false },
			x: { show: false }
		},
		legend: { hide: true },
		interaction: {enabled: false},
	});

	charts.eth1rxgauge = c3.generate({
		bindto: ".eth1-rx-gauge",
		data: {
		columns: [
			['rx', 30],
		],
		type : 'gauge',
		},
		gauge: {
			label: {
				format: formatbandwidth,
				show: false
			},
			max: 1000000,
		},
		color: {
			pattern: [ '#7887AB', '#4F628E', '#162955', '#061539'],
			threshold: {
				values: [30, 60, 90, 100]
			}
		}
	});

	charts.eth1txgauge = c3.generate({
		bindto: ".eth1-tx-gauge",
		data: {
			columns: [
				['tx', 30],
			],
			type : 'gauge',
		},
		gauge: {
			label: {
				format: formatbandwidth,
				show: false
			},
			max: 1000000,
		},
		color: {
			pattern: ['#88CC88', '#55AA55', '#116611', '#004400'],
			threshold: {
				values: [30, 60, 90, 100]
			}
		}
	});

	charts.eth2line = c3.generate({
		bindto: ".eth2-line",
		data: {
			columns: [
				['rx'].concat(new Array(100).fill(0)),
				['tx'].concat(new Array(100).fill(0)),
			]
		},
		point: {
			show: false
		},
		axis: {
			y: { show: false },
			x: { show: false }
		},
		legend: { hide: true },
		interaction: {enabled: false},
	});

	charts.eth2rxgauge = c3.generate({
		bindto: ".eth2-rx-gauge",
		data: {
			columns: [
				['rx', 30],
			],
			type : 'gauge',
		},
		gauge: {
			label: {
				format: formatbandwidth,
				show: false
			},
			max: 1000000,
		},
		color: {
			pattern: [ '#7887AB', '#4F628E', '#162955', '#061539'],
			threshold: {
				values: [30, 60, 90, 100]
			}
		}
	});

	charts.eth2txgauge = c3.generate({
		bindto: ".eth2-tx-gauge",
		data: {
			columns: [
				['tx', 30],
			],
			type : 'gauge',
		},
		gauge: {
			label: {
				format: formatbandwidth,
				show: false
			},
			max: 1000000,
		},
		color: {
			pattern: ['#88CC88', '#55AA55', '#116611', '#004400'],
			threshold: {
				values: [30, 60, 90, 100]
			}
		}
	});

	charts.dscpbar = c3.generate({
		bindto: ".dscp-bar",
		data: {
			columns: [
				['DSCP Values', 35, 40, 10, 1, 4, 0, 0, 5, 0, 0, 0, 0, 0, 4,1]
			],
			type: 'bar',
			color: function (color, d) { return dscp_label_colours[d.index]; }
		},
		bar: {
			width: 50, // this makes bar width 100px
		},
		size: {
			height: 200,
			width: 1000
		},
		axis: {
			x: {
				type: 'category',
				categories: dscp_labels
			}
		},
		interaction: {enabled: false},
	});

	return charts;
}

function formatbandwidth(bytes, ratio)
{
	bits = bytes * 8

	if(bits > (1024 * 1024)) {
		return Math.floor(bits/ (1024*1024)) + ' Mb/s'
	} else if(bits > 1024) {
		return Math.floor(bits/ (1024)) + ' Kb/s'
	}
	return Math.floor(bits) + ' b/s'
}

var ws;

function init()
{
	var charts = setupcharts();

	websocketuri= "ws://" + window.location.hostname + ":8080/ifstatus";

	ws = new WebSocket(websocketuri, "SUPERNET");
	ws.onopen = function (event) {
		console.log("ws connected");
	};

	ws.onmessage = function (event) {
		netdata = JSON.parse(event.data)

		if(!netdata['interfaces'] ||!netdata['interfaces'].length)
			return;

		eth1 = netdata['interfaces'][1]
		eth2 = netdata['interfaces'][2]

		dscp = netdata['dscp']

		charts.eth1line.load({
			columns: [
				['rx'].concat(netdata[eth1]["rx"]),
				['tx'].concat(netdata[eth1]["tx"])
			]
		});

		charts.eth1rxgauge .load({
			columns: [
				['rx'].concat(netdata[eth1]["rx"].slice(-1)[0]),
			]
		});

		charts.eth1txgauge .load({
			columns: [
				['tx'].concat(netdata[eth1]["tx"].slice(-1)[0]),
			]
		});

		charts.eth2line.load({
			columns: [
				['rx'].concat(netdata[eth2]["rx"]),
				['tx'].concat(netdata[eth2]["tx"])
			]
		});

		charts.eth2rxgauge .load({
			columns: [
				['rx'].concat(netdata[eth2]["rx"].slice(-1)[0]),
			]
		});

		charts.eth2txgauge .load({
			columns: [
				['tx'].concat(netdata[eth2]["tx"].slice(-1)[0]),
			]
		});

		charts.dscpbar.load({
			columns: [
				['DSCP Values'].concat(dscp)
			]
		});
	}
}
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.BufferAttribute = function ( array, itemSize ) {

	this.array = array;
	this.itemSize = itemSize;

	this.needsUpdate = false;

};

THREE.BufferAttribute.prototype = {

	constructor: THREE.BufferAttribute,

	get length () {

		return this.array.length;

	},

	copyAt: function ( index1, attribute, index2 ) {

		index1 *= this.itemSize;
		index2 *= attribute.itemSize;

		for ( var i = 0, l = this.itemSize; i < l; i ++ ) {

			this.array[ index1 + i ] = attribute.array[ index2 + i ];

		}

		return this;

	},

	copyArray: function ( array ) {

		this.array.set( array );

		return this;

	},

	copyColorsArray: function ( colors ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = colors.length; i < l; i ++ ) {

			var color = colors[ i ];

			if ( color === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
				color = new THREE.Color();

			}

			array[ offset ++ ] = color.r;
			array[ offset ++ ] = color.g;
			array[ offset ++ ] = color.b;

		}

		return this;

	},

	copyFacesArray: function ( faces ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = faces.length; i < l; i ++ ) {

			var face = faces[ i ];

			array[ offset ++ ] = face.a;
			array[ offset ++ ] = face.b;
			array[ offset ++ ] = face.c;

		}

		return this;

	},

	copyVector2sArray: function ( vectors ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = vectors.length; i < l; i ++ ) {

			var vector = vectors[ i ];

			if ( vector === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
				vector = new THREE.Vector2();

			}

			array[ offset ++ ] = vector.x;
			array[ offset ++ ] = vector.y;

		}

		return this;

	},

	copyVector3sArray: function ( vectors ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = vectors.length; i < l; i ++ ) {

			var vector = vectors[ i ];

			if ( vector === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
				vector = new THREE.Vector3();

			}

			array[ offset ++ ] = vector.x;
			array[ offset ++ ] = vector.y;
			array[ offset ++ ] = vector.z;

		}

		return this;

	},

	copyVector4sArray: function ( vectors ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = vectors.length; i < l; i ++ ) {

			var vector = vectors[ i ];

			if ( vector === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
				vector = new THREE.Vector4();

			}

			array[ offset ++ ] = vector.x;
			array[ offset ++ ] = vector.y;
			array[ offset ++ ] = vector.z;
			array[ offset ++ ] = vector.w;

		}

		return this;

	},

	set: function ( value, offset ) {

		if ( offset === undefined ) offset = 0;

		this.array.set( value, offset );

		return this;

	},

	getX: function ( index ) {

		return this.array[ index * this.itemSize ];

	},

	setX: function ( index, x ) {

		this.array[ index * this.itemSize ] = x;

		return this;

	},

	getY: function ( index ) {

		return this.array[ index * this.itemSize + 1 ];

	},

	setY: function ( index, y ) {

		this.array[ index * this.itemSize + 1 ] = y;

		return this;

	},

	getZ: function ( index ) {

		return this.array[ index * this.itemSize + 2 ];

	},

	setZ: function ( index, z ) {

		this.array[ index * this.itemSize + 2 ] = z;

		return this;

	},

	getW: function ( index ) {

		return this.array[ index * this.itemSize + 3 ];

	},

	setW: function ( index, w ) {

		this.array[ index * this.itemSize + 3 ] = w;

		return this;

	},

	setXY: function ( index, x, y ) {

		index *= this.itemSize;

		this.array[ index + 0 ] = x;
		this.array[ index + 1 ] = y;

		return this;

	},

	setXYZ: function ( index, x, y, z ) {

		index *= this.itemSize;

		this.array[ index + 0 ] = x;
		this.array[ index + 1 ] = y;
		this.array[ index + 2 ] = z;

		return this;

	},

	setXYZW: function ( index, x, y, z, w ) {

		index *= this.itemSize;

		this.array[ index + 0 ] = x;
		this.array[ index + 1 ] = y;
		this.array[ index + 2 ] = z;
		this.array[ index + 3 ] = w;

		return this;

	},

	clone: function () {

		return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize );

	}

};

//

THREE.Int8Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint8Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint8ClampedAttribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Int16Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint16Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Int32Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint32Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Float32Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Float64Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};
<commit_msg>BufferAttribute: .length is now the number of elements. See #6473 @benaadams do you mind changing the other ones? O:)<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.BufferAttribute = function ( array, itemSize ) {

	this.array = array;
	this.itemSize = itemSize;

	this.needsUpdate = false;

};

THREE.BufferAttribute.prototype = {

	constructor: THREE.BufferAttribute,

	get length () {

		return this.array.length / this.itemSize;

	},

	copyAt: function ( index1, attribute, index2 ) {

		index1 *= this.itemSize;
		index2 *= attribute.itemSize;

		for ( var i = 0, l = this.itemSize; i < l; i ++ ) {

			this.array[ index1 + i ] = attribute.array[ index2 + i ];

		}

		return this;

	},

	copyArray: function ( array ) {

		this.array.set( array );

		return this;

	},

	copyColorsArray: function ( colors ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = colors.length; i < l; i ++ ) {

			var color = colors[ i ];

			if ( color === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
				color = new THREE.Color();

			}

			array[ offset ++ ] = color.r;
			array[ offset ++ ] = color.g;
			array[ offset ++ ] = color.b;

		}

		return this;

	},

	copyFacesArray: function ( faces ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = faces.length; i < l; i ++ ) {

			var face = faces[ i ];

			array[ offset ++ ] = face.a;
			array[ offset ++ ] = face.b;
			array[ offset ++ ] = face.c;

		}

		return this;

	},

	copyVector2sArray: function ( vectors ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = vectors.length; i < l; i ++ ) {

			var vector = vectors[ i ];

			if ( vector === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
				vector = new THREE.Vector2();

			}

			array[ offset ++ ] = vector.x;
			array[ offset ++ ] = vector.y;

		}

		return this;

	},

	copyVector3sArray: function ( vectors ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = vectors.length; i < l; i ++ ) {

			var vector = vectors[ i ];

			if ( vector === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
				vector = new THREE.Vector3();

			}

			array[ offset ++ ] = vector.x;
			array[ offset ++ ] = vector.y;
			array[ offset ++ ] = vector.z;

		}

		return this;

	},

	copyVector4sArray: function ( vectors ) {

		var array = this.array, offset = 0;

		for ( var i = 0, l = vectors.length; i < l; i ++ ) {

			var vector = vectors[ i ];

			if ( vector === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
				vector = new THREE.Vector4();

			}

			array[ offset ++ ] = vector.x;
			array[ offset ++ ] = vector.y;
			array[ offset ++ ] = vector.z;
			array[ offset ++ ] = vector.w;

		}

		return this;

	},

	set: function ( value, offset ) {

		if ( offset === undefined ) offset = 0;

		this.array.set( value, offset );

		return this;

	},

	getX: function ( index ) {

		return this.array[ index * this.itemSize ];

	},

	setX: function ( index, x ) {

		this.array[ index * this.itemSize ] = x;

		return this;

	},

	getY: function ( index ) {

		return this.array[ index * this.itemSize + 1 ];

	},

	setY: function ( index, y ) {

		this.array[ index * this.itemSize + 1 ] = y;

		return this;

	},

	getZ: function ( index ) {

		return this.array[ index * this.itemSize + 2 ];

	},

	setZ: function ( index, z ) {

		this.array[ index * this.itemSize + 2 ] = z;

		return this;

	},

	getW: function ( index ) {

		return this.array[ index * this.itemSize + 3 ];

	},

	setW: function ( index, w ) {

		this.array[ index * this.itemSize + 3 ] = w;

		return this;

	},

	setXY: function ( index, x, y ) {

		index *= this.itemSize;

		this.array[ index + 0 ] = x;
		this.array[ index + 1 ] = y;

		return this;

	},

	setXYZ: function ( index, x, y, z ) {

		index *= this.itemSize;

		this.array[ index + 0 ] = x;
		this.array[ index + 1 ] = y;
		this.array[ index + 2 ] = z;

		return this;

	},

	setXYZW: function ( index, x, y, z, w ) {

		index *= this.itemSize;

		this.array[ index + 0 ] = x;
		this.array[ index + 1 ] = y;
		this.array[ index + 2 ] = z;
		this.array[ index + 3 ] = w;

		return this;

	},

	clone: function () {

		return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize );

	}

};

//

THREE.Int8Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Int8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint8Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Uint8Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint8ClampedAttribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Uint8ClampedAttribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Int16Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Int16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint16Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Uint16Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Int32Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Int32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Uint32Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Uint32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Float32Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Float32Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};

THREE.Float64Attribute = function ( data, itemSize ) {

	THREE.warn( 'THREE.Float64Attribute has been removed. Use THREE.BufferAttribute( array, itemSize ) instead.' );
	return new THREE.BufferAttribute( data, itemSize );

};
<|endoftext|>