<commit_before>/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function() {
  'use strict';

  /**
   * Class constructor for Snackbar MDL component.
   * Implements MDL component design pattern defined at:
   * https://github.com/jasonmayes/mdl-component-design-pattern
   *
   * @constructor
   * @param {HTMLElement} element The element that will be upgraded.
   */
  var MaterialSnackbar = function MaterialSnackbar(element) {
    this.element_ = element;
    this.textElement_ = this.element_.querySelector('.' + this.cssClasses_.MESSAGE);
    this.actionElement_ = this.element_.querySelector('.' + this.cssClasses_.ACTION);
    if (!this.textElement_) {
      throw new Error('There must be a message element for a snackbar.');
    }
    if (!this.actionElement_) {
      throw new Error('There must be an action element for a snackbar.');
    }
    this.active = false;
    this.actionHandler_ = undefined;
    this.message_ = undefined;
    this.actionText_ = undefined;
    this.queuedNotifications_ = [];
    this.setActionHidden_(true);
  };
  window['MaterialSnackbar'] = MaterialSnackbar;

  /**
   * Store constants in one place so they can be updated easily.
   *
   * @enum {string | number}
   * @private
   */
  MaterialSnackbar.prototype.Constant_ = {
    // The duration of the snackbar show/hide animation, in ms.
    ANIMATION_LENGTH: 250
  };

  /**
   * Store strings for class names defined by this component that are used in
   * JavaScript. This allows us to simply change it in one place should we
   * decide to modify at a later date.
   *
   * @enum {string}
   * @private
   */
  MaterialSnackbar.prototype.cssClasses_ = {
    SNACKBAR: 'mdl-snackbar',
    MESSAGE: 'mdl-snackbar__text',
    ACTION: 'mdl-snackbar__action',
    ACTIVE: 'mdl-snackbar--active'
  };

  /**
   * Display the snackbar.
   *
   * @private
   */
  MaterialSnackbar.prototype.displaySnackbar_ = function() {
    this.element_.setAttribute('aria-hidden', 'true');

    if (this.actionHandler_) {
      this.actionElement_.textContent = this.actionText_;
      this.actionElement_.addEventListener('click', this.actionHandler_);
      this.setActionHidden_(false);
    }

    this.textElement_.textContent = this.message_;
    this.element_.classList.add(this.cssClasses_.ACTIVE);
    this.element_.setAttribute('aria-hidden', 'false');
    setTimeout(this.cleanup_.bind(this), this.timeout_);

  };

  /**
   * Show the snackbar.
   *
   * @param {Object} data The data for the notification.
   * @public
   */
  MaterialSnackbar.prototype.showSnackbar = function(data) {
    if (data === undefined) {
      throw new Error(
        'Please provide a data object with at least a message to display.');
    }
    if (data['message'] === undefined) {
      throw new Error('Please provide a message to be displayed.');
    }
    if (data['actionHandler'] && !data['actionText']) {
      throw new Error('Please provide action text with the handler.');
    }
    if (this.active) {
      this.queuedNotifications_.push(data);
    } else {
      this.active = true;
      this.message_ = data['message'];
      if (data['timeout']) {
        this.timeout_ = data['timeout'];
      } else {
        this.timeout_ = 2750;
      }
      if (data['actionHandler']) {
        this.actionHandler_ = data['actionHandler'];
      }
      if (data['actionText']) {
        this.actionText_ = data['actionText'];
      }
      this.displaySnackbar_();
    }
  };
  MaterialSnackbar.prototype['showSnackbar'] = MaterialSnackbar.prototype.showSnackbar;

  /**
   * Check if the queue has items within it.
   * If it does, display the next entry.
   *
   * @private
   */
  MaterialSnackbar.prototype.checkQueue_ = function() {
    if (this.queuedNotifications_.length > 0) {
      this.showSnackbar(this.queuedNotifications_.shift());
    }
  };

  /**
   * Cleanup the snackbar event listeners and accessiblity attributes.
   *
   * @private
   */
  MaterialSnackbar.prototype.cleanup_ = function() {
    this.element_.classList.remove(this.cssClasses_.ACTIVE);
    setTimeout(function() {
      this.element_.setAttribute('aria-hidden', 'true');
      this.textElement_.textContent = '';
      if (!Boolean(this.actionElement_.getAttribute('aria-hidden'))) {
        this.setActionHidden_(true);
        this.actionElement_.textContent = '';
        this.actionElement_.removeEventListener('click', this.actionHandler_);
      }
      this.actionHandler_ = undefined;
      this.message_ = undefined;
      this.actionText_ = undefined;
      this.active = false;
      this.checkQueue_();
    }.bind(this), /** @type {number} */ (this.Constant_.ANIMATION_LENGTH));
  };

  /**
   * Set the action handler hidden state.
   *
   * @param {boolean} value
   * @private
   */
  MaterialSnackbar.prototype.setActionHidden_ = function(value) {
    if (value) {
      this.actionElement_.setAttribute('aria-hidden', 'true');
    } else {
      this.actionElement_.removeAttribute('aria-hidden');
    }
  };

  // The component registers itself. It can assume componentHandler is available
  // in the global scope.
  componentHandler.register({
    constructor: MaterialSnackbar,
    classAsString: 'MaterialSnackbar',
    cssClass: 'mdl-js-snackbar',
    widget: true
  });

})();<commit_msg>Removes unused file<commit_after><|endoftext|>


<commit_before>let uiRoutes = require('ui/routes');
var CryptoJS = require("crypto-js");

let _objHttp = undefined;
const _http = function (req, http) {
  req.method = req.method || "POST";

  http = http || _objHttp;
  return _objHttp(req);
}

const encrypt = function (data, callback) {
  let enc = CryptoJS.AES.encrypt(data, "kibana-auth-plugin-made-by-goofy-encryptkey").toString();
  callback(enc);
}

const loginRouteInfo = {
  template: require('plugins/kibana-auth/login/login.html'),
  controller: function ($scope, $http) {
    _objHttp = $http;
    $('nav').remove();

    _http({
          url: "/getUserGroup"
    }).then(function (res) {
      if (res.data) {
        location.replace('/');
      }
    })

    $scope.doLogin = function(e) {
      $('input[type="submit"]').hide();

      encrypt($("[name=password]").val(), function (enc) {

        _http({
          url: "/trylogin",
          data: {
            username: $("[name=username]").val(),
            password: enc
          }
        }).then(function(res) {
          if (res.data == '') {
            $scope.message = 'logged in successfully';
            location.replace('/');
          } else {
            $scope.message = res.data;
          }
          $('input[type="submit"]').show();
        }, function (res) {
          $scope.message = res.statusText;
          $('input[type="submit"]').show();
        });

      });
    }
  }
}

const managerRouteInfo = {
  template: require('plugins/kibana-auth/login/manager.html'),
  controller: function ($scope, $http) {
    _objHttp = $http;

    $scope.createData = {group:''};
    $scope.users = $scope.groups = null;
    $scope.editUsers = $scope.editGroups = {};
    $scope.createTarget = "User";
    $scope.creating = false;
    $scope.userLevel = 99999;

    const _default_groups = [
      { name: "Admin", level: 0 },
      { name: "Manager", level: 1 }
    ];

    const init = function () {
      searchAll('group').then(function () {
        _http({
          url: "/getUserGroup"
        }).then(function (res) {
          if (!res.data) {
            location.replace('/');
          }

          $scope.userLevel = $scope.getGroup(res.data).level;

          _updateAcceptedGroups();
          if ($scope.userLevel > 1) {
            location.replace('/');
          }
        });

        searchAll();
      });
    }

    const _updateAcceptedGroups = function () {
        $scope.accepted_groups = $scope.groups.filter(function (n) {

          return n.level >= $scope.userLevel;
        });
    }
    const searchAll = function (target) {
      return _req('searchAll', undefined, undefined, target).then(function (res) {
        if (target && target.toLowerCase() == 'group') {
          $scope.groups = _default_groups.filter(function (group) {
            return $scope.getGroup(group.name, res.data).level == 99999;
          }).concat(res.data);

          _updateAcceptedGroups();
        } else {
          $scope.users = res.data;
        }
        $scope.$applyAsync();
      });
    }

    const _req = function (act, data, req, target) {
      req = req || {
        data: data
      };
      target = target || "user";
      req.url = req.url || "/kibana-auth/" + target.toLowerCase() + "/" + act;
      return _http(req);
    }

    $scope.getGroup = function (groupName, groups) {
      groups = groups || $scope.groups || _default_groups;

      let filtered = groups.filter(function (group) {
        return group.name == groupName;
      });

      return filtered.length > 0 ? filtered[0] : {name:'Removed', level:99999};
    }

    $scope.editUser = function (e, user) {
      if ($scope.userLevel <= $scope.getGroup(user.group).level || $scope.userLevel == 0) {
        $scope.editUsers[user.name] = true;
      } else {
        alert('You cannot modify accounts are higher privileges than you.')
      }
    }

    $scope.editGroup = function (e, group) {
      if ($scope.userLevel < $scope.getGroup(group.name).level) {
        $scope.editGroups[group.name] = true;
      } else {
        alert('You cannot modify groups are higher privileges than you.')
      }
    }

    $scope.create = function (e) {
      if ($scope.creating) {
        return false;
      }

      if (!$scope.createData || !$scope.createData.name) {
        $scope.message = "Invalid " + $scope.createTarget + " name";
        return false;
      }

      if (!$scope.createData.group) {
        $scope.message = "Invalid group";
        return false;
      }

      $scope.creating = true;
      $scope.createTarget = $scope.createTarget;

      if ($scope.createTarget == 'Group') {
        $scope.createData.level = 2;
      } else {
        $scope.createData.level = undefined;
      }

      _req('create', {data: $scope.createData}, undefined, $scope.createTarget).then(function (res) {
        if (!res.data) {
          $scope.message = "Failed to add" + $scope.createTarget;
        }

        $scope.creating = false;

        setTimeout(function () {
          if ($scope.createTarget == 'User') {
            searchAll();
          } else {
            searchAll('group');
          }
         }, 1000);
      });
    }

    $scope.updateUser = function (e, user) {
      _req('update', {data: user}).then(function (res) {
        if (!res.data) {
          alert('Failed to update user');
        } else {

        }

        $scope.editUsers[user.name] = false;

        setTimeout(searchAll, 1000);
      });
    }

    $scope.deleteUser = function (e, user) {
      if (!confirm('Are you sure you want to delete ' + user.name)) {
        return false;
      }

      _req('delete', {data: user}).then(function (res) {
        if (!res.data) {
          alert('Failed to delete user');
        } else {

        }

        $scope.editUsers[user.name] = false;

        setTimeout(searchAll, 1000);
      });
    }

    $scope.updateGroup = function (e, group) {
      _req('update', {data: group}, undefined, 'group').then(function (res) {
        if (!res.data) {
          alert('Failed to update group');
        } else {

        }

        $scope.editGroups[group.name] = false;

        setTimeout(function () { searchAll('group'); }, 1000);
      });
    }

    $scope.deleteGroup = function (e, group) {
      if (!confirm('Are you sure you want to delete ' + group.name)) {
        return false;
      }

      _req('delete', {data: group}, undefined, 'group').then(function (res) {
        if (!res.data) {
          alert('Failed to delete group');
        } else {

        }

        $scope.editGroups[group.name] = false;

        setTimeout(function () { searchAll('group'); }, 1000);
      });
    }

    init();
  }
}

