<commit_before>'use strict';

publicApp.controller('ColumnsCtrl', function($scope, $http) {
    var wshost = 'ws://127.0.0.1:9000/api/stream/webSocket';
    var ssehost = 'http://127.0.0.1:9000/api/stream/sse';
    var sseping = 'http://127.0.0.1:9000/api/stream/ping';

    var socket;
    if(window.MozWebSocket) {
        window.WebSocket=window.MozWebSocket;
    }
    if(!window.WebSocket) {
        alert('Votre navigateur ne supporte pas les webSocket !');
        return false;
    } else {
        socket = new WebSocket(wshost);
        socket.onopen = function() { console.log('socket ouverte'); }
        socket.onclose = function() { console.log('socket fermée'); }
        socket.onerror = function() { console.log('Une erreur est survenue'); }
        socket.onmessage = function(msg){
            var data;
            try { //tente de parser data
                data = JSON.parse(msg.data);
            } catch(exception) {
                data = msg.data
            }
            //ici on poura effectuer tout ce que l'on veux sur notre objet data
            executeCommand(data);
        }
    }

    if (!window.WebSocket && !!window.EventSource) {
        var source = new EventSource(ssehost);
        source.addEventListener('message', function(msg) {
            var data;
            try { //tente de parser data
                data = JSON.parse(msg.data);
            } catch(exception) {
                data = msg.data
            }
            //ici on poura effectuer tout ce que l'on veux sur notre objet data
            executeCommand(data);
            $http.get(sseping);
        }, false);

        source.addEventListener('open', function(e) {console.log('socket ouverte');}, false);
        source.addEventListener('error', function(e) {console.log('Une erreur est survenue');}, false);
    }

    $scope.truncateString = function(chaine) {
      if(chaine.length > 120) {
        return String(chaine).substring(0, 120)+"...";
      }
      else {
        return chaine;
      }
    }

    $scope.addColumn = function() {
        if($scope.serviceProposes == undefined) {
          var json = {"cmd":"allUnifiedRequests"};
          socket.send(JSON.stringify(json));
        }
        if($scope.columns == undefined) {
          $scope.columns = [];
        }
        $scope.columns.push({"title":"",
                              "oldTitle":"",
                              "showModifyColumn":"true",
                              "newColumn":"true",
                              "unifiedRequests":[]});
    };

    $scope.modifyColumn = function(column) {
      console.log("column", column);
      column.showModifyColumn = !column.showModifyColumn;
      if (column.showModifyColumn == true) {
        if($scope.serviceProposes == undefined) {
          var json = {"cmd":"allUnifiedRequests"};
          socket.send(JSON.stringify(json));
        }
      }
      if(column.showModifyColumn == true) {
        column.oldTitle = column.title;
      }
      else {
        column.title = column.oldTitle;
      }
    };

    $scope.addService = function(service, column) {
      if(service.socialNetworkToken) {
        console.log("service",service);
        var clientUnifiedRequest = serverToUnifiedRequest(service.service);
        column.unifiedRequests.push(clientUnifiedRequest);
      }
      else {
        $scope.openPopup(service, column);
      }
    }

    $scope.deleteService = function(service, column) {
      var existInColumn = false;
      var indexInColumn = -1;
      for (var i = 0; i < column.unifiedRequests.length; i++) {
        if(column.unifiedRequests[i].service == service.service) {
          existInColumn = true;
          indexInColumn = i;
          break;
        }
      }
      if(existInColumn && indexInColumn > -1) {
        column.unifiedRequests.splice(indexInColumn,1);
      }
    }

    $scope.changeColumn = function(column) {
      column.showErrorTitleAlreadyExist = false;
      column.showErrorTitleRequired = false;
      var json = "";
      var unifiedRequests = [];
      for (var i = 0; i < column.unifiedRequests.length; i++) {
        unifiedRequests.push(clientToServerUnifiedRequest(column.unifiedRequests[i]));
      };
      if(!column.newColumn) {
        json = {"cmd":"modColumn",
                 "body":{
                   "title": column.oldTitle,
                   "column":{
                     "title":column.title,
                     "unifiedRequests": unifiedRequests
                   }
                 }
                };
      } else {
        column.newColumn = false;
        json = {"cmd":"addColumn",
                "body":{
                  "title":column.title,
                  "unifiedRequests": unifiedRequests
                }
              };
      }
      if(column.title =="") {
        column.showErrorTitleRequired = true;
      }
      else {
        column.showErrorTitleRequired = false;
        var nombreName = 0;
        for (var i = 0; i < $scope.columns.length; i++) {
          if($scope.columns[i].title == column.title) {
            nombreName++;
          }
        };
        if(nombreName > 1) {
          column.showErrorTitleAlreadyExist = true;
        }
        else {
          column.showErrorTitleAlreadyExist = false;
          column.messages = [];
          column.showModifyColumn= !column.showModifyColumn;
          socket.send(JSON.stringify(json));
        }
      }
    }

    $scope.deleteColumn = function(column) {
      $scope.lastColumnDeleted = {"cmd":"delColumn", "body":{"title": column.title}};
      socket.send(JSON.stringify($scope.lastColumnDeleted));
    }

    $scope.serviceHasTypeChar = function(service) {
      if(service.typeServiceChar != "") {
        return true;
      }
      return false;
    }

    $scope.typeServiceCharByService = function(service) {
      var socialNetworkName = service.split(".")[0];
      var typeService = service.split(".")[1];
        if(typeService == "group") {
          return "ഹ";
        }
        else if(typeService == "user") {
          if(socialNetworkName == "twitter") {
            return "@";
          }
          else {
            return "😊";
          }
        }
        else if (typeService == "hashtag") {
          return "#";
        }
        return "";
    }

    $scope.openPopup = function(service, column) {
      var _service = service;
      var _column = column;
      var scope = $scope;
      var newwindow = window.open("/auth/"+service.socialNetwork, 'Connexion', 'height=500,width=500');

      if (newwindow !== undefined) {
        if (window.focus) newwindow.focus();

        newwindow.onclose = function() {
          $http.get("/api/providers/services").success(function(data) {
            executeCommand({"cmd":"allUnifiedRequests","body":data});
            var serviceJson = {"service":_service.socialNetwork+"."+_service.typeService,
                            "args":_service.args
                          };
            _column.unifiedRequests.push(serviceJson);
          });
        };
        newwindow.onbeforeunload = function() {
          $http.get("/api/providers/services").success(function(data) {
            executeCommand({"cmd":"allUnifiedRequests","body":data});
            var serviceJson = {"service":_service.socialNetwork+"."+_service.typeService,
                            "args":_service.args
                          };
            _column.unifiedRequests.push(serviceJson);
          });
        };
      }
      return false;
    }

function getColumnByName(name) {
    for (var i = 0; i < $scope.columns.length; i++) {
        if ($scope.columns[i].title == name) {
            return $scope.columns[i];
        }
    }
}

function fillExplainService(typeService, socialNetwork) {
  if(typeService == "group") {
    return "Click here to display a specific Facebook group.";
  }
  else if(typeService == "user") {
    if(socialNetwork == "twitter") {
      return "Click here to display tweets of a specific Twitter user.";
    }
    else {
      return "Click here to display the wall of a specific Facebook user.";
    }
  }
  else if (typeService == "hashtag") {
    return "Click here to display tweets of a specific Twitter hashtag.";
  }
  else {
    return "Click here to display your "+socialNetwork+" "+typeService+".";
  }
}

function executeCommand(data) {
    if(data.cmd == "allUnifiedRequests") {
      var serviceProposes = new Array();
      for (var i = 0; i < data.body.length; i++) {
          var elementBodySocialNetwork = data.body[i];
          var services = elementBodySocialNetwork.services;
          for (var j = 0; j < services.length; j++) {
            var service = {socialNetwork:elementBodySocialNetwork.endpoint,
                            socialNetworkToken:elementBodySocialNetwork.hasToken,
                            typeService:services[j].service.split(".")[1],
                            typeServiceChar:"",
                            explainService:"",
                            args:{},
                            service:services[j]
                          };
            service.explainService = fillExplainService(service.typeService, service.socialNetwork);
            service.typeServiceChar = $scope.typeServiceCharByService(services[j].service);
            for (var k = 0; k < services[j].args.length; k++) {
              service.args[services[j].args[k]] = "";
            };
            serviceProposes.push(service);
          }
      };
      if(!$scope.$$phase) {
        $scope.$apply(function() {
          $scope.serviceProposes = serviceProposes;
        });
      }
      else {
        $scope.serviceProposes = serviceProposes;
      }
    } else if(data.cmd == "msg") {
        var columnTitle = data.body.column;
        var column = getColumnByName(columnTitle);
        $scope.$apply(function() {
            if(column.messages == undefined) {
                column.messages = [];
            }
            column.messages.push(data.body.msg);
            var insertSort = function(sortMe) {
              for(var i=0, j, tmp; i<sortMe.length; ++i ) {
                tmp = sortMe[i];
                for(j=i-1; j>=0 && sortMe[j].createdAt < tmp.createdAt; --j) {
                  sortMe[j+1] = sortMe[j];
                }
                sortMe[j+1] = tmp;
              }
            }
            insertSort(column.messages);
        });
    } else if(data.cmd == "allColumns") {
        console.log("columns",data.body);
        $scope.$apply(function() {
            $scope.columns = [];
            var cols = data.body;
            for (var i = 0; i < cols.length; i++) {
                var originalColumn = cols[i];
                var clientColumn = {};
                clientColumn.title = originalColumn.title;
                clientColumn.unifiedRequests = [];
                for (var j = 0; j < originalColumn.unifiedRequests.length; j++) {
                  var unifiedRequest = originalColumn.unifiedRequests[j];
                  var clientUnifiedRequest = serverToClientUnifiedRequest(unifiedRequest);
                  clientColumn.unifiedRequests.push(clientUnifiedRequest);
                };
                clientColumn.showModifyColumn = false;
                $scope.columns.push(clientColumn);
            }
        });
    } else if(data.cmd == "delColumn" && data.body == "Ok") {
      $scope.$apply(function() {
        var title = $scope.lastColumnDeleted.body.title;
        var columnIndice = 0;
        var columnFind = false;
        for (var i = 0; i < $scope.columns.length; i++) {
          if($scope.columns[i].title == title) {
            columnIndice = i;
            columnFind = true;
            break;
          }
        }
        if(columnFind) {
          $scope.columns.splice(columnIndice,1);
        }
        $scope.lastColumnDeleted = undefined;
      });
    } else if(data.cmd == "userInfos") {
      $scope.$apply(function() {
        if($scope.userInfos == undefined) {
          $scope.userInfos = [];
        }
        $scope.userInfos.push(data.body);
        console.log($scope.userInfos[0].username);
      });
    }
    else {
      console.error("cmd not found : ", data);
    }
}

  function serverToUnifiedRequest(unifiedRequest) {
    var clientUnifiedRequest = {};
    clientUnifiedRequest.service = unifiedRequest.service;
    clientUnifiedRequest.providerName = unifiedRequest.service.split(".")[0];
    clientUnifiedRequest.serviceName = unifiedRequest.service.split(".")[1];
    clientUnifiedRequest.args = []
    for (var index in unifiedRequest.args) {
      var key = unifiedRequest.args[index];
      clientUnifiedRequest.args.push({"key":key,"value":""});
    };
    clientUnifiedRequest.hasArguments = clientUnifiedRequest.args.length > 0;
    return clientUnifiedRequest;
  }

  function serverToClientUnifiedRequest(unifiedRequest) {
    var clientUnifiedRequest = {};
    clientUnifiedRequest.service = unifiedRequest.service;
    clientUnifiedRequest.providerName = unifiedRequest.service.split(".")[0];
    clientUnifiedRequest.serviceName = unifiedRequest.service.split(".")[1];
    clientUnifiedRequest.args = []
    for (var key in unifiedRequest.args) {
      var value = unifiedRequest.args[key];
      console.log("value", value);
      clientUnifiedRequest.args.push({"key":key,"value":value});
    };
    clientUnifiedRequest.hasArguments = clientUnifiedRequest.args.length > 0;
    return clientUnifiedRequest;
  }

  function clientToServerUnifiedRequest(unifiedRequest) {
    var serverUnifiedRequest = {};
    serverUnifiedRequest.service = unifiedRequest.providerName+"."+unifiedRequest.serviceName;
    serverUnifiedRequest.args = {}
    for (var index in unifiedRequest.args) {
      var arg = unifiedRequest.args[index];
      serverUnifiedRequest.args[arg.key] = arg.value;
    };
    return serverUnifiedRequest;
  }

});

