<commit_before>/**
 * Each section of the site has its own module. It probably also has
 * submodules, though this boilerplate is too simple to demonstrate it. Within
 * `src/app/home`, however, could exist several additional folders representing
 * additional modules that would then be listed as dependencies of this one.
 * For example, a `note` section could have the submodules `note.create`,
 * `note.delete`, `note.edit`, etc.
 *
 * Regardless, so long as dependencies are managed correctly, the build process
 * will automatically take take of the rest.
 *
 * The dependencies block here is also where component dependencies should be
 * specified, as shown below.
 */

angular.module( 'App.list', [
  'ui.router',
  'ngProgress',
  'ngAnimate',
  'ui.bootstrap',
  'ui.bootstrap.tpls',
  'flow'
])

/**
 * Filters
 */
.filter('classicDate', function() {
  return function(date) {
    date = (date<10000000000)?date*1000:date;
    return moment(date).format('YYYY-MM-DD, h:mm:ss a');
  };
})

.filter('fromNow', function() {
  return function(date) {
    date = (date<10000000000)?date*1000:date;
    return moment(date).fromNow();
  };
})

.filter('fileSize', function() {
  return function(bytes) {
    return humanFileSize(bytes);
  };
})

/**
 * Each section or module of the site can also have its own routes. AngularJS
 * will handle ensuring they are all available at run-time, but splitting it
 * this way makes each module more "self-contained".
 */
.config(function ViewConfig( $stateProvider ) {
  $stateProvider.state( 'list', {
    url: '/list/{path:.*}',
    views: {
      "main": {
        controller: 'ListCtrl',
        templateUrl: 'list/list.tpl.html'
      }
    },
    data:{ pageTitle: 'Listing resources' }
  });
})

.config(['flowFactoryProvider', function (flowFactoryProvider) {
  flowFactoryProvider.defaults = {
    permanentErrors: [404, 500, 501],
    maxChunkRetries: 1,
    chunkRetryInterval: 5000,
    simultaneousUploads: 4
  };
  flowFactoryProvider.on('catchAll', function (event) {
    console.log('catchAll', arguments);
  });
  // Can be used with different implementations of Flow.js
  // flowFactoryProvider.factory = fustyFlowFactory;
}])

/**
 * And of course we define a controller for our route.
 */
.controller( 'ListCtrl', function ListController( $scope, $http, $location, $modal, $sce, $stateParams, ngProgress ) {
  $scope.hideMenu = function() {
    $scope.$parent.showMenu = false;
  };

  // variables
  $scope.schema = '';
  $scope.resources = [];
  $scope.listLocation = true;
  $scope.breadCrumbs = [];

  // var storage = $scope.$parent.userProfile.storagespace;
  // $scope.schema = (storage !== undefined)?storage.slice(0, storage.indexOf('://')):$location.$$protocol;
  // $scope.path = $stateParams.path;

  $scope.prepareList = function(url) {
    if (url && url.length > 0) {
      $scope.listLocation = true;
      $location.path('/list/'+stripSchema(url));
    } else {
      $scope.listLocation = false;
      notify('Warning', 'Please provide a URL');
    }
  };

  // TODO: rdflib fetch does not respond properly to 404
  $scope.listDir = function (url) {
    console.log("Requested path: "+url); // debug
    var elms = url.split("/");
    var schema = '';
    var path = '';
    if (elms[0].substring(0, 4) == 'http') {
      schema = elms[0];
      elms.splice(0,1);
    } else {
      schema = 'https';
    }
    $scope.path = schema+'://';
    console.log("So far: "+$scope.path);

    for (i=0; i<elms.length; i++) {
      if (elms[i].length > 0) {
        path = (i===0)?elms[0]+'/':path+elms[i]+'/';
        var dir = {
          uri: '#/list/'+schema+'/'+path,
          name: elms[i]
        };

        $scope.breadCrumbs.push(dir);
      }
    }
    $scope.path += path;

    // start progress bar
    ngProgress.reset();
    ngProgress.start();

    var RDF = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
    var RDFS = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
    var LDP = $rdf.Namespace("http://www.w3.org/ns/ldp#");
    var POSIX = $rdf.Namespace("http://www.w3.org/ns/posix/stat#");

    var g = $rdf.graph();
    var f = $rdf.fetcher(g, TIMEOUT);
    // add CORS proxy
    $rdf.Fetcher.crossSiteProxyTemplate=PROXY;

    // fetch user data
    f.nowOrWhenFetched($scope.path,undefined,function(ok, body) {
      if (!ok) {
        notify('Error', 'Could not fetch dir listing.');
        ngProgress.complete();
        $scope.listLocation = false;

        console.log(ok);
        console.log(body);
      } else {
        $scope.listLocation = true;
      }
      $scope.$apply();

      var dirs = g.statementsMatching(undefined, RDF("type"), POSIX("Directory"));
      for ( var i in dirs ) {
        if ( dirs[i].subject.uri.split('://')[1].split('/').length <= 2 ) {
          continue;
        }
        var d = {};
        if ( dirs[i].subject.uri == $scope.path ) {
          d = {
            uri: dirs[i].subject.uri,
            path: dirname(document.location.href)+'/',
            type: '-',
            name: '../',
            mtime: g.any(dirs[i].subject, POSIX("mtime")).value,
            size: '-'
          };
        } else {
          var base = (document.location.href.charAt(document.location.href.length - 1) === '/')?document.location.href:document.location.href+'/';
          d = {
            uri: dirs[i].subject.uri,
            path: base+basename(dirs[i].subject.uri)+'/',
            type: 'Directory',
            name: basename(dirs[i].subject.value),
            mtime: g.any(dirs[i].subject, POSIX("mtime")).value,
            size: '-'
          };
        }
        $scope.resources.push(d);
      }
      var files = g.statementsMatching(undefined, RDF("type"), RDFS("Resource"));
      for (i in files) {
        var f = {
          uri: files[i].subject.uri,
          path: '#/view/'+stripSchema(files[i].subject.uri),
          type: 'File', // TODO: use the real type
          name: basename(files[i].subject.value),
          mtime: g.any(files[i].subject, POSIX("mtime")).value,
          size: g.any(files[i].subject, POSIX("size")).value
        };
        $scope.resources.push(f);
        $scope.$apply();
      }
      console.log($scope.resources);
      ngProgress.complete();
      $scope.$apply();
    });
  };

  $scope.upload = function () {
    console.log("Uploading files");
    console.log($flow.files);
  };

  $scope.newDir = function(dirName) {
    $http({
      method: 'POST',
      url: $scope.path,
      data: '',
      headers: {
        'Content-Type': 'text/turtle',
        'Link': '<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"',
        'Slug': dirName
      },
      withCredentials: true
    }).
    success(function(data, status) {
      if (status == 200 || status == 201) {
        notify('Success', 'Directory created.');
        // add dir to local list
        var now = new Date().getTime();
        var base = (document.location.href.charAt(document.location.href.length - 1) === '/')?document.location.href:document.location.href+'/';
        var d = {
            uri: $scope.path+dirName,
            path: base+basename($scope.path+dirName)+'/',
            type: 'Directory',
            name: dirName,
            mtime: now,
            size: '-'
          };
        console.log(d);
        $scope.resources.push(d);
      }
    }).
    error(function(data, status) {
      if (status == 401) {
        notify('Forbidden', 'Authentication required to create new directory.');
      } else if (status == 403) {
        notify('Forbidden', 'Insufficient permissions to create new directory.');
      } else {
        notify('Failed'+status, data);
      }
    });
  };

  $scope.newFile = function(fileName) {
    $http({
      method: 'PUT',
      url: $scope.path+fileName,
      data: '',
      headers: {
        'Content-Type': 'text/turtle',
        'Link': '<http://www.w3.org/ns/ldp#Resource>; rel="type"'
      },
      withCredentials: true
    }).
    success(function(data, status, headers) {
      if (status == 200 || status == 201) {
        notify('Success', 'Resource created.');
        // Add resource to the list
        var res = headers('Location');
        var f = {
          uri: res,
          path: '#/view/'+stripSchema(res),
          type: 'File', // TODO: use the real type
          name: basename(res),
          mtime: moment().fromNow(),
          size: '-'
        };
        // TODO Refresh the view
        $scope.resources.push(f);
        // Add

      }
    }).
    error(function(data, status) {
      if (status == 401) {
        notify('Forbidden', 'Authentication required to create new resource.');
      } else if (status == 403) {
        notify('Forbidden', 'Insufficient permissions to create new resource.');
      } else {
        notify('Failed'+status, data);
      }
    });
  };

  $scope.refreshResource = function(uri) {
    // TODO
  };

  $scope.deleteResource = function(resourceUri) {
    $http({
      method: 'DELETE',
      url: resourceUri,
      withCredentials: true
    }).
    success(function(data, status) {
      if (status == 200 || status == 201) {
        notify('Success', basename(resourceUri)+' was deleted.');
        $scope.removeResource(resourceUri);
      }
    }).
    error(function(data, status) {
      if (status == 401) {
        notify('Forbidden', 'Authentication required to delete resource.');
      } else if (status == 403) {
        notify('Forbidden', 'Insufficient permissions to delete resource.');
      } else if (status == 409) {
        notify('Failed', 'Conflict detected. In case of directory, check if not empty.');
      } else {
        notify('Failed'+status, data);
      }
    });
  };

  $scope.removeResource = function(uri) {
    if ($scope.resources) {
      for(var i = $scope.resources.length - 1; i >= 0; i--){
        if($scope.resources[i].uri == uri){
            $scope.resources.splice(i,1);
        }
      }
    }
  };

  // New dir dialog
  $scope.openNewDir = function () {
    var modalInstance = $modal.open({
      templateUrl: 'newdir.html',
      controller: ModalNewDirCtrl,
      size: 'sm'
    });
    modalInstance.result.then($scope.newDir);
  };
  // New file creation dialog
  $scope.openNewFile = function () {
    var modalInstance = $modal.open({
      templateUrl: 'newfile.html',
      controller: ModalNewFileCtrl,
      size: 'sm'
    });
    modalInstance.result.then($scope.newFile);
  };
  // Remove resource dialog
  $scope.openDelete = function (uri) {
    console.log("Calling openDelete for "+uri);
    var modalInstance = $modal.open({
      templateUrl: 'delete.html',
      controller: ModalDeleteCtrl,
      size: 'sm',
      resolve: {
        delUri: function () {
          return uri;
        }
      }
    });
    modalInstance.result.then($scope.deleteResource);
  };
  // New file upload dialog
  $scope.openNewUpload = function () {
    var modalInstance = $modal.open({
      templateUrl: 'uploadfiles.html',
      controller: ModalUploadCtrl,
      size: 'sm'
    });
  };

  // Display list for current path
  if ($stateParams.path.length > 0) {
    $scope.listDir($stateParams.path);
  } else {
    $scope.listLocation = false;
  }
 });