uiRoutes.enable();
uiRoutes
.when('/', loginRouteInfo)
.when('/manager', managerRouteInfo)
.when('/:type', loginRouteInfo);<commit_msg>fixed bug<commit_after>let uiRoutes = require('ui/routes');
var CryptoJS = require("crypto-js");

let _objHttp = undefined;
const _http = function (req, http) {
  req.method = req.method || "POST";

  http = http || _objHttp;
  return _objHttp(req);
}

const encrypt = function (data, callback) {
  let enc = CryptoJS.AES.encrypt(data, "kibana-auth-plugin-made-by-goofy-encryptkey").toString();
  callback(enc);
}

const loginRouteInfo = {
  template: require('plugins/kibana-auth/login/login.html'),
  controller: function ($scope, $http) {
    _objHttp = $http;
    $('nav').remove();

    _http({
          url: "/getUserGroup"
    }).then(function (res) {
      if (res.data) {
        location.replace('/');
      }
    })

    $scope.doLogin = function(e) {
      $('input[type="submit"]').hide();

      encrypt($("[name=password]").val(), function (enc) {

        _http({
          url: "/trylogin",
          data: {
            username: $("[name=username]").val(),
            password: enc
          }
        }).then(function(res) {
          if (res.data == '') {
            $scope.message = 'logged in successfully';
            location.replace('/');
          } else {
            $scope.message = res.data;
          }
          $('input[type="submit"]').show();
        }, function (res) {
          $scope.message = res.statusText;
          $('input[type="submit"]').show();
        });

      });
    }
  }
}

const managerRouteInfo = {
  template: require('plugins/kibana-auth/login/manager.html'),
  controller: function ($scope, $http) {
    _objHttp = $http;

    $scope.createData = {group:''};
    $scope.users = $scope.groups = null;
    $scope.editUsers = $scope.editGroups = {};
    $scope.createTarget = "User";
    $scope.creating = false;
    $scope.userLevel = 99999;

    const _default_groups = [
      { name: "Admin", level: 0 },
      { name: "Manager", level: 1 }
    ];

    const init = function () {
      searchAll('group').then(function () {
        _http({
          url: "/getUserGroup"
        }).then(function (res) {
          if (!res.data) {
            location.replace('/');
          }

          $scope.userLevel = $scope.getGroup(res.data).level;

          _updateAcceptedGroups();
          if ($scope.userLevel > 1) {
            location.replace('/');
          }
        });

        searchAll();
      });
    }

    const _updateAcceptedGroups = function () {
        $scope.accepted_groups = $scope.groups.filter(function (n) {

          return n.level >= $scope.userLevel;
        });
    }
    const searchAll = function (target) {
      return _req('searchAll', undefined, undefined, target).then(function (res) {
        if (target && target.toLowerCase() == 'group') {
          $scope.groups = _default_groups.filter(function (group) {
            return $scope.getGroup(group.name, res.data).level == 99999;
          }).concat(res.data);

          _updateAcceptedGroups();
        } else {
          $scope.users = res.data;
        }
        $scope.$applyAsync();
      });
    }

    const _req = function (act, data, req, target) {
      req = req || {
        data: data
      };
      target = target || "user";
      req.url = req.url || "/kibana-auth/" + target.toLowerCase() + "/" + act;
      return _http(req);
    }

    $scope.getGroup = function (groupName, groups) {
      groups = groups || $scope.groups || _default_groups;

      let filtered = groups.filter(function (group) {
        return group.name == groupName;
      });

      return filtered.length > 0 ? filtered[0] : {name:'Removed', level:99999};
    }

    $scope.editUser = function (e, user) {
      if ($scope.userLevel <= $scope.getGroup(user.group).level || $scope.userLevel == 0) {
        $scope.editUsers[user.name] = true;
      } else {
        alert('You cannot modify accounts are higher privileges than you.')
      }
    }

    $scope.editGroup = function (e, group) {
      if ($scope.userLevel < $scope.getGroup(group.name).level) {
        $scope.editGroups[group.name] = true;
      } else {
        alert('You cannot modify groups are higher privileges than you.')
      }
    }

    $scope.create = function (e) {
      if ($scope.creating) {
        return false;
      }

      if (!$scope.createData || !$scope.createData.name) {
        $scope.message = "Invalid " + $scope.createTarget + " name";
        return false;
      }

      $scope.creating = true;
      $scope.createTarget = $scope.createTarget;

      if ($scope.createTarget == 'Group') {
        $scope.createData.level = 2;
      } else {
        if (!$scope.createData.group) {
          $scope.message = "Invalid group";
          return false;
        }

        $scope.createData.level = undefined;
      }

      _req('create', {data: $scope.createData}, undefined, $scope.createTarget).then(function (res) {
        if (!res.data) {
          $scope.message = "Failed to add" + $scope.createTarget;
        }

        $scope.creating = false;

        setTimeout(function () {
          if ($scope.createTarget == 'User') {
            searchAll();
          } else {
            searchAll('group');
          }
         }, 1000);
      });
    }

    $scope.updateUser = function (e, user) {
      _req('update', {data: user}).then(function (res) {
        if (!res.data) {
          alert('Failed to update user');
        } else {

        }

        $scope.editUsers[user.name] = false;

        setTimeout(searchAll, 1000);
      });
    }

    $scope.deleteUser = function (e, user) {
      if (!confirm('Are you sure you want to delete ' + user.name)) {
        return false;
      }

      _req('delete', {data: user}).then(function (res) {
        if (!res.data) {
          alert('Failed to delete user');
        } else {

        }

        $scope.editUsers[user.name] = false;

        setTimeout(searchAll, 1000);
      });
    }

    $scope.updateGroup = function (e, group) {
      _req('update', {data: group}, undefined, 'group').then(function (res) {
        if (!res.data) {
          alert('Failed to update group');
        } else {

        }

        $scope.editGroups[group.name] = false;

        setTimeout(function () { searchAll('group'); }, 1000);
      });
    }

    $scope.deleteGroup = function (e, group) {
      if (!confirm('Are you sure you want to delete ' + group.name)) {
        return false;
      }

      _req('delete', {data: group}, undefined, 'group').then(function (res) {
        if (!res.data) {
          alert('Failed to delete group');
        } else {

        }

        $scope.editGroups[group.name] = false;

        setTimeout(function () { searchAll('group'); }, 1000);
      });
    }

    init();
  }
}

uiRoutes.enable();
uiRoutes
.when('/', loginRouteInfo)
.when('/manager', managerRouteInfo)
.when('/:type', loginRouteInfo);
<|endoftext|>


<commit_before>var layer = layer || {};