function dragOver(target, ev)
{
	ev.preventDefault();
}

function dragStart(target,ev)
{
	target.style.opacity = "0.5";
	ev.dataTransfer.setData("text/html", target.innerHTML);
	ev.dataTransfer.setData("id", target.id);
	ev.dataTransfer.effectAllowed = 'move';
}

function dragEnter(target, ev) {
	target.style.backgroundColor = "red";
	ev.preventDefault();
}

function dragLeave(target, ev) {
	target.style.backgroundColor = "pink";
	ev.preventDefault();
}

function dragEnd(target,ev)
{
	target.style.backgroundColor = "pink";
	target.style.opacity = "1";
}

function drop(target,ev)
{
	ev.preventDefault();
	var fromHtml=ev.dataTransfer.getData("text/html");
	var id=ev.dataTransfer.getData("id");

	var toHtml = target.innerHTML;

	target.innerHTML = fromHtml;
	document.getElementById(id).innerHTML = toHtml;

	target.style.backgroundColor = "pink";
	target.style.opacity = "1";
	// angular.element(target).scope().$root.$eval();
	var scope = angular.element(target).scope();
    // update the model with a wrap in $apply(fn) which will refresh the view for us
    // scope.$apply(function() {
    // 	console.log("test");
    //     scope.$eval(scope.data);
    // 	console.log("test apres");
    // });

}
<commit_msg>add default image when user or message haven't images<commit_after>'use strict';