// Modal Ctrls
var ModalNewDirCtrl = function ($scope, $modalInstance) {
  $scope.newDir = function(dirName) {
    $modalInstance.close(dirName);
  };

  $scope.ok = function () {
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};

var ModalNewFileCtrl = function ($scope, $modalInstance) {
  // TODO
  // $scope.expr = "/^[A-Za-z0-9_-(\.)]*$/";

  $scope.newFile = function(fileName) {
    $modalInstance.close(fileName);
  };

  $scope.ok = function () {
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};

var ModalDeleteCtrl = function ($scope, $modalInstance, delUri) {
  $scope.delUri = delUri;

  $scope.deleteResource = function() {
    $modalInstance.close($scope.delUri);
  };

  $scope.ok = function () {
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };

};<commit_msg>Trimming whitespaces when creating new resources.<commit_after>/**
 * Each section of the site has its own module. It probably also has
 * submodules, though this boilerplate is too simple to demonstrate it. Within
 * `src/app/home`, however, could exist several additional folders representing
 * additional modules that would then be listed as dependencies of this one.
 * For example, a `note` section could have the submodules `note.create`,
 * `note.delete`, `note.edit`, etc.
 *
 * Regardless, so long as dependencies are managed correctly, the build process
 * will automatically take take of the rest.
 *
 * The dependencies block here is also where component dependencies should be
 * specified, as shown below.
 */

angular.module( 'App.list', [
  'ui.router',
  'ngProgress',
  'ngAnimate',
  'ui.bootstrap',
  'ui.bootstrap.tpls',
  'flow'
])

/**
 * Filters
 */
.filter('classicDate', function() {
  return function(date) {
    date = (date<10000000000)?date*1000:date;
    return moment(date).format('YYYY-MM-DD, h:mm:ss a');
  };
})

.filter('fromNow', function() {
  return function(date) {
    date = (date<10000000000)?date*1000:date;
    return moment(date).fromNow();
  };
})

.filter('fileSize', function() {
  return function(bytes) {
    return humanFileSize(bytes);
  };
})

/**
 * Each section or module of the site can also have its own routes. AngularJS
 * will handle ensuring they are all available at run-time, but splitting it
 * this way makes each module more "self-contained".
 */
.config(function ViewConfig( $stateProvider ) {
  $stateProvider.state( 'list', {
    url: '/list/{path:.*}',
    views: {
      "main": {
        controller: 'ListCtrl',
        templateUrl: 'list/list.tpl.html'
      }
    },
    data:{ pageTitle: 'Listing resources' }
  });
})

.config(['flowFactoryProvider', function (flowFactoryProvider) {
  flowFactoryProvider.defaults = {
    permanentErrors: [404, 500, 501],
    maxChunkRetries: 1,
    chunkRetryInterval: 5000,
    simultaneousUploads: 4
  };
  flowFactoryProvider.on('catchAll', function (event) {
    console.log('catchAll', arguments);
  });
  // Can be used with different implementations of Flow.js
  // flowFactoryProvider.factory = fustyFlowFactory;
}])

/**
 * And of course we define a controller for our route.
 */
.controller( 'ListCtrl', function ListController( $scope, $http, $location, $modal, $sce, $stateParams, ngProgress ) {
  $scope.hideMenu = function() {
    $scope.$parent.showMenu = false;
  };

  // variables
  $scope.schema = '';
  $scope.resources = [];
  $scope.listLocation = true;
  $scope.breadCrumbs = [];

  // var storage = $scope.$parent.userProfile.storagespace;
  // $scope.schema = (storage !== undefined)?storage.slice(0, storage.indexOf('://')):$location.$$protocol;
  // $scope.path = $stateParams.path;

  $scope.prepareList = function(url) {
    if (url && url.length > 0) {
      $scope.listLocation = true;
      $location.path('/list/'+stripSchema(url));
    } else {
      $scope.listLocation = false;
      notify('Warning', 'Please provide a URL');
    }
  };

  // TODO: rdflib fetch does not respond properly to 404
  $scope.listDir = function (url) {
    console.log("Requested path: "+url); // debug
    var elms = url.split("/");
    var schema = '';
    var path = '';
    if (elms[0].substring(0, 4) == 'http') {
      schema = elms[0];
      elms.splice(0,1);
    } else {
      schema = 'https';
    }
    $scope.path = schema+'://';
    console.log("So far: "+$scope.path);

    for (i=0; i<elms.length; i++) {
      if (elms[i].length > 0) {
        path = (i===0)?elms[0]+'/':path+elms[i]+'/';
        var dir = {
          uri: '#/list/'+schema+'/'+path,
          name: elms[i]
        };

        $scope.breadCrumbs.push(dir);
      }
    }
    $scope.path += path;

    // start progress bar
    ngProgress.reset();
    ngProgress.start();

    var RDF = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
    var RDFS = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
    var LDP = $rdf.Namespace("http://www.w3.org/ns/ldp#");
    var POSIX = $rdf.Namespace("http://www.w3.org/ns/posix/stat#");

    var g = $rdf.graph();
    var f = $rdf.fetcher(g, TIMEOUT);
    // add CORS proxy
    $rdf.Fetcher.crossSiteProxyTemplate=PROXY;

    // fetch user data
    f.nowOrWhenFetched($scope.path,undefined,function(ok, body) {
      if (!ok) {
        notify('Error', 'Could not fetch dir listing.');
        ngProgress.complete();
        $scope.listLocation = false;

        console.log(ok);
        console.log(body);
      } else {
        $scope.listLocation = true;
      }
      $scope.$apply();

      var dirs = g.statementsMatching(undefined, RDF("type"), POSIX("Directory"));
      for ( var i in dirs ) {
        if ( dirs[i].subject.uri.split('://')[1].split('/').length <= 2 ) {
          continue;
        }
        var d = {};
        if ( dirs[i].subject.uri == $scope.path ) {
          d = {
            uri: dirs[i].subject.uri,
            path: dirname(document.location.href)+'/',
            type: '-',
            name: '../',
            mtime: g.any(dirs[i].subject, POSIX("mtime")).value,
            size: '-'
          };
        } else {
          var base = (document.location.href.charAt(document.location.href.length - 1) === '/')?document.location.href:document.location.href+'/';
          d = {
            uri: dirs[i].subject.uri,
            path: base+basename(dirs[i].subject.uri)+'/',
            type: 'Directory',
            name: basename(dirs[i].subject.value),
            mtime: g.any(dirs[i].subject, POSIX("mtime")).value,
            size: '-'
          };
        }
        $scope.resources.push(d);
      }
      var files = g.statementsMatching(undefined, RDF("type"), RDFS("Resource"));
      for (i in files) {
        var f = {
          uri: files[i].subject.uri,
          path: '#/view/'+stripSchema(files[i].subject.uri),
          type: 'File', // TODO: use the real type
          name: basename(files[i].subject.value),
          mtime: g.any(files[i].subject, POSIX("mtime")).value,
          size: g.any(files[i].subject, POSIX("size")).value
        };
        $scope.resources.push(f);
        $scope.$apply();
      }
      console.log($scope.resources);
      ngProgress.complete();
      $scope.$apply();
    });
  };

  $scope.upload = function () {
    console.log("Uploading files");
    console.log($flow.files);
  };

  $scope.newDir = function(dirName) {
    // trim whitespaces
    dirName = dirName.replace(/^\s+|\s+$/g, "");
    $http({
      method: 'PUT',
      url: $scope.path+dirName,
      data: '',
      headers: {
        'Content-Type': 'text/turtle',
        'Link': '<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'
      },
      withCredentials: true
    }).
    success(function(data, status) {
      if (status == 200 || status == 201) {
        notify('Success', 'Directory created.');
        // add dir to local list
        var now = new Date().getTime();
        var base = (document.location.href.charAt(document.location.href.length - 1) === '/')?document.location.href:document.location.href+'/';
        var d = {
            uri: $scope.path+dirName,
            path: base+basename($scope.path+dirName)+'/',
            type: 'Directory',
            name: dirName,
            mtime: now,
            size: '-'
          };
        console.log(d);
        $scope.resources.push(d);
      }
    }).
    error(function(data, status) {
      if (status == 401) {
        notify('Forbidden', 'Authentication required to create new directory.');
      } else if (status == 403) {
        notify('Forbidden', 'Insufficient permissions to create new directory.');
      } else {
        notify('Failed'+status, data);
      }
    });
  };

  $scope.newFile = function(fileName) {
    // trim whitespaces
    fileName = fileName.replace(/^\s+|\s+$/g, "");
    $http({
      method: 'PUT',
      url: $scope.path+fileName,
      data: '',
      headers: {
        'Content-Type': 'text/turtle',
        'Link': '<http://www.w3.org/ns/ldp#Resource>; rel="type"'
      },
      withCredentials: true
    }).
    success(function(data, status, headers) {
      if (status == 200 || status == 201) {
        notify('Success', 'Resource created.');
        // Add resource to the list
        var res = headers('Location');
        var f = {
          uri: res,
          path: '#/view/'+stripSchema(res),
          type: 'File', // TODO: use the real type
          name: basename(res),
          mtime: moment().fromNow(),
          size: '-'
        };
        // TODO Refresh the view
        $scope.resources.push(f);
        // Add

      }
    }).
    error(function(data, status) {
      if (status == 401) {
        notify('Forbidden', 'Authentication required to create new resource.');
      } else if (status == 403) {
        notify('Forbidden', 'Insufficient permissions to create new resource.');
      } else {
        notify('Failed'+status, data);
      }
    });
  };

  $scope.refreshResource = function(uri) {
    // TODO
  };

  $scope.deleteResource = function(resourceUri) {
    $http({
      method: 'DELETE',
      url: resourceUri,
      withCredentials: true
    }).
    success(function(data, status) {
      if (status == 200 || status == 201) {
        notify('Success', basename(resourceUri)+' was deleted.');
        $scope.removeResource(resourceUri);
      }
    }).
    error(function(data, status) {
      if (status == 401) {
        notify('Forbidden', 'Authentication required to delete resource.');
      } else if (status == 403) {
        notify('Forbidden', 'Insufficient permissions to delete resource.');
      } else if (status == 409) {
        notify('Failed', 'Conflict detected. In case of directory, check if not empty.');
      } else {
        notify('Failed'+status, data);
      }
    });
  };

  $scope.removeResource = function(uri) {
    if ($scope.resources) {
      for(var i = $scope.resources.length - 1; i >= 0; i--){
        if($scope.resources[i].uri == uri){
            $scope.resources.splice(i,1);
        }
      }
    }
  };

  // New dir dialog
  $scope.openNewDir = function () {
    var modalInstance = $modal.open({
      templateUrl: 'newdir.html',
      controller: ModalNewDirCtrl,
      size: 'sm'
    });
    modalInstance.result.then($scope.newDir);
  };
  // New file creation dialog
  $scope.openNewFile = function () {
    var modalInstance = $modal.open({
      templateUrl: 'newfile.html',
      controller: ModalNewFileCtrl,
      size: 'sm'
    });
    modalInstance.result.then($scope.newFile);
  };
  // Remove resource dialog
  $scope.openDelete = function (uri) {
    console.log("Calling openDelete for "+uri);
    var modalInstance = $modal.open({
      templateUrl: 'delete.html',
      controller: ModalDeleteCtrl,
      size: 'sm',
      resolve: {
        delUri: function () {
          return uri;
        }
      }
    });
    modalInstance.result.then($scope.deleteResource);
  };
  // New file upload dialog
  $scope.openNewUpload = function () {
    var modalInstance = $modal.open({
      templateUrl: 'uploadfiles.html',
      controller: ModalUploadCtrl,
      size: 'sm'
    });
  };

  // Display list for current path
  if ($stateParams.path.length > 0) {
    $scope.listDir($stateParams.path);
  } else {
    $scope.listLocation = false;
  }
 });

// Modal Ctrls
var ModalNewDirCtrl = function ($scope, $modalInstance) {
  $scope.newDir = function(dirName) {
    $modalInstance.close(dirName);
  };

  $scope.ok = function () {
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};

var ModalNewFileCtrl = function ($scope, $modalInstance) {
  // TODO
  // $scope.expr = "/^[A-Za-z0-9_-(\.)]*$/";

  $scope.newFile = function(fileName) {
    $modalInstance.close(fileName);
  };

  $scope.ok = function () {
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};

var ModalDeleteCtrl = function ($scope, $modalInstance, delUri) {
  $scope.delUri = delUri;

  $scope.deleteResource = function() {
    $modalInstance.close($scope.delUri);
  };

  $scope.ok = function () {
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };

};<|endoftext|>


<commit_before>'use strict';

angular.module('kiwiWeb')
.controller('MainCtrl', function ($scope, $state, lang) {
  $scope.lang = lang.data;
  $scope.changeTitle($scope.lang.title);
  $scope.pageClass = '';
  $scope.transition = {};
  $scope.transition.baseDuration = 6;

  var sections = [
    'main.landing',
    'main.products',
    'main.residential',
    'main.business',
    'main.dedicated',
    'main.metromesh'
  ];

  $scope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {

    var fromIndex, toIndex, direction, steps;

    toIndex = sections.indexOf(toState.name);
    fromIndex = sections.indexOf(fromState.name);
    direction = toIndex > fromIndex  ? 1 : -1;

    $scope.transition.css = direction > 0 ? 'up' : 'down';
  });

});
<commit_msg>Removes transition logic from main controller.<commit_after>'use strict';

angular.module('kiwiWeb')
.controller('MainCtrl', ['$scope', '$state', 'lang', function ($scope, $state, lang) {
  $scope.lang = lang.data;
  $scope.changeTitle($scope.lang.title);
  $scope.pageClass = '';

}]);
<|endoftext|>


<commit_before>var $ = require('jquery');

module.exports = {
  tableRowItems: function (first, second, cls) {
    return $('
')
      .addClass(cls)
      .append($('
').append(first))
      .append($('
').append(second));
  },

  tableRow: function (description, data) {
    return this.tableRowItems(
      $('').text(description),
      $('<input readonly="readonly"/>').val(data));
  },

  textRow: function (description, data, cls) {
    return this.tableRowItems(
      $('').text(description),
      $('<textarea readonly="readonly" class="gethDeployText"/>').val(data),
      cls);
  },

  formatAssemblyText: function (asm, prefix, source) {
    var self = this;
    if (typeof asm === typeof '' || asm === null || asm === undefined) {
      return prefix + asm + '\n';
    }
    var text = prefix + '.code\n';
    $.each(asm['.code'], function (i, item) {
      var v = item.value === undefined ? '' : item.value;
      var src = '';
      if (item.begin !== undefined && item.end !== undefined) {
        src = source.slice(item.begin, item.end).replace('\n', '\\n', 'g');
      }
      if (src.length > 30) {
        src = src.slice(0, 30) + '...';
      }
      if (item.name !== 'tag') {
        text += '  ';
      }
      text += prefix + item.name + ' ' + v + '\t\t\t' + src + '\n';
    });
    text += prefix + '.data\n';
    if (asm['.data']) {
      $.each(asm['.data'], function (i, item) {
        text += '  ' + prefix + '' + i + ':\n';
        text += self.formatAssemblyText(item, prefix + '    ', source);
      });
    }
    return text;
  },

  gethDeploy: function (contractName, jsonInterface, bytecode) {
    var code = '';
    var funABI = this.getConstructorInterface(JSON.parse(jsonInterface));

    funABI.inputs.forEach(function (inp) {
      code += 'var ' + inp.name + ' = /* var of type ' + inp.type + ' here */ ;\n';
    });

    code += 'var ' + contractName + 'Contract = web3.eth.contract(' + jsonInterface.replace('\n', '') + ');' +
      '\nvar ' + contractName + ' = ' + contractName + 'Contract.new(';

    funABI.inputs.forEach(function (inp) {
      code += '\n   ' + inp.name + ',';
    });

    code += '\n   {' +
      '\n     from: web3.eth.accounts[0], ' +
      "\n     data: '" + bytecode + "', " +
      '\n     gas: 4700000' +
      '\n   }, function (e, contract){' +
      '\n    console.log(e, contract);' +
      "\n    if (typeof contract.address !== 'undefined') {" +
      "\n         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);" +
      '\n    }' +
      '\n })';

    return code;
  },

  getConstructorInterface: function (abi) {
    var funABI = { 'name': '', 'inputs': [], 'type': 'constructor', 'outputs': [] };
    for (var i = 0; i < abi.length; i++) {
      if (abi[i].type === 'constructor') {
        funABI.inputs = abi[i].inputs || [];
        break;
      }
    }
    return funABI;
  },

  formatGasEstimates: function (data) {
    // FIXME: the whole gasEstimates object should be nil instead
    if (data.creation === undefined && data.external === undefined && data.internal === undefined) {
      return;
    }
    var gasToText = function (g) { return g === null ? 'unknown' : g; };
    var text = '';
    var fun;
    if ('creation' in data) {
      text += 'Creation: ' + gasToText(data.creation[0]) + ' + ' + gasToText(data.creation[1]) + '\n';
    }

    if ('external' in data) {
      text += 'External:\n';
      for (fun in data.external) {
        text += '  ' + fun + ': ' + gasToText(data.external[fun]) + '\n';
      }
    }

    if ('internal' in data) {
      text += 'Internal:\n';
      for (fun in data.internal) {
        text += '  ' + fun + ': ' + gasToText(data.internal[fun]) + '\n';
      }
    }
    return text;
  },

  detailsOpen: {},
  getDetails: function (contract, source, contractName) {
    var button = $('<button>Toggle Details</button>');
    var details = $('
')
      .append(this.tableRow('Solidity Interface', contract.solidity_interface));

    if (contract.opcodes !== '') {
      details.append(this.tableRow('Opcodes', contract.opcodes));
    }

    var funHashes = '';
    for (var fun in contract.functionHashes) {
      funHashes += contract.functionHashes[fun] + ' ' + fun + '\n';
    }
    details.append($('Functions'));
    details.append($('
').text(funHashes));

    var gasEstimates = this.formatGasEstimates(contract.gasEstimates);
    if (gasEstimates) {
      details.append($('Gas Estimates'));
      details.append($('
').text(gasEstimates));
    }

    if (contract.runtimeBytecode && contract.runtimeBytecode.length > 0) {
      details.append(this.tableRow('Runtime Bytecode', contract.runtimeBytecode));
    }

    if (contract.assembly !== null) {
      details.append($('Assembly'));
      var assembly = $('
').text(this.formatAssemblyText(contract.assembly, '', source));
      details.append(assembly);
    }

    var self = this;
    button.click(function () { self.detailsOpen[contractName] = !self.detailsOpen[contractName]; details.toggle(); });
    if (this.detailsOpen[contractName]) {
      details.show();
    }
    return $('
').append(button).append(details);
  }
};
<commit_msg>Remove Solidity Interface from the output<commit_after>var $ = require('jquery');

module.exports = {
  tableRowItems: function (first, second, cls) {
    return $('
')
      .addClass(cls)
      .append($('
').append(first))
      .append($('
').append(second));
  },

  tableRow: function (description, data) {
    return this.tableRowItems(
      $('').text(description),
      $('<input readonly="readonly"/>').val(data));
  },

  textRow: function (description, data, cls) {
    return this.tableRowItems(
      $('').text(description),
      $('<textarea readonly="readonly" class="gethDeployText"/>').val(data),
      cls);
  },

  formatAssemblyText: function (asm, prefix, source) {
    var self = this;
    if (typeof asm === typeof '' || asm === null || asm === undefined) {
      return prefix + asm + '\n';
    }
    var text = prefix + '.code\n';
    $.each(asm['.code'], function (i, item) {
      var v = item.value === undefined ? '' : item.value;
      var src = '';
      if (item.begin !== undefined && item.end !== undefined) {
        src = source.slice(item.begin, item.end).replace('\n', '\\n', 'g');
      }
      if (src.length > 30) {
        src = src.slice(0, 30) + '...';
      }
      if (item.name !== 'tag') {
        text += '  ';
      }
      text += prefix + item.name + ' ' + v + '\t\t\t' + src + '\n';
    });
    text += prefix + '.data\n';
    if (asm['.data']) {
      $.each(asm['.data'], function (i, item) {
        text += '  ' + prefix + '' + i + ':\n';
        text += self.formatAssemblyText(item, prefix + '    ', source);
      });
    }
    return text;
  },

  gethDeploy: function (contractName, jsonInterface, bytecode) {
    var code = '';
    var funABI = this.getConstructorInterface(JSON.parse(jsonInterface));

    funABI.inputs.forEach(function (inp) {
      code += 'var ' + inp.name + ' = /* var of type ' + inp.type + ' here */ ;\n';
    });

    code += 'var ' + contractName + 'Contract = web3.eth.contract(' + jsonInterface.replace('\n', '') + ');' +
      '\nvar ' + contractName + ' = ' + contractName + 'Contract.new(';

    funABI.inputs.forEach(function (inp) {
      code += '\n   ' + inp.name + ',';
    });

    code += '\n   {' +
      '\n     from: web3.eth.accounts[0], ' +
      "\n     data: '" + bytecode + "', " +
      '\n     gas: 4700000' +
      '\n   }, function (e, contract){' +
      '\n    console.log(e, contract);' +
      "\n    if (typeof contract.address !== 'undefined') {" +
      "\n         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);" +
      '\n    }' +
      '\n })';

    return code;
  },

  getConstructorInterface: function (abi) {
    var funABI = { 'name': '', 'inputs': [], 'type': 'constructor', 'outputs': [] };
    for (var i = 0; i < abi.length; i++) {
      if (abi[i].type === 'constructor') {
        funABI.inputs = abi[i].inputs || [];
        break;
      }
    }
    return funABI;
  },

  formatGasEstimates: function (data) {
    // FIXME: the whole gasEstimates object should be nil instead
    if (data.creation === undefined && data.external === undefined && data.internal === undefined) {
      return;
    }
    var gasToText = function (g) { return g === null ? 'unknown' : g; };
    var text = '';
    var fun;
    if ('creation' in data) {
      text += 'Creation: ' + gasToText(data.creation[0]) + ' + ' + gasToText(data.creation[1]) + '\n';
    }

    if ('external' in data) {
      text += 'External:\n';
      for (fun in data.external) {
        text += '  ' + fun + ': ' + gasToText(data.external[fun]) + '\n';
      }
    }

    if ('internal' in data) {
      text += 'Internal:\n';
      for (fun in data.internal) {
        text += '  ' + fun + ': ' + gasToText(data.internal[fun]) + '\n';
      }
    }
    return text;
  },

  detailsOpen: {},
  getDetails: function (contract, source, contractName) {
    var button = $('<button>Toggle Details</button>');
    var details = $('
');

    if (contract.opcodes !== '') {
      details.append(this.tableRow('Opcodes', contract.opcodes));
    }

    var funHashes = '';
    for (var fun in contract.functionHashes) {
      funHashes += contract.functionHashes[fun] + ' ' + fun + '\n';
    }
    details.append($('Functions'));
    details.append($('
').text(funHashes));

    var gasEstimates = this.formatGasEstimates(contract.gasEstimates);
    if (gasEstimates) {
      details.append($('Gas Estimates'));
      details.append($('
').text(gasEstimates));
    }

    if (contract.runtimeBytecode && contract.runtimeBytecode.length > 0) {
      details.append(this.tableRow('Runtime Bytecode', contract.runtimeBytecode));
    }

    if (contract.assembly !== null) {
      details.append($('Assembly'));
      var assembly = $('
').text(this.formatAssemblyText(contract.assembly, '', source));
      details.append(assembly);
    }

    var self = this;
    button.click(function () { self.detailsOpen[contractName] = !self.detailsOpen[contractName]; details.toggle(); });
    if (this.detailsOpen[contractName]) {
      details.show();
    }
    return $('
').append(button).append(details);
  }
};
<|endoftext|>


<commit_before>const BN = require('bn.js')
const ethUtil = require('ethereumjs-util')

module.exports = class U256 {
  constructor (value) {
    // This is the case when data is copied from WASM
    if (value instanceof Uint8Array) {
      this._value = new BN(value, 16, 'le')
    } else if ((typeof value === 'string') && ethUtil.isHexPrefixed(value)) {
      this._value = new BN(value, 16)
    } else {
      this._value = new BN(value, 10)
    }
  }

  toString (radix = 10) {
    if (radix === 16) {
      return '0x' + this._value.toString(16)
    }
    return this._value.toString(radix)
  }

  toBuffer (width) {
    if (width <= 0 || width > 32) {
      throw new Error('Invalid U256 width')
    }
    return this._value.toBuffer('le', width || 32)
  }

  sub (u256) {
    return new U256(this._value.sub(u256._value))
  }

  add (u256) {
    return new U256(this._value.add(u256._value))
  }

  mul (u256) {
    return new U256(this._value.mul(u256._value))
  }

  div (u256) {
    return new U256(this._value.div(u256._value))
  }

  lt (u256) {
    return this._value.lt(u256._value)
  }

  gt (u256) {
    return this._value.gt(u256._value)
  }
}
<commit_msg>U256: fix reading hex prefixed numbers<commit_after>const BN = require('bn.js')
const ethUtil = require('ethereumjs-util')

module.exports = class U256 {
  constructor (value) {
    // This is the case when data is copied from WASM
    if (value instanceof Uint8Array) {
      this._value = new BN(value, 16, 'le')
    } else if ((typeof value === 'string') && ethUtil.isHexPrefixed(value)) {
      this._value = new BN(ethUtil.stripHexPrefix(value), 16)
    } else {
      this._value = new BN(value, 10)
    }
  }

  toString (radix = 10) {
    if (radix === 16) {
      return '0x' + this._value.toString(16)
    }
    return this._value.toString(radix)
  }

  toBuffer (width) {
    if (width <= 0 || width > 32) {
      throw new Error('Invalid U256 width')
    }
    return this._value.toBuffer('le', width || 32)
  }

  sub (u256) {
    return new U256(this._value.sub(u256._value))
  }

  add (u256) {
    return new U256(this._value.add(u256._value))
  }

  mul (u256) {
    return new U256(this._value.mul(u256._value))
  }

  div (u256) {
    return new U256(this._value.div(u256._value))
  }

  lt (u256) {
    return this._value.lt(u256._value)
  }

  gt (u256) {
    return this._value.gt(u256._value)
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  env: {
    es6: true,
    node: true,
  },
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  rules: {
    // possible errors
    'no-cond-assign': ['error', 'always'],
    'no-console': 'warn',
    'no-constant-condition': 'error',
    'no-control-regex': 'error',
    'no-debugger': 'warn',
    'no-dupe-args': 'error',
    'no-dupe-keys': 'error',
    'no-duplicate-case': 'error',
    'no-empty-character-class': 'error',
    'no-empty': ['error', {allowEmptyCatch: true}],
    'no-ex-assign': 'error',
    'no-extra-boolean-cast': 'error',
    // issue: https://github.com/eslint/eslint/issues/3107
    'no-extra-parens': ['error', 'functions'],
    'no-extra-semi': 'error',
    'no-func-assign': 'error',
    'no-inner-declarations': 'error',
    'no-invalid-regexp': 'error',
    'no-irregular-whitespace': 'error',
    'no-obj-calls': 'error',
    'no-prototype-builtins': 'error',
    'no-regex-spaces': 'error',
    'no-sparse-arrays': 'error',
    'no-template-curly-in-string': 'error',
    'no-unexpected-multiline': 'error',
    'no-unreachable': 'error',
    'no-unsafe-finally': 'error',
    'no-unsafe-negation': 'error',
    'use-isnan': 'error',
    'valid-jsdoc': 'off',
    'valid-typeof': ['error', {requireStringLiterals: true}],

    // best practices
    'accessor-pairs': 'error',
    'array-callback-return': 'error',
    'block-scoped-var': 'error', // rely on `no-var` rule
    'class-methods-use-this': 'off',
    'complexity': ['warn', 11],
    'consistent-return': 'error',
    'curly': 'error',
    'default-case': 'error',
    'dot-location': ['error', 'property'],
    'dot-notation': 'error',
    'eqeqeq': 'error',
    'guard-for-in': 'error', // rely on `no-restricted-syntax` rule
    'no-alert': 'warn',
    'no-caller': 'error',
    'no-case-declarations': 'error',
    'no-div-regex': 'off',
    'no-else-return': 'error',
    'no-empty-function': 'error',
    'no-empty-pattern': 'error',
    'no-eq-null': 'error', // rely on `eqeqeq` rule
    'no-eval': 'error',
    'no-extend-native': 'error',
    'no-extra-bind': 'error',
    'no-extra-label': 'error',
    'no-fallthrough': 'error',
    'no-floating-decimal': 'error',
    'no-global-assign': 'error',
    'no-implicit-coercion': ['error', {boolean: false}],
    'no-implicit-globals': 'error',
    'no-implied-eval': 'error',
    // TODO: Enable when issue has been fixed.
    // issue: https://github.com/babel/eslint-plugin-babel/issues/12
    // 'no-invalid-this': 'error',
    'no-iterator': 'error',
    'no-labels': 'error',
    'no-lone-blocks': 'error',
    'no-loop-func': 'error',
    'no-magic-numbers': 'off',
    'no-multi-spaces': 'error',
    'no-multi-str': 'error',
    'no-new-func': 'error',
    'no-new-wrappers': 'error',
    'no-new': 'error',
    'no-octal-escape': 'error',
    'no-octal': 'error',
    'no-param-reassign': ['error', {props: true}],
    'no-proto': 'error',
    'no-redeclare': 'error',
    'no-return-assign': ['error', 'always'],
    'no-script-url': 'off',
    'no-self-assign': ['error', {props: true}],
    'no-self-compare': 'error',
    'no-sequences': 'error',
    'no-throw-literal': 'error',
    'no-unmodified-loop-condition': 'error',
    'no-unused-expressions': 'error',
    'no-unused-labels': 'error',
    'no-useless-call': 'error',
    'no-useless-concat': 'error',
    'no-useless-escape': 'error',
    'no-void': 'error',
    'no-warning-comments': 'warn',
    'no-with': 'error',
    'radix': ['error', 'as-needed'],
    'vars-on-top': 'error', // rely on `one-var` rule
    'wrap-iife': ['error', 'inside'],
    'yoda': 'error',

    // strict mode
    'strict': 'error',

    // variables
    'init-declarations': 'error',
    'no-catch-shadow': 'off',
    'no-delete-var': 'error',
    'no-label-var': 'error',
    'no-restricted-globals': ['error', 'isNaN', 'parseInt', 'parseFloat'], // use `Number` property functions instead
    'no-shadow-restricted-names': 'error',
    'no-shadow': 'error',
    'no-undef-init': 'error',
    'no-undef': 'error',
    'no-undefined': 'off',
    'no-unused-vars': 'error',
    'no-use-before-define': ['error', 'nofunc'],

    // node.js and commonjs
    'callback-return': 'off',
    'global-require': 'off',
    'handle-callback-err': 'error',
    'no-mixed-requires': 'error', // rely on `one-var` rule
    'no-new-require': 'error',
    'no-path-concat': 'error',
    'no-process-env': 'off',
    'no-process-exit': 'off',
    'no-restricted-modules': 'off',
    'no-restricted-properties': [
      'error',
      {
        object: 'Object',
        property: 'assign',
        message: 'Use object spread operator `{...obj}` instead.',
      },
    ],
    'no-sync': 'off',

    // stylistic issues
    'array-bracket-spacing': 'error',
    'block-spacing': 'error',
    'brace-style': ['error', '1tbs', {allowSingleLine: true}],
    'camelcase': ['error', {properties: 'never'}],
    'comma-dangle': ['error', 'always-multiline'],
    'comma-spacing': 'error',
    'comma-style': ['error', 'last'],
    'computed-property-spacing': 'error',
    'consistent-this': 'off',
    'eol-last': 'error',
    'func-call-spacing': 'error',
    'func-names': ['error', 'never'],
    'func-style': ['error', 'declaration', {allowArrowFunctions: true}],
    'id-blacklist': 'off',
    'id-length': 'off',
    'id-match': 'off',
    'indent': ['error', 2, {SwitchCase: 1}],
    'jsx-quotes': 'off',
    'key-spacing': 'error',
    'line-comment-position': 'off',
    'keyword-spacing': 'error',
    'linebreak-style': 'error',
    'lines-around-comment': 'off',
    'lines-around-directive': ['error', {before: 'never', after: 'always'}],
    'max-depth': 'warn',
    'max-len': 'off',
    'max-lines': 'off',
    'max-nested-callbacks': ['warn', 4],
    'max-params': ['warn', 5],
    'max-statements-per-line': 'warn',
    'max-statements': 'off',
    'multiline-ternary': 'off',
    'new-cap': 'error',
    'new-parens': 'error',
    'newline-after-var': 'error',
    'newline-before-return': 'error',
    'newline-per-chained-call': 'error',
    'no-array-constructor': 'error',
    'no-bitwise': 'off',
    'no-continue': 'error',
    'no-inline-comments': 'off',
    'no-lonely-if': 'error',
    'no-mixed-operators': 'error',
    'no-mixed-spaces-and-tabs': 'error',
    'no-multiple-empty-lines': ['error', {max: 1, maxBOF: 0}],
    'no-negated-condition': 'error',
    // IMO, there is no better alternatives
    // http://stackoverflow.com/questions/32289340/alternative-to-nested-ternary-operator-in-js
    'no-nested-ternary': 'off',
    'no-new-object': 'error',
    'no-plusplus': 'off',
    // use for-of with Object.keys() instead of for-in
    // https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
    'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
    'no-tabs': 'error',
    'no-ternary': 'off',
    'no-trailing-spaces': ['error', {skipBlankLines: true}],
    'no-underscore-dangle': ['error', {allowAfterThis: true, allowAfterSuper: true}],
    'no-unneeded-ternary': ['error', {defaultAssignment: false}],
    'no-whitespace-before-property': 'error',
    // TODO: Enable when issue has been fixed.
    // issue: https://github.com/eslint/eslint/issues/6488
    // 'object-curly-newline': ['error', {multiline: true, minProperties: 4}],
    'object-curly-spacing': 'error',
    'object-property-newline': ['error', {allowMultiplePropertiesPerLine: true}],
    'one-var-declaration-per-line': 'error', // rely on `one-var` rule
    'one-var': ['error', 'never'],
    'operator-assignment': ['error', 'always'],
    'operator-linebreak': 'error',
    'padded-blocks': ['error', 'never'],
    'quote-props': ['error', 'as-needed'],
    'quotes': ['error', 'single'],
    'require-jsdoc': 'off',
    'semi-spacing': 'error',
    'semi': 'error',
    'sort-keys': 'off',
    'sort-vars': 'off',
    'space-before-blocks': 'error',
    'space-before-function-paren': ['error', {anonymous: 'always', named: 'never'}],
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': ['error', 'always', {block: {balanced: true}}],
    'unicode-bom': 'error',
    'wrap-regex': 'off',

    // ecmascript 6 rules
    'arrow-body-style': ['error', 'as-needed'],
    'arrow-parens': 'error',
    'arrow-spacing': 'error',
    'constructor-super': 'error',
    'generator-star-spacing': 'error',
    'no-class-assign': 'error',
    'no-confusing-arrow': 'off',
    'no-const-assign': 'error',
    'no-dupe-class-members': 'error',
    'no-duplicate-imports': ['error', {includeExports: true}],
    'no-new-symbol': 'error',
    'no-restricted-imports': 'off',
    'no-this-before-super': 'error',
    'no-useless-computed-key': 'error',
    'no-useless-constructor': 'error',
    'no-useless-rename': 'error',
    'no-var': 'error',
    'object-shorthand': 'error',
    'prefer-arrow-callback': 'error',
    'prefer-const': 'error',
    'prefer-numeric-literals': 'error',
    'prefer-reflect': 'error',
    'prefer-rest-params': 'error',
    'prefer-spread': 'error',
    'prefer-template': 'error',
    'require-yield': 'error',
    'rest-spread-spacing': 'error',
    'sort-imports': 'off',
    'symbol-description': 'off',
    'template-curly-spacing': 'error',
    'yield-star-spacing': 'error',
  },
};
<commit_msg>Add `func-name-matching` rule<commit_after>'use strict';

module.exports = {
  env: {
    es6: true,
    node: true,
  },
  parserOptions: {
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  rules: {
    // possible errors
    'no-cond-assign': ['error', 'always'],
    'no-console': 'warn',
    'no-constant-condition': 'error',
    'no-control-regex': 'error',
    'no-debugger': 'warn',
    'no-dupe-args': 'error',
    'no-dupe-keys': 'error',
    'no-duplicate-case': 'error',
    'no-empty-character-class': 'error',
    'no-empty': ['error', {allowEmptyCatch: true}],
    'no-ex-assign': 'error',
    'no-extra-boolean-cast': 'error',
    // issue: https://github.com/eslint/eslint/issues/3107
    'no-extra-parens': ['error', 'functions'],
    'no-extra-semi': 'error',
    'no-func-assign': 'error',
    'no-inner-declarations': 'error',
    'no-invalid-regexp': 'error',
    'no-irregular-whitespace': 'error',
    'no-obj-calls': 'error',
    'no-prototype-builtins': 'error',
    'no-regex-spaces': 'error',
    'no-sparse-arrays': 'error',
    'no-template-curly-in-string': 'error',
    'no-unexpected-multiline': 'error',
    'no-unreachable': 'error',
    'no-unsafe-finally': 'error',
    'no-unsafe-negation': 'error',
    'use-isnan': 'error',
    'valid-jsdoc': 'off',
    'valid-typeof': ['error', {requireStringLiterals: true}],

    // best practices
    'accessor-pairs': 'error',
    'array-callback-return': 'error',
    'block-scoped-var': 'error', // rely on `no-var` rule
    'class-methods-use-this': 'off',
    'complexity': ['warn', 11],
    'consistent-return': 'error',
    'curly': 'error',
    'default-case': 'error',
    'dot-location': ['error', 'property'],
    'dot-notation': 'error',
    'eqeqeq': 'error',
    'guard-for-in': 'error', // rely on `no-restricted-syntax` rule
    'no-alert': 'warn',
    'no-caller': 'error',
    'no-case-declarations': 'error',
    'no-div-regex': 'off',
    'no-else-return': 'error',
    'no-empty-function': 'error',
    'no-empty-pattern': 'error',
    'no-eq-null': 'error', // rely on `eqeqeq` rule
    'no-eval': 'error',
    'no-extend-native': 'error',
    'no-extra-bind': 'error',
    'no-extra-label': 'error',
    'no-fallthrough': 'error',
    'no-floating-decimal': 'error',
    'no-global-assign': 'error',
    'no-implicit-coercion': ['error', {boolean: false}],
    'no-implicit-globals': 'error',
    'no-implied-eval': 'error',
    // TODO: Enable when issue has been fixed.
    // issue: https://github.com/babel/eslint-plugin-babel/issues/12
    // 'no-invalid-this': 'error',
    'no-iterator': 'error',
    'no-labels': 'error',
    'no-lone-blocks': 'error',
    'no-loop-func': 'error',
    'no-magic-numbers': 'off',
    'no-multi-spaces': 'error',
    'no-multi-str': 'error',
    'no-new-func': 'error',
    'no-new-wrappers': 'error',
    'no-new': 'error',
    'no-octal-escape': 'error',
    'no-octal': 'error',
    'no-param-reassign': ['error', {props: true}],
    'no-proto': 'error',
    'no-redeclare': 'error',
    'no-return-assign': ['error', 'always'],
    'no-script-url': 'off',
    'no-self-assign': ['error', {props: true}],
    'no-self-compare': 'error',
    'no-sequences': 'error',
    'no-throw-literal': 'error',
    'no-unmodified-loop-condition': 'error',
    'no-unused-expressions': 'error',
    'no-unused-labels': 'error',
    'no-useless-call': 'error',
    'no-useless-concat': 'error',
    'no-useless-escape': 'error',
    'no-void': 'error',
    'no-warning-comments': 'warn',
    'no-with': 'error',
    'radix': ['error', 'as-needed'],
    'vars-on-top': 'error', // rely on `one-var` rule
    'wrap-iife': ['error', 'inside'],
    'yoda': 'error',

    // strict mode
    'strict': 'error',

    // variables
    'init-declarations': 'error',
    'no-catch-shadow': 'off',
    'no-delete-var': 'error',
    'no-label-var': 'error',
    'no-restricted-globals': ['error', 'isNaN', 'parseInt', 'parseFloat'], // use `Number` property functions instead
    'no-shadow-restricted-names': 'error',
    'no-shadow': 'error',
    'no-undef-init': 'error',
    'no-undef': 'error',
    'no-undefined': 'off',
    'no-unused-vars': 'error',
    'no-use-before-define': ['error', 'nofunc'],

    // node.js and commonjs
    'callback-return': 'off',
    'global-require': 'off',
    'handle-callback-err': 'error',
    'no-mixed-requires': 'error', // rely on `one-var` rule
    'no-new-require': 'error',
    'no-path-concat': 'error',
    'no-process-env': 'off',
    'no-process-exit': 'off',
    'no-restricted-modules': 'off',
    'no-restricted-properties': [
      'error',
      {
        object: 'Object',
        property: 'assign',
        message: 'Use object spread operator `{...obj}` instead.',
      },
    ],
    'no-sync': 'off',

    // stylistic issues
    'array-bracket-spacing': 'error',
    'block-spacing': 'error',
    'brace-style': ['error', '1tbs', {allowSingleLine: true}],
    'camelcase': ['error', {properties: 'never'}],
    'comma-dangle': ['error', 'always-multiline'],
    'comma-spacing': 'error',
    'comma-style': ['error', 'last'],
    'computed-property-spacing': 'error',
    'consistent-this': 'off',
    'eol-last': 'error',
    'func-call-spacing': 'error',
    'func-name-matching': 'error',
    'func-names': ['error', 'never'],
    'func-style': ['error', 'declaration', {allowArrowFunctions: true}],
    'id-blacklist': 'off',
    'id-length': 'off',
    'id-match': 'off',
    'indent': ['error', 2, {SwitchCase: 1}],
    'jsx-quotes': 'off',
    'key-spacing': 'error',
    'line-comment-position': 'off',
    'keyword-spacing': 'error',
    'linebreak-style': 'error',
    'lines-around-comment': 'off',
    'lines-around-directive': ['error', {before: 'never', after: 'always'}],
    'max-depth': 'warn',
    'max-len': 'off',
    'max-lines': 'off',
    'max-nested-callbacks': ['warn', 4],
    'max-params': ['warn', 5],
    'max-statements-per-line': 'warn',
    'max-statements': 'off',
    'multiline-ternary': 'off',
    'new-cap': 'error',
    'new-parens': 'error',
    'newline-after-var': 'error',
    'newline-before-return': 'error',
    'newline-per-chained-call': 'error',
    'no-array-constructor': 'error',
    'no-bitwise': 'off',
    'no-continue': 'error',
    'no-inline-comments': 'off',
    'no-lonely-if': 'error',
    'no-mixed-operators': 'error',
    'no-mixed-spaces-and-tabs': 'error',
    'no-multiple-empty-lines': ['error', {max: 1, maxBOF: 0}],
    'no-negated-condition': 'error',
    // IMO, there is no better alternatives
    // http://stackoverflow.com/questions/32289340/alternative-to-nested-ternary-operator-in-js
    'no-nested-ternary': 'off',
    'no-new-object': 'error',
    'no-plusplus': 'off',
    // use for-of with Object.keys() instead of for-in
    // https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
    'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
    'no-tabs': 'error',
    'no-ternary': 'off',
    'no-trailing-spaces': ['error', {skipBlankLines: true}],
    'no-underscore-dangle': ['error', {allowAfterThis: true, allowAfterSuper: true}],
    'no-unneeded-ternary': ['error', {defaultAssignment: false}],
    'no-whitespace-before-property': 'error',
    // TODO: Enable when issue has been fixed.
    // issue: https://github.com/eslint/eslint/issues/6488
    // 'object-curly-newline': ['error', {multiline: true, minProperties: 4}],
    'object-curly-spacing': 'error',
    'object-property-newline': ['error', {allowMultiplePropertiesPerLine: true}],
    'one-var-declaration-per-line': 'error', // rely on `one-var` rule
    'one-var': ['error', 'never'],
    'operator-assignment': ['error', 'always'],
    'operator-linebreak': 'error',
    'padded-blocks': ['error', 'never'],
    'quote-props': ['error', 'as-needed'],
    'quotes': ['error', 'single'],
    'require-jsdoc': 'off',
    'semi-spacing': 'error',
    'semi': 'error',
    'sort-keys': 'off',
    'sort-vars': 'off',
    'space-before-blocks': 'error',
    'space-before-function-paren': ['error', {anonymous: 'always', named: 'never'}],
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': ['error', 'always', {block: {balanced: true}}],
    'unicode-bom': 'error',
    'wrap-regex': 'off',

    // ecmascript 6 rules
    'arrow-body-style': ['error', 'as-needed'],
    'arrow-parens': 'error',
    'arrow-spacing': 'error',
    'constructor-super': 'error',
    'generator-star-spacing': 'error',
    'no-class-assign': 'error',
    'no-confusing-arrow': 'off',
    'no-const-assign': 'error',
    'no-dupe-class-members': 'error',
    'no-duplicate-imports': ['error', {includeExports: true}],
    'no-new-symbol': 'error',
    'no-restricted-imports': 'off',
    'no-this-before-super': 'error',
    'no-useless-computed-key': 'error',
    'no-useless-constructor': 'error',
    'no-useless-rename': 'error',
    'no-var': 'error',
    'object-shorthand': 'error',
    'prefer-arrow-callback': 'error',
    'prefer-const': 'error',
    'prefer-numeric-literals': 'error',
    'prefer-reflect': 'error',
    'prefer-rest-params': 'error',
    'prefer-spread': 'error',
    'prefer-template': 'error',
    'require-yield': 'error',
    'rest-spread-spacing': 'error',
    'sort-imports': 'off',
    'symbol-description': 'off',
    'template-curly-spacing': 'error',
    'yield-star-spacing': 'error',
  },
};
<|endoftext|>


<commit_before>/*! Responsive Menu */
// http://tympanus.net/codrops/2013/05/08/responsive-retina-ready-menu/
//  The function to change the class
var changeClass = function (r,className1,className2) {
  var regex = new RegExp("(?:^|\\s+)" + className1 + "(?:\\s+|$)");
  if( regex.test(r.className) ) {
    r.className = r.className.replace(regex,' '+className2+' ');
    }
    else{
    r.className = r.className.replace(new RegExp("(?:^|\\s+)" + className2 + "(?:\\s+|$)"),' '+className1+' ');
    }
    return r.className;
};
//  Creating our button in JS for smaller screens
var menuElements = document.getElementById('site-nav');
menuElements.insertAdjacentHTML('afterBegin','<button type="button" role="button" id="menutoggle" class="navtoogle navicon-lines-button x" aria-hidden="true">menu</button>');

//  Toggle the class on click to show / hide the menu
document.getElementById('menutoggle').onclick = function() {
  changeClass(this, 'navtoogle active', 'navtoogle');
};
// http://tympanus.net/codrops/2013/05/08/responsive-retina-ready-menu/comment-page-2/#comment-438918
document.onclick = function(e) {
  var mobileButton = document.getElementById('menutoggle'),
    buttonStyle =  mobileButton.currentStyle ? mobileButton.currentStyle.display : getComputedStyle(mobileButton, null).display;

  if(buttonStyle === 'block' && e.target !== mobileButton && new RegExp(' ' + 'active' + ' ').test(' ' + mobileButton.className + ' ')) {
    changeClass(mobileButton, 'navtoogle active', 'navtoogle');
  }
};

/*! Plugin options and other jQuery stuff */

// FitVids options
$(function() {
	$("article").fitVids();
});

// Table of Contents toggle
$(function() {
  $(".toc h3").click(function () {
    $("#drawer").toggleClass("js-hidden");
  });
});

// Add lightbox class to all image links
$("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.JPG'],a[href$='.png'],a[href$='.gif']").addClass("image-popup");

// Magnific-Popup options
$(document).ready(function() {
  $('.image-popup').magnificPopup({
    type: 'image',
    tLoading: 'Loading image #%curr%...',
    gallery: {
      enabled: true,
      navigateByImgClick: true,
      preload: [0,1] // Will preload 0 - before current, and 1 after the current image
    },
    image: {
      tError: 'Image #%curr% could not be loaded.',
    },
    removalDelay: 300, // Delay in milliseconds before popup is removed
    // Class that is added to body when popup is open.
    // make it unique to apply your CSS animations just to this exact popup
    mainClass: 'mfp-fade'
  });
});<commit_msg>Revert "Revert "menu""<commit_after>/*! Responsive Menu */
// http://tympanus.net/codrops/2013/05/08/responsive-retina-ready-menu/
//  The function to change the class
var changeClass = function (r,className1,className2) {
  var regex = new RegExp("(?:^|\\s+)" + className1 + "(?:\\s+|$)");
  if( regex.test(r.className) ) {
    r.className = r.className.replace(regex,' '+className2+' ');
    }
    else{
    r.className = r.className.replace(new RegExp("(?:^|\\s+)" + className2 + "(?:\\s+|$)"),' '+className1+' ');
    }
    return r.className;
};
//  Creating our button in JS for smaller screens
var menuElements = document.getElementById('site-nav');
menuElements.insertAdjacentHTML('afterBegin','<button type="button" role="button" id="menutoggle" class="navtoogle navicon-lines-button x" aria-hidden="true">MENU</button>');

//  Toggle the class on click to show / hide the menu
document.getElementById('menutoggle').onclick = function() {
  changeClass(this, 'navtoogle active', 'navtoogle');
};
// http://tympanus.net/codrops/2013/05/08/responsive-retina-ready-menu/comment-page-2/#comment-438918
document.onclick = function(e) {
  var mobileButton = document.getElementById('menutoggle'),
    buttonStyle =  mobileButton.currentStyle ? mobileButton.currentStyle.display : getComputedStyle(mobileButton, null).display;

  if(buttonStyle === 'block' && e.target !== mobileButton && new RegExp(' ' + 'active' + ' ').test(' ' + mobileButton.className + ' ')) {
    changeClass(mobileButton, 'navtoogle active', 'navtoogle');
  }
};

/*! Plugin options and other jQuery stuff */

// FitVids options
$(function() {
	$("article").fitVids();
});

// Table of Contents toggle
$(function() {
  $(".toc h3").click(function () {
    $("#drawer").toggleClass("js-hidden");
  });
});

// Add lightbox class to all image links
$("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.JPG'],a[href$='.png'],a[href$='.gif']").addClass("image-popup");

// Magnific-Popup options
$(document).ready(function() {
  $('.image-popup').magnificPopup({
    type: 'image',
    tLoading: 'Loading image #%curr%...',
    gallery: {
      enabled: true,
      navigateByImgClick: true,
      preload: [0,1] // Will preload 0 - before current, and 1 after the current image
    },
    image: {
      tError: 'Image #%curr% could not be loaded.',
    },
    removalDelay: 300, // Delay in milliseconds before popup is removed
    // Class that is added to body when popup is open.
    // make it unique to apply your CSS animations just to this exact popup
    mainClass: 'mfp-fade'
  });
});
<|endoftext|>


<commit_before>/* global jQuery, wpa0, wp */
jQuery(document).ready(function($) {
    //uploading files variable
    var media_frame;
    $(document).on('click', '#wpa0_choose_icon', function(event) {
        event.preventDefault();
        //If the frame already exists, reopen it
        if (typeof(media_frame)!=="undefined") {
            media_frame.close();
        }

        var related_control_id = 'wpa0_icon_url';
        if (typeof($(this).attr('related')) != 'undefined' &&
            $(this).attr('related') != '')
        {
            related_control_id = $(this).attr('related');
        }

        //Create WP media frame.
        media_frame = wp.media.frames.customHeader = wp.media({
            title: wpa0.media_title,
            library: {
                type: 'image'
            },
            button: {
                text: wpa0.media_button
            },
            multiple: false
        });

        // Set the frame callback
        media_frame.on('select', function() {
            var attachment = media_frame.state().get('selection').first().toJSON();
            $('#'+related_control_id).val(attachment.url).change();
        });

        //Open modal
        media_frame.open();
    });

    /*
    Generic form confirm stop
     */
    $('form.js-a0-confirm-submit').submit(function (e) {
        if ( ! confirmToContinue($(this)) ) {
            e.preventDefault();
        }
    });

    /*
    Show/hide field for specific switches
     */
    $('[data-expand][data-expand!=""]').each( function() {
        var $thisSwitch = $( this );
        var $showFieldRow = $( '#' + $thisSwitch.attr( 'data-expand' ).trim() ).closest( 'tr' );

        if ( $showFieldRow.length ) {
            if ( ! $thisSwitch.prop( 'checked' ) ) {
                $showFieldRow.hide();
            }
            $thisSwitch.change(function() {
                if ( $( this ).prop( 'checked' ) ) {
                    $showFieldRow.show();
                } else {
                    $showFieldRow.hide();
                }
            } );
        }
    });

    /*
    Import and Export settings tabs
     */
    $('.js-a0-upload-toggle').click(function(){
        $('#js-a0-upload-file').toggle();
        $('#js-a0-paste-json').toggle();
    });

    $('.js-a0-import-export-tabs').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    /*
    Admin settings tab switching
     */
    var currentTab;
    if ( window.location.hash ) {
        currentTab = window.location.hash.replace( '#', '' );
    } else if ( localStorageAvailable() && window.localStorage.getItem( 'Auth0WPSettingsTab' ) ) {
        // Previous tab being used
        currentTab = window.localStorage.getItem( 'Auth0WPSettingsTab' );
    } else {
        // Default tab if no saved tab was found
        currentTab = 'features';
    }

    // Uses the Bootstrap tab plugin
    $('#tab-' + currentTab).tab('show');

    // Controls whether the submit button is showing or not
    var $settingsForm = $( '#js-a0-settings-form' );
    $settingsForm.attr( 'data-tab-showing', currentTab );

    // Set the tab showing on the form and persist the tab
    $( '.js-a0-settings-tabs' ).click( function () {
        window.location.hash = '';
        var tabHref = $( this ).attr( 'aria-controls' ).trim();
        $settingsForm.attr( 'data-tab-showing', tabHref );
        if ( localStorageAvailable() ) {
            window.localStorage.setItem( 'Auth0WPSettingsTab', tabHref );
        }
    } );

    /*
    Clear cache button on Basic settings page
     */
    var deleteCacheId = 'auth0_delete_cache_transient';
    var $deleteCacheButton = $( '#' + deleteCacheId );
    $deleteCacheButton.click( function(e) {
        e.preventDefault();
        $deleteCacheButton.prop( 'disabled', true ).text( wpa0.ajax_working );
        var postData = {
            'action': deleteCacheId,
            '_ajax_nonce': wpa0.clear_cache_nonce
        };

        $.post(wpa0.ajax_url, postData, function() {
            $deleteCacheButton.prop( 'disabled', false ).text( wpa0.ajax_done );
        }, 'json');
    } );

    /*
    Clear cache button on Basic settings page
     */
    var rotateMigrationTokenId = 'auth0_rotate_migration_token';
    var $rotateMigrationTokenButton = $( '#' + rotateMigrationTokenId );
    $rotateMigrationTokenButton.click( function(e) {
        e.preventDefault();

        if (!confirmToContinue($rotateMigrationTokenButton) ) {
            return;
        }

        $rotateMigrationTokenButton.prop( 'disabled', true ).text( wpa0.ajax_working );
        var postData = {
            'action': rotateMigrationTokenId,
            '_ajax_nonce': wpa0.rotate_token_nonce
        };

        $.post(wpa0.ajax_url, postData, function() {
            $( '#auth0_migration_token' ).text(wpa0.refresh_prompt);
            $rotateMigrationTokenButton.remove();
        }, 'json');
    } );

    /*
    Initial setup
     */
    $('.js-a0-setup-input').keydown(function(e){
        // Do not submit the form if the enter key is pressed.
        if(13 === e.keyCode) {
            e.preventDefault();
            return false;
        }
    });

    $('.js-a0-select-setup').click(function (e) {
        e.preventDefault();
        $('#profile-type').val($(this).attr('data-profile-type'));
        $('#connectionSelectedModal').modal();
    });

    $('#manuallySetToken').click(function (e) {
        e.preventDefault();
        $('#enterTokenModal').modal();
        $('#connectionSelectedModal').modal('hide');
    });

    $('#automaticSetup').click(function (e) {
        e.preventDefault();
        $('#profile-form').submit();
    });

  /**
   *
   * @param $el
   * @returns {boolean}
   */
  function confirmToContinue( $el ) {
      var message = $el.attr('data-confirm-msg');
      if ( !message || !message.length ) {
        message = wpa0.form_confirm_submit_msg;
      }

      return window.confirm(message);
    }

    /**
     * Can we use localStorage?
     *
     * @returns {boolean}
     */
    function localStorageAvailable() {
        try {
            var x = '__Auth0_localStorage_assertion__';
            window.localStorage.setItem(x, x);
            window.localStorage.removeItem(x);
            return true;
        }
        catch(e) {
            return false;
        }
    }
});
<commit_msg>Minor cleanup<commit_after>/* global jQuery, wpa0, wp */
jQuery(document).ready(function($) {
    //uploading files variable
    var media_frame;
    $(document).on('click', '#wpa0_choose_icon', function(event) {
        event.preventDefault();
        //If the frame already exists, reopen it
        if (typeof(media_frame)!=="undefined") {
            media_frame.close();
        }

        var related_control_id = 'wpa0_icon_url';
        if (typeof($(this).attr('related')) != 'undefined' &&
            $(this).attr('related') != '')
        {
            related_control_id = $(this).attr('related');
        }

        //Create WP media frame.
        media_frame = wp.media.frames.customHeader = wp.media({
            title: wpa0.media_title,
            library: {
                type: 'image'
            },
            button: {
                text: wpa0.media_button
            },
            multiple: false
        });

        // Set the frame callback
        media_frame.on('select', function() {
            var attachment = media_frame.state().get('selection').first().toJSON();
            $('#'+related_control_id).val(attachment.url).change();
        });

        //Open modal
        media_frame.open();
    });

    /*
    Generic form confirm stop
     */
    $('form.js-a0-confirm-submit').submit(function (e) {
        if ( cancelAction($(this)) ) {
            e.preventDefault();
        }
    });

    /*
    Show/hide field for specific switches
     */
    $('[data-expand][data-expand!=""]').each( function() {
        var $thisSwitch = $( this );
        var $showFieldRow = $( '#' + $thisSwitch.attr( 'data-expand' ).trim() ).closest( 'tr' );

        if ( $showFieldRow.length ) {
            if ( ! $thisSwitch.prop( 'checked' ) ) {
                $showFieldRow.hide();
            }
            $thisSwitch.change(function() {
                if ( $( this ).prop( 'checked' ) ) {
                    $showFieldRow.show();
                } else {
                    $showFieldRow.hide();
                }
            } );
        }
    });

    /*
    Import and Export settings tabs
     */
    $('.js-a0-upload-toggle').click(function(){
        $('#js-a0-upload-file').toggle();
        $('#js-a0-paste-json').toggle();
    });

    $('.js-a0-import-export-tabs').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    /*
    Admin settings tab switching
     */
    var currentTab;
    if ( window.location.hash ) {
        currentTab = window.location.hash.replace( '#', '' );
    } else if ( localStorageAvailable() && window.localStorage.getItem( 'Auth0WPSettingsTab' ) ) {
        // Previous tab being used
        currentTab = window.localStorage.getItem( 'Auth0WPSettingsTab' );
    } else {
        // Default tab if no saved tab was found
        currentTab = 'features';
    }

    // Uses the Bootstrap tab plugin
    $('#tab-' + currentTab).tab('show');

    // Controls whether the submit button is showing or not
    var $settingsForm = $( '#js-a0-settings-form' );
    $settingsForm.attr( 'data-tab-showing', currentTab );

    // Set the tab showing on the form and persist the tab
    $( '.js-a0-settings-tabs' ).click( function () {
        window.location.hash = '';
        var tabHref = $( this ).attr( 'aria-controls' ).trim();
        $settingsForm.attr( 'data-tab-showing', tabHref );
        if ( localStorageAvailable() ) {
            window.localStorage.setItem( 'Auth0WPSettingsTab', tabHref );
        }
    } );

    /*
    Clear cache button on Basic settings page
     */
    var deleteCacheId = 'auth0_delete_cache_transient';
    var $deleteCacheButton = $( '#' + deleteCacheId );
    $deleteCacheButton.click( function(e) {
        e.preventDefault();
        $deleteCacheButton.prop( 'disabled', true ).text( wpa0.ajax_working );
        var postData = {
            'action': deleteCacheId,
            '_ajax_nonce': wpa0.clear_cache_nonce
        };

        $.post(wpa0.ajax_url, postData, function() {
            $deleteCacheButton.prop( 'disabled', false ).text( wpa0.ajax_done );
        }, 'json');
    } );

    /*
    Generate new migration token button on Advanced settings page
     */
    var rotateTokenId = 'auth0_rotate_migration_token';
    var $rotateTokenButton = $( '#' + rotateTokenId );
    $rotateTokenButton.click( function(e) {
        e.preventDefault();

        if (cancelAction($rotateTokenButton) ) {
            return;
        }

        $rotateTokenButton.prop( 'disabled', true ).text( wpa0.ajax_working );
        var postData = {
            'action': rotateTokenId,
            '_ajax_nonce': wpa0.rotate_token_nonce
        };
        $.post(wpa0.ajax_url, postData, function() {
            $( '#auth0_migration_token' ).text(wpa0.refresh_prompt);
            $rotateTokenButton.remove();
        }, 'json');
    } );

    /*
    Initial setup
     */
    $('.js-a0-setup-input').keydown(function(e){
        // Do not submit the form if the enter key is pressed.
        if(13 === e.keyCode) {
            e.preventDefault();
            return false;
        }
    });

    $('.js-a0-select-setup').click(function (e) {
        e.preventDefault();
        $('#profile-type').val($(this).attr('data-profile-type'));
        $('#connectionSelectedModal').modal();
    });

    $('#manuallySetToken').click(function (e) {
        e.preventDefault();
        $('#enterTokenModal').modal();
        $('#connectionSelectedModal').modal('hide');
    });

    $('#automaticSetup').click(function (e) {
        e.preventDefault();
        $('#profile-form').submit();
    });

  /**
   * Show a JS confirm box to give a chance to cancel an on-page action.
   *
   * @param {object} $el - jQuery selector for confirmation message.
   *
   * @returns {boolean}
   */
  function cancelAction( $el ) {
      var message = $el.attr('data-confirm-msg');
      if ( !message || !message.length ) {
        message = wpa0.form_confirm_submit_msg;
      }

      return !window.confirm(message);
    }

    /**
     * Can we use localStorage?
     *
     * @returns {boolean}
     */
    function localStorageAvailable() {
        try {
            var x = '__Auth0_localStorage_assertion__';
            window.localStorage.setItem(x, x);
            window.localStorage.removeItem(x);
            return true;
        }
        catch(e) {
            return false;
        }
    }
});
<|endoftext|>


<commit_before>wp.customize.controlConstructor['kirki-color'] = wp.customize.kirkiDynamicControl.extend({

	initKirkiControl: function() {
		var control = this,
		    html,
		    clear,
		    picker;

		control.addHTML();

		picker = control.container.find( '.kirki-color-control' );

		// If we have defined any extra choices, make sure they are passed-on to Iris.
		if ( ! _.isUndefined( control.params.choices ) ) {
			picker.wpColorPicker( control.params.choices );
		}

		// Tweaks to make the "clear" buttons work.
		setTimeout( function() {
			clear = control.container.find( '.wp-picker-clear' );
			clear.click( function() {
				control.setting.set( '' );
			});
		}, 200 );

		// Saves our settings to the WP API
		picker.wpColorPicker({
			change: function() {

				// Small hack: the picker needs a small delay
				setTimeout( function() {
					control.setting.set( picker.val() );
				}, 20 );
			}
		});
	},

	addHTML: function() {
		var control = this,
		    html    = '';

		html  = '';
			html += '' + control.params.label + '';
			html += '' + control.params.description + '';
			html += '<input type="text" data-palette="' + control.params.palette + '" data-default-color="' + control.params['default'] + '" data-alpha="' + control.params.alpha + '" value="' + control.params.value + '" class="kirki-color-control" ' + control.params.link + ' />';
		html += '';

		control.container.html( html );

	}
});
<commit_msg>Fix failing test.<commit_after>wp.customize.controlConstructor['kirki-color'] = wp.customize.kirkiDynamicControl.extend({

	initKirkiControl: function() {
		var control = this,
		    html,
		    clear,
		    picker;

		control.addHTML();

		picker = control.container.find( '.kirki-color-control' );

		// If we have defined any extra choices, make sure they are passed-on to Iris.
		if ( ! _.isUndefined( control.params.choices ) ) {
			picker.wpColorPicker( control.params.choices );
		}

		// Tweaks to make the "clear" buttons work.
		setTimeout( function() {
			clear = control.container.find( '.wp-picker-clear' );
			clear.click( function() {
				control.setting.set( '' );
			});
		}, 200 );

		// Saves our settings to the WP API
		picker.wpColorPicker({
			change: function() {

				// Small hack: the picker needs a small delay
				setTimeout( function() {
					control.setting.set( picker.val() );
				}, 20 );
			}
		});
	},

	addHTML: function() {
		var control = this,
		    html    = '';

		html  = '';
			html += '' + control.params.label + '';
			html += '' + control.params.description + '';
			html += '<input type="text" data-palette="' + control.params.palette + '" data-default-color="' + control.params['default'] + '" data-alpha="' + control.params.alpha + '" value="' + control.params.value + '" class="kirki-color-control" ' + control.params.link + ' />';
		html += '';

		control.container.html( html );

	}
});
<|endoftext|>


<commit_before>"use strict";

/**
 * Main JS file for GhostScroll behaviours
 */

var $sitehead = $('#site-head');

/* Globals jQuery, document */
(function ($) {
	$(document).ready(initialize);
	$(window).resize(onViewportChange);
	$(window).scroll(onViewportChange);

	function initialize() {
		setupJumpHandlers();
		fontAwesomeDecorators();
		fontAwesomeReplacement();

		function setupJumpHandlers() {
                    // FitVids for responsive videos
            $('.post-content').fitVids();
                    // Arrow top in fixed menu
            $('#totop-arrow').click(function () {
            smoothScroll($sitehead);
            });
			$('#header-arrow').click( function () {
				var $first = $(".post").first();
				smoothScroll($first);
			});

            $('.btn.first').click( function () {
			    var $first = $(".post").first();
				smoothScroll($first);
		    });

			$('.fn-item, .btn').click(function (evt) {
        var $this = $(this);
				var href = $this.attr("href");

        // We don't want to prevent a link from working if it is external.
        if (href.slice(0,1) === "#") {
          evt.preventDefault();
          var title = $this.text();
          window.history.pushState(title, title, href);
          smoothScroll($(href))
        }
			});
		}

		function fontAwesomeDecorators() {
			$('ul > li').before('');
			$('blockquote p').prepend('');
			$('blockquote p').append('');
		}

		function fontAwesomeReplacement() {
			// // Matches
			// @fa-singleword@
			// @fa-dash-separated-words@
			// // Does *not* match
			// \@fa-escaped@
			// @fa-space separated@
			// @fa-Invalid-Case@
			// @fa-Invalid-(H^R@
			// @fa-will-match@@fa-will-not-match@
			//
			// Note: JS doesn't support negative lookbehinds. Thus to permit
			// escaped examples (\@fa-foo@) we capture the preceeding
			// character. This shouldn't pose a problem except in the event of
			// adjacent font-awesome characters (that are not space separated).
			// See last example above.
			var reg = /([^\\])@(fa-[-a-z]+)@/g;

			var $posts = $("#posts-wrapper")
			$posts.html($posts.html().replace(reg, "$1"));
		}
	}

	function onViewportChange() {
		conditionallyShowNav();
		highlightActiveSection();

		function conditionallyShowNav() {
      var isTooNarrow = $(window).width() < 500;
      var shouldDisplayNav = !isTooNarrow && !isElementInViewport($sitehead);
			var navOpacity = shouldDisplayNav ? 1 : 0;
			$(".fixed-nav").css("opacity", navOpacity);
		}

		function highlightActiveSection() {
			$(".post-holder").each(function () {
				var $this = $(this);
				var postId = $this.attr("id");
				var $thisNavLink = $(".fn-item[href='#" + postId + "']");
				var $previousArrow = $(this).prev('.post-holder').find('.post-after');

				if(isElementInViewport($this)) {
					$thisNavLink.addClass('active');
					$previousArrow.fadeOut('slow');
				} else {
					$thisNavLink.removeClass('active');
					$previousArrow.fadeIn('slow');
				}
			});
		}

		function isElementInViewport($element) {
			var scrollPosition = $(window).scrollTop();
			var topOfElement = $element.offset().top;
			var bottomOfElement = topOfElement + $element.height();

			var isAboveElement = topOfElement > scrollPosition;
			var isBelowElement = scrollPosition >= bottomOfElement;

			return (!isAboveElement && !isBelowElement);
		}
	}

	function smoothScroll ($element) {
		$('html, body').animate({
			scrollTop: $element.offset().top
		}, 400);
	}

}(jQuery));<commit_msg>btn removed from JumpHandlers<commit_after>"use strict";

/**
 * Main JS file for GhostScroll behaviours
 */

var $sitehead = $('#site-head');

/* Globals jQuery, document */
(function ($) {
	$(document).ready(initialize);
	$(window).resize(onViewportChange);
	$(window).scroll(onViewportChange);

	function initialize() {
		setupJumpHandlers();
		fontAwesomeDecorators();
		fontAwesomeReplacement();

		function setupJumpHandlers() {
                    // FitVids for responsive videos
            $('.post-content').fitVids();
                    // Arrow top in fixed menu
            $('#totop-arrow').click(function () {
            smoothScroll($sitehead);
            });
			$('#header-arrow').click( function () {
				var $first = $(".post").first();
				smoothScroll($first);
			});

            $('.btn.first').click( function () {
			    var $first = $(".post").first();
				smoothScroll($first);
		    });

			$('.fn-item').click(function (evt) {
        var $this = $(this);
				var href = $this.attr("href");

        // We don't want to prevent a link from working if it is external.
        if (href.slice(0,1) === "#") {
          evt.preventDefault();
          var title = $this.text();
          window.history.pushState(title, title, href);
          smoothScroll($(href))
        }
			});
		}

		function fontAwesomeDecorators() {
			$('ul > li').before('');
			$('blockquote p').prepend('');
			$('blockquote p').append('');
		}

		function fontAwesomeReplacement() {
			// // Matches
			// @fa-singleword@
			// @fa-dash-separated-words@
			// // Does *not* match
			// \@fa-escaped@
			// @fa-space separated@
			// @fa-Invalid-Case@
			// @fa-Invalid-(H^R@
			// @fa-will-match@@fa-will-not-match@
			//
			// Note: JS doesn't support negative lookbehinds. Thus to permit
			// escaped examples (\@fa-foo@) we capture the preceeding
			// character. This shouldn't pose a problem except in the event of
			// adjacent font-awesome characters (that are not space separated).
			// See last example above.
			var reg = /([^\\])@(fa-[-a-z]+)@/g;

			var $posts = $("#posts-wrapper")
			$posts.html($posts.html().replace(reg, "$1"));
		}
	}

	function onViewportChange() {
		conditionallyShowNav();
		highlightActiveSection();

		function conditionallyShowNav() {
      var isTooNarrow = $(window).width() < 500;
      var shouldDisplayNav = !isTooNarrow && !isElementInViewport($sitehead);
			var navOpacity = shouldDisplayNav ? 1 : 0;
			$(".fixed-nav").css("opacity", navOpacity);
		}

		function highlightActiveSection() {
			$(".post-holder").each(function () {
				var $this = $(this);
				var postId = $this.attr("id");
				var $thisNavLink = $(".fn-item[href='#" + postId + "']");
				var $previousArrow = $(this).prev('.post-holder').find('.post-after');

				if(isElementInViewport($this)) {
					$thisNavLink.addClass('active');
					$previousArrow.fadeOut('slow');
				} else {
					$thisNavLink.removeClass('active');
					$previousArrow.fadeIn('slow');
				}
			});
		}

		function isElementInViewport($element) {
			var scrollPosition = $(window).scrollTop();
			var topOfElement = $element.offset().top;
			var bottomOfElement = topOfElement + $element.height();

			var isAboveElement = topOfElement > scrollPosition;
			var isBelowElement = scrollPosition >= bottomOfElement;

			return (!isAboveElement && !isBelowElement);
		}
	}

	function smoothScroll ($element) {
		$('html, body').animate({
			scrollTop: $element.offset().top
		}, 400);
	}

}(jQuery));<|endoftext|>


<commit_before>/**
 * Main JS file for GhostScroll behaviours
 */

var $post = $('.post');
var $fnav = $('.fixed-nav');
var $postafter = $('.post-after');
var $sitehead = $('#site-head');

/* Globals jQuery, document */
(function ($) {
	"use strict";
	function srcTo (el) {
		$('html, body').animate({
			scrollTop: el.offset().top
		}, 1000);
	}
	$(document).ready(function(){

        // FitVids for responsive videos
        $('.post-content').fitVids();

		$postafter.each(function (e) {
			var bg = $(this).parent().css('background-color')
			$(this).css('border-top-color', bg);

			if (e % 2 == 0) {
				$(this).addClass("even");
			}
		});

		$('.btn.first').click( function () {

		$('.btn.first, #header-arrow').click( function () {
            var $first = $post.first();
			srcTo($first);
		});
		$('.btn.last').click( function () {
            var $last = $post.last();
			srcTo($last);
		});
		$('#header-arrow').click(function () {
			srcTo($first);
		});
        $('#totop-arrow').click(function () {
            srcTo($sitehead);
        });

		$('.post-title').each(function () {
			var t = $(this).text();
			var index = $(this).parents('.post-holder').index();
			$fnav.append(""+t+"")
			$(this).parents('article').attr('id',t.toLowerCase().split(' ').join('-'));
			$('.fn-item').last().click(function () {
				var i = $(this).attr('item_index');
				var s = $(".post[item_index='"+i+"']");

				$('html, body').animate({
					scrollTop: s.offset().top
				}, 0);

			});
		});

		$('.post.last').next('.post-after').hide();
		if($sitehead.length) {
			$(window).scroll( function () {
				var w = $(window).scrollTop();
				var g = $sitehead.offset().top;
				var h = $sitehead.offset().top + $sitehead.height()-100;

				/*var paralex = 30 + w/13 + "%";
    			$sitehead.css("background-position-y", paralex); */

    			$sitehead.css("background-position-y");

				if(w >= g && w<=h) {
					$('.fixed-nav').fadeOut('fast');
				} else if($(window).width()>500) {
					$('.fixed-nav').fadeIn('slow');
				}

				$post.each(function () {
					var f = $(this).offset().top;
					var b = $(this).offset().top + $(this).height();
					var t = $(this).parent('.post-holder').index();
					var i = $(".fn-item[item_index='"+t+"']");
					var a = $(this).parent('.post-holder').prev('.post-holder').find('.post-after');

					$(this).attr('item_index', t);

					if(w >= f && w<=b) {
						i.addClass('active');
						a.fadeOut('slow');
					} else {
						i.removeClass('active');
						a.fadeIn('slow');
					}
				});
			});
		}

		$('ul li').before('');
		$('blockquote p').prepend('');
		$('blockquote p').append('');
	});

	$post.each(function () {
		var postText = $(this).html();
		var fa  = [];
		for(var i=0; i < icons.length; i++) {
			fa[i]       = {};
			fa[i].str   = "@"+ icons[i]+ "@";
			fa[i].icon  = icons[i];
			fa[i].int   = postText.search(fa[i].str);

			if(fa[i].int > -1 ) {
				fa[i].count = postText.match(new RegExp(fa[i].str,"g")).length;
				for(var j=0; j < fa[i].count; j++) {
					$(this).html($(this).html().replace(fa[i].str, ""))
				}
			}
		}
	});

}(jQuery));
<commit_msg>Remove jquery post-after arrow logic<commit_after>/**
 * Main JS file for GhostScroll behaviours
 */

var $post = $('.post');
var $fnav = $('.fixed-nav');
var $postafter = $('.post-after');
var $sitehead = $('#site-head');

/* Globals jQuery, document */
(function ($) {
	"use strict";
	function srcTo (el) {
		$('html, body').animate({
			scrollTop: el.offset().top
		}, 1000);
	}
	$(document).ready(function(){

        // FitVids for responsive videos
        $('.post-content').fitVids();

		$('.btn.first').click( function () {

		$('.btn.first, #header-arrow').click( function () {
            var $first = $post.first();
			srcTo($first);
		});
		$('.btn.last').click( function () {
            var $last = $post.last();
			srcTo($last);
		});
		$('#header-arrow').click(function () {
			srcTo($first);
		});
        $('#totop-arrow').click(function () {
            srcTo($sitehead);
        });

		$('.post-title').each(function () {
			var t = $(this).text();
			var index = $(this).parents('.post-holder').index();
			$fnav.append(""+t+"")
			$(this).parents('article').attr('id',t.toLowerCase().split(' ').join('-'));
			$('.fn-item').last().click(function () {
				var i = $(this).attr('item_index');
				var s = $(".post[item_index='"+i+"']");

				$('html, body').animate({
					scrollTop: s.offset().top
				}, 0);

			});
		});

		if($sitehead.length) {
			$(window).scroll( function () {
				var w = $(window).scrollTop();
				var g = $sitehead.offset().top;
				var h = $sitehead.offset().top + $sitehead.height()-100;

				/*var paralex = 30 + w/13 + "%";
    			$sitehead.css("background-position-y", paralex); */

    			$sitehead.css("background-position-y");

				if(w >= g && w<=h) {
					$('.fixed-nav').fadeOut('fast');
				} else if($(window).width()>500) {
					$('.fixed-nav').fadeIn('slow');
				}

				$post.each(function () {
					var f = $(this).offset().top;
					var b = $(this).offset().top + $(this).height();
					var t = $(this).parent('.post-holder').index();
					var i = $(".fn-item[item_index='"+t+"']");
					var a = $(this).parent('.post-holder').prev('.post-holder').find('.post-after');

					$(this).attr('item_index', t);

					if(w >= f && w<=b) {
						i.addClass('active');
						a.fadeOut('slow');
					} else {
						i.removeClass('active');
						a.fadeIn('slow');
					}
				});
			});
		}

		$('ul li').before('');
		$('blockquote p').prepend('');
		$('blockquote p').append('');
	});

	$post.each(function () {
		var postText = $(this).html();
		var fa  = [];
		for(var i=0; i < icons.length; i++) {
			fa[i]       = {};
			fa[i].str   = "@"+ icons[i]+ "@";
			fa[i].icon  = icons[i];
			fa[i].int   = postText.search(fa[i].str);

			if(fa[i].int > -1 ) {
				fa[i].count = postText.match(new RegExp(fa[i].str,"g")).length;
				for(var j=0; j < fa[i].count; j++) {
					$(this).html($(this).html().replace(fa[i].str, ""))
				}
			}
		}
	});

}(jQuery));
<|endoftext|>


<commit_before>"use strict";

function runTOMTOM() {
	this.disabled = true;
	var $tomtomRunning = $('#tomtom-running').toggleClass('hidden');
	var $tomtomResults = $('#tomtom-results').empty();
	$.ajax({
		url: baseURL + 'api/run_tomtom',
		type: 'POST',
		dataType: 'json',
		data: { matrix: JSON.stringify(pspm) },
		context: this,
		success: function(json) {
			console.log(json);
			if (!json.file) {
				$tomtomResults.html(json.name);
			} else {
				$tomtomResults
					.append($('<a/>', {
						href: baseURL + json.file,
						html: json.name
					}));
			}
			$tomtomRunning.toggleClass('hidden');
			this.disabled = false;
		}
	});
}

$(function () {
	var motifLen = pspm.length;
	var canvasWidth = 50 * motifLen;

	isblogo.makeLogo('motif-logo', {
		alphabet: ['A', 'C', 'G', 'T'],
		values: pspm
	},
	{
		width: canvasWidth,
		height: 200,
		glyphStyle: 'bold 20pt Helvetica'
	});

	$('#gene-table').dataTable({
		aoColumnDefs: [{sType: 'scientific', aTargets: [5]}],
		aaSorting: [[5, 'asc']],
		fnRowCallback: function (nRow, aData, iDisplayIndex) {
			if (aData[5] > 0.001) {
				var roundp = Number(aData[5]).toPrecision(2);
			} else {
				var roundp = Number(Number(aData[5]).toPrecision(3)).toExponential();
			}
			$('td:eq(4)', nRow).html(Number(aData[4]).toFixed(2));
			$('td:eq(5)', nRow).html(roundp);
			$('td:eq(0)', nRow).empty().append($('<a/>')
				.attr('href', baseURL + 'gene/details/' + aData[0])
				.html(aData[0]));
			return nRow;
		}
	});

	// TOMTOM
	$('#run-tomtom').click(runTOMTOM);
});
<commit_msg>removed console.log<commit_after>"use strict";

function runTOMTOM() {
	this.disabled = true;
	var $tomtomRunning = $('#tomtom-running').toggleClass('hidden');
	var $tomtomResults = $('#tomtom-results').empty();
	$.ajax({
		url: baseURL + 'api/run_tomtom',
		type: 'POST',
		dataType: 'json',
		data: { matrix: JSON.stringify(pspm) },
		context: this,
		success: function(json) {
			if (!json.file) {
				$tomtomResults.html(json.name);
			} else {
				$tomtomResults
					.append($('<a/>', {
						href: baseURL + json.file,
						html: json.name
					}));
			}
			$tomtomRunning.toggleClass('hidden');
			this.disabled = false;
		}
	});
}

$(function () {
	var motifLen = pspm.length;
	var canvasWidth = 50 * motifLen;

	isblogo.makeLogo('motif-logo', {
		alphabet: ['A', 'C', 'G', 'T'],
		values: pspm
	},
	{
		width: canvasWidth,
		height: 200,
		glyphStyle: 'bold 20pt Helvetica'
	});

	$('#gene-table').dataTable({
		aoColumnDefs: [{sType: 'scientific', aTargets: [5]}],
		aaSorting: [[5, 'asc']],
		fnRowCallback: function (nRow, aData, iDisplayIndex) {
			if (aData[5] > 0.001) {
				var roundp = Number(aData[5]).toPrecision(2);
			} else {
				var roundp = Number(Number(aData[5]).toPrecision(3)).toExponential();
			}
			$('td:eq(4)', nRow).html(Number(aData[4]).toFixed(2));
			$('td:eq(5)', nRow).html(roundp);
			$('td:eq(0)', nRow).empty().append($('<a/>')
				.attr('href', baseURL + 'gene/details/' + aData[0])
				.html(aData[0]));
			return nRow;
		}
	});

	// TOMTOM
	$('#run-tomtom').click(runTOMTOM);
});
<|endoftext|>