layer.loading = function(source,type,value){
    var id = source+"_"+type+"_"+value;
    id = id.toUpperCase().split(' ').join('_');
    var layerstack = $("
").attr({"id":id,"class":"layer list"})
        .append($('').height("20px"))
        .append('' + source + '' + value);
    $("#list").prepend(layerstack);
}
layer.remove = function(id){
    console.log(id);
    $(".layer.list").remove("#"+id);
}
layer.init = function() {
    /* Add Layer Setup*/
    $("#add_new_layer_dialog").css({'visibility':'visible'});
    $("#add_new_layer_dialog").children().hide();
    $("#add_new_layer_dialog").hide();
    $("#layers .option a#add_layer").click(
        function() {
            if ($("#add_new_layer_dialog").is(":visible")){
                $("#add_new_layer_dialog .dialog_button.output").hide();
                $("#add_new_layer_dialog").hide();
            }else{
                $("#add_new_layer_dialog").show();
                $("#add_new_layer_dialog .dialog_buttons").show();
                $("#add_new_layer_dialog").css({"height":"auto"});
            }
        });
        /*add click function to the add points button*/
        $('#add_points_button').click(function(){
            $("#add_new_layer_dialog .dialog_buttons").hide();
            $("#add_points_dialog input").attr({'value': "Artibeus concolor"});
            $("#add_points_dialog").show();
        });
        /*add click function to the add points button*/
        $('#add_range_button').click(function(){
            $("#add_new_layer_dialog .dialog_buttons").hide();
            $("#add_range_dialog input").attr({'value': "Artibeus concolor"});
            $("#add_range_dialog").show();
        });
        $("#gbif_points_search").click(function(){
            $("#add_points_dialog").hide();
            $("#add_new_layer_dialog").hide();
            var val = $("#gbif_points_search_box").val();
            console.log(val);
            layer.loading("GBIF","points",val);
        });
    /* Delete Layer Setup */
    $("#layers .option a#delete_layer").click(function(){
        var id = $("#layers .layer.list input:checked").parent().attr('id');
        console.log(id);
        layer.remove(id);
    });

    /* SETUP SORTABLE LAYER STACK */
    $("#layers #list").sortable(
        {
            items: '.layer',
            containment: '#layers #list',
            cursor: 'move'
        });
    $("#list").disableSelection();
};
<commit_msg>layer widge march continues<commit_after>var layer = layer || {};

layer.loading = function(source,type,value){
    var id = source+"_"+type+"_"+value;
    id = id.toUpperCase().split(' ').join('_');
    var layerstack = $("
").attr({"id":id,"class":"layer list"})
        .append($('').height("20px"))
        .append('' + source + '' + value);
    $("#list").prepend(layerstack);
}
layer.remove = function(id){
    /* should add a safety check here */
    $(".layer.list").remove("#"+id);
}
layer.init = function() {
    /* Add Layer Setup*/
    $("#add_new_layer_dialog").css({'visibility':'visible'});
    $("#add_new_layer_dialog").children().hide();
    $("#add_new_layer_dialog").hide();
    $("#layers .option a#add_layer").click(
        function() {
            if ($("#add_new_layer_dialog").is(":visible")){
                $("#add_new_layer_dialog .dialog_button.output").hide();
                $("#add_new_layer_dialog").hide();
            }else{
                $("#add_new_layer_dialog").show();
                $("#add_new_layer_dialog .dialog_buttons").show();
                $("#add_new_layer_dialog").css({"height":"auto"});
            }
        });
        /*add click function to the add points button*/
        $('#add_points_button').click(function(){
            $("#add_new_layer_dialog .dialog_buttons").hide();
            $("#add_points_dialog input").attr({'value': "Artibeus concolor"});
            $("#add_points_dialog").show();
        });
        /*add click function to the add points button*/
        $('#add_range_button').click(function(){
            $("#add_new_layer_dialog .dialog_buttons").hide();
            $("#add_range_dialog input").attr({'value': "Artibeus concolor"});
            $("#add_range_dialog").show();
        });

        /* start the add layer method from the search bar */
        $("#gbif_points_search").click(function(){
            $("#add_points_dialog").hide();
            $("#add_new_layer_dialog").hide();
            var val = $("#gbif_points_search_box").val();
            layer.loading("GBIF","points",val);
        });
        $("#mol_range_search").click(function(){
            $("#add_range_dialog").hide();
            $("#add_new_layer_dialog").hide();
            var val = $("#mol_range_search_box").val();
            layer.loading("MOL","range",val);
        });

    /* Delete Layer Setup */
    $("#layers .option a#delete_layer").click(function(){
        var id = $("#layers .layer.list input:checked").parent().attr('id');
        console.log(id);
        layer.remove(id);
    });

    /* SETUP SORTABLE LAYER STACK */
    $("#layers #list").sortable(
        {
            items: '.layer',
            containment: '#layers #list',
            cursor: 'move'
        });
    $("#list").disableSelection();
};
<|endoftext|>


<commit_before>// @flow

import { danger, fail, warn, markdown } from 'danger';
const fs = require('fs');

// Move all JS files towards using flow
const changes = danger.git.created_files.concat(danger.git.modified_files);
const unFlowedFiles = changes.filter(path => !path.startsWith('test/') && path.endsWith('js'))
  .filter(filepath => {
    const content = fs.readFileSync(filepath);
    return !content.includes('@flow');
  });

if (unFlowedFiles.length > 0) {
  const flowLinks = [
    ' * [Main Site](https://flowtype.org)',
    ' * [Types](https://flowtype.org/docs/quick-reference.html#primitives)',
    ' * [What is Flow?](https://code.facebook.com/posts/1505962329687926/flow-a-new-static-type-checker-for-javascript/)',
    ' * [Danger\'s flow glossary](https://github.com/danger/danger-js/blob/master/docs/js_glossary.md)',
  ];
  markdown('If you are new to Flow, here are some resources: \n\n' + flowLinks.join('\n'));
  warn(`These new JS files do not have Flow enabled: ${unFlowedFiles.join(', ')}`);
}

// Request a CHANGELOG entry
const hasChangelog = danger.git.modified_files.includes('changelog.md');
if (!hasChangelog) { fail('Please add a changelog entry for your changes.'); }

// Politely ask for their name on the entry too
const changelogDiff = danger.git.diffForFile('changelog.md');
const contributorName = danger.github.pr.user.login;
if (changelogDiff && changelogDiff.indexOf(contributorName) === -1) {
  warn('Please add your GitHub name to "' + contributorName + '" the changelog entry.');
}
<commit_msg>Reverse check for Flow on Danger"<commit_after>// @flow

import { danger, fail, warn, markdown } from 'danger';
const fs = require('fs');

// Move all JS files towards using flow
const changedFiles = danger.git.created_files.concat(danger.git.modified_files);
const unFlowedFiles = changedFiles.filter(path => !path.startsWith('test/') && path.endsWith('js'))
  .filter(filepath => {
    const content = fs.readFileSync(filepath);
    return content.includes('@flow');
  });

if (unFlowedFiles.length > 0) {
  const flowLinks = [
    ' * [Main Site](https://flowtype.org)',
    ' * [Types](https://flowtype.org/docs/quick-reference.html#primitives)',
    ' * [What is Flow?](https://code.facebook.com/posts/1505962329687926/flow-a-new-static-type-checker-for-javascript/)',
    ' * [Danger\'s flow glossary](https://github.com/danger/danger-js/blob/master/docs/js_glossary.md)',
  ];
  markdown('If you are new to Flow, here are some resources: \n\n' + flowLinks.join('\n'));
  warn(`These new JS files do not have Flow enabled: ${unFlowedFiles.join(', ')}`);
}

// Request a CHANGELOG entry
const hasChangelog = changedFiles.includes('changelog.md');
if (!hasChangelog) { fail('Please add a changelog entry for your changedFiles.'); }

// Politely ask for their name on the entry too
const changelogDiff = danger.git.diffForFile('changelog.md');
const contributorName = danger.github.pr.user.login;
if (changelogDiff && changelogDiff.indexOf(contributorName) === -1) {
  warn('Please add your GitHub name to "' + contributorName + '" the changelog entry.');
}
<|endoftext|>


<commit_before>define([
	'app',
	'meetupRafflerControllers',
	'meetupRafflerServices',
	'json!../data/winners.json',
	'meetupHelpers'
], function(app, meetupRafflerControllers, meetupRafflerServices, previousWinners) {
	'use strict';

	// Controller

	meetupRafflerControllers.controller('meetup', ['$scope', '$rootScope', '$route', 'meetupEventService', 'meetupEventRsvpsService', 'authService', 'configService',
		function($scope, $rootScope, $route, meetupEventService, meetupEventRsvpsService, authService, configService) {

			if (!authService.isLoggedIn()) {

			}

			$scope.getRandomMember = function() {
				app.getRandomMember($rootScope, $scope, previousWinners);
			}

			$scope.resetMemberTiles = function() {
				app.clearWinner();
				$scope.isSelectingPrizeWinner = false;
			}

			$scope.isSelectingPrizeWinner = false;

			var groupId = $route.current.params['groupId'];

			if (!configService.useMeetupWebServices()) {
				require([
					"json!../data/meetup.json",
					"json!../data/rsvps.json"
				], function(dataMeetup, dataMeetupRsvps) {
					$scope.$apply(function() {
						$scope.meetup = dataMeetup.results[0];
						$scope.rsvps = app.explodeTheGuests(dataMeetupRsvps.results);
					});
				});
			} else {
				var meetup = meetupEventService.getmeetup({
					group_id: groupId,
					access_token: authService.accessToken()
				});

				meetup.$promise
					.then(
						function(event) {
							$scope.meetup = event.results[0];

							var rsvps = meetupEventRsvpsService.getEventRsvps({
								event_id: $scope.meetup.id,
								access_token: authService.accessToken()
							});

							return rsvps.$promise;
						},
						function(response) {
							console.log(response);
						})
					.then(
						function(eventRsvps) {
							$scope.rsvps = explodeTheGuests(eventRsvps.results);
						},
						function(response) {
							console.log(response);
						});
			}
		}
	]);

	// Service

	meetupRafflerServices.factory('meetupEventService', ['$resource',
		function($resource) {
			// TODO - do we need to handle previous meetups too
			var resource = $resource('https://api.meetup.com/2/events?&status=upcoming,past&limited_events=true&page=1&desc=true&group_id=:group_id&access_token=:access_token',
				{
					access_token : '@access_token'
				},
				{
					get: {
						cache: true
					}
				});
			return {
				getmeetup: function(options) {
					var meetup = resource.get({
						group_id: options.group_id,
						access_token: options.access_token
					});
					return meetup;
				}
			}
		}
	]);

	meetupRafflerServices.factory('meetupEventRsvpsService', ['$resource',
		function($resource) {
			var resource = $resource('https://api.meetup.com/2/rsvps?&rsvp=yes&event_id=:event_id&access_token=:access_token',
				{
					access_token : '@access_token'
				},
				{
					get: {
						cache: true
					}
				});
			return {
				getEventRsvps: function(options) {
					var meetupRsvps = resource.get({
						event_id: options.event_id,
						access_token: options.access_token
					});
					return meetupRsvps;
				}
			}
		}
	]);
});
<commit_msg>Fixed incorrect rsvp call when in online mode<commit_after>define([
	'app',
	'meetupRafflerControllers',
	'meetupRafflerServices',
	'json!../data/winners.json',
	'meetupHelpers'
], function(app, meetupRafflerControllers, meetupRafflerServices, previousWinners) {
	'use strict';

	// Controller

	meetupRafflerControllers.controller('meetup', ['$scope', '$rootScope', '$route', 'meetupEventService', 'meetupEventRsvpsService', 'authService', 'configService',
		function($scope, $rootScope, $route, meetupEventService, meetupEventRsvpsService, authService, configService) {

			if (!authService.isLoggedIn()) {

			}

			$scope.getRandomMember = function() {
				app.getRandomMember($rootScope, $scope, previousWinners);
			}

			$scope.resetMemberTiles = function() {
				app.clearWinner();
				$scope.isSelectingPrizeWinner = false;
			}

			$scope.isSelectingPrizeWinner = false;

			var groupId = $route.current.params['groupId'];

			if (!configService.useMeetupWebServices()) {
				require([
					"json!../data/meetup.json",
					"json!../data/rsvps.json"
				], function(dataMeetup, dataMeetupRsvps) {
					$scope.$apply(function() {
						$scope.meetup = dataMeetup.results[0];
						$scope.rsvps = app.explodeTheGuests(dataMeetupRsvps.results);
					});
				});
			} else {
				var meetup = meetupEventService.getmeetup({
					group_id: groupId,
					access_token: authService.accessToken()
				});

				meetup.$promise
					.then(
						function(event) {
							$scope.meetup = event.results[0];

							var rsvps = meetupEventRsvpsService.getEventRsvps({
								event_id: $scope.meetup.id,
								access_token: authService.accessToken()
							});

							return rsvps.$promise;
						},
						function(response) {
							console.log(response);
						})
					.then(
						function(eventRsvps) {
							$scope.rsvps = app.explodeTheGuests(eventRsvps.results);
						},
						function(response) {
							console.log(response);
						});
			}
		}
	]);

	// Service

	meetupRafflerServices.factory('meetupEventService', ['$resource',
		function($resource) {
			// TODO - do we need to handle previous meetups too
			var resource = $resource('https://api.meetup.com/2/events?&status=upcoming,past&limited_events=true&page=1&desc=true&group_id=:group_id&access_token=:access_token',
				{
					access_token : '@access_token'
				},
				{
					get: {
						cache: true
					}
				});
			return {
				getmeetup: function(options) {
					var meetup = resource.get({
						group_id: options.group_id,
						access_token: options.access_token
					});
					return meetup;
				}
			}
		}
	]);

	meetupRafflerServices.factory('meetupEventRsvpsService', ['$resource',
		function($resource) {
			var resource = $resource('https://api.meetup.com/2/rsvps?&rsvp=yes&event_id=:event_id&access_token=:access_token',
				{
					access_token : '@access_token'
				},
				{
					get: {
						cache: true
					}
				});
			return {
				getEventRsvps: function(options) {
					var meetupRsvps = resource.get({
						event_id: options.event_id,
						access_token: options.access_token
					});
					return meetupRsvps;
				}
			}
		}
	]);
});
<|endoftext|>


<commit_before>doinnothin = (function(sw, $) {

	var times = [];

	var btn = $('#go').click(function(e) {
		e.preventDefault();
		if(sw.running()) {
			sw.stop();
			var stats = sw.stats();
			times.push(stats);
			btn.attr('value', 'I\'m doin\' nothin\'');
			$('#time').text('');
			eventManager.trigger('timer-stopped', e, {stats: stats});
		} else {
			sw.reset();
			sw.start();
			btn.attr('value', 'I\'m doin\' somethin\'');
			updateCounter();

			eventManager.trigger('timer-started', e, {});
		}
	});

	function updateCounter() {
		if(sw.running()) {
			$('#time').text('So far... ' + sw.currentSeconds() + 's');
			setTimeout(updateCounter, 10);
		}
	}

	$('#total a').click(function(e) {
		e.preventDefault();
		$('#total span').text(ret.totalMinutes() + ' minutes');
	});

	$('#save a').click(function(e) {
		e.preventDefault();
		if(times.length) {
			$.post('/save', { start: times[0].started, times: times }, function(result) {
				$('#save a').addClass('saved');
			});
		}
	});

	var ret = {
		times: times,
		totalSeconds: function() {
			return times.map(function(x) {
				return x.seconds;
			}).reduce(function(x, y) {
				return x + (y || 0);
			});
		},
		totalMilliseconds: function() {
			return times.map(function(x) {
				return x.milliseconds;
			}).reduce(function(x, y) {
				return x + (y || 0);
			});
		},
		totalMinutes: function() {
			return ret.totalSeconds() / 60;
		}
	};

	return ret;

})(stopwatch, jQuery);

window.cookieMonster = (function() {
	if(!Array.prototype.filter) {
		Array.prototype.filter = function(fn) {
			var ret = [];
			for(var i=0,l=this.length; i<l; i++) {
				if(fn(this[i], i)) ret.push(this[i]);
			}
			return ret;
		};
	};
	return {
		add: function(key, value) {
			document.cookie = key + '=' + JSON.stringify(value);
		},
		get: function(key) {
			var cookies = document.cookie.split('; ')
				.filter(function(x) {
					return x.split('=')[0] == key;
				}).map(function(x) {
					var s = x.split('=')[1];
					return JSON.parse(s);
				});

			if(cookies && cookies.length > 0) {
				return cookies[0];
			}
			return;
		},
		remove: function(key, value) {
			document.cookie = key + '=' + JSON.stringify(value) + ';expires=' + 'Thu, 01-Jan-70 00:00:01 GMT;';
		}
	};
})();

window.localDB = (function() {

	var pageStorage = (function() {
		var db = {};
		return {
			getItem: function(key) {
				if(!key) return;
				return db[key];
			},
			setItem: function(key, value) {
				if(!key) return;
				db[key] = value;
			},
			removeItem: function(key) {
				if(!key || !db[key]) return;
				delete db[key];
			},
			clear: function() {
				db = {};
			}
		};
	})();

	var cookieStorage = (function() {
		cookieMonster.add('cookieStorage', {});
		function getDB() {
			return cookieMonster.get('cookieStorage');
		};
		return {
			getItem: function(key) {
				if(!key) return;
				var db = getDB();
				return db[key];
			},
			setItem: function(key, value) {
				if(!key) return;
				var db = getDB();
				db[key] = value;
				cookieMonster.add('cookieStorage', db);
			},
			removeItem: function(key) {
				if(!key) return;

			},
			clear: function() {

			}
		};
	})();

	function get(key, storage) {
		var s = storage.getItem(key);
		if(s) {
			return JSON.parse(s);
		}
		return undefined;
	}

	function getStorage(type) {
		type = type || 'localStorage';
		switch(type) {
			case 'sessionStorage':
				return sessionStorage;
			case 'pageStorage':
				return pageStorage;
			case 'cookieStorage':
				return cookieStorage;
			default:
				return localStorage;
		};
	}

	function set(key, value, storage) {
		storage.setItem(key, JSON.stringify(value));
	}

	function del(key, storage) {
		storage.removeItem(key);
	}

	return {
		getItem: function(key, type) {
			if(!key) return;
			var storage = getStorage(type);
			return get(key, storage);
		},
		setItem: function(key, value, type) {
			if(!key) return;
			var storage = getStorage(type);
			set(key, value, storage);
		},
		removeItem: function(key, type) {
			if(!key) return;
			var storage = getStorage(type);
			del(key, type);
		},
		clear: function(type) {
			var storage = getStorage(type);
			storage.clear();
		}
	};

})();
<commit_msg>renaming from localDB to storageBox<commit_after>doinnothin = (function(sw, $) {

	var times = [];

	var btn = $('#go').click(function(e) {
		e.preventDefault();
		if(sw.running()) {
			sw.stop();
			var stats = sw.stats();
			times.push(stats);
			btn.attr('value', 'I\'m doin\' nothin\'');
			$('#time').text('');
			eventManager.trigger('timer-stopped', e, {stats: stats});
		} else {
			sw.reset();
			sw.start();
			btn.attr('value', 'I\'m doin\' somethin\'');
			updateCounter();

			eventManager.trigger('timer-started', e, {});
		}
	});

	function updateCounter() {
		if(sw.running()) {
			$('#time').text('So far... ' + sw.currentSeconds() + 's');
			setTimeout(updateCounter, 10);
		}
	}

	$('#total a').click(function(e) {
		e.preventDefault();
		$('#total span').text(ret.totalMinutes() + ' minutes');
	});

	$('#save a').click(function(e) {
		e.preventDefault();
		if(times.length) {
			$.post('/save', { start: times[0].started, times: times }, function(result) {
				$('#save a').addClass('saved');
			});
		}
	});

	var ret = {
		times: times,
		totalSeconds: function() {
			return times.map(function(x) {
				return x.seconds;
			}).reduce(function(x, y) {
				return x + (y || 0);
			});
		},
		totalMilliseconds: function() {
			return times.map(function(x) {
				return x.milliseconds;
			}).reduce(function(x, y) {
				return x + (y || 0);
			});
		},
		totalMinutes: function() {
			return ret.totalSeconds() / 60;
		}
	};

	return ret;

})(stopwatch, jQuery);

window.cookieMonster = (function() {
	if(!Array.prototype.filter) {
		Array.prototype.filter = function(fn) {
			var ret = [];
			for(var i=0,l=this.length; i<l; i++) {
				if(fn(this[i], i)) ret.push(this[i]);
			}
			return ret;
		};
	};
	return {
		add: function(key, value) {
			document.cookie = key + '=' + JSON.stringify(value);
		},
		get: function(key) {
			var cookies = document.cookie.split('; ')
				.filter(function(x) {
					return x.split('=')[0] == key;
				}).map(function(x) {
					var s = x.split('=')[1];
					return JSON.parse(s);
				});

			if(cookies && cookies.length > 0) {
				return cookies[0];
			}
			return;
		},
		remove: function(key, value) {
			document.cookie = key + '=' + JSON.stringify(value) + ';expires=' + 'Thu, 01-Jan-70 00:00:01 GMT;';
		}
	};
})();

window.storageBox = (function() {

	var pageStorage = (function() {
		var db = {};
		return {
			getItem: function(key) {
				if(!key) return;
				return db[key];
			},
			setItem: function(key, value) {
				if(!key) return;
				db[key] = value;
			},
			removeItem: function(key) {
				if(!key || !db[key]) return;
				delete db[key];
			},
			clear: function() {
				db = {};
			}
		};
	})();

	var cookieStorage = (function() {
		cookieMonster.add('cookieStorage', {});
		function getDB() {
			return cookieMonster.get('cookieStorage');
		};
		return {
			getItem: function(key) {
				if(!key) return;
				var db = getDB();
				return db[key];
			},
			setItem: function(key, value) {
				if(!key) return;
				var db = getDB();
				db[key] = value;
				cookieMonster.add('cookieStorage', db);
			},
			removeItem: function(key) {
				if(!key) return;

			},
			clear: function() {
				cookieMonster.add('cookieStorage', {});
			}
		};
	})();

	function get(key, storage) {
		var s = storage.getItem(key);
		if(s) {
			return JSON.parse(s);
		}
		return undefined;
	}

	function getStorage(type) {
		type = type || 'localStorage';
		switch(type) {
			case 'sessionStorage':
				return sessionStorage;
			case 'pageStorage':
				return pageStorage;
			case 'cookieStorage':
				return cookieStorage;
			default:
				return localStorage;
		};
	}

	function set(key, value, storage) {
		storage.setItem(key, JSON.stringify(value));
	}

	function del(key, storage) {
		storage.removeItem(key);
	}

	return {
		getItem: function(key, type) {
			if(!key) return;
			var storage = getStorage(type);
			return get(key, storage);
		},
		setItem: function(key, value, type) {
			if(!key) return;
			var storage = getStorage(type);
			set(key, value, storage);
		},
		removeItem: function(key, type) {
			if(!key) return;
			var storage = getStorage(type);
			del(key, type);
		},
		clear: function(type) {
			var storage = getStorage(type);
			storage.clear();
		},
		getDB: getStorage
	};

})();
<|endoftext|>


<commit_before>// @flow

// import { danger, warn } from "danger"
import fs from "fs"

// Request a CHANGELOG entry
const hasChangelog = danger.git.modified_files.includes("changelog.md")
if (!hasChangelog) { warn("Please add a changelog entry for your changes.") }

// Politely ask for their name on the entry too
const changelogDiff = danger.git.diffForFile("changelog.md")
const contributorName = danger.github.pr.user.login
if (changelogDiff && changelogDiff.indexOf(contributorName) === -1) {
  warn("Please add your GitHub name to the changelog entry, so we can attribute you.")
}

const jsFiles = danger.git.created_files.filter(path => path.endsWith("js"))

// new js files should have `@flow` at the top
// but exclude tests from being flow-ey
const unFlowedFiles = jsFiles.filter(path => !path.endsWith("test.js"))
  .filter(filepath => {
    const content = fs.readFileSync(filepath).toString()
    return !content.includes("@flow")
  })

if (unFlowedFiles.length > 0) {
  warn(`These new JS files do not have Flow enabled: ${unFlowedFiles.join(", ")}`)
}

<commit_msg>chore(dangerfile): update dangerfile<commit_after>// import { danger, warn } from "danger"
import fs from "fs"

// Request a CHANGELOG entry
const hasChangelog = danger.git.modified_files.includes("changelog.md")
if (!hasChangelog) { warn("Please add a changelog entry for your changes.") }

// Politely ask for their name on the entry too
const changelogDiff = danger.git.diffForFile("changelog.md")
const contributorName = danger.github.pr.user.login
if (changelogDiff && changelogDiff.indexOf(contributorName) === -1) {
  warn("Please add your GitHub name to the changelog entry, so we can attribute you.")
}

const jsFiles = danger.git.created_files.filter(path => path.endsWith("js"))<|endoftext|>


<commit_before>define([
  // Libs
  "jquery",
  "use!underscore",
  "use!backbone"
],

function($, _, Backbone) {
  // Put application wide code here

  return {
    // This is useful when developing if you don't want to use a
    // build process every time you change a template.
    //
    // Delete if you are using a different template loading method.
    fetchTemplate: function(path, done) {
      var JST = window.JST = window.JST || {};

      // Should be an instant synchronous way of getting the template, if it
      // exists in the JST object.
      if (JST[path]) {
        return done(JST[path]);
      }

      // Fetch it asynchronously if not available from JST
      return $.get(path, function(contents) {
        var tmpl = _.template(contents);

        // Set the global JST cache and return the template
        done(JST[path] = tmpl);
      });
    },

    // Create a custom object with a nested Views object
    module: function(additionalProps) {
      return _.extend({ Views: {} }, additionalProps);
    },

    // Keep active application instances namespaced under an app object.
    app: _.extend({}, Backbone.Events)
  };
});
<commit_msg>Set dataType of fetchTemplate to "text."<commit_after>define([
  // Libs
  "jquery",
  "use!underscore",
  "use!backbone"
],

function($, _, Backbone) {
  // Put application wide code here

  return {
    // This is useful when developing if you don't want to use a
    // build process every time you change a template.
    //
    // Delete if you are using a different template loading method.
    fetchTemplate: function(path, done) {
      var JST = window.JST = window.JST || {};

      // Should be an instant synchronous way of getting the template, if it
      // exists in the JST object.
      if (JST[path]) {
        return done(JST[path]);
      }

      // Fetch it asynchronously if not available from JST
      return $.get(path, function(contents) {
        var tmpl = _.template(contents);

        // Set the global JST cache and return the template
        done(JST[path] = tmpl);
      }, "text");
    },

    // Create a custom object with a nested Views object
    module: function(additionalProps) {
      return _.extend({ Views: {} }, additionalProps);
    },

    // Keep active application instances namespaced under an app object.
    app: _.extend({}, Backbone.Events)
  };
});
<|endoftext|>


<commit_before>(function (window) {

// in nodejs, global is an object
// in normal browser environment, global is undefined
// in webpack, global is set to window
var isNodeJs   = typeof global !== "undefined" && global.window === undefined;
var isCommonJs = typeof module === "object" && module && typeof module.exports === "object";

// require, that the nodejs will handle, but will remain not processed by webpack and the like
var obfuscatedRequire = function (moduleName)
{
  return module["r" + "equire"](moduleName);
}

var RestsigApi =
  function (url, secureUrl, modifyRequest)
  {
    var self = this;
    var postfix          = '/v' + this.version + '/';
    var contextUrl       = url + postfix;
    var secureContextUrl = (secureUrl || url.replace(/^http:/, "https:")) + postfix;

    this.cookieJar = isNodeJs ? obfuscatedRequire('request').jar() : undefined;

    if(!modifyRequest) modifyRequest = function (req) { return req; };

    var finalModifyRequest = function (req)
    {
      if (isNodeJs) req.jar = self.cookieJar;
      return modifyRequest(req);
    }

    RestsigApi.setContext(this, contextUrl, secureContextUrl, finalModifyRequest);
  };

var jqFun;
if (isNodeJs)
{
  // Export as Node module.
  module.exports = RestsigApi;

  RestsigApi.ajaxCall = nodeRequest;
}
else
{
  if (isCommonJs) {
    // Export as CommonJs
    module.exports = RestsigApi;
    jqFun = function () { return require("jquery"); };
  } else if (typeof define === "function" && define.amd) {
    // Export as AMD.
    define("RestsigApi", [], function () { return RestsigApi; });
    jqFun = function () { return window.$; };
  } else {
    // Export as global.
    window.RestsigApi = RestsigApi;
    jqFun = function () { return window.$; };
  }

  RestsigApi.ajaxCall = jQueryRequest;
}

RestsigApi.addObject = function (obj1, obj2)
{
  for (var fld in obj2)
    obj1[fld] = obj2[fld];
};

RestsigApi.defaultAjaxOptions = {};
RestsigApi.defaultHeaders = {};

function jQueryRequest (method, url, params, success, error, contentType, acceptHeader, data, callOpts, modifyRequest)
{
  var q = window.Q || function (a) { return a };
  var jq = jqFun();

  var headers = jq.extend(true, {}, RestsigApi.defaultHeaders);
  RestsigApi.addObject(headers, { Accept : acceptHeader });

  var callData =
    { type        : method
    , url         : url + (params ? '?' + jq.param(params) : '')
    , cache       : false
    , success     : success || function () {}
    , error       : error || function () {}
    , contentType : contentType
    , headers     : headers
    , xhrFields   : { withCredentials: true }
    , data        : data || []
    };

  callData = modifyRequest(callData);

  RestsigApi.addObject(callData, RestsigApi.defaultAjaxOptions);
  RestsigApi.addObject(callData, callOpts);

  return q(jq.ajax(callData));
}

function nodeRequest (method, url, params, onSuccess, onError, contentType, acceptHeader, data, callOpts, modifyRequest)
{
  var allParams = {};
  RestsigApi.addObject(allParams, params);

  if (method === "GET" || method === "HEAD")
    // Avoid cached API responses.
    allParams._ = Date.now();

  var headers = { "Content-type" : contentType
                , "Accept"       : acceptHeader
                };

  RestsigApi.addObject(headers, RestsigApi.defaultHeaders);

  var callData =
    { url     : url
    , qs      : allParams
    , method  : method
    , headers : headers
    };

  if (data) callData.body = data;

  callData = modifyRequest(callData);

  RestsigApi.addObject(callData, RestsigApi.defaultAjaxOptions);
  RestsigApi.addObject(callData, callOpts);

  return require("q").Promise(function (resolve, reject)
  {
    obfuscatedRequire("request")(callData, callback);

    function callback (error, message, body)
    {
      if (message && message.statusCode >= 200 && message.statusCode < 300)
      {
        var parsedResponse = parse(body);
        onSuccess && onSuccess(parsedResponse, message);
        resolve(parsedResponse)
      }
      else
      {
        if (!error)
        {
          error = new Error("HTTP request error");
          error.statusCode = message.statusCode;
          error.responseBody = body;
        }

        error.response = parse(body);

        if (onError)
          onError(error);

        reject(error);
      }
    }
  });

  function parse (response)
  {
    if (acceptHeader.split(";").indexOf('text/json') >= 0)
    {
      var r = response;
      try
      {
        r = JSON.parse(response);
      }
      catch (e)
      {
        return r;
      }
      return r;
    }
    else return response;
  }
}

RestsigApi.setContext =
  function (obj, url, secureUrl, modifyRequest)
  {
    obj.contextUrl = url;
    obj.secureContextUrl = secureUrl;
    obj.modifyRequest = modifyRequest;
    for (var fld in obj)
    {
      if (obj[fld] != undefined && obj[fld].apiObjectType != undefined && obj[fld].apiObjectType == 'resourceDir')
      {
        var postfix = fld.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase() + '/';
        RestsigApi.setContext(obj[fld], url + postfix, secureUrl + postfix, modifyRequest);
      }
    }
  };RestsigApi.prototype.version = "1.0.0";
RestsigApi.prototype.Stocks =
  function Stocks (url, secureUrl, modifyRequest)
  {
    if (this instanceof Stocks)
    {
      RestsigApi.setContext(this, url, secureUrl, modifyRequest);
    }
    else
    {
      return Stocks.access(url, secureUrl, modifyRequest);
    }
  };
RestsigApi.prototype.Stocks.apiObjectType = "resourceDir";
RestsigApi.prototype.Stocks.byCode =
  function (string)
  {
    var postfix = 'code/' + encodeURIComponent(string) + '/';
    var accessor = new this(this.contextUrl + postfix, this.secureContextUrl + postfix, this.modifyRequest);
    accessor.get =
      function (success, error, params, callOpts)
      {
        return RestsigApi.ajaxCall("GET", this.contextUrl + '', params, success, error, "text/plain", "text/json", undefined, callOpts, this.modifyRequest);
      };
    return accessor;
  };

})(this);<commit_msg>Generate new sig.js for Api.Brand<commit_after>(function (window) {

// in nodejs, global is an object
// in normal browser environment, global is undefined
// in webpack, global is set to window
var isNodeJs   = typeof global !== "undefined" && global.window === undefined;
var isCommonJs = typeof module === "object" && module && typeof module.exports === "object";

// require, that the nodejs will handle, but will remain not processed by webpack and the like
var obfuscatedRequire = function (moduleName)
{
  return module["r" + "equire"](moduleName);
}

var RestsigApi =
  function (url, secureUrl, modifyRequest)
  {
    var self = this;
    var postfix          = '/v' + this.version + '/';
    var contextUrl       = url + postfix;
    var secureContextUrl = (secureUrl || url.replace(/^http:/, "https:")) + postfix;

    this.cookieJar = isNodeJs ? obfuscatedRequire('request').jar() : undefined;

    if(!modifyRequest) modifyRequest = function (req) { return req; };

    var finalModifyRequest = function (req)
    {
      if (isNodeJs) req.jar = self.cookieJar;
      return modifyRequest(req);
    }

    RestsigApi.setContext(this, contextUrl, secureContextUrl, finalModifyRequest);
  };

var jqFun;
if (isNodeJs)
{
  // Export as Node module.
  module.exports = RestsigApi;

  RestsigApi.ajaxCall = nodeRequest;
}
else
{
  if (isCommonJs) {
    // Export as CommonJs
    module.exports = RestsigApi;
    jqFun = function () { return require("jquery"); };
  } else if (typeof define === "function" && define.amd) {
    // Export as AMD.
    define("RestsigApi", [], function () { return RestsigApi; });
    jqFun = function () { return window.$; };
  } else {
    // Export as global.
    window.RestsigApi = RestsigApi;
    jqFun = function () { return window.$; };
  }

  RestsigApi.ajaxCall = jQueryRequest;
}

RestsigApi.addObject = function (obj1, obj2)
{
  for (var fld in obj2)
    obj1[fld] = obj2[fld];
};

RestsigApi.defaultAjaxOptions = {};
RestsigApi.defaultHeaders = {};

function jQueryRequest (method, url, params, success, error, contentType, acceptHeader, data, callOpts, modifyRequest)
{
  var q = window.Q || function (a) { return a };
  var jq = jqFun();

  var headers = jq.extend(true, {}, RestsigApi.defaultHeaders);
  RestsigApi.addObject(headers, { Accept : acceptHeader });

  var callData =
    { type        : method
    , url         : url + (params ? '?' + jq.param(params) : '')
    , cache       : false
    , success     : success || function () {}
    , error       : error || function () {}
    , contentType : contentType
    , headers     : headers
    , xhrFields   : { withCredentials: true }
    , data        : data || []
    };

  callData = modifyRequest(callData);

  RestsigApi.addObject(callData, RestsigApi.defaultAjaxOptions);
  RestsigApi.addObject(callData, callOpts);

  return q(jq.ajax(callData));
}

function nodeRequest (method, url, params, onSuccess, onError, contentType, acceptHeader, data, callOpts, modifyRequest)
{
  var allParams = {};
  RestsigApi.addObject(allParams, params);

  if (method === "GET" || method === "HEAD")
    // Avoid cached API responses.
    allParams._ = Date.now();

  var headers = { "Content-type" : contentType
                , "Accept"       : acceptHeader
                };

  RestsigApi.addObject(headers, RestsigApi.defaultHeaders);

  var callData =
    { url     : url
    , qs      : allParams
    , method  : method
    , headers : headers
    };

  if (data) callData.body = data;

  callData = modifyRequest(callData);

  RestsigApi.addObject(callData, RestsigApi.defaultAjaxOptions);
  RestsigApi.addObject(callData, callOpts);

  return require("q").Promise(function (resolve, reject)
  {
    obfuscatedRequire("request")(callData, callback);

    function callback (error, message, body)
    {
      if (message && message.statusCode >= 200 && message.statusCode < 300)
      {
        var parsedResponse = parse(body);
        onSuccess && onSuccess(parsedResponse, message);
        resolve(parsedResponse)
      }
      else
      {
        if (!error)
        {
          error = new Error("HTTP request error");
          error.statusCode = message.statusCode;
          error.responseBody = body;
        }

        error.response = parse(body);

        if (onError)
          onError(error);

        reject(error);
      }
    }
  });

  function parse (response)
  {
    if (acceptHeader.split(";").indexOf('text/json') >= 0)
    {
      var r = response;
      try
      {
        r = JSON.parse(response);
      }
      catch (e)
      {
        return r;
      }
      return r;
    }
    else return response;
  }
}

RestsigApi.setContext =
  function (obj, url, secureUrl, modifyRequest)
  {
    obj.contextUrl = url;
    obj.secureContextUrl = secureUrl;
    obj.modifyRequest = modifyRequest;
    for (var fld in obj)
    {
      if (obj[fld] != undefined && obj[fld].apiObjectType != undefined && obj[fld].apiObjectType == 'resourceDir')
      {
        var postfix = fld.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase() + '/';
        RestsigApi.setContext(obj[fld], url + postfix, secureUrl + postfix, modifyRequest);
      }
    }
  };RestsigApi.prototype.version = "1.0.0";
RestsigApi.prototype.Brands =
  function Brands (url, secureUrl, modifyRequest)
  {
    if (this instanceof Brands)
    {
      RestsigApi.setContext(this, url, secureUrl, modifyRequest);
    }
    else
    {
      return Brands.access(url, secureUrl, modifyRequest);
    }
  };
RestsigApi.prototype.Brands.apiObjectType = "resourceDir";
RestsigApi.prototype.Brands.byLike =
  function (string)
  {
    var postfix = 'like/' + encodeURIComponent(string) + '/';
    var accessor = new this(this.contextUrl + postfix, this.secureContextUrl + postfix, this.modifyRequest);
    accessor.get =
      function (success, error, params, callOpts)
      {
        return RestsigApi.ajaxCall("GET", this.contextUrl + '', params, success, error, "text/plain", "text/json", undefined, callOpts, this.modifyRequest);
      };
    return accessor;
  };
RestsigApi.prototype.Stocks =
  function Stocks (url, secureUrl, modifyRequest)
  {
    if (this instanceof Stocks)
    {
      RestsigApi.setContext(this, url, secureUrl, modifyRequest);
    }
    else
    {
      return Stocks.access(url, secureUrl, modifyRequest);
    }
  };
RestsigApi.prototype.Stocks.apiObjectType = "resourceDir";
RestsigApi.prototype.Stocks.byCode =
  function (string)
  {
    var postfix = 'code/' + encodeURIComponent(string) + '/';
    var accessor = new this(this.contextUrl + postfix, this.secureContextUrl + postfix, this.modifyRequest);
    accessor.get =
      function (success, error, params, callOpts)
      {
        return RestsigApi.ajaxCall("GET", this.contextUrl + '', params, success, error, "text/plain", "text/json", undefined, callOpts, this.modifyRequest);
      };
    return accessor;
  };

})(this);<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { Autobind } from 'es-decorators';
import { toastr } from 'react-redux-toastr';
import { Router } from 'routes';

// Redux
import { connect } from 'react-redux';
import { setTitle } from 'components/widgets/editor/redux/widgetEditor';

// Services
import WidgetService from 'services/WidgetService';
import DatasetsService from 'services/DatasetsService';

// Components
import Spinner from 'components/ui/Spinner';
import WidgetEditor from 'components/widgets/editor/WidgetEditor';
import Button from 'components/ui/Button';
import Input from 'components/form/Input';
import Field from 'components/form/Field';
import Select from 'components/form/SelectInput';

// Utils
import { getChartConfig, canRenderChart, getChartInfo } from 'utils/widgets/WidgetHelper';
import { logEvent } from 'utils/analytics';

const FORM_ELEMENTS = {
  elements: {
  },
  validate() {
    const elements = this.elements;
    Object.keys(elements).forEach((k) => {
      elements[k].validate();
    });
  },
  isValid() {
    const elements = this.elements;
    const valid = Object.keys(elements)
      .map(k => elements[k].isValid())
      .filter(v => v !== null)
      .every(element => element);

    return valid;
  }
};

class WidgetsNew extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      loadingPublishedDatasets: true,
      loadingUserDatasets: true,
      submitting: false,
      datasets: [],
      selectedDataset: props.dataset,
      widget: {}
    };

    // Services
    this.widgetService = new WidgetService(null, { apiURL: process.env.CONTROL_TOWER_URL });
    this.datasetsService = new DatasetsService({
      language: props.locale
    });
  }

  componentDidMount() {
    this.loadDatasets();
  }

  @Autobind
  async onSubmit(event) {
    if (event) event.preventDefault();

    const { widget, selectedDataset, datasets } = this.state;
    const { widgetEditor, user } = this.props;
    const {
      visualizationType,
      band,
      limit,
      value,
      category,
      color,
      size,
      orderBy,
      aggregateFunction,
      chartType,
      filters,
      areaIntersection,
      layer,
      title,
      zoom,
      latLng
    } = widgetEditor;

    const dataset = datasets.find(elem => elem.value === selectedDataset);
    const { type, provider, tableName } = dataset;

    if (!canRenderChart(widgetEditor, provider)) {
      toastr.error('Error', 'Please create a widget in order to save it');
      return;
    }

    logEvent('My RW', 'User creates new widget', this.state.datasets.find(d => d.id === this.state.selectedDataset).label);

    this.setState({ loading: true });

    let chartConfig;

    // If the visualization if a map, we don't have any chartConfig
    if (visualizationType !== 'map') {
      const chartInfo = getChartInfo(dataset.id, type, provider, widgetEditor);

      try {
        chartConfig = await getChartConfig(
          dataset.id,
          type,
          tableName,
          band,
          provider,
          chartInfo
        );
      } catch (err) {
        this.setState({
          saved: false,
          loading: false
        });
        toastr.error('Error', 'Unable to generate the configuration of the chart');

        return;
      }
    }

    const widgetConfig = {
      widgetConfig: Object.assign(
        {},
        // If the widget is a map, we want to add some extra info
        // in widgetConfig so the widget is compatible with other
        // apps that use the same API
        // The type and layer_id are not necessary for the editor
        // because it is already saved in widgetConfig.paramsConfig
        (
          visualizationType === 'map'
            ? { type: 'map', layer_id: layer && layer.id, zoom, ...latLng }
            : {}
        ),
        {
          paramsConfig: {
            visualizationType,
            band: band && { name: band.name },
            limit,
            value,
            category,
            color,
            size,
            orderBy,
            aggregateFunction,
            chartType,
            filters,
            areaIntersection,
            layer: layer && layer.id
          }
        },
        chartConfig
      )
    };

    const widgetObj = Object.assign(
      {},
      {
        name: title,
        description: widget.description,
        authors: widget.authors,
        source: widget.source,
        sourceUrl: widget.sourceUrl
      },
      widgetConfig
    );

    this.widgetService.saveUserWidget(widgetObj, selectedDataset, user.token)
      .then((response) => {
        if (response.errors) {
          const errorMessage = response.errors[0].detail;
          this.setState({
            saved: false,
            loading: false
          });

          toastr.error('Error', errorMessage);
        } else {
          Router.pushRoute('myrw', { tab: 'widgets', subtab: 'my_widgets' });
          toastr.success('Success', 'Widget created successfully!');
        }
      }).catch((err) => {
        this.setState({
          saved: false,
          loading: false
        });
        toastr.err('Error', err);
      });
  }

  loadDatasets() {
    this.datasetsService.fetchAllData({ filters: { published: true }, includes: 'metadata' }).then((response) => {
      this.setState({
        datasets: [...this.state.datasets, ...response.map((dataset) => {
          const metadata = dataset.metadata[0];
          return ({
            id: dataset.id,
            type: dataset.type,
            provider: dataset.provider,
            tableName: dataset.tableName,
            label: metadata && metadata.attributes.info
              ? metadata.attributes.info.name
              : dataset.name,
            value: dataset.id
          });
        })],
        loadingPublishedDatasets: false
      });
    });

    this.datasetsService.fetchAllData(
      { filters: { userId: this.props.user.id }, includes: 'metadata' }).then((response) => {
      this.setState({
        datasets: [...this.state.datasets, ...response.map((dataset) => {
          const metadata = dataset.metadata[0];
          return ({
            id: dataset.id,
            type: dataset.type,
            provider: dataset.provider,
            tableName: dataset.tableName,
            label: metadata && metadata.attributes.info
              ? metadata.attributes.info.name
              : dataset.name,
            value: dataset.id
          });
        })],
        loadingUserDatasets: false
      });
    });
  }

  @Autobind
  handleChange(value) {
    const newWidgetObj = Object.assign({}, this.state.widget, value);
    this.setState({ widget: newWidgetObj });

    if (Object.keys(value).indexOf('name') !== -1) {
      this.props.setTitle(value.name);
    }
  }

  @Autobind
  handleDatasetSelected(value) {
    this.setState({
      selectedDataset: value
    });
  }

  @Autobind
  handleWidgetEditorError() { // eslint-disable-line class-methods-use-this
    toastr.error('Error', 'An error occured with the widget editor');
  }

  render() {
    const {
      loading,
      widget,
      submitting,
      datasets,
      selectedDataset,
      loadingUserDatasets,
      loadingPublishedDatasets
    } = this.state;
    const { widgetEditor } = this.props;

    return (

        <Spinner
          className="-light"
          isLoading={loading || loadingPublishedDatasets || loadingUserDatasets}
        />
        {datasets &&

            <Field
              onChange={this.handleDatasetSelected}
              className="-fluid"
              options={datasets}
              properties={{
                name: 'dataset',
                label: 'Dataset',
                value: selectedDataset,
                default: selectedDataset,
                required: true,
                instanceId: 'selectDataset'
              }}
            >
              {Select}
            </Field>

        }
        {selectedDataset &&

          <WidgetEditor
            widget={widget}
            dataset={selectedDataset}
            mode="widget"
            onUpdateWidget={this.onSubmit}
            showSaveButton
            onError={this.handleWidgetEditorError}
          />

            <form className="form-container" onSubmit={this.onSubmit}>
              <fieldset className="c-field-container">
                <Field
                  ref={(c) => { if (c) FORM_ELEMENTS.elements.title = c; }}
                  onChange={value => this.handleChange({ name: value })}
                  validations={['required']}
                  properties={{
                    title: 'title',
                    label: 'Title',
                    type: 'text',
                    required: true,
                    default: widgetEditor.title || '',
                    value: widgetEditor.title || '',
                    placeholder: 'Widget title'
                  }}
                >
                  {Input}
                </Field>
                <Field
                  ref={(c) => { if (c) FORM_ELEMENTS.elements.description = c; }}
                  onChange={value => this.handleChange({ description: value })}
                  properties={{
                    title: 'description',
                    label: 'Description',
                    type: 'text',
                    placeholder: 'Widget description'
                  }}
                >
                  {Input}
                </Field>
                <Field
                  ref={(c) => { if (c) FORM_ELEMENTS.elements.authors = c; }}
                  onChange={value => this.handleChange({ authors: value })}
                  properties={{
                    title: 'authors',
                    label: 'Authors',
                    type: 'text',
                    placeholder: 'Author name'
                  }}
                >
                  {Input}
                </Field>

                  <Field
                    ref={(c) => { if (c) FORM_ELEMENTS.elements.source = c; }}
                    onChange={value => this.handleChange({ source: value })}
                    properties={{
                      title: 'source',
                      label: 'Source name',
                      type: 'text',
                      placeholder: 'Source name'
                    }}
                  >
                    {Input}
                  </Field>
                  <Field
                    ref={(c) => { if (c) FORM_ELEMENTS.elements.sourceUrl = c; }}
                    onChange={value => this.handleChange({ sourceUrl: value })}
                    properties={{
                      title: 'sourceUrl',
                      label: 'Source URL',
                      type: 'text',
                      placeholder: 'Paste a URL here'
                    }}
                  >
                    {Input}
                  </Field>

              </fieldset>

                <Button
                  properties={{
                    type: 'submit',
                    disabled: submitting,
                    className: '-a'
                  }}
                >
                  Save
                </Button>

            </form>

        }

    );
  }
}