publicApp.controller('ColumnsCtrl', function($scope, $http) {
    var wshost = 'ws://127.0.0.1:9000/api/stream/webSocket';
    var ssehost = 'http://127.0.0.1:9000/api/stream/sse';
    var sseping = 'http://127.0.0.1:9000/api/stream/ping';

    var socket;
    if(window.MozWebSocket) {
        window.WebSocket=window.MozWebSocket;
    }
    if(!window.WebSocket) {
        alert('Votre navigateur ne supporte pas les webSocket !');
        return false;
    } else {
        socket = new WebSocket(wshost);
        socket.onopen = function() { console.log('socket ouverte'); }
        socket.onclose = function() { console.log('socket fermée'); }
        socket.onerror = function() { console.log('Une erreur est survenue'); }
        socket.onmessage = function(msg){
            var data;
            try { //tente de parser data
                data = JSON.parse(msg.data);
            } catch(exception) {
                data = msg.data
            }
            //ici on poura effectuer tout ce que l'on veux sur notre objet data
            executeCommand(data);
        }
    }

    if (!window.WebSocket && !!window.EventSource) {
        var source = new EventSource(ssehost);
        source.addEventListener('message', function(msg) {
            var data;
            try { //tente de parser data
                data = JSON.parse(msg.data);
            } catch(exception) {
                data = msg.data
            }
            //ici on poura effectuer tout ce que l'on veux sur notre objet data
            executeCommand(data);
            $http.get(sseping);
        }, false);

        source.addEventListener('open', function(e) {console.log('socket ouverte');}, false);
        source.addEventListener('error', function(e) {console.log('Une erreur est survenue');}, false);
    }

    $scope.truncateString = function(chaine) {
      if(chaine.length > 120) {
        return String(chaine).substring(0, 120)+"...";
      }
      else {
        return chaine;
      }
    }

    $scope.addColumn = function() {
        if($scope.serviceProposes == undefined) {
          var json = {"cmd":"allUnifiedRequests"};
          socket.send(JSON.stringify(json));
        }
        if($scope.columns == undefined) {
          $scope.columns = [];
        }
        $scope.columns.push({"title":"",
                              "oldTitle":"",
                              "showModifyColumn":"true",
                              "newColumn":"true",
                              "unifiedRequests":[]});
    };

    $scope.modifyColumn = function(column) {
      column.showModifyColumn = !column.showModifyColumn;
      if (column.showModifyColumn == true) {
        if($scope.serviceProposes == undefined) {
          var json = {"cmd":"allUnifiedRequests"};
          socket.send(JSON.stringify(json));
        }
      }
      if(column.showModifyColumn == true) {
        column.oldTitle = column.title;
      }
      else {
        column.title = column.oldTitle;
      }
    };

    $scope.addService = function(service, column) {
      if(service.socialNetworkToken) {
        var clientUnifiedRequest = serverToUnifiedRequest(service.service);
        column.unifiedRequests.push(clientUnifiedRequest);
      }
      else {
        $scope.openPopup(service, column);
      }
    }

    $scope.deleteService = function(service, column) {
      var existInColumn = false;
      var indexInColumn = -1;
      for (var i = 0; i < column.unifiedRequests.length; i++) {
        if(column.unifiedRequests[i].service == service.service) {
          existInColumn = true;
          indexInColumn = i;
          break;
        }
      }
      if(existInColumn && indexInColumn > -1) {
        column.unifiedRequests.splice(indexInColumn,1);
      }
    }

    $scope.changeColumn = function(column) {
      column.showErrorTitleAlreadyExist = false;
      column.showErrorTitleRequired = false;
      var json = "";
      var unifiedRequests = [];
      for (var i = 0; i < column.unifiedRequests.length; i++) {
        unifiedRequests.push(clientToServerUnifiedRequest(column.unifiedRequests[i]));
      };
      if(!column.newColumn) {
        json = {"cmd":"modColumn",
                 "body":{
                   "title": column.oldTitle,
                   "column":{
                     "title":column.title,
                     "unifiedRequests": unifiedRequests
                   }
                 }
                };
      } else {
        column.newColumn = false;
        json = {"cmd":"addColumn",
                "body":{
                  "title":column.title,
                  "unifiedRequests": unifiedRequests
                }
              };
      }
      if(column.title =="") {
        column.showErrorTitleRequired = true;
      }
      else {
        column.showErrorTitleRequired = false;
        var nombreName = 0;
        for (var i = 0; i < $scope.columns.length; i++) {
          if($scope.columns[i].title == column.title) {
            nombreName++;
          }
        };
        if(nombreName > 1) {
          column.showErrorTitleAlreadyExist = true;
        }
        else {
          column.showErrorTitleAlreadyExist = false;
          column.messages = [];
          column.showModifyColumn= !column.showModifyColumn;
          socket.send(JSON.stringify(json));
        }
      }
    }

    $scope.deleteColumn = function(column) {
      $scope.lastColumnDeleted = {"cmd":"delColumn", "body":{"title": column.title}};
      socket.send(JSON.stringify($scope.lastColumnDeleted));
    }

    $scope.serviceHasTypeChar = function(service) {
      if(service.typeServiceChar != "") {
        return true;
      }
      return false;
    }

    $scope.typeServiceCharByService = function(service) {
      var socialNetworkName = service.split(".")[0];
      var typeService = service.split(".")[1];
        if(typeService == "group") {
          return "ഹ";
        }
        else if(typeService == "user") {
          if(socialNetworkName == "twitter") {
            return "@";
          }
          else {
            return "😊";
          }
        }
        else if (typeService == "hashtag") {
          return "#";
        }
        return "";
    }

    $scope.openPopup = function(service, column) {
      var _service = service;
      var _column = column;
      var scope = $scope;
      var newwindow = window.open("/auth/"+service.socialNetwork, 'Connexion', 'height=500,width=500');

      if (newwindow !== undefined) {
        if (window.focus) newwindow.focus();

        newwindow.onclose = function() {
          $http.get("/api/providers/services").success(function(data) {
            executeCommand({"cmd":"allUnifiedRequests","body":data});
            var serviceJson = {"service":_service.socialNetwork+"."+_service.typeService,
                            "args":_service.args
                          };
            _column.unifiedRequests.push(serviceJson);
          });
        };
        newwindow.onbeforeunload = function() {
          $http.get("/api/providers/services").success(function(data) {
            executeCommand({"cmd":"allUnifiedRequests","body":data});
            var serviceJson = {"service":_service.socialNetwork+"."+_service.typeService,
                            "args":_service.args
                          };
            _column.unifiedRequests.push(serviceJson);
          });
        };
      }
      return false;
    }

function getColumnByName(name) {
    for (var i = 0; i < $scope.columns.length; i++) {
        if ($scope.columns[i].title == name) {
            return $scope.columns[i];
        }
    }
}

function fillExplainService(typeService, socialNetwork) {
  if(typeService == "group") {
    return "Click here to display a specific Facebook group.";
  }
  else if(typeService == "user") {
    if(socialNetwork == "twitter") {
      return "Click here to display tweets of a specific Twitter user.";
    }
    else {
      return "Click here to display the wall of a specific Facebook user.";
    }
  }
  else if (typeService == "hashtag") {
    return "Click here to display tweets of a specific Twitter hashtag.";
  }
  else {
    return "Click here to display your "+socialNetwork+" "+typeService+".";
  }
}

function checkExistingImage(image) {
  if(image == "" || image == undefined) {
    return "assets/img/image-default.png";
  }
  else {
    return image;
  }
}

function executeCommand(data) {
    if(data.cmd == "allUnifiedRequests") {
      var serviceProposes = new Array();
      for (var i = 0; i < data.body.length; i++) {
          var elementBodySocialNetwork = data.body[i];
          var services = elementBodySocialNetwork.services;
          for (var j = 0; j < services.length; j++) {
            var service = {socialNetwork:elementBodySocialNetwork.endpoint,
                            socialNetworkToken:elementBodySocialNetwork.hasToken,
                            typeService:services[j].service.split(".")[1],
                            typeServiceChar:"",
                            explainService:"",
                            args:{},
                            service:services[j]
                          };
            service.explainService = fillExplainService(service.typeService, service.socialNetwork);
            service.typeServiceChar = $scope.typeServiceCharByService(services[j].service);
            for (var k = 0; k < services[j].args.length; k++) {
              service.args[services[j].args[k]] = "";
            };
            serviceProposes.push(service);
          }
      };
      if(!$scope.$$phase) {
        $scope.$apply(function() {
          $scope.serviceProposes = serviceProposes;
        });
      }
      else {
        $scope.serviceProposes = serviceProposes;
      }
    } else if(data.cmd == "msg") {
        var columnTitle = data.body.column;
        var column = getColumnByName(columnTitle);
        $scope.$apply(function() {
            if(column.messages == undefined) {
                column.messages = [];
            }
            data.body.msg.authorAvatar = checkExistingImage(data.body.msg.authorAvatar);
            column.messages.push(data.body.msg);
            var insertSort = function(sortMe) {
              for(var i=0, j, tmp; i<sortMe.length; ++i ) {
                tmp = sortMe[i];
                for(j=i-1; j>=0 && sortMe[j].createdAt < tmp.createdAt; --j) {
                  sortMe[j+1] = sortMe[j];
                }
                sortMe[j+1] = tmp;
              }
            }
            insertSort(column.messages);
        });
    } else if(data.cmd == "allColumns") {
        $scope.$apply(function() {
            $scope.columns = [];
            var cols = data.body;
            for (var i = 0; i < cols.length; i++) {
                var originalColumn = cols[i];
                var clientColumn = {};
                clientColumn.title = originalColumn.title;
                clientColumn.unifiedRequests = [];
                for (var j = 0; j < originalColumn.unifiedRequests.length; j++) {
                  var unifiedRequest = originalColumn.unifiedRequests[j];
                  var clientUnifiedRequest = serverToClientUnifiedRequest(unifiedRequest);
                  clientColumn.unifiedRequests.push(clientUnifiedRequest);
                };
                clientColumn.showModifyColumn = false;
                $scope.columns.push(clientColumn);
            }
        });
    } else if(data.cmd == "delColumn" && data.body == "Ok") {
      $scope.$apply(function() {
        var title = $scope.lastColumnDeleted.body.title;
        var columnIndice = 0;
        var columnFind = false;
        for (var i = 0; i < $scope.columns.length; i++) {
          if($scope.columns[i].title == title) {
            columnIndice = i;
            columnFind = true;
            break;
          }
        }
        if(columnFind) {
          $scope.columns.splice(columnIndice,1);
        }
        $scope.lastColumnDeleted = undefined;
      });
    } else if(data.cmd == "userInfos") {
      $scope.$apply(function() {
        if($scope.userInfos == undefined) {
          $scope.userInfos = [];
        }
        data.body.avatar = checkExistingImage(data.body.avatar);
        $scope.userInfos.push(data.body);
      });
    }
    else {
      console.error("cmd not found : ", data);
    }
}

  function serverToUnifiedRequest(unifiedRequest) {
    var clientUnifiedRequest = {};
    clientUnifiedRequest.service = unifiedRequest.service;
    clientUnifiedRequest.providerName = unifiedRequest.service.split(".")[0];
    clientUnifiedRequest.serviceName = unifiedRequest.service.split(".")[1];
    clientUnifiedRequest.args = []
    for (var index in unifiedRequest.args) {
      var key = unifiedRequest.args[index];
      clientUnifiedRequest.args.push({"key":key,"value":""});
    };
    clientUnifiedRequest.hasArguments = clientUnifiedRequest.args.length > 0;
    return clientUnifiedRequest;
  }

  function serverToClientUnifiedRequest(unifiedRequest) {
    var clientUnifiedRequest = {};
    clientUnifiedRequest.service = unifiedRequest.service;
    clientUnifiedRequest.providerName = unifiedRequest.service.split(".")[0];
    clientUnifiedRequest.serviceName = unifiedRequest.service.split(".")[1];
    clientUnifiedRequest.args = []
    for (var key in unifiedRequest.args) {
      var value = unifiedRequest.args[key];
      console.log("value", value);
      clientUnifiedRequest.args.push({"key":key,"value":value});
    };
    clientUnifiedRequest.hasArguments = clientUnifiedRequest.args.length > 0;
    return clientUnifiedRequest;
  }

  function clientToServerUnifiedRequest(unifiedRequest) {
    var serverUnifiedRequest = {};
    serverUnifiedRequest.service = unifiedRequest.providerName+"."+unifiedRequest.serviceName;
    serverUnifiedRequest.args = {}
    for (var index in unifiedRequest.args) {
      var arg = unifiedRequest.args[index];
      serverUnifiedRequest.args[arg.key] = arg.value;
    };
    return serverUnifiedRequest;
  }

});