WidgetsNew.propTypes = {
  dataset: PropTypes.string,
  // Store
  user: PropTypes.object.isRequired,
  widgetEditor: PropTypes.object.isRequired,
  setTitle: PropTypes.func.isRequired,
  locale: PropTypes.string.isRequired
};

const mapStateToProps = state => ({
  user: state.user,
  widgetEditor: state.widgetEditor,
  locale: state.common.locale
});

const mapDispatchToProps = dispatch => ({
  setTitle: title => dispatch(setTitle(title))
});

export default connect(mapStateToProps, mapDispatchToProps)(WidgetsNew);
<commit_msg>Prevent My RW to use the WidgetEditor's "onError" prop<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { Autobind } from 'es-decorators';
import { toastr } from 'react-redux-toastr';
import { Router } from 'routes';

// Redux
import { connect } from 'react-redux';
import { setTitle } from 'components/widgets/editor/redux/widgetEditor';

// Services
import WidgetService from 'services/WidgetService';
import DatasetsService from 'services/DatasetsService';

// Components
import Spinner from 'components/ui/Spinner';
import WidgetEditor from 'components/widgets/editor/WidgetEditor';
import Button from 'components/ui/Button';
import Input from 'components/form/Input';
import Field from 'components/form/Field';
import Select from 'components/form/SelectInput';