function dragOver(target, ev)
{
	ev.preventDefault();
}

function dragStart(target,ev)
{
	target.style.opacity = "0.5";
	ev.dataTransfer.setData("text/html", target.innerHTML);
	ev.dataTransfer.setData("id", target.id);
	ev.dataTransfer.effectAllowed = 'move';
}

function dragEnter(target, ev) {
	target.style.backgroundColor = "red";
	ev.preventDefault();
}

function dragLeave(target, ev) {
	target.style.backgroundColor = "pink";
	ev.preventDefault();
}

function dragEnd(target,ev)
{
	target.style.backgroundColor = "pink";
	target.style.opacity = "1";
}

function drop(target,ev)
{
	ev.preventDefault();
	var fromHtml=ev.dataTransfer.getData("text/html");
	var id=ev.dataTransfer.getData("id");

	var toHtml = target.innerHTML;

	target.innerHTML = fromHtml;
	document.getElementById(id).innerHTML = toHtml;

	target.style.backgroundColor = "pink";
	target.style.opacity = "1";
	// angular.element(target).scope().$root.$eval();
	var scope = angular.element(target).scope();
    // update the model with a wrap in $apply(fn) which will refresh the view for us
    // scope.$apply(function() {
    // 	console.log("test");
    //     scope.$eval(scope.data);
    // 	console.log("test apres");
    // });

}
<|endoftext|>


<commit_before>import Edit from './L.PM.Edit';

Edit.Circle = Edit.extend({
    initialize(layer) {
        this._layer = layer;
        this._enabled = false;
    },
    toggleEdit(options) {
        if (!this.enabled()) {
            this.enable(options);
        } else {
            this.disable();
        }
    },
    enabled() {
        return this._enabled;
    },
    enable(options) {
        L.Util.setOptions(this, options);

        this._map = this._layer._map;

        if (!this.enabled()) {
            // if it was already enabled, disable first
            // we don't block enabling again because new options might be passed
            this.disable();
        }

        // change state
        this._enabled = true;

        // // init markers
        this._initMarkers();

        // if polygon gets removed from map, disable edit mode
        this._layer.on('remove', (e) => {
            this.disable(e.target);
        });
    },
    disable(layer = this._layer) {
        // if it's not enabled, it doesn't need to be disabled
        if (!this.enabled()) {
            return false;
        }

        // prevent disabling if layer is being dragged
        if (layer.pm._dragging) {
            return false;
        }
        layer.pm._enabled = false;
        layer.pm._helperLayers.clearLayers();

        // clean up draggable
        layer.off('mousedown');
        layer.off('mouseup');

        // remove draggable class
        const el = layer._path ? layer._path : this._layer._renderer._container;
        L.DomUtil.removeClass(el, 'leaflet-pm-draggable');

        if (this._layerEdited) {
            this._layer.fire('pm:update', {});
        }
        this._layerEdited = false;

        return true;
    },
    _initMarkers() {
        const map = this._map;

        // cleanup old ones first
        if (this._helperLayers) {
            this._helperLayers.clearLayers();
        }

        // add markerGroup to map, markerGroup includes regular and middle markers
        this._helperLayers = new L.LayerGroup().addTo(map);

        // create marker for each coordinate
        const center = this._layer.getLatLng();
        const radius = this._layer._radius;

        const outer = this._getLatLngOnCircle(center, radius);

        this._centerMarker = this._createCenterMarker(center);
        this._outerMarker = this._createOuterMarker(outer);
        this._markers = [this._centerMarker, this._outerMarker];
        this._createHintLine(this._centerMarker, this._outerMarker);

        if (this.options.snappable) {
            this._initSnappableMarkers();
        }
    },
    _getLatLngOnCircle(center, radius) {
        const pointA = this._map.project(center);
        const pointB = L.point(pointA.x + radius, pointA.y);

        return this._map.unproject(pointB);
    },
    _resizeCircle() {
        this._syncHintLine();
        this._syncCircleRadius();
    },
    _moveCircle(e) {
        const center = e.latlng;
        this._layer.setLatLng(center);

        const radius = this._layer._radius;

        const outer = this._getLatLngOnCircle(center, radius);
        this._outerMarker.setLatLng(outer);
        this._syncHintLine();

        this._layer.fire('pm:centerplaced', {
            layer: this._layer,
            latlng: center,
        });
    },
    _onMarkerDragStart(e) {
        this._layer.fire('pm:markerdragstart', {
            markerEvent: e,
        });
    },
    _onMarkerDragEnd(e) {
        // fire edit event
        this._fireEdit();

        // fire markerdragend event
        this._layer.fire('pm:markerdragend', {
            markerEvent: e,
        });
    },
    _syncCircleRadius() {
        const A = this._centerMarker.getLatLng();
        const B = this._outerMarker.getLatLng();

        const distance = A.distanceTo(B);

        this._layer.setRadius(distance);
    },
    _syncHintLine() {
        const A = this._centerMarker.getLatLng();
        const B = this._outerMarker.getLatLng();

        // set coords for hintline from marker to last vertex of drawin polyline
        this._hintline.setLatLngs([A, B]);
    },
    _createHintLine(markerA, markerB) {
        const A = markerA.getLatLng();
        const B = markerB.getLatLng();
        this._hintline = L.polyline([A, B], this.options.hintlineStyle);
        this._hintline._pmTempLayer = true;
        this._helperLayers.addLayer(this._hintline);
    },
    _createCenterMarker(latlng) {
        const marker = this._createMarker(latlng);

        marker.on('move', this._moveCircle, this);
        // marker.on('contextmenu', this._removeMarker, this);

        return marker;
    },
    _createOuterMarker(latlng) {
        const marker = this._createMarker(latlng);
        if (this.options.preventVertexEdit) {
            marker.dragging.disable();
        }
        marker.on('move', this._resizeCircle, this);
        // marker.on('contextmenu', this._removeMarker, this);

        return marker;
    },
    _createMarker(latlng) {
        const marker = new L.Marker(latlng, {
            draggable: true,
            icon: L.divIcon({ className: 'marker-icon' }),
        });

        marker._origLatLng = latlng;
        marker._pmTempLayer = true;

        marker.on('dragstart', this._onMarkerDragStart, this);
        marker.on('dragend', this._onMarkerDragEnd, this);

        this._helperLayers.addLayer(marker);

        return marker;
    },
    _fireEdit() {
        // fire edit event
        this._layer.fire('pm:edit');
        this._layerEdited = true;
    },
});
<commit_msg>added drag cursor to circle centerMarker. Fixes #356<commit_after>import Edit from './L.PM.Edit';

Edit.Circle = Edit.extend({
    initialize(layer) {
        this._layer = layer;
        this._enabled = false;
    },
    toggleEdit(options) {
        if (!this.enabled()) {
            this.enable(options);
        } else {
            this.disable();
        }
    },
    enabled() {
        return this._enabled;
    },
    enable(options) {
        L.Util.setOptions(this, options);

        this._map = this._layer._map;

        if (!this.enabled()) {
            // if it was already enabled, disable first
            // we don't block enabling again because new options might be passed
            this.disable();
        }

        // change state
        this._enabled = true;

        // // init markers
        this._initMarkers();

        // if polygon gets removed from map, disable edit mode
        this._layer.on('remove', (e) => {
            this.disable(e.target);
        });
    },
    disable(layer = this._layer) {
        // if it's not enabled, it doesn't need to be disabled
        if (!this.enabled()) {
            return false;
        }

        // prevent disabling if layer is being dragged
        if (layer.pm._dragging) {
            return false;
        }
        layer.pm._enabled = false;
        layer.pm._helperLayers.clearLayers();

        // clean up draggable
        layer.off('mousedown');
        layer.off('mouseup');

        // remove draggable class
        const el = layer._path ? layer._path : this._layer._renderer._container;
        L.DomUtil.removeClass(el, 'leaflet-pm-draggable');

        if (this._layerEdited) {
            this._layer.fire('pm:update', {});
        }
        this._layerEdited = false;

        return true;
    },
    _initMarkers() {
        const map = this._map;

        // cleanup old ones first
        if (this._helperLayers) {
            this._helperLayers.clearLayers();
        }

        // add markerGroup to map, markerGroup includes regular and middle markers
        this._helperLayers = new L.LayerGroup().addTo(map);

        // create marker for each coordinate
        const center = this._layer.getLatLng();
        const radius = this._layer._radius;

        const outer = this._getLatLngOnCircle(center, radius);

        this._centerMarker = this._createCenterMarker(center);
        this._outerMarker = this._createOuterMarker(outer);
        this._markers = [this._centerMarker, this._outerMarker];
        this._createHintLine(this._centerMarker, this._outerMarker);

        if (this.options.snappable) {
            this._initSnappableMarkers();
        }
    },
    _getLatLngOnCircle(center, radius) {
        const pointA = this._map.project(center);
        const pointB = L.point(pointA.x + radius, pointA.y);

        return this._map.unproject(pointB);
    },
    _resizeCircle() {
        this._syncHintLine();
        this._syncCircleRadius();
    },
    _moveCircle(e) {
        const center = e.latlng;
        this._layer.setLatLng(center);

        const radius = this._layer._radius;

        const outer = this._getLatLngOnCircle(center, radius);
        this._outerMarker.setLatLng(outer);
        this._syncHintLine();

        this._layer.fire('pm:centerplaced', {
            layer: this._layer,
            latlng: center,
        });
    },
    _onMarkerDragStart(e) {
        this._layer.fire('pm:markerdragstart', {
            markerEvent: e,
        });
    },
    _onMarkerDragEnd(e) {
        // fire edit event
        this._fireEdit();

        // fire markerdragend event
        this._layer.fire('pm:markerdragend', {
            markerEvent: e,
        });
    },
    _syncCircleRadius() {
        const A = this._centerMarker.getLatLng();
        const B = this._outerMarker.getLatLng();

        const distance = A.distanceTo(B);

        this._layer.setRadius(distance);
    },
    _syncHintLine() {
        const A = this._centerMarker.getLatLng();
        const B = this._outerMarker.getLatLng();

        // set coords for hintline from marker to last vertex of drawin polyline
        this._hintline.setLatLngs([A, B]);
    },
    _createHintLine(markerA, markerB) {
        const A = markerA.getLatLng();
        const B = markerB.getLatLng();
        this._hintline = L.polyline([A, B], this.options.hintlineStyle);
        this._hintline._pmTempLayer = true;
        this._helperLayers.addLayer(this._hintline);
    },
    _createCenterMarker(latlng) {
        const marker = this._createMarker(latlng);

        L.DomUtil.addClass(marker._icon, 'leaflet-pm-draggable');
        marker.on('move', this._moveCircle, this);
        // marker.on('contextmenu', this._removeMarker, this);

        return marker;
    },
    _createOuterMarker(latlng) {
        const marker = this._createMarker(latlng);
        if (this.options.preventVertexEdit) {
            marker.dragging.disable();
        }
        marker.on('move', this._resizeCircle, this);
        // marker.on('contextmenu', this._removeMarker, this);

        return marker;
    },
    _createMarker(latlng) {
        const marker = new L.Marker(latlng, {
            draggable: true,
            icon: L.divIcon({ className: 'marker-icon' }),
        });

        marker._origLatLng = latlng;
        marker._pmTempLayer = true;

        marker.on('dragstart', this._onMarkerDragStart, this);
        marker.on('dragend', this._onMarkerDragEnd, this);

        this._helperLayers.addLayer(marker);

        return marker;
    },
    _fireEdit() {
        // fire edit event
        this._layer.fire('pm:edit');
        this._layerEdited = true;
    },
});
<|endoftext|>


<commit_before>/*
 * @title gulpfile.babel.js
 * @description A directory file loader to include all the gulp tasks
 */

require('time-require');
/*********************************************************************************
 1. IMPORTS
 *********************************************************************************/

import fs from 'fs';
import gulp from 'gulp';
import plumber from 'gulp-plumber';
import sharedPaths from './shared/paths.js';
import sharedEvents from './shared/events.js';

/*********************************************************************************
 2. GLOBALS
 *********************************************************************************/

global.gulp = gulp;
global.plumber = plumber;
global.sharedPaths = sharedPaths;
global.sharedEvents = sharedEvents;
global.options = {
  env: 'production'
};

/*********************************************************************************
 3. TASK LOADER
 *********************************************************************************/

function createGulpTaks(name) {
  name = name.replace('.js','');
  return gulp.task(name, () => {
    require(`${__dirname}/tasks/${name}`);
  });
}

fs.readdirSync(`${__dirname}/tasks/`).forEach(function (filename, i) {
  createGulpTaks(filename);
});
<commit_msg>enhancement(gulp): creating and loading tasks programatically, forgot to run fn<commit_after>/*
 * @title gulpfile.babel.js
 * @description A directory file loader to include all the gulp tasks
 */

require('time-require');
/*********************************************************************************
 1. IMPORTS
 *********************************************************************************/

import fs from 'fs';
import gulp from 'gulp';
import plumber from 'gulp-plumber';
import sharedPaths from './shared/paths.js';
import sharedEvents from './shared/events.js';

/*********************************************************************************
 2. GLOBALS
 *********************************************************************************/

global.gulp = gulp;
global.plumber = plumber;
global.sharedPaths = sharedPaths;
global.sharedEvents = sharedEvents;
global.options = {
  env: 'production'
};

/*********************************************************************************
 3. TASK LOADER
 *********************************************************************************/

function createGulpTaks(name) {
  name = name.replace('.js','');
  gulp.task(name, () => {
    require(`${__dirname}/tasks/${name}`)();
  });
}

fs.readdirSync(`${__dirname}/tasks/`).forEach(function (filename, i) {
  createGulpTaks(filename);
});
<|endoftext|>


<commit_before>/**
 * @file GroupList component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import List from '../List';
import Theme from '../Theme';
import Tip from '../Tip';

import SelectMode from '../_statics/SelectMode';
import LIST_SEPARATOR from '../_statics/ListSeparator';

import Util from '../_vendors/Util';
import Event from '../_vendors/Event';
import Calculation from '../_vendors/Calculation';

class GroupList extends Component {

    static SelectMode = SelectMode;
    static LIST_SEPARATOR = LIST_SEPARATOR;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: Calculation.getInitValue(props)
        };

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: Calculation.getInitValue(nextProps)
            });
        }
    }

    render() {

        const {children, className, style, data, disabled, ...restProps} = this.props,
            {value} = this.state,

            listClassName = classNames('group-list', {
                [className]: className
            });

        return (

 {
                     Event.wheelHandler(e, this.props);
                 }}>

                {
                    data && data.map((item, index) => {

                        if (item === LIST_SEPARATOR) {
                            return

;
                        }

                        return (

{item.name}

                                <List {...restProps}
                                      data={item.children}
                                      value={value}/>

                        );

                    })
                }

                {children}

        );

    }
}

GroupList.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme of the list item select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * Children passed into the ListItem.
     */
    data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

        // group name
        name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        children: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

            /**
             * The CSS class name of the list button.
             */
            className: PropTypes.string,

            /**
             * Override the styles of the list button.
             */
            style: PropTypes.object,

            /**
             * The theme of the list button.
             */
            theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

            /**
             * The text value of the list button.Type can be string or number.
             */
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The list item's display text. Type can be string, number or bool.
             */
            text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The desc value of the list button. Type can be string or number.
             */
            desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * If true,the list item will be disabled.
             */
            disabled: PropTypes.bool,

            /**
             * If true,the button will be have loading effect.
             */
            isLoading: PropTypes.bool,

            /**
             * If true,the element's ripple effect will be disabled.
             */
            disableTouchRipple: PropTypes.bool,

            /**
             * Use this property to display an icon. It will display on the left.
             */
            iconCls: PropTypes.string,

            /**
             * Use this property to display an icon. It will display on the right.
             */
            rightIconCls: PropTypes.string,

            /**
             * The message of tip.
             */
            tip: PropTypes.string,

            /**
             * The position of tip.
             */
            tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)),

            /**
             * If true,the item will have center displayed ripple effect.
             */
            rippleDisplayCenter: PropTypes.bool,

            /**
             * You can create a complicated renderer callback instead of value and desc prop.
             */
            itemRenderer: PropTypes.func,

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onClick: PropTypes.func

        }), PropTypes.string, PropTypes.number]))

    }), PropTypes.symbol])).isRequired,

    /**
     * The id field name in data. (default: "id")
     */
    idField: PropTypes.string,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the list will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * If true, the list will be at loading status.
     */
    isLoading: PropTypes.bool,

    /**
     * The mode of listItem.Can be normal,checkbox.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    shouldPreventContainerScroll: PropTypes.bool,

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the list-item select.
     */
    onItemClick: PropTypes.func,

    /**
     * Callback function fired when the list changed.
     */
    onChange: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func

};