// Utils
import { getChartConfig, canRenderChart, getChartInfo } from 'utils/widgets/WidgetHelper';
import { logEvent } from 'utils/analytics';

const FORM_ELEMENTS = {
  elements: {
  },
  validate() {
    const elements = this.elements;
    Object.keys(elements).forEach((k) => {
      elements[k].validate();
    });
  },
  isValid() {
    const elements = this.elements;
    const valid = Object.keys(elements)
      .map(k => elements[k].isValid())
      .filter(v => v !== null)
      .every(element => element);

    return valid;
  }
};

class WidgetsNew extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      loadingPublishedDatasets: true,
      loadingUserDatasets: true,
      submitting: false,
      datasets: [],
      selectedDataset: props.dataset,
      widget: {}
    };

    // Services
    this.widgetService = new WidgetService(null, { apiURL: process.env.CONTROL_TOWER_URL });
    this.datasetsService = new DatasetsService({
      language: props.locale
    });
  }

  componentDidMount() {
    this.loadDatasets();
  }

  @Autobind
  async onSubmit(event) {
    if (event) event.preventDefault();

    const { widget, selectedDataset, datasets } = this.state;
    const { widgetEditor, user } = this.props;
    const {
      visualizationType,
      band,
      limit,
      value,
      category,
      color,
      size,
      orderBy,
      aggregateFunction,
      chartType,
      filters,
      areaIntersection,
      layer,
      title,
      zoom,
      latLng
    } = widgetEditor;

    const dataset = datasets.find(elem => elem.value === selectedDataset);
    const { type, provider, tableName } = dataset;

    if (!canRenderChart(widgetEditor, provider)) {
      toastr.error('Error', 'Please create a widget in order to save it');
      return;
    }

    logEvent('My RW', 'User creates new widget', this.state.datasets.find(d => d.id === this.state.selectedDataset).label);

    this.setState({ loading: true });

    let chartConfig;

    // If the visualization if a map, we don't have any chartConfig
    if (visualizationType !== 'map') {
      const chartInfo = getChartInfo(dataset.id, type, provider, widgetEditor);

      try {
        chartConfig = await getChartConfig(
          dataset.id,
          type,
          tableName,
          band,
          provider,
          chartInfo
        );
      } catch (err) {
        this.setState({
          saved: false,
          loading: false
        });
        toastr.error('Error', 'Unable to generate the configuration of the chart');

        return;
      }
    }

    const widgetConfig = {
      widgetConfig: Object.assign(
        {},
        // If the widget is a map, we want to add some extra info
        // in widgetConfig so the widget is compatible with other
        // apps that use the same API
        // The type and layer_id are not necessary for the editor
        // because it is already saved in widgetConfig.paramsConfig
        (
          visualizationType === 'map'
            ? { type: 'map', layer_id: layer && layer.id, zoom, ...latLng }
            : {}
        ),
        {
          paramsConfig: {
            visualizationType,
            band: band && { name: band.name },
            limit,
            value,
            category,
            color,
            size,
            orderBy,
            aggregateFunction,
            chartType,
            filters,
            areaIntersection,
            layer: layer && layer.id
          }
        },
        chartConfig
      )
    };

    const widgetObj = Object.assign(
      {},
      {
        name: title,
        description: widget.description,
        authors: widget.authors,
        source: widget.source,
        sourceUrl: widget.sourceUrl
      },
      widgetConfig
    );

    this.widgetService.saveUserWidget(widgetObj, selectedDataset, user.token)
      .then((response) => {
        if (response.errors) {
          const errorMessage = response.errors[0].detail;
          this.setState({
            saved: false,
            loading: false
          });

          toastr.error('Error', errorMessage);
        } else {
          Router.pushRoute('myrw', { tab: 'widgets', subtab: 'my_widgets' });
          toastr.success('Success', 'Widget created successfully!');
        }
      }).catch((err) => {
        this.setState({
          saved: false,
          loading: false
        });
        toastr.err('Error', err);
      });
  }

  loadDatasets() {
    this.datasetsService.fetchAllData({ filters: { published: true }, includes: 'metadata' }).then((response) => {
      this.setState({
        datasets: [...this.state.datasets, ...response.map((dataset) => {
          const metadata = dataset.metadata[0];
          return ({
            id: dataset.id,
            type: dataset.type,
            provider: dataset.provider,
            tableName: dataset.tableName,
            label: metadata && metadata.attributes.info
              ? metadata.attributes.info.name
              : dataset.name,
            value: dataset.id
          });
        })],
        loadingPublishedDatasets: false
      });
    });

    this.datasetsService.fetchAllData(
      { filters: { userId: this.props.user.id }, includes: 'metadata' }).then((response) => {
      this.setState({
        datasets: [...this.state.datasets, ...response.map((dataset) => {
          const metadata = dataset.metadata[0];
          return ({
            id: dataset.id,
            type: dataset.type,
            provider: dataset.provider,
            tableName: dataset.tableName,
            label: metadata && metadata.attributes.info
              ? metadata.attributes.info.name
              : dataset.name,
            value: dataset.id
          });
        })],
        loadingUserDatasets: false
      });
    });
  }

  @Autobind
  handleChange(value) {
    const newWidgetObj = Object.assign({}, this.state.widget, value);
    this.setState({ widget: newWidgetObj });

    if (Object.keys(value).indexOf('name') !== -1) {
      this.props.setTitle(value.name);
    }
  }

  @Autobind
  handleDatasetSelected(value) {
    this.setState({
      selectedDataset: value
    });
  }

  render() {
    const {
      loading,
      widget,
      submitting,
      datasets,
      selectedDataset,
      loadingUserDatasets,
      loadingPublishedDatasets
    } = this.state;
    const { widgetEditor } = this.props;

    return (

        <Spinner
          className="-light"
          isLoading={loading || loadingPublishedDatasets || loadingUserDatasets}
        />
        {datasets &&

            <Field
              onChange={this.handleDatasetSelected}
              className="-fluid"
              options={datasets}
              properties={{
                name: 'dataset',
                label: 'Dataset',
                value: selectedDataset,
                default: selectedDataset,
                required: true,
                instanceId: 'selectDataset'
              }}
            >
              {Select}
            </Field>

        }
        {selectedDataset &&

          <WidgetEditor
            widget={widget}
            dataset={selectedDataset}
            mode="widget"
            onUpdateWidget={this.onSubmit}
            showSaveButton
          />

            <form className="form-container" onSubmit={this.onSubmit}>
              <fieldset className="c-field-container">
                <Field
                  ref={(c) => { if (c) FORM_ELEMENTS.elements.title = c; }}
                  onChange={value => this.handleChange({ name: value })}
                  validations={['required']}
                  properties={{
                    title: 'title',
                    label: 'Title',
                    type: 'text',
                    required: true,
                    default: widgetEditor.title || '',
                    value: widgetEditor.title || '',
                    placeholder: 'Widget title'
                  }}
                >
                  {Input}
                </Field>
                <Field
                  ref={(c) => { if (c) FORM_ELEMENTS.elements.description = c; }}
                  onChange={value => this.handleChange({ description: value })}
                  properties={{
                    title: 'description',
                    label: 'Description',
                    type: 'text',
                    placeholder: 'Widget description'
                  }}
                >
                  {Input}
                </Field>
                <Field
                  ref={(c) => { if (c) FORM_ELEMENTS.elements.authors = c; }}
                  onChange={value => this.handleChange({ authors: value })}
                  properties={{
                    title: 'authors',
                    label: 'Authors',
                    type: 'text',
                    placeholder: 'Author name'
                  }}
                >
                  {Input}
                </Field>

                  <Field
                    ref={(c) => { if (c) FORM_ELEMENTS.elements.source = c; }}
                    onChange={value => this.handleChange({ source: value })}
                    properties={{
                      title: 'source',
                      label: 'Source name',
                      type: 'text',
                      placeholder: 'Source name'
                    }}
                  >
                    {Input}
                  </Field>
                  <Field
                    ref={(c) => { if (c) FORM_ELEMENTS.elements.sourceUrl = c; }}
                    onChange={value => this.handleChange({ sourceUrl: value })}
                    properties={{
                      title: 'sourceUrl',
                      label: 'Source URL',
                      type: 'text',
                      placeholder: 'Paste a URL here'
                    }}
                  >
                    {Input}
                  </Field>

              </fieldset>

                <Button
                  properties={{
                    type: 'submit',
                    disabled: submitting,
                    className: '-a'
                  }}
                >
                  Save
                </Button>

            </form>

        }

    );
  }
}