GroupList.defaultProps = {

    theme: Theme.DEFAULT,
    selectTheme: Theme.DEFAULT,

    data: [],

    idField: 'id',
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    disabled: false,
    selectMode: SelectMode.SINGLE_SELECT,
    shouldPreventContainerScroll: true,

    radioUncheckedIconCls: 'fas fa-check',
    radioCheckedIconCls: 'fas fa-check',
    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square'

};

export default GroupList;<commit_msg>update GroupList<commit_after>/**
 * @file GroupList component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import List from '../List';
import Theme from '../Theme';
import Tip from '../Tip';

import SelectMode from '../_statics/SelectMode';
import LIST_SEPARATOR from '../_statics/ListSeparator';

import Util from '../_vendors/Util';
import Event from '../_vendors/Event';
import Calculation from '../_vendors/Calculation';

class GroupList extends Component {

    static SelectMode = SelectMode;
    static LIST_SEPARATOR = LIST_SEPARATOR;
    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            value: Calculation.getInitValue(props)
        };

    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.state.value) {
            this.setState({
                value: Calculation.getInitValue(nextProps)
            });
        }
    }

    render() {

        const {children, className, style, data, disabled, ...restProps} = this.props,
            {value} = this.state,

            listClassName = classNames('group-list', {
                [className]: className
            });

        return (

 Event.wheelHandler(e, this.props)}>

                {
                    data && data.map((item, index) => item === LIST_SEPARATOR ?

                        :

{item.name}

                            <List {...restProps}
                                  data={item.children}
                                  value={value}/>

                    )
                }

                {children}

        );

    }
}

GroupList.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme.
     */
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The theme of the list item select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * Children passed into the ListItem.
     */
    data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

        // group name
        name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

        children: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({

            /**
             * The CSS class name of the list button.
             */
            className: PropTypes.string,

            /**
             * Override the styles of the list button.
             */
            style: PropTypes.object,

            /**
             * The theme of the list button.
             */
            theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

            /**
             * The text value of the list button.Type can be string or number.
             */
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The list item's display text. Type can be string, number or bool.
             */
            text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * The desc value of the list button. Type can be string or number.
             */
            desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

            /**
             * If true,the list item will be disabled.
             */
            disabled: PropTypes.bool,

            /**
             * If true,the button will be have loading effect.
             */
            isLoading: PropTypes.bool,

            /**
             * If true,the element's ripple effect will be disabled.
             */
            disableTouchRipple: PropTypes.bool,

            /**
             * Use this property to display an icon. It will display on the left.
             */
            iconCls: PropTypes.string,

            /**
             * Use this property to display an icon. It will display on the right.
             */
            rightIconCls: PropTypes.string,

            /**
             * The message of tip.
             */
            tip: PropTypes.string,

            /**
             * The position of tip.
             */
            tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)),

            /**
             * If true,the item will have center displayed ripple effect.
             */
            rippleDisplayCenter: PropTypes.bool,

            /**
             * You can create a complicated renderer callback instead of value and desc prop.
             */
            itemRenderer: PropTypes.func,

            /**
             * Callback function fired when a list item touch-tapped.
             */
            onClick: PropTypes.func

        }), PropTypes.string, PropTypes.number]))

    }), PropTypes.symbol])).isRequired,

    /**
     * The id field name in data. (default: "id")
     */
    idField: PropTypes.string,

    /**
     * The value field name in data. (default: "value")
     */
    valueField: PropTypes.string,

    /**
     * The display field name in data. (default: "text")
     */
    displayField: PropTypes.string,

    /**
     * The description field name in data. (default: "desc")
     */
    descriptionField: PropTypes.string,

    /**
     * If true, the list will be disabled.
     */
    disabled: PropTypes.bool,

    /**
     * If true, the list will be at loading status.
     */
    isLoading: PropTypes.bool,

    /**
     * The mode of listItem.Can be normal,checkbox.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    shouldPreventContainerScroll: PropTypes.bool,

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    /**
     * You can create a complicated renderer callback instead of value and desc prop.
     */
    renderer: PropTypes.func,

    /**
     * Callback function fired when the list-item select.
     */
    onItemClick: PropTypes.func,

    /**
     * Callback function fired when the list changed.
     */
    onChange: PropTypes.func,

    /**
     * Callback function fired when wrapper wheeled.
     */
    onWheel: PropTypes.func

};

GroupList.defaultProps = {

    theme: Theme.DEFAULT,
    selectTheme: Theme.DEFAULT,

    data: [],

    idField: 'id',
    valueField: 'value',
    displayField: 'text',
    descriptionField: 'desc',
    disabled: false,
    selectMode: SelectMode.SINGLE_SELECT,
    shouldPreventContainerScroll: true,

    radioUncheckedIconCls: 'fas fa-check',
    radioCheckedIconCls: 'fas fa-check',
    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square'

};

export default GroupList;<|endoftext|>


<commit_before>'use strict'

var argv = require('yargs').argv
var browserify = require('browserify')
var buffer = require('vinyl-buffer')
var gulp = require('gulp')
var gulpif = require('gulp-if')
var path = require('path')
var size = require('gulp-size')
var source = require('vinyl-source-stream')
var uglify = require('gulp-uglify')
var varify = require('varify')

var modules = {}
modules = {
  'dgram': 'chrome-dgram',
  'winston': 'winston-browser'
}

gulp.task('browserify', browserifyTask)

function browserifyTask() {
  var destFile = argv.production? 'udp-hole-puncher.min.js': 'udp-hole-puncher.debug.js'
  var destFolder = path.join(__dirname, 'build')
  var entry = path.join(__dirname, 'index.js')
  return bundle(entry, modules, destFile, destFolder, argv.production)
}

function bundle(entry, replacements, destFile, destFolder, production) {
  // set browserify options
  var options = {
    entries: entry,
    extensions: ['.js'],
    debug: production ? false : true
  }
  // create bundler
  var bundler = browserify(options)
  // replace libs
  for (var originalModule in replacements) {
    var replacementModule = replacements[originalModule]
    bundler = bundler.require(replacementModule, {
       expose: originalModule
    })
  }
  // babelify transformation
  bundler.transform(
    varify, {
      global: true
    }
  )
  // bundle
  return bundler.bundle()
    .on('error', function (err) {
      console.log(err.toString());
      this.emit('end');
    })
    .pipe(source(destFile))
    .pipe(gulpif(production, buffer()))
    .pipe(gulpif(production, uglify()))
    .pipe(gulpif(production, size()))
    .pipe(gulp.dest(destFolder))
}

module.exports.bundle = bundle
<commit_msg>converted to ES6 + eslint airbnb<commit_after>const argv = require('yargs').argv;
const babelify = require('babelify');
const browserify = require('browserify');
const buffer = require('vinyl-buffer');
const gulp = require('gulp');
const gulpif = require('gulp-if');
const path = require('path');
const size = require('gulp-size');
const source = require('vinyl-source-stream');
const uglify = require('gulp-uglify');
const varify = require('varify');

let modules = {};
modules = {
  dgram: 'chrome-dgram',
  winston: 'winston-browser',
};

const bundle = (entry, replacements, destFile, destFolder, production) => {
  // set browserify options
  const options = {
    entries: entry,
    extensions: ['.js'],
    debug: !production,
  };
  // create bundler
  let bundler = browserify(options);
  // replace libs
  Object.keys(replacements).forEach((originalModule) => {
    bundler = bundler.require(
      replacements[originalModule],
      {
        expose: originalModule,
      } // eslint-disable-line comma-dangle
    );
  });
  // babelify transformation
  bundler.transform(
    babelify,
    {
      global: true,
      presets: ['es2015'],
    } // eslint-disable-line comma-dangle
  );
  // babelify transformation
  bundler.transform(
    varify,
    {
      global: true,
    } // eslint-disable-line comma-dangle
  );
  // bundle
  return bundler.bundle()
    .on('error', (err) => {
      console.log(err.toString());
      this.emit('end');
    })
    .pipe(source(destFile))
    .pipe(gulpif(production, buffer()))
    .pipe(gulpif(production, uglify()))
    .pipe(gulpif(production, size()))
    .pipe(gulp.dest(destFolder));
};

const browserifyTask = () => {
  const destFile = argv.production ? 'udp-hole-puncher.min.js' : 'udp-hole-puncher.debug.js';
  const destFolder = path.join(__dirname, 'build');
  const entry = path.join(__dirname, 'index.js');
  return bundle(entry, modules, destFile, destFolder, argv.production);
};

gulp.task('browserify', browserifyTask);

module.exports.bundle = bundle;
<|endoftext|>