WidgetsNew.propTypes = {
  dataset: PropTypes.string,
  // Store
  user: PropTypes.object.isRequired,
  widgetEditor: PropTypes.object.isRequired,
  setTitle: PropTypes.func.isRequired,
  locale: PropTypes.string.isRequired
};

const mapStateToProps = state => ({
  user: state.user,
  widgetEditor: state.widgetEditor,
  locale: state.common.locale
});

const mapDispatchToProps = dispatch => ({
  setTitle: title => dispatch(setTitle(title))
});

export default connect(mapStateToProps, mapDispatchToProps)(WidgetsNew);
<|endoftext|>


<commit_before>var BackEndMessaging = (function () {

    function sendMessage(message, onResponse) {
        var msg = MessagePassing.PrepareMessage(message);
        chrome.runtime.sendMessage(msg, onResponse);
    }

    function shouldProcess(message) {
        return message.to == MessagePassing.Destinations.BACK;
    }

    return {

        handleMessage: function (rawMessage, sender, sendResponse) {

            debug("BackEndMessaging handleMessage");

            // make sure we should process this message
            if (!shouldProcess(rawMessage)) {
                debug("We should not process this message:", rawMessage);
                return;
            }

            debug("We should process this message:", rawMessage);

            var message = MessagePassing.ParseMessage(rawMessage);

            /** @var message MessagePassing */
            switch (message.type) {
                case MessagePassing.MessageTypes.NEW_DATA_CREATED:
                    debug("Received a message of type NEW_DATA_CREATED: ", message);

                    var appController = ApplicationController.getInstance();
                    appController.newDataCreated(message.content);

                    break;
                case MessagePassing.MessageTypes.OPENED_WINDOW:
                    var appController = ApplicationController.getInstance();
                    appController.appStarted();
                    break;
                case MessagePassing.MessageTypes.CLOSING_WINDOW:
                    debug("Received a message of type CLOSING_WINDOW", message);

                    var appController = ApplicationController.getInstance();
                    appController.appClosed();
                    break;
                case MessagePassing.MessageTypes.PRINT_PEER_LIST:
                    debug("Received a message to print the peer list");
                    var c = Context.getInstance();
                    c.printPeerList();
                    break;
                case MessagePassing.MessageTypes.PERFORM_DIRECT_REPLICATION_REQUEST:
                    debug("Received a message to perform direct replication");
                    var c = Context.getInstance();
                    var peers = c.getAllPeers();
                    if (peers.length > 0) {
                        log("Sending direct replication request to peer ["+peers[0].getReplicaIdentityString()+"] at "+ peers[0].getIpAddress());
                        ReplicationController.SendDirectReplicationRequest(peers[0]);
                    } else {
                        log("NOT Sending direct replication request because we don't have enough peers.");
                    }
                    break;
                default:
                    debug("Received message that should not handle [" + message.type + "]: ", message);
            }

        },

        sendMessage: function (message, onResponse) {
            return sendMessage(message, onResponse);
        }

    };
})();
<commit_msg>Adding support for new_cell_value message type. The frontend can now set new values to the cells :)<commit_after>var BackEndMessaging = (function () {

    function sendMessage(message, onResponse) {
        var msg = MessagePassing.PrepareMessage(message);
        chrome.runtime.sendMessage(msg, onResponse);
    }

    function shouldProcess(message) {
        return message.to == MessagePassing.Destinations.BACK;
    }

    return {

        handleMessage: function (rawMessage, sender, sendResponse) {

            debug("BackEndMessaging handleMessage");

            // make sure we should process this message
            if (!shouldProcess(rawMessage)) {
                debug("We should not process this message:", rawMessage);
                return;
            }

            debug("We should process this message:", rawMessage);

            var message = MessagePassing.ParseMessage(rawMessage);

            /** @var message MessagePassing */
            switch (message.type) {
                case MessagePassing.MessageTypes.NEW_DATA_CREATED:
                    debug("Received a message of type NEW_DATA_CREATED: ", message);

                    var appController = ApplicationController.getInstance();
                    appController.newDataCreated(message.content);

                    break;
                case MessagePassing.MessageTypes.OPENED_WINDOW:
                    var appController = ApplicationController.getInstance();
                    appController.appStarted();
                    break;
                case MessagePassing.MessageTypes.CLOSING_WINDOW:
                    debug("Received a message of type CLOSING_WINDOW", message);

                    var appController = ApplicationController.getInstance();
                    appController.appClosed();
                    break;
                case MessagePassing.MessageTypes.PRINT_PEER_LIST:
                    debug("Received a message to print the peer list");
                    var c = Context.getInstance();
                    c.printPeerList();
                    break;
                case MessagePassing.MessageTypes.PERFORM_DIRECT_REPLICATION_REQUEST:
                    debug("Received a message to perform direct replication");
                    var c = Context.getInstance();
                    var peers = c.getAllPeers();
                    if (peers.length > 0) {
                        log("Sending direct replication request to peer ["+peers[0].getReplicaIdentityString()+"] at "+ peers[0].getIpAddress());
                        ReplicationController.SendDirectReplicationRequest(peers[0]);
                    } else {
                        log("NOT Sending direct replication request because we don't have enough peers.");
                    }
                    break;
                case MessagePassing.MessageTypes.NEW_CELL_VALUE:
                        debug("Received a message with a new cell value");
                        var appController = ApplicationController.getInstance();
                        var content = message.content;
                        appController.updatedCellValue(content.row, content.col, content.value);
                    break;
                default:
                    debug("Received message that should not handle [" + message.type + "]: ", message);
            }

        },

        sendMessage: function (message, onResponse) {
            return sendMessage(message, onResponse);
        }

    };
})();
<|endoftext|>