<commit_before>(function(root) {
    var get   = typeof require == 'function' && require('request')
    var hyve  = typeof exports != 'undefined'?  exports : { }

    // Fills a template with data from an object
    function format(string, data) {
        return string.replace( /{{(?:#(.+?)#)?\s*(.+?)\s*}}/g
                             , function(m, cond, id) {
                                 var rv = data[id]
                                 return rv? (cond || '') + rv
                                          : cond? '' : m })
    }

    // Pulls data from several streams and handle all them with the given
    // callback
    function stream(query, callback, custom_services) {
        var services
        services = custom_services || Object.keys(hyve.feeds)

        services.forEach(function(service){
            var options = hyve.feeds[service.toLowerCase()]
            setInterval(function(){
                var feed_url = format( options.feed_url,
                                     { query:  query
                                     , apikey: options.api_key })

                fetch(feed_url, service, callback)
            }, options.interval)
        })
    }

    // Fetches a JSON stream
    var fetch = function() {
        var counter   = 0
        var callbacks = { }
        var head      = !get && document.getElementsByTagName('head')[0]

        // Returns a qualified identifier pointing to a callback
        function get_callback() {
            return format('hyve.callbacks.f{{id}}', { id: ++counter })
        }

        // Requires an URI using JSONP
        function jsonp(url, callback) {
            hyve.callbacks['f' + counter] = callback
            var s = document.createElement('script')
            s.setAttribute('src', url)
            head.appendChild(s)
        }

        // Requires an URI using Node.js's request library
        function request(url, callback) {
            get({uri: url}, function(error, res, data) {
                try {
                    callback(JSON.parse(data))
                }
                catch(e){
                    console.log({ }, e)
                }
            })
        }

        // Abstracts fetching URIs.
        function fetch(url, service, callback) {
            var fn = pass(service, callback)
            var cb = !get && get_callback()
            url    = format(url, { callback: cb })

            var fetcher = get? request : jsonp
            fetcher(url, fn)
        }

        // Higher-order function to process the fetched data
        function pass(service, callback) {
            return function(data) {
                hyve.feeds[service].parse(data, callback)
            }
        }

        // Export the `fetch` function
        return fetch
    }()

    // Exports data to the outside world
    root.hyve      = hyve
    hyve.stream    = stream
    hyve.callbacks = []
    hyve.feeds     = {
            twitter: {
                interval : 2000,
                feed_url :'http://search.twitter.com/search.json?q={{query}}{{#&callback=#callback}}',
                parse : function(data,callback){
                    if (data.refresh_url != null){
                        this.feed_url = 'http://search.twitter.com/search.json'
                                      + data.refresh_url
                                      + '{{#&callback=#callback}}'
                    }
                    for (var i in data.results){
                        var item = data.results[i]
                        callback({
                            'service' : 'twitter',
                            'user' : {
                                'id' : item.from_user_id_str,
                                'name' : item.from_user,
                                'avatar' : item.profile_image_url,
                            },
                            'id' : item.id_str,
                            'date' : item.created_at, //TODO: normalize
                            'text' : item.text,
                            'source' : item.source,
                        })
                    }
                }
            },
            identica: {
                interval : 6000,
                feed_url :'http://identi.ca/api/search.json?q={{query}}{{#&callback=#callback}}',
                parse : function(data,callback){
                    if (data.refresh_url != null){
                        this.feed_url = 'http://identi.ca/api/search.json' + data.refresh_url+ '{{#&callback=#callback}}'
                    }
                    for (var i in data.results){
                        var item = data.results[i]
                        callback({
                            'service' : 'identica',
                            'user' : {
                                'id' : item.from_user_id_str,
                                'name' : item.from_user,
                                'avatar' : item.profile_image_url,
                            },
                            'id' : item.id_str,
                            'date' : item.created_at, //TODO: normalize
                            'text' : item.text,
                            'source' : item.source
                        })
                    }
                }
            },
            buzz: {
                interval : 5000,
                api_key: '',
                feed_url :'https://www.googleapis.com/buzz/v1/activities/search?q={{query}}&alt=json&orderby=published{{#&callback=#callback}}{{#&key=#apikey}}',
                parse : function(data,callback){
                    if (this.orig_url == null){
                        this.orig_url = this.feed_url
                    }
                    if (data.data.items != null){
                        var last_date = data.data.items[0].updated.split('.')[0]
                        this.feed_url = this.orig_url.replace('{{query}}','{{query}}%20AND%20date%3E' + last_date)
                    }
                    for (var i in data.data.items){
                        if (data.data.items[i].title != '-'){
                            var item = data.date.items[i]
                            callback({
                                'service' : 'buzz',
                                'user' : {
                                    'id' : item.actor.name,
                                    'name' : item.actor.name,
                                    'avatar' : item.actor.thumbnailUrl,
                                    'source' : item.actor.profileUrl
                                },
                                'id' : item.id.split(':')[3],
                                'date' : item.published, //TODO normalize
                                'text' : item.title,
                                'source' : item.object.links.alternate[0].href
                            })
                        }
                    }
                }
            },
            facebook: {
                interval : 3000,
                feed_url : 'https://graph.facebook.com/search?q={{query}}&type=post{{#&callback=#callback}}',
                parse : function(data,callback){
                    if (data.data != null){
                        if (data.paging != null) {
                            this.feed_url = data.paging.previous + '{{#&callback=#callback}}'
                        }
                        for (var i in data.data){
                            var item = data.data[i]
                            if (item.message != null){
                                callback({
                                    'service' : 'facebook',
                                    'user' : {
                                        'id' : item.from.id,
                                        'name' : item.from.name,
                                        'avatar' : 'http://graph.facebook.com/'+item.from.id+'/picture'
                                    },
                                    'id' : item.id,
                                    'date' : item.created_time, //TODO: normalize
                                    'text' : item.message,
                                    'source' : 'http://facebook.com/'+item.from.id
                                })
                            }
                        }
                    }
                }
            },
            reddit: {
                interval : 5000,
                feed_url : 'http://www.reddit.com/search.json?q={{query}}&sort=new{{#&jsonp=#callback}}',
                parse : function(data,callback){
                    if (data.data.children[0]){
                        if (this.orig_url == null){
                            this.orig_url = this.feed_url
                        }
                        var before = data.data.children[0].data.name
                        if (before != null){
                            this.feed_url = this.orig_url + '&before=' + before
                        }
                        for (var i in data.data.children){
                            var item = data.data.children[i].data
                            callback({
                                'service' : 'reddit',
                                'user' : {
                                    'id' : '',
                                    'name' : '',
                                    'avatar' : ''
                                },
                                'id' : '',
                                'date' : '', //TODO: normalize
                                'text' : item.title,
                                'source' : '',
                                'thumbnail':''
                            })
                        }
                    }
                }
            },
            flickr: {
                interval : 10000,
                api_key : '',
                feed_url : 'http://api.flickr.com/services/feeds/photos_public.gne?format=json&tagmode=all&tags={{query}}{{#&jsoncallback=#callback}}&extras=date_upload,date_taken,owner_name,geo,tags,views',
                parse : function(data,callback){
                    if (this.items_seen == null){
                        this.items_seen = {};
                    }
                    for (var i in data.items){
                        var item = data.items[i]
                        if (this.items_seen[item.media.m] == null){
                            this.items_seen[item.media.m] = true
                            callback({
                                'service' : 'flickr',
                                'user' : {
                                    'id' : '',
                                    'name' : '',
                                    'avatar' : ''
                                },
                                'id' : '',
                                'date' : '', //TODO: normalize
                                'text' : item.description,
                                'source' : '',
                                'thumbnail':''
                            })
                        }
                    }
                }
            },
            youtube: {
                interval : 8000,
                feed_url : 'http://gdata.youtube.com/feeds/api/videos?q={{query}}&time=today&orderby=published&format=5&max-results=20&v=2&alt=jsonc{{#&callback=#callback}}',
                parse : function(data,callback){
                    if (this.items_seen == null){
                        this.items_seen = {};
                    }
                    for (var i in data.data.items){
                        var item = data.data.items[i]
                        if (this.items_seen[item.id] == null){
                            this.items_seen[item.id] = true
                            callback({
                                'service' : 'youtube',
                                'user' : {
                                    'id' : '',
                                    'name' : '',
                                    'avatar' : ''
                                },
                                'id' : '',
                                'date' : '', //TODO: normalize
                                'text' : item.description,
                                'source' : '',
                                'thumbnail':''
                            })
                        }
                    }
                }
            }
        }
})(this);

/*
$.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&u=http%3A%2F%2Fen.search.wordpress.com%2F%3Fq%3D' + query + '%26f%3Djson&_callback=?', function(data){                                  $('
Wordpress

').appendTo($('body')).show('slow')
    $.each(data.value.items, function(i,item) {
        $('
'+ item.author + ' : ' + item.title + '
').hide().appendTo($('body')).show('slow')
    });
});
});*/
<commit_msg>Fixes a swapped ternary expression. Orz<commit_after>(function(root) {
    var get   = typeof require == 'function' && require('request')
    var hyve  = typeof exports != 'undefined'?  exports : { }

    // Fills a template with data from an object
    function format(string, data) {
        return string.replace( /{{(?:#(.+?)#)?\s*(.+?)\s*}}/g
                             , function(m, cond, id) {
                                 var rv = data[id]
                                 return rv? (cond || '') + rv
                                          :  cond? m : '' })
    }

    // Pulls data from several streams and handle all them with the given
    // callback
    function stream(query, callback, custom_services) {
        var services
        services = custom_services || Object.keys(hyve.feeds)

        services.forEach(function(service){
            var options = hyve.feeds[service.toLowerCase()]
            setInterval(function(){
                var feed_url = format( options.feed_url,
                                     { query:  query
                                     , apikey: options.api_key })

                fetch(feed_url, service, callback)
            }, options.interval)
        })
    }

    // Fetches a JSON stream
    var fetch = function() {
        var counter   = 0
        var callbacks = { }
        var head      = !get && document.getElementsByTagName('head')[0]

        // Returns a qualified identifier pointing to a callback
        function get_callback() {
            return format('hyve.callbacks.f{{id}}', { id: ++counter })
        }

        // Requires an URI using JSONP
        function jsonp(url, callback) {
            hyve.callbacks['f' + counter] = callback
            var s = document.createElement('script')
            s.setAttribute('src', url)
            head.appendChild(s)
        }

        // Requires an URI using Node.js's request library
        function request(url, callback) {
            get({uri: url}, function(error, res, data) {
                try {
                    callback(JSON.parse(data))
                }
                catch(e){
                    callback({ }, e)
                }
            })
        }

        // Abstracts fetching URIs.
        function fetch(url, service, callback) {
            var fn = pass(service, callback)
            var cb = !get && get_callback()
            url    = format(url, { callback: cb })

            var fetcher = get? request : jsonp
            fetcher(url, fn)
        }

        // Higher-order function to process the fetched data
        function pass(service, callback) {
            return function(data) {
                hyve.feeds[service].parse(data, callback)
            }
        }

        // Export the `fetch` function
        return fetch
    }()

    // Exports data to the outside world
    root.hyve      = hyve
    hyve.stream    = stream
    hyve.callbacks = []
    hyve.feeds     = {
            twitter: {
                interval : 2000,
                feed_url :'http://search.twitter.com/search.json?q={{query}}{{#&callback=#callback}}',
                parse : function(data,callback){
                    if (data.refresh_url != null){
                        this.feed_url = 'http://search.twitter.com/search.json'
                                      + data.refresh_url
                                      + '{{#&callback=#callback}}'
                    }
                    for (var i in data.results){
                        var item = data.results[i]
                        callback({
                            'service' : 'twitter',
                            'user' : {
                                'id' : item.from_user_id_str,
                                'name' : item.from_user,
                                'avatar' : item.profile_image_url,
                            },
                            'id' : item.id_str,
                            'date' : item.created_at, //TODO: normalize
                            'text' : item.text,
                            'source' : item.source,
                        })
                    }
                }
            },
            identica: {
                interval : 6000,
                feed_url :'http://identi.ca/api/search.json?q={{query}}{{#&callback=#callback}}',
                parse : function(data,callback){
                    if (data.refresh_url != null){
                        this.feed_url = 'http://identi.ca/api/search.json' + data.refresh_url+ '{{#&callback=#callback}}'
                    }
                    for (var i in data.results){
                        var item = data.results[i]
                        callback({
                            'service' : 'identica',
                            'user' : {
                                'id' : item.from_user_id_str,
                                'name' : item.from_user,
                                'avatar' : item.profile_image_url,
                            },
                            'id' : item.id_str,
                            'date' : item.created_at, //TODO: normalize
                            'text' : item.text,
                            'source' : item.source
                        })
                    }
                }
            },
            buzz: {
                interval : 5000,
                api_key: '',
                feed_url :'https://www.googleapis.com/buzz/v1/activities/search?q={{query}}&alt=json&orderby=published{{#&callback=#callback}}{{#&key=#apikey}}',
                parse : function(data,callback){
                    if (this.orig_url == null){
                        this.orig_url = this.feed_url
                    }
                    if (data.data.items != null){
                        var last_date = data.data.items[0].updated.split('.')[0]
                        this.feed_url = this.orig_url.replace('{{query}}','{{query}}%20AND%20date%3E' + last_date)
                    }
                    for (var i in data.data.items){
                        if (data.data.items[i].title != '-'){
                            var item = data.data.items[i]
                            callback({
                                'service' : 'buzz',
                                'user' : {
                                    'id' : item.actor.name,
                                    'name' : item.actor.name,
                                    'avatar' : item.actor.thumbnailUrl,
                                    'source' : item.actor.profileUrl
                                },
                                'id' : item.id.split(':')[3],
                                'date' : item.published, //TODO normalize
                                'text' : item.title,
                                'source' : item.object.links.alternate[0].href
                            })
                        }
                    }
                }
            },
            facebook: {
                interval : 3000,
                feed_url : 'https://graph.facebook.com/search?q={{query}}&type=post{{#&callback=#callback}}',
                parse : function(data,callback){
                    if (data.data != null){
                        if (data.paging != null) {
                            this.feed_url = data.paging.previous + '{{#&callback=#callback}}'
                        }
                        for (var i in data.data){
                            var item = data.data[i]
                            if (item.message != null){
                                callback({
                                    'service' : 'facebook',
                                    'user' : {
                                        'id' : item.from.id,
                                        'name' : item.from.name,
                                        'avatar' : 'http://graph.facebook.com/'+item.from.id+'/picture'
                                    },
                                    'id' : item.id,
                                    'date' : item.created_time, //TODO: normalize
                                    'text' : item.message,
                                    'source' : 'http://facebook.com/'+item.from.id
                                })
                            }
                        }
                    }
                }
            },
            reddit: {
                interval : 5000,
                feed_url : 'http://www.reddit.com/search.json?q={{query}}&sort=new{{#&jsonp=#callback}}',
                parse : function(data,callback){
                    if (data.data.children[0]){
                        if (this.orig_url == null){
                            this.orig_url = this.feed_url
                        }
                        var before = data.data.children[0].data.name
                        if (before != null){
                            this.feed_url = this.orig_url + '&before=' + before
                        }
                        for (var i in data.data.children){
                            var item = data.data.children[i].data
                            callback({
                                'service' : 'reddit',
                                'user' : {
                                    'id' : '',
                                    'name' : '',
                                    'avatar' : ''
                                },
                                'id' : '',
                                'date' : '', //TODO: normalize
                                'text' : item.title,
                                'source' : '',
                                'thumbnail':''
                            })
                        }
                    }
                }
            },
            flickr: {
                interval : 10000,
                api_key : '',
                feed_url : 'http://api.flickr.com/services/feeds/photos_public.gne?format=json&tagmode=all&tags={{query}}{{#&jsoncallback=#callback}}&extras=date_upload,date_taken,owner_name,geo,tags,views',
                parse : function(data,callback){
                    if (this.items_seen == null){
                        this.items_seen = {};
                    }
                    for (var i in data.items){
                        var item = data.items[i]
                        if (this.items_seen[item.media.m] == null){
                            this.items_seen[item.media.m] = true
                            callback({
                                'service' : 'flickr',
                                'user' : {
                                    'id' : '',
                                    'name' : '',
                                    'avatar' : ''
                                },
                                'id' : '',
                                'date' : '', //TODO: normalize
                                'text' : item.description,
                                'source' : '',
                                'thumbnail':''
                            })
                        }
                    }
                }
            },
            youtube: {
                interval : 8000,
                feed_url : 'http://gdata.youtube.com/feeds/api/videos?q={{query}}&time=today&orderby=published&format=5&max-results=20&v=2&alt=jsonc{{#&callback=#callback}}',
                parse : function(data,callback){
                    if (this.items_seen == null){
                        this.items_seen = {};
                    }
                    for (var i in data.data.items){
                        var item = data.data.items[i]
                        if (this.items_seen[item.id] == null){
                            this.items_seen[item.id] = true
                            callback({
                                'service' : 'youtube',
                                'user' : {
                                    'id' : '',
                                    'name' : '',
                                    'avatar' : ''
                                },
                                'id' : '',
                                'date' : '', //TODO: normalize
                                'text' : item.description,
                                'source' : '',
                                'thumbnail':''
                            })
                        }
                    }
                }
            }
        }
})(this);

/*
$.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=332d9216d8910ba39e6c2577fd321a6a&_render=json&u=http%3A%2F%2Fen.search.wordpress.com%2F%3Fq%3D' + query + '%26f%3Djson&_callback=?', function(data){                                  $('
Wordpress

').appendTo($('body')).show('slow')
    $.each(data.value.items, function(i,item) {
        $('
'+ item.author + ' : ' + item.title + '
').hide().appendTo($('body')).show('slow')
    });
});
});*/
<|endoftext|>