<commit_before>var assert = require("assert");
var path = require("path");
var Promise = require("promise");
var promisify = require("promisify-node");
var rimraf = promisify("rimraf");

describe("Clone", function() {
  var http = path.resolve("test/repos/http");
  var https = path.resolve("test/repos/https");
  var ssh = path.resolve("test/repos/ssh");
  var git = path.resolve("test/repos/git");
  var file = path.resolve("test/repos/file");

  var Repository = require("../../lib/repository");
  var Clone = require("../../lib/clone");
  var NodeGit = require("../../");

  before(function() {
    return Promise.all([
      rimraf(http),
      rimraf(https),
      rimraf(ssh),
      rimraf(git),
      rimraf(file),
    ]);
  });

  it("can clone with http", function() {
    var url = "http://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, http, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with https", function() {
    var url = "https://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, https, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with ssh", function() {
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      ignoreCertErrors: 1,
      remoteCallbacks: {
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyFromAgent(userName);
        }
      }
    };

    return Clone.clone(url, ssh, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with git", function() {
    var url = "git://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, git, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with filesystem", function() {
    var prefix = process.platform === "win32" ? "" : "file://";
    var url = prefix + path.resolve("test/repos/empty");

    return Clone.clone(url, file).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });
});
<commit_msg>Skip ssh test in Windows until we figure out how<commit_after>var assert = require("assert");
var path = require("path");
var Promise = require("promise");
var promisify = require("promisify-node");
var rimraf = promisify("rimraf");

describe("Clone", function() {
  var http = path.resolve("test/repos/http");
  var https = path.resolve("test/repos/https");
  var ssh = path.resolve("test/repos/ssh");
  var git = path.resolve("test/repos/git");
  var file = path.resolve("test/repos/file");

  var Repository = require("../../lib/repository");
  var Clone = require("../../lib/clone");
  var NodeGit = require("../../");

  before(function() {
    return Promise.all([
      rimraf(http),
      rimraf(https),
      rimraf(ssh),
      rimraf(git),
      rimraf(file),
    ]);
  });

  it("can clone with http", function() {
    var url = "http://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, http, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with https", function() {
    var url = "https://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, https, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  // FIXME: Anyone know how to start and use ssh-agent in Windows?
  var testSsh = process.platform === "win32" ? it.skip : it;

  testSsh("can clone with ssh", function() {
    var url = "git@github.com:nodegit/test.git";
    var opts = {
      ignoreCertErrors: 1,
      remoteCallbacks: {
        credentials: function(url, userName) {
          return NodeGit.Cred.sshKeyFromAgent(userName);
        }
      }
    };

    return Clone.clone(url, ssh, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with git", function() {
    var url = "git://github.com/nodegit/test.git";
    var opts = { ignoreCertErrors: 1 };

    return Clone.clone(url, git, opts).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });

  it("can clone with filesystem", function() {
    var prefix = process.platform === "win32" ? "" : "file://";
    var url = prefix + path.resolve("test/repos/empty");

    return Clone.clone(url, file).then(function(repository) {
      assert.ok(repository instanceof Repository);
    });
  });
});
<|endoftext|>