You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@zeppelin.apache.org by ah...@apache.org on 2017/04/20 04:52:40 UTC
[1/8] zeppelin git commit: [ZEPPELIN-1940] lint rule set is NOT
applied at all.
Repository: zeppelin
Updated Branches:
refs/heads/master 13aabe3e4 -> 19b0f30f8
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/ngenter/ngenter.directive.test.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/ngenter/ngenter.directive.test.js b/zeppelin-web/src/components/ngenter/ngenter.directive.test.js
index d347155..49f97cc 100644
--- a/zeppelin-web/src/components/ngenter/ngenter.directive.test.js
+++ b/zeppelin-web/src/components/ngenter/ngenter.directive.test.js
@@ -1,25 +1,24 @@
-describe('Directive: ngEnter', function() {
-
+describe('Directive: ngEnter', function () {
// load the directive's module
- beforeEach(angular.mock.module('zeppelinWebApp'));
+ beforeEach(angular.mock.module('zeppelinWebApp'))
- var element;
- var scope;
+ let element
+ let scope
- beforeEach(inject(function($rootScope) {
- scope = $rootScope.$new();
- }));
+ beforeEach(inject(function ($rootScope) {
+ scope = $rootScope.$new()
+ }))
- it('should be define', inject(function($compile) {
- element = angular.element('<ng-enter></ng-enter>');
- element = $compile(element)(scope);
- expect(element.text()).toBeDefined();
- }));
+ it('should be define', inject(function ($compile) {
+ element = angular.element('<ng-enter></ng-enter>')
+ element = $compile(element)(scope)
+ expect(element.text()).toBeDefined()
+ }))
- //Test the rest of function in ngEnter
+ // Test the rest of function in ngEnter
/* it('should make hidden element visible', inject(function ($compile) {
element = angular.element('<ng-enter></ng-enter>');
element = $compile(element)(scope);
expect(element.text()).toBe('this is the ngEnter directive');
- }));*/
-});
+ })); */
+})
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/ngescape/ngescape.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/ngescape/ngescape.directive.js b/zeppelin-web/src/components/ngescape/ngescape.directive.js
index 4c404aa..b52a7a7 100644
--- a/zeppelin-web/src/components/ngescape/ngescape.directive.js
+++ b/zeppelin-web/src/components/ngescape/ngescape.directive.js
@@ -12,18 +12,17 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('ngEscape', ngEscape);
+angular.module('zeppelinWebApp').directive('ngEscape', ngEscape)
-function ngEscape() {
- return function(scope, element, attrs) {
- element.bind('keydown keyup', function(event) {
+function ngEscape () {
+ return function (scope, element, attrs) {
+ element.bind('keydown keyup', function (event) {
if (event.which === 27) {
- scope.$apply(function() {
- scope.$eval(attrs.ngEscape);
- });
- event.preventDefault();
+ scope.$apply(function () {
+ scope.$eval(attrs.ngEscape)
+ })
+ event.preventDefault()
}
- });
- };
+ })
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/noteAction/noteAction.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/noteAction/noteAction.service.js b/zeppelin-web/src/components/noteAction/noteAction.service.js
index e08a6c3..f925975 100644
--- a/zeppelin-web/src/components/noteAction/noteAction.service.js
+++ b/zeppelin-web/src/components/noteAction/noteAction.service.js
@@ -12,172 +12,172 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').service('noteActionSrv', noteActionSrv);
+angular.module('zeppelinWebApp').service('noteActionSrv', noteActionSrv)
-function noteActionSrv(websocketMsgSrv, $location, renameSrv, noteListDataFactory) {
- 'ngInject';
+function noteActionSrv (websocketMsgSrv, $location, renameSrv, noteListDataFactory) {
+ 'ngInject'
- this.moveNoteToTrash = function(noteId, redirectToHome) {
+ this.moveNoteToTrash = function (noteId, redirectToHome) {
BootstrapDialog.confirm({
closable: true,
title: 'Move this note to trash?',
message: 'This note will be moved to <strong>trash</strong>.',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.moveNoteToTrash(noteId);
+ websocketMsgSrv.moveNoteToTrash(noteId)
if (redirectToHome) {
- $location.path('/');
+ $location.path('/')
}
}
}
- });
- };
+ })
+ }
- this.moveFolderToTrash = function(folderId) {
+ this.moveFolderToTrash = function (folderId) {
BootstrapDialog.confirm({
closable: true,
title: 'Move this folder to trash?',
message: 'This folder will be moved to <strong>trash</strong>.',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.moveFolderToTrash(folderId);
+ websocketMsgSrv.moveFolderToTrash(folderId)
}
}
- });
- };
+ })
+ }
- this.removeNote = function(noteId, redirectToHome) {
+ this.removeNote = function (noteId, redirectToHome) {
BootstrapDialog.confirm({
type: BootstrapDialog.TYPE_WARNING,
closable: true,
title: 'WARNING! This note will be removed permanently',
message: 'This cannot be undone. Are you sure?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.deleteNote(noteId);
+ websocketMsgSrv.deleteNote(noteId)
if (redirectToHome) {
- $location.path('/');
+ $location.path('/')
}
}
}
- });
- };
+ })
+ }
- this.removeFolder = function(folderId) {
+ this.removeFolder = function (folderId) {
BootstrapDialog.confirm({
type: BootstrapDialog.TYPE_WARNING,
closable: true,
title: 'WARNING! This folder will be removed permanently',
message: 'This cannot be undone. Are you sure?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.removeFolder(folderId);
+ websocketMsgSrv.removeFolder(folderId)
}
}
- });
- };
+ })
+ }
- this.restoreAll = function() {
+ this.restoreAll = function () {
BootstrapDialog.confirm({
closable: true,
title: 'Are you sure want to restore all notes in the trash?',
message: 'Folders and notes in the trash will be ' +
'<strong>merged</strong> into their original position.',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.restoreAll();
+ websocketMsgSrv.restoreAll()
}
}
- });
- };
+ })
+ }
- this.emptyTrash = function() {
+ this.emptyTrash = function () {
BootstrapDialog.confirm({
type: BootstrapDialog.TYPE_WARNING,
closable: true,
title: 'WARNING! Notes under trash will be removed permanently',
message: 'This cannot be undone. Are you sure?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.emptyTrash();
+ websocketMsgSrv.emptyTrash()
}
}
- });
- };
+ })
+ }
- this.clearAllParagraphOutput = function(noteId) {
+ this.clearAllParagraphOutput = function (noteId) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Do you want to clear all output?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.clearAllParagraphOutput(noteId);
+ websocketMsgSrv.clearAllParagraphOutput(noteId)
}
}
- });
- };
+ })
+ }
- this.renameNote = function(noteId, notePath) {
+ this.renameNote = function (noteId, notePath) {
renameSrv.openRenameModal({
title: 'Rename note',
oldName: notePath,
- callback: function(newName) {
- websocketMsgSrv.renameNote(noteId, newName);
+ callback: function (newName) {
+ websocketMsgSrv.renameNote(noteId, newName)
}
- });
- };
+ })
+ }
- this.renameFolder = function(folderId) {
+ this.renameFolder = function (folderId) {
renameSrv.openRenameModal({
title: 'Rename folder',
oldName: folderId,
- callback: function(newName) {
- var newFolderId = normalizeFolderId(newName);
+ callback: function (newName) {
+ let newFolderId = normalizeFolderId(newName)
if (_.has(noteListDataFactory.flatFolderMap, newFolderId)) {
BootstrapDialog.confirm({
type: BootstrapDialog.TYPE_WARNING,
closable: true,
title: 'WARNING! The folder will be MERGED',
message: 'The folder will be merged into <strong>' + newFolderId + '</strong>. Are you sure?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.renameFolder(folderId, newFolderId);
+ websocketMsgSrv.renameFolder(folderId, newFolderId)
}
}
- });
+ })
} else {
- websocketMsgSrv.renameFolder(folderId, newFolderId);
+ websocketMsgSrv.renameFolder(folderId, newFolderId)
}
}
- });
- };
+ })
+ }
- function normalizeFolderId(folderId) {
- folderId = folderId.trim();
+ function normalizeFolderId (folderId) {
+ folderId = folderId.trim()
while (folderId.indexOf('\\') > -1) {
- folderId = folderId.replace('\\', '/');
+ folderId = folderId.replace('\\', '/')
}
while (folderId.indexOf('///') > -1) {
- folderId = folderId.replace('///', '/');
+ folderId = folderId.replace('///', '/')
}
- folderId = folderId.replace('//', '/');
+ folderId = folderId.replace('//', '/')
if (folderId === '/') {
- return '/';
+ return '/'
}
if (folderId[0] === '/') {
- folderId = folderId.substring(1);
+ folderId = folderId.substring(1)
}
if (folderId.slice(-1) === '/') {
- folderId = folderId.slice(0, -1);
+ folderId = folderId.slice(0, -1)
}
- return folderId;
+ return folderId
}
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.js b/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.js
index f92bfaf..ab6956a 100644
--- a/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.js
+++ b/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.js
@@ -12,71 +12,70 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').factory('noteListDataFactory', noteListDataFactory);
+angular.module('zeppelinWebApp').factory('noteListDataFactory', noteListDataFactory)
-function noteListDataFactory(TRASH_FOLDER_ID) {
- 'ngInject';
+function noteListDataFactory (TRASH_FOLDER_ID) {
+ 'ngInject'
- var notes = {
+ const notes = {
root: {children: []},
flatList: [],
flatFolderMap: {},
- setNotes: function(notesList) {
+ setNotes: function (notesList) {
// a flat list to boost searching
notes.flatList = _.map(notesList, (note) => {
- note.isTrash = note.name ?
- note.name.split('/')[0] === TRASH_FOLDER_ID : false;
- return note;
- });
+ note.isTrash = note.name
+ ? note.name.split('/')[0] === TRASH_FOLDER_ID : false
+ return note
+ })
// construct the folder-based tree
- notes.root = {children: []};
- notes.flatFolderMap = {};
- _.reduce(notesList, function(root, note) {
- var noteName = note.name || note.id;
- var nodes = noteName.match(/([^\/][^\/]*)/g);
+ notes.root = {children: []}
+ notes.flatFolderMap = {}
+ _.reduce(notesList, function (root, note) {
+ let noteName = note.name || note.id
+ let nodes = noteName.match(/([^\/][^\/]*)/g)
// recursively add nodes
- addNode(root, nodes, note.id);
+ addNode(root, nodes, note.id)
- return root;
- }, notes.root);
+ return root
+ }, notes.root)
}
- };
+ }
- var addNode = function(curDir, nodes, noteId) {
+ const addNode = function (curDir, nodes, noteId) {
if (nodes.length === 1) { // the leaf
curDir.children.push({
name: nodes[0],
id: noteId,
path: curDir.id ? curDir.id + '/' + nodes[0] : nodes[0],
isTrash: curDir.id ? curDir.id.split('/')[0] === TRASH_FOLDER_ID : false
- });
+ })
} else { // a folder node
- var node = nodes.shift();
- var dir = _.find(curDir.children,
- function(c) {return c.name === node && c.children !== undefined;});
+ let node = nodes.shift()
+ let dir = _.find(curDir.children,
+ function (c) { return c.name === node && c.children !== undefined })
if (dir !== undefined) { // found an existing dir
- addNode(dir, nodes, noteId);
+ addNode(dir, nodes, noteId)
} else {
- var newDir = {
+ let newDir = {
id: curDir.id ? curDir.id + '/' + node : node,
name: node,
hidden: true,
children: [],
isTrash: curDir.id ? curDir.id.split('/')[0] === TRASH_FOLDER_ID : false
- };
+ }
// add the folder to flat folder map
- notes.flatFolderMap[newDir.id] = newDir;
+ notes.flatFolderMap[newDir.id] = newDir
- curDir.children.push(newDir);
- addNode(newDir, nodes, noteId);
+ curDir.children.push(newDir)
+ addNode(newDir, nodes, noteId)
}
}
- };
+ }
- return notes;
+ return notes
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.test.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.test.js b/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.test.js
index 85fb2ba..d1acc5d 100644
--- a/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.test.js
+++ b/zeppelin-web/src/components/noteListDataFactory/noteList.datafactory.test.js
@@ -1,17 +1,16 @@
-describe('Factory: NoteList', function() {
+describe('Factory: NoteList', function () {
+ let noteList
- var noteList;
+ beforeEach(function () {
+ angular.mock.module('zeppelinWebApp')
- beforeEach(function() {
- angular.mock.module('zeppelinWebApp');
+ inject(function ($injector) {
+ noteList = $injector.get('noteListDataFactory')
+ })
+ })
- inject(function($injector) {
- noteList = $injector.get('noteListDataFactory');
- });
- });
-
- it('should generate both flat list and folder-based list properly', function() {
- var notesList = [
+ it('should generate both flat list and folder-based list properly', function () {
+ let notesList = [
{name: 'A', id: '000001'},
{name: 'B', id: '000002'},
{id: '000003'}, // note without name
@@ -21,57 +20,56 @@ describe('Factory: NoteList', function() {
{name: '/C/CB/CBA', id: '000007'}, // same name with another note
{name: 'C///CB//CBB', id: '000008'},
{name: 'D/D[A/DA]B', id: '000009'} // check if '[' and ']' considered as folder seperator
- ];
- noteList.setNotes(notesList);
-
- var flatList = noteList.flatList;
- expect(flatList.length).toBe(9);
- expect(flatList[0].name).toBe('A');
- expect(flatList[0].id).toBe('000001');
- expect(flatList[1].name).toBe('B');
- expect(flatList[2].name).toBeUndefined();
- expect(flatList[3].name).toBe('/C/CA');
- expect(flatList[4].name).toBe('/C/CB');
- expect(flatList[5].name).toBe('/C/CB/CBA');
- expect(flatList[6].name).toBe('/C/CB/CBA');
- expect(flatList[7].name).toBe('C///CB//CBB');
- expect(flatList[8].name).toBe('D/D[A/DA]B');
+ ]
+ noteList.setNotes(notesList)
- var folderList = noteList.root.children;
- expect(folderList.length).toBe(5);
- expect(folderList[0].name).toBe('A');
- expect(folderList[0].id).toBe('000001');
- expect(folderList[1].name).toBe('B');
- expect(folderList[2].name).toBe('000003');
- expect(folderList[3].name).toBe('C');
- expect(folderList[3].id).toBe('C');
- expect(folderList[3].children.length).toBe(3);
- expect(folderList[3].children[0].name).toBe('CA');
- expect(folderList[3].children[0].id).toBe('000004');
- expect(folderList[3].children[0].children).toBeUndefined();
- expect(folderList[3].children[1].name).toBe('CB');
- expect(folderList[3].children[1].id).toBe('000005');
- expect(folderList[3].children[1].children).toBeUndefined();
- expect(folderList[3].children[2].name).toBe('CB');
- expect(folderList[3].children[2].id).toBe('C/CB');
- expect(folderList[3].children[2].children.length).toBe(3);
- expect(folderList[3].children[2].children[0].name).toBe('CBA');
- expect(folderList[3].children[2].children[0].id).toBe('000006');
- expect(folderList[3].children[2].children[0].children).toBeUndefined();
- expect(folderList[3].children[2].children[1].name).toBe('CBA');
- expect(folderList[3].children[2].children[1].id).toBe('000007');
- expect(folderList[3].children[2].children[1].children).toBeUndefined();
- expect(folderList[3].children[2].children[2].name).toBe('CBB');
- expect(folderList[3].children[2].children[2].id).toBe('000008');
- expect(folderList[3].children[2].children[2].children).toBeUndefined();
- expect(folderList[4].name).toBe('D');
- expect(folderList[4].id).toBe('D');
- expect(folderList[4].children.length).toBe(1);
- expect(folderList[4].children[0].name).toBe('D[A');
- expect(folderList[4].children[0].id).toBe('D/D[A');
- expect(folderList[4].children[0].children[0].name).toBe('DA]B');
- expect(folderList[4].children[0].children[0].id).toBe('000009');
- expect(folderList[4].children[0].children[0].children).toBeUndefined();
- });
+ let flatList = noteList.flatList
+ expect(flatList.length).toBe(9)
+ expect(flatList[0].name).toBe('A')
+ expect(flatList[0].id).toBe('000001')
+ expect(flatList[1].name).toBe('B')
+ expect(flatList[2].name).toBeUndefined()
+ expect(flatList[3].name).toBe('/C/CA')
+ expect(flatList[4].name).toBe('/C/CB')
+ expect(flatList[5].name).toBe('/C/CB/CBA')
+ expect(flatList[6].name).toBe('/C/CB/CBA')
+ expect(flatList[7].name).toBe('C///CB//CBB')
+ expect(flatList[8].name).toBe('D/D[A/DA]B')
-});
+ let folderList = noteList.root.children
+ expect(folderList.length).toBe(5)
+ expect(folderList[0].name).toBe('A')
+ expect(folderList[0].id).toBe('000001')
+ expect(folderList[1].name).toBe('B')
+ expect(folderList[2].name).toBe('000003')
+ expect(folderList[3].name).toBe('C')
+ expect(folderList[3].id).toBe('C')
+ expect(folderList[3].children.length).toBe(3)
+ expect(folderList[3].children[0].name).toBe('CA')
+ expect(folderList[3].children[0].id).toBe('000004')
+ expect(folderList[3].children[0].children).toBeUndefined()
+ expect(folderList[3].children[1].name).toBe('CB')
+ expect(folderList[3].children[1].id).toBe('000005')
+ expect(folderList[3].children[1].children).toBeUndefined()
+ expect(folderList[3].children[2].name).toBe('CB')
+ expect(folderList[3].children[2].id).toBe('C/CB')
+ expect(folderList[3].children[2].children.length).toBe(3)
+ expect(folderList[3].children[2].children[0].name).toBe('CBA')
+ expect(folderList[3].children[2].children[0].id).toBe('000006')
+ expect(folderList[3].children[2].children[0].children).toBeUndefined()
+ expect(folderList[3].children[2].children[1].name).toBe('CBA')
+ expect(folderList[3].children[2].children[1].id).toBe('000007')
+ expect(folderList[3].children[2].children[1].children).toBeUndefined()
+ expect(folderList[3].children[2].children[2].name).toBe('CBB')
+ expect(folderList[3].children[2].children[2].id).toBe('000008')
+ expect(folderList[3].children[2].children[2].children).toBeUndefined()
+ expect(folderList[4].name).toBe('D')
+ expect(folderList[4].id).toBe('D')
+ expect(folderList[4].children.length).toBe(1)
+ expect(folderList[4].children[0].name).toBe('D[A')
+ expect(folderList[4].children[0].id).toBe('D/D[A')
+ expect(folderList[4].children[0].children[0].name).toBe('DA]B')
+ expect(folderList[4].children[0].children[0].id).toBe('000009')
+ expect(folderList[4].children[0].children[0].children).toBeUndefined()
+ })
+})
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/noteName-create/notename.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/noteName-create/notename.controller.js b/zeppelin-web/src/components/noteName-create/notename.controller.js
index 865d653..815e9d5 100644
--- a/zeppelin-web/src/components/noteName-create/notename.controller.js
+++ b/zeppelin-web/src/components/noteName-create/notename.controller.js
@@ -12,96 +12,93 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('NotenameCtrl', NotenameCtrl);
+angular.module('zeppelinWebApp').controller('NotenameCtrl', NotenameCtrl)
-function NotenameCtrl($scope, noteListDataFactory, $routeParams, websocketMsgSrv) {
- 'ngInject';
+function NotenameCtrl ($scope, noteListDataFactory, $routeParams, websocketMsgSrv) {
+ 'ngInject'
- var vm = this;
- vm.clone = false;
- vm.notes = noteListDataFactory;
- vm.websocketMsgSrv = websocketMsgSrv;
- $scope.note = {};
- $scope.interpreterSettings = {};
- $scope.note.defaultInterpreter = null;
+ let vm = this
+ vm.clone = false
+ vm.notes = noteListDataFactory
+ vm.websocketMsgSrv = websocketMsgSrv
+ $scope.note = {}
+ $scope.interpreterSettings = {}
+ $scope.note.defaultInterpreter = null
- vm.createNote = function() {
+ vm.createNote = function () {
if (!vm.clone) {
- var defaultInterpreterId = '';
+ let defaultInterpreterId = ''
if ($scope.note.defaultInterpreter !== null) {
- defaultInterpreterId = $scope.note.defaultInterpreter.id;
+ defaultInterpreterId = $scope.note.defaultInterpreter.id
}
- vm.websocketMsgSrv.createNotebook($scope.note.notename, defaultInterpreterId);
- $scope.note.defaultInterpreter = $scope.interpreterSettings[0];
+ vm.websocketMsgSrv.createNotebook($scope.note.notename, defaultInterpreterId)
+ $scope.note.defaultInterpreter = $scope.interpreterSettings[0]
} else {
- var noteId = $routeParams.noteId;
- vm.websocketMsgSrv.cloneNote(noteId, $scope.note.notename);
+ let noteId = $routeParams.noteId
+ vm.websocketMsgSrv.cloneNote(noteId, $scope.note.notename)
}
- };
+ }
- vm.handleNameEnter = function() {
- angular.element('#noteNameModal').modal('toggle');
- vm.createNote();
- };
+ vm.handleNameEnter = function () {
+ angular.element('#noteNameModal').modal('toggle')
+ vm.createNote()
+ }
vm.preVisible = function(clone, sourceNoteName, path) {
- vm.clone = clone;
- vm.sourceNoteName = sourceNoteName;
- $scope.note.notename = vm.clone ? vm.cloneNoteName() : vm.newNoteName(path);
- $scope.$apply();
- };
+ vm.clone = clone
+ vm.sourceNoteName = sourceNoteName
+ $scope.note.notename = vm.clone ? vm.cloneNoteName() : vm.newNoteName(path)
+ $scope.$apply()
+ }
vm.newNoteName = function(path) {
- var newCount = 1;
- angular.forEach(vm.notes.flatList, function(noteName) {
- noteName = noteName.name;
+ let newCount = 1
+ angular.forEach(vm.notes.flatList, function (noteName) {
+ noteName = noteName.name
if (noteName.match(/^Untitled Note [0-9]*$/)) {
- var lastCount = noteName.substr(14) * 1;
+ let lastCount = noteName.substr(14) * 1
if (newCount <= lastCount) {
- newCount = lastCount + 1;
+ newCount = lastCount + 1
}
}
- });
- return (path ? path + '/' : '') +'Untitled Note ' + newCount;
- };
-
- vm.cloneNoteName = function() {
- var copyCount = 1;
- var newCloneName = '';
- var lastIndex = vm.sourceNoteName.lastIndexOf(' ');
- var endsWithNumber = !!vm.sourceNoteName.match('^.+?\\s\\d$');
- var noteNamePrefix = endsWithNumber ? vm.sourceNoteName.substr(0, lastIndex) : vm.sourceNoteName;
- var regexp = new RegExp('^' + noteNamePrefix + ' .+');
-
- angular.forEach(vm.notes.flatList, function(noteName) {
- noteName = noteName.name;
+ })
+ return (path ? path + '/' : '') + 'Untitled Note ' + newCount
+ }
+
+ vm.cloneNoteName = function () {
+ let copyCount = 1
+ let newCloneName = ''
+ let lastIndex = vm.sourceNoteName.lastIndexOf(' ')
+ let endsWithNumber = !!vm.sourceNoteName.match('^.+?\\s\\d$')
+ let noteNamePrefix = endsWithNumber ? vm.sourceNoteName.substr(0, lastIndex) : vm.sourceNoteName
+ let regexp = new RegExp('^' + noteNamePrefix + ' .+')
+
+ angular.forEach(vm.notes.flatList, function (noteName) {
+ noteName = noteName.name
if (noteName.match(regexp)) {
- var lastCopyCount = noteName.substr(lastIndex).trim();
- newCloneName = noteNamePrefix;
- lastCopyCount = parseInt(lastCopyCount);
+ let lastCopyCount = noteName.substr(lastIndex).trim()
+ newCloneName = noteNamePrefix
+ lastCopyCount = parseInt(lastCopyCount)
if (copyCount <= lastCopyCount) {
- copyCount = lastCopyCount + 1;
+ copyCount = lastCopyCount + 1
}
}
- });
+ })
if (!newCloneName) {
- newCloneName = vm.sourceNoteName;
+ newCloneName = vm.sourceNoteName
}
- return newCloneName + ' ' + copyCount;
- };
-
- vm.getInterpreterSettings = function() {
- vm.websocketMsgSrv.getInterpreterSettings();
- };
+ return newCloneName + ' ' + copyCount
+ }
+ vm.getInterpreterSettings = function () {
+ vm.websocketMsgSrv.getInterpreterSettings()
+ }
- $scope.$on('interpreterSettings', function(event, data) {
- $scope.interpreterSettings = data.interpreterSettings;
-
- //initialize default interpreter with Spark interpreter
- $scope.note.defaultInterpreter = data.interpreterSettings[0];
- });
+ $scope.$on('interpreterSettings', function (event, data) {
+ $scope.interpreterSettings = data.interpreterSettings
+ // initialize default interpreter with Spark interpreter
+ $scope.note.defaultInterpreter = data.interpreterSettings[0]
+ })
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/noteName-create/notename.controller.test.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/noteName-create/notename.controller.test.js b/zeppelin-web/src/components/noteName-create/notename.controller.test.js
index 47e79c1..61bce14 100644
--- a/zeppelin-web/src/components/noteName-create/notename.controller.test.js
+++ b/zeppelin-web/src/components/noteName-create/notename.controller.test.js
@@ -1,40 +1,39 @@
-describe('Controller: NotenameCtrl', function() {
- beforeEach(angular.mock.module('zeppelinWebApp'));
+describe('Controller: NotenameCtrl', function () {
+ beforeEach(angular.mock.module('zeppelinWebApp'))
- var scope;
- var ctrl;
- var noteList;
+ let scope
+ let ctrl
+ let noteList
- beforeEach(inject(function($injector, $rootScope, $controller) {
- noteList = $injector.get('noteListDataFactory');
- scope = $rootScope.$new();
+ beforeEach(inject(function ($injector, $rootScope, $controller) {
+ noteList = $injector.get('noteListDataFactory')
+ scope = $rootScope.$new()
ctrl = $controller('NotenameCtrl', {
$scope: scope,
noteListDataFactory: noteList
- });
- }));
+ })
+ }))
- it('should create a new name from current name when cloneNoteName is called', function() {
- var notesList = [
+ it('should create a new name from current name when cloneNoteName is called', function () {
+ let notesList = [
{name: 'dsds 1', id: '1'},
{name: 'dsds 2', id: '2'},
{name: 'test name', id: '3'},
{name: 'aa bb cc', id: '4'},
{name: 'Untitled Note 6', id: '4'}
- ];
+ ]
- noteList.setNotes(notesList);
+ noteList.setNotes(notesList)
- ctrl.sourceNoteName = 'test name';
- expect(ctrl.cloneNoteName()).toEqual('test name 1');
- ctrl.sourceNoteName = 'aa bb cc';
- expect(ctrl.cloneNoteName()).toEqual('aa bb cc 1');
- ctrl.sourceNoteName = 'Untitled Note 6';
- expect(ctrl.cloneNoteName()).toEqual('Untitled Note 7');
- ctrl.sourceNoteName = 'My_note';
- expect(ctrl.cloneNoteName()).toEqual('My_note 1');
- ctrl.sourceNoteName = 'dsds 2';
- expect(ctrl.cloneNoteName()).toEqual('dsds 3');
- });
-
-});
+ ctrl.sourceNoteName = 'test name'
+ expect(ctrl.cloneNoteName()).toEqual('test name 1')
+ ctrl.sourceNoteName = 'aa bb cc'
+ expect(ctrl.cloneNoteName()).toEqual('aa bb cc 1')
+ ctrl.sourceNoteName = 'Untitled Note 6'
+ expect(ctrl.cloneNoteName()).toEqual('Untitled Note 7')
+ ctrl.sourceNoteName = 'My_note'
+ expect(ctrl.cloneNoteName()).toEqual('My_note 1')
+ ctrl.sourceNoteName = 'dsds 2'
+ expect(ctrl.cloneNoteName()).toEqual('dsds 3')
+ })
+})
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/noteName-create/visible.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/noteName-create/visible.directive.js b/zeppelin-web/src/components/noteName-create/visible.directive.js
index 6dd19da..48c170f 100644
--- a/zeppelin-web/src/components/noteName-create/visible.directive.js
+++ b/zeppelin-web/src/components/noteName-create/visible.directive.js
@@ -12,9 +12,9 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('modalvisible', modalvisible);
+angular.module('zeppelinWebApp').directive('modalvisible', modalvisible)
-function modalvisible() {
+function modalvisible () {
return {
restrict: 'A',
scope: {
@@ -22,25 +22,24 @@ function modalvisible() {
postVisibleCallback: '&postvisiblecallback',
targetinput: '@targetinput'
},
- link: function(scope, element, attrs) {
+ link: function (scope, element, attrs) {
// Add some listeners
- var previsibleMethod = scope.preVisibleCallback;
- var postVisibleMethod = scope.postVisibleCallback;
- element.on('show.bs.modal',function(e) {
- var relatedTarget = angular.element(e.relatedTarget);
- var clone = relatedTarget.data('clone');
- var sourceNoteName = relatedTarget.data('source-note-name');
- var path = relatedTarget.data('path');
- var cloneNote = clone ? true : false;
- previsibleMethod()(cloneNote, sourceNoteName, path);
- });
- element.on('shown.bs.modal', function(e) {
+ let previsibleMethod = scope.preVisibleCallback
+ let postVisibleMethod = scope.postVisibleCallback
+ element.on('show.bs.modal', function (e) {
+ let relatedTarget = angular.element(e.relatedTarget)
+ let clone = relatedTarget.data('clone')
+ let sourceNoteName = relatedTarget.data('source-note-name')
+ let path = relatedTarget.data('path')
+ let cloneNote = clone ? true : false
+ previsibleMethod()(cloneNote, sourceNoteName, path)
+ })
+ element.on('shown.bs.modal', function (e) {
if (scope.targetinput) {
- angular.element(e.target).find('input#' + scope.targetinput).select();
+ angular.element(e.target).find('input#' + scope.targetinput).select()
}
- postVisibleMethod();
- });
+ postVisibleMethod()
+ })
}
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/noteName-import/notenameImport.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/noteName-import/notenameImport.controller.js b/zeppelin-web/src/components/noteName-import/notenameImport.controller.js
index 74c9c59..b42e8d8 100644
--- a/zeppelin-web/src/components/noteName-import/notenameImport.controller.js
+++ b/zeppelin-web/src/components/noteName-import/notenameImport.controller.js
@@ -12,74 +12,74 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('NoteImportCtrl', NoteImportCtrl);
-
-function NoteImportCtrl($scope, $timeout, websocketMsgSrv) {
- 'ngInject';
-
- var vm = this;
- $scope.note = {};
- $scope.note.step1 = true;
- $scope.note.step2 = false;
- $scope.maxLimit = '';
- var limit = 0;
-
- websocketMsgSrv.listConfigurations();
- $scope.$on('configurationsInfo', function(scope, event) {
- limit = event.configurations['zeppelin.websocket.max.text.message.size'];
- $scope.maxLimit = Math.round(limit / 1048576);
- });
-
- vm.resetFlags = function() {
- $scope.note = {};
- $scope.note.step1 = true;
- $scope.note.step2 = false;
- angular.element('#noteImportFile').val('');
- };
-
- $scope.uploadFile = function() {
- angular.element('#noteImportFile').click();
- };
-
- $scope.importFile = function(element) {
- $scope.note.errorText = '';
- $scope.note.importFile = element.files[0];
- var file = $scope.note.importFile;
- var reader = new FileReader();
+angular.module('zeppelinWebApp').controller('NoteImportCtrl', NoteImportCtrl)
+
+function NoteImportCtrl ($scope, $timeout, websocketMsgSrv) {
+ 'ngInject'
+
+ let vm = this
+ $scope.note = {}
+ $scope.note.step1 = true
+ $scope.note.step2 = false
+ $scope.maxLimit = ''
+ let limit = 0
+
+ websocketMsgSrv.listConfigurations()
+ $scope.$on('configurationsInfo', function (scope, event) {
+ limit = event.configurations['zeppelin.websocket.max.text.message.size']
+ $scope.maxLimit = Math.round(limit / 1048576)
+ })
+
+ vm.resetFlags = function () {
+ $scope.note = {}
+ $scope.note.step1 = true
+ $scope.note.step2 = false
+ angular.element('#noteImportFile').val('')
+ }
+
+ $scope.uploadFile = function () {
+ angular.element('#noteImportFile').click()
+ }
+
+ $scope.importFile = function (element) {
+ $scope.note.errorText = ''
+ $scope.note.importFile = element.files[0]
+ let file = $scope.note.importFile
+ let reader = new FileReader()
if (file.size > limit) {
- $scope.note.errorText = 'File size limit Exceeded!';
- $scope.$apply();
- return;
+ $scope.note.errorText = 'File size limit Exceeded!'
+ $scope.$apply()
+ return
}
- reader.onloadend = function() {
- vm.processImportJson(reader.result);
- };
+ reader.onloadend = function () {
+ vm.processImportJson(reader.result)
+ }
if (file) {
- reader.readAsText(file);
+ reader.readAsText(file)
}
- };
-
- $scope.uploadURL = function() {
- $scope.note.errorText = '';
- $scope.note.step1 = false;
- $timeout(function() {
- $scope.note.step2 = true;
- }, 400);
- };
-
- vm.importBack = function() {
- $scope.note.errorText = '';
- $timeout(function() {
- $scope.note.step1 = true;
- }, 400);
- $scope.note.step2 = false;
- };
-
- vm.importNote = function() {
- $scope.note.errorText = '';
+ }
+
+ $scope.uploadURL = function () {
+ $scope.note.errorText = ''
+ $scope.note.step1 = false
+ $timeout(function () {
+ $scope.note.step2 = true
+ }, 400)
+ }
+
+ vm.importBack = function () {
+ $scope.note.errorText = ''
+ $timeout(function () {
+ $scope.note.step1 = true
+ }, 400)
+ $scope.note.step2 = false
+ }
+
+ vm.importNote = function () {
+ $scope.note.errorText = ''
if ($scope.note.importUrl) {
jQuery.ajax({
url: $scope.note.importUrl,
@@ -89,50 +89,48 @@ function NoteImportCtrl($scope, $timeout, websocketMsgSrv) {
xhrFields: {
withCredentials: false
},
- error: function(xhr, ajaxOptions, thrownError) {
- $scope.note.errorText = 'Unable to Fetch URL';
- $scope.$apply();
- }}).done(function(data) {
- vm.processImportJson(data);
- });
+ error: function (xhr, ajaxOptions, thrownError) {
+ $scope.note.errorText = 'Unable to Fetch URL'
+ $scope.$apply()
+ }}).done(function (data) {
+ vm.processImportJson(data)
+ })
} else {
- $scope.note.errorText = 'Enter URL';
- $scope.$apply();
+ $scope.note.errorText = 'Enter URL'
+ $scope.$apply()
}
- };
+ }
- vm.processImportJson = function(result) {
+ vm.processImportJson = function (result) {
if (typeof result !== 'object') {
try {
- result = JSON.parse(result);
+ result = JSON.parse(result)
} catch (e) {
- $scope.note.errorText = 'JSON parse exception';
- $scope.$apply();
- return;
+ $scope.note.errorText = 'JSON parse exception'
+ $scope.$apply()
+ return
}
-
}
if (result.paragraphs && result.paragraphs.length > 0) {
if (!$scope.note.noteImportName) {
- $scope.note.noteImportName = result.name;
+ $scope.note.noteImportName = result.name
} else {
- result.name = $scope.note.noteImportName;
+ result.name = $scope.note.noteImportName
}
- websocketMsgSrv.importNote(result);
- //angular.element('#noteImportModal').modal('hide');
+ websocketMsgSrv.importNote(result)
+ // angular.element('#noteImportModal').modal('hide');
} else {
- $scope.note.errorText = 'Invalid JSON';
+ $scope.note.errorText = 'Invalid JSON'
}
- $scope.$apply();
- };
+ $scope.$apply()
+ }
/*
** $scope.$on functions below
*/
- $scope.$on('setNoteMenu', function(event, notes) {
- vm.resetFlags();
- angular.element('#noteImportModal').modal('hide');
- });
+ $scope.$on('setNoteMenu', function (event, notes) {
+ vm.resetFlags()
+ angular.element('#noteImportModal').modal('hide')
+ })
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/notevarshareService/notevarshare.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/notevarshareService/notevarshare.service.js b/zeppelin-web/src/components/notevarshareService/notevarshare.service.js
index a4bf7bc..04981bf 100644
--- a/zeppelin-web/src/components/notevarshareService/notevarshare.service.js
+++ b/zeppelin-web/src/components/notevarshareService/notevarshare.service.js
@@ -12,28 +12,28 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').service('noteVarShareService', noteVarShareService);
+angular.module('zeppelinWebApp').service('noteVarShareService', noteVarShareService)
-function noteVarShareService() {
- 'ngInject';
+function noteVarShareService () {
+ 'ngInject'
- var store = {};
+ let store = {}
- this.clear = function() {
- store = {};
- };
+ this.clear = function () {
+ store = {}
+ }
- this.put = function(key, value) {
- store[key] = value;
- };
+ this.put = function (key, value) {
+ store[key] = value
+ }
- this.get = function(key) {
- return store[key];
- };
+ this.get = function (key) {
+ return store[key]
+ }
- this.del = function(key) {
- var v = store[key];
- delete store[key];
- return v;
- };
+ this.del = function (key) {
+ let v = store[key]
+ delete store[key]
+ return v
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe-popup.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe-popup.directive.js b/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe-popup.directive.js
index 595ed2f..69ea454 100644
--- a/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe-popup.directive.js
+++ b/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe-popup.directive.js
@@ -12,14 +12,13 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('popoverHtmlUnsafePopup', popoverHtmlUnsafePopup);
+angular.module('zeppelinWebApp').directive('popoverHtmlUnsafePopup', popoverHtmlUnsafePopup)
-function popoverHtmlUnsafePopup() {
+function popoverHtmlUnsafePopup () {
return {
restrict: 'EA',
replace: true,
scope: {title: '@', content: '@', placement: '@', animation: '&', isOpen: '&'},
templateUrl: 'components/popover-html-unsafe/popover-html-unsafe-popup.html'
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe.directive.js b/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe.directive.js
index ad2f7ea..d4dd546 100644
--- a/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe.directive.js
+++ b/zeppelin-web/src/components/popover-html-unsafe/popover-html-unsafe.directive.js
@@ -12,11 +12,10 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('popoverHtmlUnsafe', popoverHtmlUnsafe);
+angular.module('zeppelinWebApp').directive('popoverHtmlUnsafe', popoverHtmlUnsafe)
-function popoverHtmlUnsafe($tooltip) {
- 'ngInject';
+function popoverHtmlUnsafe ($tooltip) {
+ 'ngInject'
- return $tooltip('popoverHtmlUnsafe', 'popover', 'click');
+ return $tooltip('popoverHtmlUnsafe', 'popover', 'click')
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/rename/rename.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/rename/rename.controller.js b/zeppelin-web/src/components/rename/rename.controller.js
index 61fe1d6..305c519 100644
--- a/zeppelin-web/src/components/rename/rename.controller.js
+++ b/zeppelin-web/src/components/rename/rename.controller.js
@@ -12,36 +12,35 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('RenameCtrl', RenameCtrl);
+angular.module('zeppelinWebApp').controller('RenameCtrl', RenameCtrl)
-function RenameCtrl($scope) {
- 'ngInject';
+function RenameCtrl ($scope) {
+ 'ngInject'
- var self = this;
+ let self = this
- $scope.params = {newName: ''};
- $scope.isValid = true;
+ $scope.params = {newName: ''}
+ $scope.isValid = true
- $scope.rename = function() {
- angular.element('#renameModal').modal('hide');
- self.callback($scope.params.newName);
- };
+ $scope.rename = function () {
+ angular.element('#renameModal').modal('hide')
+ self.callback($scope.params.newName)
+ }
- $scope.$on('openRenameModal', function(event, options) {
- self.validator = options.validator || defaultValidator;
- self.callback = options.callback || function() {};
+ $scope.$on('openRenameModal', function (event, options) {
+ self.validator = options.validator || defaultValidator
+ self.callback = options.callback || function () {}
- $scope.title = options.title || 'Rename';
- $scope.params.newName = options.oldName || '';
- $scope.validate = function() {
- $scope.isValid = self.validator($scope.params.newName);
- };
+ $scope.title = options.title || 'Rename'
+ $scope.params.newName = options.oldName || ''
+ $scope.validate = function () {
+ $scope.isValid = self.validator($scope.params.newName)
+ }
- angular.element('#renameModal').modal('show');
- });
+ angular.element('#renameModal').modal('show')
+ })
- function defaultValidator(str) {
- return !!str.trim();
+ function defaultValidator (str) {
+ return !!str.trim()
}
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/rename/rename.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/rename/rename.service.js b/zeppelin-web/src/components/rename/rename.service.js
index c25e145..135f85d 100644
--- a/zeppelin-web/src/components/rename/rename.service.js
+++ b/zeppelin-web/src/components/rename/rename.service.js
@@ -12,12 +12,12 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').service('renameSrv', renameSrv);
+angular.module('zeppelinWebApp').service('renameSrv', renameSrv)
-function renameSrv($rootScope) {
- 'ngInject';
+function renameSrv ($rootScope) {
+ 'ngInject'
- var self = this;
+ let self = this
/**
* <options schema>
@@ -26,7 +26,7 @@ function renameSrv($rootScope) {
* callback: (newName: string)=>void - callback onButtonClick
* validator: (str: string)=>boolean - input validator
*/
- self.openRenameModal = function(options) {
- $rootScope.$broadcast('openRenameModal', options);
- };
+ self.openRenameModal = function (options) {
+ $rootScope.$broadcast('openRenameModal', options)
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/resizable/resizable.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/resizable/resizable.directive.js b/zeppelin-web/src/components/resizable/resizable.directive.js
index afcfd1b..f0eed76 100644
--- a/zeppelin-web/src/components/resizable/resizable.directive.js
+++ b/zeppelin-web/src/components/resizable/resizable.directive.js
@@ -12,59 +12,58 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('resizable', resizable);
+angular.module('zeppelinWebApp').directive('resizable', resizable)
-function resizable() {
- var resizableConfig = {
+function resizable () {
+ let resizableConfig = {
autoHide: true,
handles: 'se',
helper: 'resizable-helper',
- stop: function() {
- angular.element(this).css({'width': '100%', 'height': '100%'});
+ stop: function () {
+ angular.element(this).css({'width': '100%', 'height': '100%'})
}
- };
+ }
return {
restrict: 'A',
scope: {
callback: '&onResize'
},
- link: function postLink(scope, elem, attrs) {
- attrs.$observe('resize', function(resize) {
- var resetResize = function(elem, resize) {
- var colStep = window.innerWidth / 12;
- elem.off('resizestop');
- var conf = angular.copy(resizableConfig);
+ link: function postLink (scope, elem, attrs) {
+ attrs.$observe('resize', function (resize) {
+ let resetResize = function (elem, resize) {
+ let colStep = window.innerWidth / 12
+ elem.off('resizestop')
+ let conf = angular.copy(resizableConfig)
if (resize.graphType === 'TABLE' || resize.graphType === 'TEXT') {
- conf.grid = [colStep, 10];
- conf.minHeight = 100;
+ conf.grid = [colStep, 10]
+ conf.minHeight = 100
} else {
- conf.grid = [colStep, 10000];
- conf.minHeight = 0;
+ conf.grid = [colStep, 10000]
+ conf.minHeight = 0
}
- conf.maxWidth = window.innerWidth;
+ conf.maxWidth = window.innerWidth
- elem.resizable(conf);
- elem.on('resizestop', function() {
+ elem.resizable(conf)
+ elem.on('resizestop', function () {
if (scope.callback) {
- var height = elem.height();
+ let height = elem.height()
if (height < 50) {
- height = 300;
+ height = 300
}
- scope.callback({width: Math.ceil(elem.width() / colStep), height: height});
+ scope.callback({width: Math.ceil(elem.width() / colStep), height: height})
}
- });
- };
+ })
+ }
- resize = JSON.parse(resize);
+ resize = JSON.parse(resize)
if (resize.allowresize === 'true') {
- resetResize(elem, resize);
- angular.element(window).resize(function() {
- resetResize(elem, resize);
- });
+ resetResize(elem, resize)
+ angular.element(window).resize(function () {
+ resetResize(elem, resize)
+ })
}
- });
+ })
}
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/saveAs/saveAs.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/saveAs/saveAs.service.js b/zeppelin-web/src/components/saveAs/saveAs.service.js
index 5324fe0..b9cb7c8 100644
--- a/zeppelin-web/src/components/saveAs/saveAs.service.js
+++ b/zeppelin-web/src/components/saveAs/saveAs.service.js
@@ -12,41 +12,40 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').service('saveAsService', saveAsService);
+angular.module('zeppelinWebApp').service('saveAsService', saveAsService)
-function saveAsService(browserDetectService) {
- 'ngInject';
+function saveAsService (browserDetectService) {
+ 'ngInject'
- this.saveAs = function(content, filename, extension) {
- var BOM = '\uFEFF';
+ this.saveAs = function (content, filename, extension) {
+ let BOM = '\uFEFF'
if (browserDetectService.detectIE()) {
- angular.element('body').append('<iframe id="SaveAsId" style="display: none"></iframe>');
- var frameSaveAs = angular.element('body > iframe#SaveAsId')[0].contentWindow;
- content = BOM + content;
- frameSaveAs.document.open('text/json', 'replace');
- frameSaveAs.document.write(content);
- frameSaveAs.document.close();
- frameSaveAs.focus();
- var t1 = Date.now();
- frameSaveAs.document.execCommand('SaveAs', false, filename + '.' + extension);
- var t2 = Date.now();
+ angular.element('body').append('<iframe id="SaveAsId" style="display: none"></iframe>')
+ let frameSaveAs = angular.element('body > iframe#SaveAsId')[0].contentWindow
+ content = BOM + content
+ frameSaveAs.document.open('text/json', 'replace')
+ frameSaveAs.document.write(content)
+ frameSaveAs.document.close()
+ frameSaveAs.focus()
+ let t1 = Date.now()
+ frameSaveAs.document.execCommand('SaveAs', false, filename + '.' + extension)
+ let t2 = Date.now()
- //This means, this version of IE dosen't support auto download of a file with extension provided in param
- //falling back to ".txt"
+ // This means, this version of IE dosen't support auto download of a file with extension provided in param
+ // falling back to ".txt"
if (t1 === t2) {
- frameSaveAs.document.execCommand('SaveAs', true, filename + '.txt');
+ frameSaveAs.document.execCommand('SaveAs', true, filename + '.txt')
}
- angular.element('body > iframe#SaveAsId').remove();
+ angular.element('body > iframe#SaveAsId').remove()
} else {
- content = 'data:image/svg;charset=utf-8,' + BOM + encodeURIComponent(content);
- angular.element('body').append('<a id="SaveAsId"></a>');
- var saveAsElement = angular.element('body > a#SaveAsId');
- saveAsElement.attr('href', content);
- saveAsElement.attr('download', filename + '.' + extension);
- saveAsElement.attr('target', '_blank');
- saveAsElement[0].click();
- saveAsElement.remove();
+ content = 'data:image/svg;charset=utf-8,' + BOM + encodeURIComponent(content)
+ angular.element('body').append('<a id="SaveAsId"></a>')
+ let saveAsElement = angular.element('body > a#SaveAsId')
+ saveAsElement.attr('href', content)
+ saveAsElement.attr('download', filename + '.' + extension)
+ saveAsElement.attr('target', '_blank')
+ saveAsElement[0].click()
+ saveAsElement.remove()
}
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/searchService/search.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/searchService/search.service.js b/zeppelin-web/src/components/searchService/search.service.js
index 460a3d4..a1c8640 100644
--- a/zeppelin-web/src/components/searchService/search.service.js
+++ b/zeppelin-web/src/components/searchService/search.service.js
@@ -12,23 +12,22 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').service('searchService', searchService);
+angular.module('zeppelinWebApp').service('searchService', searchService)
-function searchService($resource, baseUrlSrv) {
- 'ngInject';
+function searchService ($resource, baseUrlSrv) {
+ 'ngInject'
- this.search = function(term) {
- this.searchTerm = term.q;
- console.log('Searching for: %o', term.q);
- if (!term.q) { //TODO(bzz): empty string check
- return;
+ this.search = function (term) {
+ this.searchTerm = term.q
+ console.log('Searching for: %o', term.q)
+ if (!term.q) { // TODO(bzz): empty string check
+ return
}
- var encQuery = window.encodeURIComponent(term.q);
+ let encQuery = window.encodeURIComponent(term.q)
return $resource(baseUrlSrv.getRestApiBase() + '/notebook/search?q=' + encQuery, {}, {
query: {method: 'GET'}
- });
- };
+ })
+ }
- this.searchTerm = '';
+ this.searchTerm = ''
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/websocketEvents/websocketEvents.factory.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/websocketEvents/websocketEvents.factory.js b/zeppelin-web/src/components/websocketEvents/websocketEvents.factory.js
index 186de88..08eb16b 100644
--- a/zeppelin-web/src/components/websocketEvents/websocketEvents.factory.js
+++ b/zeppelin-web/src/components/websocketEvents/websocketEvents.factory.js
@@ -12,91 +12,91 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').factory('websocketEvents', websocketEvents);
+angular.module('zeppelinWebApp').factory('websocketEvents', websocketEvents)
-function websocketEvents($rootScope, $websocket, $location, baseUrlSrv) {
- 'ngInject';
+function websocketEvents ($rootScope, $websocket, $location, baseUrlSrv) {
+ 'ngInject'
- var websocketCalls = {};
- var pingIntervalId;
+ let websocketCalls = {}
+ let pingIntervalId
- websocketCalls.ws = $websocket(baseUrlSrv.getWebsocketUrl());
- websocketCalls.ws.reconnectIfNotNormalClose = true;
+ websocketCalls.ws = $websocket(baseUrlSrv.getWebsocketUrl())
+ websocketCalls.ws.reconnectIfNotNormalClose = true
- websocketCalls.ws.onOpen(function() {
- console.log('Websocket created');
- $rootScope.$broadcast('setConnectedStatus', true);
- pingIntervalId = setInterval(function() {
- websocketCalls.sendNewEvent({op: 'PING'});
- }, 10000);
- });
+ websocketCalls.ws.onOpen(function () {
+ console.log('Websocket created')
+ $rootScope.$broadcast('setConnectedStatus', true)
+ pingIntervalId = setInterval(function () {
+ websocketCalls.sendNewEvent({op: 'PING'})
+ }, 10000)
+ })
- websocketCalls.sendNewEvent = function(data) {
+ websocketCalls.sendNewEvent = function (data) {
if ($rootScope.ticket !== undefined) {
- data.principal = $rootScope.ticket.principal;
- data.ticket = $rootScope.ticket.ticket;
- data.roles = $rootScope.ticket.roles;
+ data.principal = $rootScope.ticket.principal
+ data.ticket = $rootScope.ticket.ticket
+ data.roles = $rootScope.ticket.roles
} else {
- data.principal = '';
- data.ticket = '';
- data.roles = '';
+ data.principal = ''
+ data.ticket = ''
+ data.roles = ''
}
- console.log('Send >> %o, %o, %o, %o, %o', data.op, data.principal, data.ticket, data.roles, data);
- websocketCalls.ws.send(JSON.stringify(data));
- };
+ console.log('Send >> %o, %o, %o, %o, %o', data.op, data.principal, data.ticket, data.roles, data)
+ websocketCalls.ws.send(JSON.stringify(data))
+ }
- websocketCalls.isConnected = function() {
- return (websocketCalls.ws.socket.readyState === 1);
- };
+ websocketCalls.isConnected = function () {
+ return (websocketCalls.ws.socket.readyState === 1)
+ }
- websocketCalls.ws.onMessage(function(event) {
- var payload;
+ websocketCalls.ws.onMessage(function (event) {
+ let payload
if (event.data) {
- payload = angular.fromJson(event.data);
+ payload = angular.fromJson(event.data)
}
console.log('Receive Json << %o', event.data)
- console.log('Receive << %o, %o', payload.op, payload);
- var op = payload.op;
- var data = payload.data;
+ console.log('Receive << %o, %o', payload.op, payload)
+ let op = payload.op
+ let data = payload.data
if (op === 'NOTE') {
- $rootScope.$broadcast('setNoteContent', data.note);
+ $rootScope.$broadcast('setNoteContent', data.note)
} else if (op === 'NEW_NOTE') {
- $location.path('/notebook/' + data.note.id);
+ $location.path('/notebook/' + data.note.id)
} else if (op === 'NOTES_INFO') {
- $rootScope.$broadcast('setNoteMenu', data.notes);
+ $rootScope.$broadcast('setNoteMenu', data.notes)
} else if (op === 'LIST_NOTE_JOBS') {
- $rootScope.$broadcast('setNoteJobs', data.noteJobs);
+ $rootScope.$broadcast('setNoteJobs', data.noteJobs)
} else if (op === 'LIST_UPDATE_NOTE_JOBS') {
- $rootScope.$broadcast('setUpdateNoteJobs', data.noteRunningJobs);
+ $rootScope.$broadcast('setUpdateNoteJobs', data.noteRunningJobs)
} else if (op === 'AUTH_INFO') {
- var btn = [];
+ let btn = []
if ($rootScope.ticket.roles === '[]') {
btn = [{
label: 'Close',
- action: function(dialog) {
- dialog.close();
+ action: function (dialog) {
+ dialog.close()
}
- }];
+ }]
} else {
btn = [{
label: 'Login',
- action: function(dialog) {
- dialog.close();
+ action: function (dialog) {
+ dialog.close()
angular.element('#loginModal').modal({
show: 'true'
- });
+ })
}
}, {
label: 'Cancel',
- action: function(dialog) {
- dialog.close();
+ action: function (dialog) {
+ dialog.close()
// using $rootScope.apply to trigger angular digest cycle
// changing $location.path inside bootstrap modal wont trigger digest
- $rootScope.$apply(function() {
- $location.path('/');
- });
+ $rootScope.$apply(function () {
+ $location.path('/')
+ })
}
- }];
+ }]
}
BootstrapDialog.show({
@@ -106,40 +106,39 @@ function websocketEvents($rootScope, $websocket, $location, baseUrlSrv) {
title: 'Insufficient privileges',
message: data.info.toString(),
buttons: btn
- });
-
+ })
} else if (op === 'PARAGRAPH') {
- $rootScope.$broadcast('updateParagraph', data);
+ $rootScope.$broadcast('updateParagraph', data)
} else if (op === 'RUN_PARAGRAPH_USING_SPELL') {
- $rootScope.$broadcast('runParagraphUsingSpell', data);
+ $rootScope.$broadcast('runParagraphUsingSpell', data)
} else if (op === 'PARAGRAPH_APPEND_OUTPUT') {
- $rootScope.$broadcast('appendParagraphOutput', data);
+ $rootScope.$broadcast('appendParagraphOutput', data)
} else if (op === 'PARAGRAPH_UPDATE_OUTPUT') {
- $rootScope.$broadcast('updateParagraphOutput', data);
+ $rootScope.$broadcast('updateParagraphOutput', data)
} else if (op === 'PROGRESS') {
- $rootScope.$broadcast('updateProgress', data);
+ $rootScope.$broadcast('updateProgress', data)
} else if (op === 'COMPLETION_LIST') {
- $rootScope.$broadcast('completionList', data);
+ $rootScope.$broadcast('completionList', data)
} else if (op === 'EDITOR_SETTING') {
- $rootScope.$broadcast('editorSetting', data);
+ $rootScope.$broadcast('editorSetting', data)
} else if (op === 'ANGULAR_OBJECT_UPDATE') {
- $rootScope.$broadcast('angularObjectUpdate', data);
+ $rootScope.$broadcast('angularObjectUpdate', data)
} else if (op === 'ANGULAR_OBJECT_REMOVE') {
- $rootScope.$broadcast('angularObjectRemove', data);
+ $rootScope.$broadcast('angularObjectRemove', data)
} else if (op === 'APP_APPEND_OUTPUT') {
- $rootScope.$broadcast('appendAppOutput', data);
+ $rootScope.$broadcast('appendAppOutput', data)
} else if (op === 'APP_UPDATE_OUTPUT') {
- $rootScope.$broadcast('updateAppOutput', data);
+ $rootScope.$broadcast('updateAppOutput', data)
} else if (op === 'APP_LOAD') {
- $rootScope.$broadcast('appLoad', data);
+ $rootScope.$broadcast('appLoad', data)
} else if (op === 'APP_STATUS_CHANGE') {
- $rootScope.$broadcast('appStatusChange', data);
+ $rootScope.$broadcast('appStatusChange', data)
} else if (op === 'LIST_REVISION_HISTORY') {
- $rootScope.$broadcast('listRevisionHistory', data);
+ $rootScope.$broadcast('listRevisionHistory', data)
} else if (op === 'NOTE_REVISION') {
- $rootScope.$broadcast('noteRevision', data);
+ $rootScope.$broadcast('noteRevision', data)
} else if (op === 'INTERPRETER_BINDINGS') {
- $rootScope.$broadcast('interpreterBindings', data);
+ $rootScope.$broadcast('interpreterBindings', data)
} else if (op === 'ERROR_INFO') {
BootstrapDialog.show({
closable: false,
@@ -150,48 +149,47 @@ function websocketEvents($rootScope, $websocket, $location, baseUrlSrv) {
buttons: [{
// close all the dialogs when there are error on running all paragraphs
label: 'Close',
- action: function() {
- BootstrapDialog.closeAll();
+ action: function () {
+ BootstrapDialog.closeAll()
}
}]
- });
+ })
} else if (op === 'SESSION_LOGOUT') {
- $rootScope.$broadcast('session_logout', data);
+ $rootScope.$broadcast('session_logout', data)
} else if (op === 'CONFIGURATIONS_INFO') {
- $rootScope.$broadcast('configurationsInfo', data);
+ $rootScope.$broadcast('configurationsInfo', data)
} else if (op === 'INTERPRETER_SETTINGS') {
- $rootScope.$broadcast('interpreterSettings', data);
+ $rootScope.$broadcast('interpreterSettings', data)
} else if (op === 'PARAGRAPH_ADDED') {
- $rootScope.$broadcast('addParagraph', data.paragraph, data.index);
+ $rootScope.$broadcast('addParagraph', data.paragraph, data.index)
} else if (op === 'PARAGRAPH_REMOVED') {
- $rootScope.$broadcast('removeParagraph', data.id);
+ $rootScope.$broadcast('removeParagraph', data.id)
} else if (op === 'PARAGRAPH_MOVED') {
- $rootScope.$broadcast('moveParagraph', data.id, data.index);
+ $rootScope.$broadcast('moveParagraph', data.id, data.index)
} else if (op === 'NOTE_UPDATED') {
- $rootScope.$broadcast('updateNote', data.name, data.config, data.info);
+ $rootScope.$broadcast('updateNote', data.name, data.config, data.info)
} else if (op === 'SET_NOTE_REVISION') {
- $rootScope.$broadcast('setNoteRevisionResult', data);
+ $rootScope.$broadcast('setNoteRevisionResult', data)
} else if (op === 'PARAS_INFO') {
- $rootScope.$broadcast('updateParaInfos', data);
+ $rootScope.$broadcast('updateParaInfos', data)
} else {
- console.error(`unknown websocket op: ${op}`);
+ console.error(`unknown websocket op: ${op}`)
}
- });
+ })
- websocketCalls.ws.onError(function(event) {
- console.log('error message: ', event);
- $rootScope.$broadcast('setConnectedStatus', false);
- });
+ websocketCalls.ws.onError(function (event) {
+ console.log('error message: ', event)
+ $rootScope.$broadcast('setConnectedStatus', false)
+ })
- websocketCalls.ws.onClose(function(event) {
- console.log('close message: ', event);
+ websocketCalls.ws.onClose(function (event) {
+ console.log('close message: ', event)
if (pingIntervalId !== undefined) {
- clearInterval(pingIntervalId);
- pingIntervalId = undefined;
+ clearInterval(pingIntervalId)
+ pingIntervalId = undefined
}
- $rootScope.$broadcast('setConnectedStatus', false);
- });
+ $rootScope.$broadcast('setConnectedStatus', false)
+ })
- return websocketCalls;
+ return websocketCalls
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/websocketEvents/websocketMsg.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/websocketEvents/websocketMsg.service.js b/zeppelin-web/src/components/websocketEvents/websocketMsg.service.js
index 0ac4d58..3f7ec6b 100644
--- a/zeppelin-web/src/components/websocketEvents/websocketMsg.service.js
+++ b/zeppelin-web/src/components/websocketEvents/websocketMsg.service.js
@@ -12,100 +12,100 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').service('websocketMsgSrv', websocketMsgSrv);
+angular.module('zeppelinWebApp').service('websocketMsgSrv', websocketMsgSrv)
-function websocketMsgSrv($rootScope, websocketEvents) {
- 'ngInject';
+function websocketMsgSrv ($rootScope, websocketEvents) {
+ 'ngInject'
return {
- getHomeNote: function() {
- websocketEvents.sendNewEvent({op: 'GET_HOME_NOTE'});
+ getHomeNote: function () {
+ websocketEvents.sendNewEvent({op: 'GET_HOME_NOTE'})
},
- createNotebook: function(noteName, defaultInterpreterId) {
+ createNotebook: function (noteName, defaultInterpreterId) {
websocketEvents.sendNewEvent({
op: 'NEW_NOTE',
data: {
name: noteName,
defaultInterpreterId: defaultInterpreterId
}
- });
+ })
},
- moveNoteToTrash: function(noteId) {
- websocketEvents.sendNewEvent({op: 'MOVE_NOTE_TO_TRASH', data: {id: noteId}});
+ moveNoteToTrash: function (noteId) {
+ websocketEvents.sendNewEvent({op: 'MOVE_NOTE_TO_TRASH', data: {id: noteId}})
},
- moveFolderToTrash: function(folderId) {
- websocketEvents.sendNewEvent({op: 'MOVE_FOLDER_TO_TRASH', data: {id: folderId}});
+ moveFolderToTrash: function (folderId) {
+ websocketEvents.sendNewEvent({op: 'MOVE_FOLDER_TO_TRASH', data: {id: folderId}})
},
- restoreNote: function(noteId) {
- websocketEvents.sendNewEvent({op: 'RESTORE_NOTE', data: {id: noteId}});
+ restoreNote: function (noteId) {
+ websocketEvents.sendNewEvent({op: 'RESTORE_NOTE', data: {id: noteId}})
},
- restoreFolder: function(folderId) {
- websocketEvents.sendNewEvent({op: 'RESTORE_FOLDER', data: {id: folderId}});
+ restoreFolder: function (folderId) {
+ websocketEvents.sendNewEvent({op: 'RESTORE_FOLDER', data: {id: folderId}})
},
- restoreAll: function() {
- websocketEvents.sendNewEvent({op: 'RESTORE_ALL'});
+ restoreAll: function () {
+ websocketEvents.sendNewEvent({op: 'RESTORE_ALL'})
},
- deleteNote: function(noteId) {
- websocketEvents.sendNewEvent({op: 'DEL_NOTE', data: {id: noteId}});
+ deleteNote: function (noteId) {
+ websocketEvents.sendNewEvent({op: 'DEL_NOTE', data: {id: noteId}})
},
- removeFolder: function(folderId) {
- websocketEvents.sendNewEvent({op: 'REMOVE_FOLDER', data: {id: folderId}});
+ removeFolder: function (folderId) {
+ websocketEvents.sendNewEvent({op: 'REMOVE_FOLDER', data: {id: folderId}})
},
- emptyTrash: function() {
- websocketEvents.sendNewEvent({op: 'EMPTY_TRASH'});
+ emptyTrash: function () {
+ websocketEvents.sendNewEvent({op: 'EMPTY_TRASH'})
},
- cloneNote: function(noteIdToClone, newNoteName) {
- websocketEvents.sendNewEvent({op: 'CLONE_NOTE', data: {id: noteIdToClone, name: newNoteName}});
+ cloneNote: function (noteIdToClone, newNoteName) {
+ websocketEvents.sendNewEvent({op: 'CLONE_NOTE', data: {id: noteIdToClone, name: newNoteName}})
},
- getNoteList: function() {
- websocketEvents.sendNewEvent({op: 'LIST_NOTES'});
+ getNoteList: function () {
+ websocketEvents.sendNewEvent({op: 'LIST_NOTES'})
},
- reloadAllNotesFromRepo: function() {
- websocketEvents.sendNewEvent({op: 'RELOAD_NOTES_FROM_REPO'});
+ reloadAllNotesFromRepo: function () {
+ websocketEvents.sendNewEvent({op: 'RELOAD_NOTES_FROM_REPO'})
},
- getNote: function(noteId) {
- websocketEvents.sendNewEvent({op: 'GET_NOTE', data: {id: noteId}});
+ getNote: function (noteId) {
+ websocketEvents.sendNewEvent({op: 'GET_NOTE', data: {id: noteId}})
},
- updateNote: function(noteId, noteName, noteConfig) {
- websocketEvents.sendNewEvent({op: 'NOTE_UPDATE', data: {id: noteId, name: noteName, config: noteConfig}});
+ updateNote: function (noteId, noteName, noteConfig) {
+ websocketEvents.sendNewEvent({op: 'NOTE_UPDATE', data: {id: noteId, name: noteName, config: noteConfig}})
},
- updatePersonalizedMode: function(noteId, modeValue) {
- websocketEvents.sendNewEvent({op: 'UPDATE_PERSONALIZED_MODE', data: {id: noteId, personalized: modeValue}});
+ updatePersonalizedMode: function (noteId, modeValue) {
+ websocketEvents.sendNewEvent({op: 'UPDATE_PERSONALIZED_MODE', data: {id: noteId, personalized: modeValue}})
},
- renameNote: function(noteId, noteName) {
- websocketEvents.sendNewEvent({op: 'NOTE_RENAME', data: {id: noteId, name: noteName}});
+ renameNote: function (noteId, noteName) {
+ websocketEvents.sendNewEvent({op: 'NOTE_RENAME', data: {id: noteId, name: noteName}})
},
- renameFolder: function(folderId, folderName) {
- websocketEvents.sendNewEvent({op: 'FOLDER_RENAME', data: {id: folderId, name: folderName}});
+ renameFolder: function (folderId, folderName) {
+ websocketEvents.sendNewEvent({op: 'FOLDER_RENAME', data: {id: folderId, name: folderName}})
},
- moveParagraph: function(paragraphId, newIndex) {
- websocketEvents.sendNewEvent({op: 'MOVE_PARAGRAPH', data: {id: paragraphId, index: newIndex}});
+ moveParagraph: function (paragraphId, newIndex) {
+ websocketEvents.sendNewEvent({op: 'MOVE_PARAGRAPH', data: {id: paragraphId, index: newIndex}})
},
- insertParagraph: function(newIndex) {
- websocketEvents.sendNewEvent({op: 'INSERT_PARAGRAPH', data: {index: newIndex}});
+ insertParagraph: function (newIndex) {
+ websocketEvents.sendNewEvent({op: 'INSERT_PARAGRAPH', data: {index: newIndex}})
},
- copyParagraph: function(newIndex, paragraphTitle, paragraphData,
+ copyParagraph: function (newIndex, paragraphTitle, paragraphData,
paragraphConfig, paragraphParams) {
websocketEvents.sendNewEvent({
op: 'COPY_PARAGRAPH',
@@ -116,10 +116,10 @@ function websocketMsgSrv($rootScope, websocketEvents) {
config: paragraphConfig,
params: paragraphParams
}
- });
+ })
},
- updateAngularObject: function(noteId, paragraphId, name, value, interpreterGroupId) {
+ updateAngularObject: function (noteId, paragraphId, name, value, interpreterGroupId) {
websocketEvents.sendNewEvent({
op: 'ANGULAR_OBJECT_UPDATED',
data: {
@@ -129,10 +129,10 @@ function websocketMsgSrv($rootScope, websocketEvents) {
value: value,
interpreterGroupId: interpreterGroupId
}
- });
+ })
},
- clientBindAngularObject: function(noteId, name, value, paragraphId) {
+ clientBindAngularObject: function (noteId, name, value, paragraphId) {
websocketEvents.sendNewEvent({
op: 'ANGULAR_OBJECT_CLIENT_BIND',
data: {
@@ -141,10 +141,10 @@ function websocketMsgSrv($rootScope, websocketEvents) {
value: value,
paragraphId: paragraphId
}
- });
+ })
},
- clientUnbindAngularObject: function(noteId, name, paragraphId) {
+ clientUnbindAngularObject: function (noteId, name, paragraphId) {
websocketEvents.sendNewEvent({
op: 'ANGULAR_OBJECT_CLIENT_UNBIND',
data: {
@@ -152,14 +152,14 @@ function websocketMsgSrv($rootScope, websocketEvents) {
name: name,
paragraphId: paragraphId
}
- });
+ })
},
- cancelParagraphRun: function(paragraphId) {
- websocketEvents.sendNewEvent({op: 'CANCEL_PARAGRAPH', data: {id: paragraphId}});
+ cancelParagraphRun: function (paragraphId) {
+ websocketEvents.sendNewEvent({op: 'CANCEL_PARAGRAPH', data: {id: paragraphId}})
},
- paragraphExecutedBySpell: function(paragraphId, paragraphTitle,
+ paragraphExecutedBySpell: function (paragraphId, paragraphTitle,
paragraphText, paragraphResultsMsg,
paragraphStatus, paragraphErrorMessage,
paragraphConfig, paragraphParams) {
@@ -172,8 +172,8 @@ function websocketMsgSrv($rootScope, websocketEvents) {
results: {
code: paragraphStatus,
msg: paragraphResultsMsg.map(dataWithType => {
- let serializedData = dataWithType.data;
- return { type: dataWithType.type, data: serializedData, };
+ let serializedData = dataWithType.data
+ return { type: dataWithType.type, data: serializedData, }
})
},
status: paragraphStatus,
@@ -181,10 +181,10 @@ function websocketMsgSrv($rootScope, websocketEvents) {
config: paragraphConfig,
params: paragraphParams
}
- });
+ })
},
- runParagraph: function(paragraphId, paragraphTitle, paragraphData, paragraphConfig, paragraphParams) {
+ runParagraph: function (paragraphId, paragraphTitle, paragraphData, paragraphConfig, paragraphParams) {
websocketEvents.sendNewEvent({
op: 'RUN_PARAGRAPH',
data: {
@@ -194,32 +194,32 @@ function websocketMsgSrv($rootScope, websocketEvents) {
config: paragraphConfig,
params: paragraphParams
}
- });
+ })
},
- runAllParagraphs: function(noteId, paragraphs) {
+ runAllParagraphs: function (noteId, paragraphs) {
websocketEvents.sendNewEvent({
op: 'RUN_ALL_PARAGRAPHS',
data: {
noteId: noteId,
paragraphs: JSON.stringify(paragraphs)
}
- });
+ })
},
- removeParagraph: function(paragraphId) {
- websocketEvents.sendNewEvent({op: 'PARAGRAPH_REMOVE', data: {id: paragraphId}});
+ removeParagraph: function (paragraphId) {
+ websocketEvents.sendNewEvent({op: 'PARAGRAPH_REMOVE', data: {id: paragraphId}})
},
- clearParagraphOutput: function(paragraphId) {
- websocketEvents.sendNewEvent({op: 'PARAGRAPH_CLEAR_OUTPUT', data: {id: paragraphId}});
+ clearParagraphOutput: function (paragraphId) {
+ websocketEvents.sendNewEvent({op: 'PARAGRAPH_CLEAR_OUTPUT', data: {id: paragraphId}})
},
- clearAllParagraphOutput: function(noteId) {
- websocketEvents.sendNewEvent({op: 'PARAGRAPH_CLEAR_ALL_OUTPUT', data: {id: noteId}});
+ clearAllParagraphOutput: function (noteId) {
+ websocketEvents.sendNewEvent({op: 'PARAGRAPH_CLEAR_ALL_OUTPUT', data: {id: noteId}})
},
- completion: function(paragraphId, buf, cursor) {
+ completion: function (paragraphId, buf, cursor) {
websocketEvents.sendNewEvent({
op: 'COMPLETION',
data: {
@@ -227,10 +227,10 @@ function websocketMsgSrv($rootScope, websocketEvents) {
buf: buf,
cursor: cursor
}
- });
+ })
},
- commitParagraph: function(paragraphId, paragraphTitle, paragraphData, paragraphConfig, paragraphParams) {
+ commitParagraph: function (paragraphId, paragraphTitle, paragraphData, paragraphConfig, paragraphParams) {
websocketEvents.sendNewEvent({
op: 'COMMIT_PARAGRAPH',
data: {
@@ -240,102 +240,101 @@ function websocketMsgSrv($rootScope, websocketEvents) {
config: paragraphConfig,
params: paragraphParams
}
- });
+ })
},
- importNote: function(note) {
+ importNote: function (note) {
websocketEvents.sendNewEvent({
op: 'IMPORT_NOTE',
data: {
note: note
}
- });
+ })
},
- checkpointNote: function(noteId, commitMessage) {
+ checkpointNote: function (noteId, commitMessage) {
websocketEvents.sendNewEvent({
op: 'CHECKPOINT_NOTE',
data: {
noteId: noteId,
commitMessage: commitMessage
}
- });
+ })
},
- setNoteRevision: function(noteId, revisionId) {
+ setNoteRevision: function (noteId, revisionId) {
websocketEvents.sendNewEvent({
op: 'SET_NOTE_REVISION',
data: {
noteId: noteId,
revisionId: revisionId
}
- });
+ })
},
- listRevisionHistory: function(noteId) {
+ listRevisionHistory: function (noteId) {
websocketEvents.sendNewEvent({
op: 'LIST_REVISION_HISTORY',
data: {
noteId: noteId
}
- });
+ })
},
- getNoteByRevision: function(noteId, revisionId) {
+ getNoteByRevision: function (noteId, revisionId) {
websocketEvents.sendNewEvent({
op: 'NOTE_REVISION',
data: {
noteId: noteId,
revisionId: revisionId
}
- });
+ })
},
- getEditorSetting: function(paragraphId, replName) {
+ getEditorSetting: function (paragraphId, replName) {
websocketEvents.sendNewEvent({
op: 'EDITOR_SETTING',
data: {
paragraphId: paragraphId,
magic: replName
}
- });
+ })
},
- isConnected: function() {
- return websocketEvents.isConnected();
+ isConnected: function () {
+ return websocketEvents.isConnected()
},
- getNoteJobsList: function() {
- websocketEvents.sendNewEvent({op: 'LIST_NOTE_JOBS'});
+ getNoteJobsList: function () {
+ websocketEvents.sendNewEvent({op: 'LIST_NOTE_JOBS'})
},
- getUpdateNoteJobsList: function(lastUpdateServerUnixTime) {
+ getUpdateNoteJobsList: function (lastUpdateServerUnixTime) {
websocketEvents.sendNewEvent(
{op: 'LIST_UPDATE_NOTE_JOBS', data: {lastUpdateUnixTime: lastUpdateServerUnixTime * 1}}
- );
+ )
},
- unsubscribeJobManager: function() {
- websocketEvents.sendNewEvent({op: 'UNSUBSCRIBE_UPDATE_NOTE_JOBS'});
+ unsubscribeJobManager: function () {
+ websocketEvents.sendNewEvent({op: 'UNSUBSCRIBE_UPDATE_NOTE_JOBS'})
},
- getInterpreterBindings: function(noteId) {
- websocketEvents.sendNewEvent({op: 'GET_INTERPRETER_BINDINGS', data: {noteId: noteId}});
+ getInterpreterBindings: function (noteId) {
+ websocketEvents.sendNewEvent({op: 'GET_INTERPRETER_BINDINGS', data: {noteId: noteId}})
},
- saveInterpreterBindings: function(noteId, selectedSettingIds) {
+ saveInterpreterBindings: function (noteId, selectedSettingIds) {
websocketEvents.sendNewEvent({op: 'SAVE_INTERPRETER_BINDINGS',
- data: {noteId: noteId, selectedSettingIds: selectedSettingIds}});
+ data: {noteId: noteId, selectedSettingIds: selectedSettingIds}})
},
- listConfigurations: function() {
- websocketEvents.sendNewEvent({op: 'LIST_CONFIGURATIONS'});
+ listConfigurations: function () {
+ websocketEvents.sendNewEvent({op: 'LIST_CONFIGURATIONS'})
},
- getInterpreterSettings: function() {
- websocketEvents.sendNewEvent({op: 'GET_INTERPRETER_SETTINGS'});
+ getInterpreterSettings: function () {
+ websocketEvents.sendNewEvent({op: 'GET_INTERPRETER_SETTINGS'})
},
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/index.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/index.js b/zeppelin-web/src/index.js
index 5afc9ff..314be64 100644
--- a/zeppelin-web/src/index.js
+++ b/zeppelin-web/src/index.js
@@ -12,65 +12,65 @@
* limitations under the License.
*/
-import './app/app.js';
-import './app/app.controller.js';
-import './app/home/home.controller.js';
-import './app/handsontable/handsonHelper.js';
-import './app/notebook/notebook.controller.js';
+import './app/app.js'
+import './app/app.controller.js'
+import './app/home/home.controller.js'
+import './app/handsontable/handsonHelper.js'
+import './app/notebook/notebook.controller.js'
-import './app/tabledata/tabledata.js';
-import './app/tabledata/transformation.js';
-import './app/tabledata/pivot.js';
-import './app/tabledata/passthrough.js';
-import './app/tabledata/columnselector.js';
-import './app/tabledata/advanced-transformation.js';
-import './app/visualization/visualization.js';
-import './app/visualization/builtins/visualization-table.js';
-import './app/visualization/builtins/visualization-nvd3chart.js';
-import './app/visualization/builtins/visualization-barchart.js';
-import './app/visualization/builtins/visualization-piechart.js';
-import './app/visualization/builtins/visualization-areachart.js';
-import './app/visualization/builtins/visualization-linechart.js';
-import './app/visualization/builtins/visualization-scatterchart.js';
+import './app/tabledata/tabledata.js'
+import './app/tabledata/transformation.js'
+import './app/tabledata/pivot.js'
+import './app/tabledata/passthrough.js'
+import './app/tabledata/columnselector.js'
+import './app/tabledata/advanced-transformation.js'
+import './app/visualization/visualization.js'
+import './app/visualization/builtins/visualization-table.js'
+import './app/visualization/builtins/visualization-nvd3chart.js'
+import './app/visualization/builtins/visualization-barchart.js'
+import './app/visualization/builtins/visualization-piechart.js'
+import './app/visualization/builtins/visualization-areachart.js'
+import './app/visualization/builtins/visualization-linechart.js'
+import './app/visualization/builtins/visualization-scatterchart.js'
-import './app/jobmanager/jobmanager.controller.js';
-import './app/jobmanager/jobs/job.controller.js';
-import './app/jobmanager/jobmanager.filter.js';
-import './app/interpreter/interpreter.controller.js';
-import './app/interpreter/interpreter.filter.js';
-import './app/credential/credential.controller.js';
-import './app/configuration/configuration.controller.js';
-import './app/notebook/paragraph/paragraph.controller.js';
-import './app/notebook/paragraph/result/result.controller.js';
-import './app/search/result-list.controller.js';
-import './app/notebookRepos/notebookRepos.controller.js';
-import './app/helium';
-import './components/arrayOrderingSrv/arrayOrdering.service.js';
-import './components/clipboard/clipboard.controller.js';
-import './components/navbar/navbar.controller.js';
-import './components/ngescape/ngescape.directive.js';
-import './components/interpreter/interpreter.directive.js';
-import './components/expandCollapse/expandCollapse.directive.js';
-import './components/noteName-create/notename.controller.js';
-import './components/noteName-import/notenameImport.controller.js';
-import './components/popover-html-unsafe/popover-html-unsafe.directive.js';
-import './components/popover-html-unsafe/popover-html-unsafe-popup.directive.js';
-import './components/editor/codeEditor.directive.js';
-import './components/ngenter/ngenter.directive.js';
-import './components/dropdowninput/dropdowninput.directive.js';
-import './components/resizable/resizable.directive.js';
-import './components/noteName-create/visible.directive.js';
-import './components/websocketEvents/websocketMsg.service.js';
-import './components/websocketEvents/websocketEvents.factory.js';
-import './components/noteListDataFactory/noteList.datafactory.js';
-import './components/baseUrl/baseUrl.service.js';
-import './components/browser-detect/browserDetect.service.js';
-import './components/saveAs/saveAs.service.js';
-import './components/searchService/search.service.js';
-import './components/login/login.controller.js';
-import './components/elasticInputCtrl/elasticInput.controller.js';
-import './components/noteAction/noteAction.service.js';
-import './components/notevarshareService/notevarshare.service.js';
-import './components/rename/rename.controller.js';
-import './components/rename/rename.service.js';
-import './components/helium/helium.service.js';
+import './app/jobmanager/jobmanager.controller.js'
+import './app/jobmanager/jobs/job.controller.js'
+import './app/jobmanager/jobmanager.filter.js'
+import './app/interpreter/interpreter.controller.js'
+import './app/interpreter/interpreter.filter.js'
+import './app/credential/credential.controller.js'
+import './app/configuration/configuration.controller.js'
+import './app/notebook/paragraph/paragraph.controller.js'
+import './app/notebook/paragraph/result/result.controller.js'
+import './app/search/result-list.controller.js'
+import './app/notebookRepos/notebookRepos.controller.js'
+import './app/helium'
+import './components/arrayOrderingSrv/arrayOrdering.service.js'
+import './components/clipboard/clipboard.controller.js'
+import './components/navbar/navbar.controller.js'
+import './components/ngescape/ngescape.directive.js'
+import './components/interpreter/interpreter.directive.js'
+import './components/expandCollapse/expandCollapse.directive.js'
+import './components/noteName-create/notename.controller.js'
+import './components/noteName-import/notenameImport.controller.js'
+import './components/popover-html-unsafe/popover-html-unsafe.directive.js'
+import './components/popover-html-unsafe/popover-html-unsafe-popup.directive.js'
+import './components/editor/codeEditor.directive.js'
+import './components/ngenter/ngenter.directive.js'
+import './components/dropdowninput/dropdowninput.directive.js'
+import './components/resizable/resizable.directive.js'
+import './components/noteName-create/visible.directive.js'
+import './components/websocketEvents/websocketMsg.service.js'
+import './components/websocketEvents/websocketEvents.factory.js'
+import './components/noteListDataFactory/noteList.datafactory.js'
+import './components/baseUrl/baseUrl.service.js'
+import './components/browser-detect/browserDetect.service.js'
+import './components/saveAs/saveAs.service.js'
+import './components/searchService/search.service.js'
+import './components/login/login.controller.js'
+import './components/elasticInputCtrl/elasticInput.controller.js'
+import './components/noteAction/noteAction.service.js'
+import './components/notevarshareService/notevarshare.service.js'
+import './components/rename/rename.controller.js'
+import './components/rename/rename.service.js'
+import './components/helium/helium.service.js'
[7/8] zeppelin git commit: [ZEPPELIN-1940] lint rule set is NOT
applied at all.
Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/interpreter/interpreter.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/interpreter/interpreter.controller.js b/zeppelin-web/src/app/interpreter/interpreter.controller.js
index 648a478..330c2ad 100644
--- a/zeppelin-web/src/app/interpreter/interpreter.controller.js
+++ b/zeppelin-web/src/app/interpreter/interpreter.controller.js
@@ -12,52 +12,52 @@
* limitations under the License.
*/
-import { ParagraphStatus, } from '../notebook/paragraph/paragraph.status';
+import { ParagraphStatus, } from '../notebook/paragraph/paragraph.status'
-angular.module('zeppelinWebApp').controller('InterpreterCtrl', InterpreterCtrl);
+angular.module('zeppelinWebApp').controller('InterpreterCtrl', InterpreterCtrl)
-function InterpreterCtrl($rootScope, $scope, $http, baseUrlSrv, ngToast, $timeout, $route) {
- 'ngInject';
+function InterpreterCtrl ($rootScope, $scope, $http, baseUrlSrv, ngToast, $timeout, $route) {
+ 'ngInject'
- var interpreterSettingsTmp = [];
- $scope.interpreterSettings = [];
- $scope.availableInterpreters = {};
- $scope.showAddNewSetting = false;
- $scope.showRepositoryInfo = false;
- $scope.searchInterpreter = '';
- $scope._ = _;
- ngToast.dismiss();
+ let interpreterSettingsTmp = []
+ $scope.interpreterSettings = []
+ $scope.availableInterpreters = {}
+ $scope.showAddNewSetting = false
+ $scope.showRepositoryInfo = false
+ $scope.searchInterpreter = ''
+ $scope._ = _
+ ngToast.dismiss()
- $scope.openPermissions = function() {
- $scope.showInterpreterAuth = true;
- };
+ $scope.openPermissions = function () {
+ $scope.showInterpreterAuth = true
+ }
- $scope.closePermissions = function() {
- $scope.showInterpreterAuth = false;
- };
+ $scope.closePermissions = function () {
+ $scope.showInterpreterAuth = false
+ }
- var getSelectJson = function() {
- var selectJson = {
+ let getSelectJson = function () {
+ let selectJson = {
tags: false,
multiple: true,
tokenSeparators: [',', ' '],
minimumInputLength: 2,
ajax: {
- url: function(params) {
+ url: function (params) {
if (!params.term) {
- return false;
+ return false
}
- return baseUrlSrv.getRestApiBase() + '/security/userlist/' + params.term;
+ return baseUrlSrv.getRestApiBase() + '/security/userlist/' + params.term
},
delay: 250,
- processResults: function(data, params) {
- var users = [];
+ processResults: function (data, params) {
+ let users = []
if (data.body.users.length !== 0) {
- for (var i = 0; i < data.body.users.length; i++) {
+ for (let i = 0; i < data.body.users.length; i++) {
users.push({
'id': data.body.users[i],
'text': data.body.users[i]
- });
+ })
}
}
return {
@@ -65,388 +65,389 @@ function InterpreterCtrl($rootScope, $scope, $http, baseUrlSrv, ngToast, $timeou
pagination: {
more: false
}
- };
+ }
},
cache: false
}
- };
- return selectJson;
- };
+ }
+ return selectJson
+ }
- $scope.togglePermissions = function(intpName) {
- angular.element('#' + intpName + 'Users').select2(getSelectJson());
+ $scope.togglePermissions = function (intpName) {
+ angular.element('#' + intpName + 'Users').select2(getSelectJson())
if ($scope.showInterpreterAuth) {
- $scope.closePermissions();
+ $scope.closePermissions()
} else {
- $scope.openPermissions();
+ $scope.openPermissions()
}
- };
+ }
- $scope.$on('ngRenderFinished', function(event, data) {
- for (var setting = 0; setting < $scope.interpreterSettings.length; setting++) {
- angular.element('#' + $scope.interpreterSettings[setting].name + 'Users').select2(getSelectJson());
+ $scope.$on('ngRenderFinished', function (event, data) {
+ for (let setting = 0; setting < $scope.interpreterSettings.length; setting++) {
+ angular.element('#' + $scope.interpreterSettings[setting].name + 'Users').select2(getSelectJson())
}
- });
+ })
- var getInterpreterSettings = function() {
+ let getInterpreterSettings = function () {
$http.get(baseUrlSrv.getRestApiBase() + '/interpreter/setting')
- .success(function(data, status, headers, config) {
- $scope.interpreterSettings = data.body;
- checkDownloadingDependencies();
- }).error(function(data, status, headers, config) {
- if (status === 401) {
- ngToast.danger({
- content: 'You don\'t have permission on this page',
- verticalPosition: 'bottom',
- timeout: '3000'
- });
- setTimeout(function() {
- window.location.replace('/');
- }, 3000);
- }
- console.log('Error %o %o', status, data.message);
- });
- };
-
- var checkDownloadingDependencies = function() {
- var isDownloading = false;
- for (var index = 0; index < $scope.interpreterSettings.length; index++) {
- var setting = $scope.interpreterSettings[index];
+ .success(function (data, status, headers, config) {
+ $scope.interpreterSettings = data.body
+ checkDownloadingDependencies()
+ }).error(function (data, status, headers, config) {
+ if (status === 401) {
+ ngToast.danger({
+ content: 'You don\'t have permission on this page',
+ verticalPosition: 'bottom',
+ timeout: '3000'
+ })
+ setTimeout(function () {
+ window.location.replace('/')
+ }, 3000)
+ }
+ console.log('Error %o %o', status, data.message)
+ })
+ }
+
+ const checkDownloadingDependencies = function () {
+ let isDownloading = false
+ for (let index = 0; index < $scope.interpreterSettings.length; index++) {
+ let setting = $scope.interpreterSettings[index]
if (setting.status === 'DOWNLOADING_DEPENDENCIES') {
- isDownloading = true;
+ isDownloading = true
}
if (setting.status === ParagraphStatus.ERROR || setting.errorReason) {
ngToast.danger({content: 'Error setting properties for interpreter \'' +
setting.group + '.' + setting.name + '\': ' + setting.errorReason,
- verticalPosition: 'top', dismissOnTimeout: false});
+ verticalPosition: 'top',
+ dismissOnTimeout: false
+ })
}
}
if (isDownloading) {
- $timeout(function() {
+ $timeout(function () {
if ($route.current.$$route.originalPath === '/interpreter') {
- getInterpreterSettings();
+ getInterpreterSettings()
}
- }, 2000);
+ }, 2000)
}
- };
-
- var getAvailableInterpreters = function() {
- $http.get(baseUrlSrv.getRestApiBase() + '/interpreter').success(function(data, status, headers, config) {
- $scope.availableInterpreters = data.body;
- }).error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- });
- };
-
- var emptyNewProperty = function(object) {
- angular.extend(object, {propertyValue: '', propertyKey: ''});
- };
-
- var emptyNewDependency = function(object) {
- angular.extend(object, {depArtifact: '', depExclude: ''});
- };
-
- var removeTMPSettings = function(index) {
- interpreterSettingsTmp.splice(index, 1);
- };
-
- $scope.copyOriginInterpreterSettingProperties = function(settingId) {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- interpreterSettingsTmp[index] = angular.copy($scope.interpreterSettings[index]);
- };
-
- $scope.setPerNoteOption = function(settingId, sessionOption) {
- var option;
+ }
+
+ let getAvailableInterpreters = function () {
+ $http.get(baseUrlSrv.getRestApiBase() + '/interpreter').success(function (data, status, headers, config) {
+ $scope.availableInterpreters = data.body
+ }).error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ })
+ }
+
+ let emptyNewProperty = function (object) {
+ angular.extend(object, {propertyValue: '', propertyKey: ''})
+ }
+
+ let emptyNewDependency = function (object) {
+ angular.extend(object, {depArtifact: '', depExclude: ''})
+ }
+
+ let removeTMPSettings = function (index) {
+ interpreterSettingsTmp.splice(index, 1)
+ }
+
+ $scope.copyOriginInterpreterSettingProperties = function (settingId) {
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ interpreterSettingsTmp[index] = angular.copy($scope.interpreterSettings[index])
+ }
+
+ $scope.setPerNoteOption = function (settingId, sessionOption) {
+ let option
if (settingId === undefined) {
- option = $scope.newInterpreterSetting.option;
+ option = $scope.newInterpreterSetting.option
} else {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- var setting = $scope.interpreterSettings[index];
- option = setting.option;
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ let setting = $scope.interpreterSettings[index]
+ option = setting.option
}
if (sessionOption === 'isolated') {
- option.perNote = sessionOption;
- option.session = false;
- option.process = true;
+ option.perNote = sessionOption
+ option.session = false
+ option.process = true
} else if (sessionOption === 'scoped') {
- option.perNote = sessionOption;
- option.session = true;
- option.process = false;
+ option.perNote = sessionOption
+ option.session = true
+ option.process = false
} else {
- option.perNote = 'shared';
- option.session = false;
- option.process = false;
+ option.perNote = 'shared'
+ option.session = false
+ option.process = false
}
- };
+ }
- $scope.setPerUserOption = function(settingId, sessionOption) {
- var option;
+ $scope.setPerUserOption = function (settingId, sessionOption) {
+ let option
if (settingId === undefined) {
- option = $scope.newInterpreterSetting.option;
+ option = $scope.newInterpreterSetting.option
} else {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- var setting = $scope.interpreterSettings[index];
- option = setting.option;
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ let setting = $scope.interpreterSettings[index]
+ option = setting.option
}
if (sessionOption === 'isolated') {
- option.perUser = sessionOption;
- option.session = false;
- option.process = true;
+ option.perUser = sessionOption
+ option.session = false
+ option.process = true
} else if (sessionOption === 'scoped') {
- option.perUser = sessionOption;
- option.session = true;
- option.process = false;
+ option.perUser = sessionOption
+ option.session = true
+ option.process = false
} else {
- option.perUser = 'shared';
- option.session = false;
- option.process = false;
+ option.perUser = 'shared'
+ option.session = false
+ option.process = false
}
- };
+ }
- $scope.getPerNoteOption = function(settingId) {
- var option;
+ $scope.getPerNoteOption = function (settingId) {
+ let option
if (settingId === undefined) {
- option = $scope.newInterpreterSetting.option;
+ option = $scope.newInterpreterSetting.option
} else {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- var setting = $scope.interpreterSettings[index];
- option = setting.option;
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ let setting = $scope.interpreterSettings[index]
+ option = setting.option
}
if (option.perNote === 'scoped') {
- return 'scoped';
+ return 'scoped'
} else if (option.perNote === 'isolated') {
- return 'isolated';
+ return 'isolated'
} else {
- return 'shared';
+ return 'shared'
}
- };
+ }
- $scope.getPerUserOption = function(settingId) {
- var option;
+ $scope.getPerUserOption = function (settingId) {
+ let option
if (settingId === undefined) {
- option = $scope.newInterpreterSetting.option;
+ option = $scope.newInterpreterSetting.option
} else {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- var setting = $scope.interpreterSettings[index];
- option = setting.option;
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ let setting = $scope.interpreterSettings[index]
+ option = setting.option
}
if (option.perUser === 'scoped') {
- return 'scoped';
+ return 'scoped'
} else if (option.perUser === 'isolated') {
- return 'isolated';
+ return 'isolated'
} else {
- return 'shared';
+ return 'shared'
}
- };
+ }
- $scope.getInterpreterRunningOption = function(settingId) {
- var sharedModeName = 'shared';
+ $scope.getInterpreterRunningOption = function (settingId) {
+ let sharedModeName = 'shared'
- var globallyModeName = 'Globally';
- var perNoteModeName = 'Per Note';
- var perUserModeName = 'Per User';
+ let globallyModeName = 'Globally'
+ let perNoteModeName = 'Per Note'
+ let perUserModeName = 'Per User'
- var option;
+ let option
if (settingId === undefined) {
- option = $scope.newInterpreterSetting.option;
+ option = $scope.newInterpreterSetting.option
} else {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- var setting = $scope.interpreterSettings[index];
- option = setting.option;
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ let setting = $scope.interpreterSettings[index]
+ option = setting.option
}
- var perNote = option.perNote;
- var perUser = option.perUser;
+ let perNote = option.perNote
+ let perUser = option.perUser
// Globally == shared_perNote + shared_perUser
if (perNote === sharedModeName && perUser === sharedModeName) {
- return globallyModeName;
+ return globallyModeName
}
if ($rootScope.ticket.ticket === 'anonymous' && $rootScope.ticket.roles === '[]') {
if (perNote !== undefined && typeof perNote === 'string' && perNote !== '') {
- return perNoteModeName;
+ return perNoteModeName
}
} else if ($rootScope.ticket.ticket !== 'anonymous') {
if (perNote !== undefined && typeof perNote === 'string' && perNote !== '') {
if (perUser !== undefined && typeof perUser === 'string' && perUser !== '') {
- return perUserModeName;
+ return perUserModeName
}
- return perNoteModeName;
+ return perNoteModeName
}
}
- option.perNote = sharedModeName;
- option.perUser = sharedModeName;
- return globallyModeName;
- };
+ option.perNote = sharedModeName
+ option.perUser = sharedModeName
+ return globallyModeName
+ }
- $scope.setInterpreterRunningOption = function(settingId, isPerNoteMode, isPerUserMode) {
- var option;
+ $scope.setInterpreterRunningOption = function (settingId, isPerNoteMode, isPerUserMode) {
+ let option
if (settingId === undefined) {
- option = $scope.newInterpreterSetting.option;
+ option = $scope.newInterpreterSetting.option
} else {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- var setting = $scope.interpreterSettings[index];
- option = setting.option;
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ let setting = $scope.interpreterSettings[index]
+ option = setting.option
}
- option.perNote = isPerNoteMode;
- option.perUser = isPerUserMode;
- };
+ option.perNote = isPerNoteMode
+ option.perUser = isPerUserMode
+ }
- $scope.updateInterpreterSetting = function(form, settingId) {
- var thisConfirm = BootstrapDialog.confirm({
+ $scope.updateInterpreterSetting = function (form, settingId) {
+ const thisConfirm = BootstrapDialog.confirm({
closable: false,
closeByBackdrop: false,
closeByKeyboard: false,
title: '',
message: 'Do you want to update this interpreter and restart with new settings?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- var setting = $scope.interpreterSettings[index];
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ let setting = $scope.interpreterSettings[index]
if (setting.propertyKey !== '' || setting.propertyKey) {
- $scope.addNewInterpreterProperty(settingId);
+ $scope.addNewInterpreterProperty(settingId)
}
if (setting.depArtifact !== '' || setting.depArtifact) {
- $scope.addNewInterpreterDependency(settingId);
+ $scope.addNewInterpreterDependency(settingId)
}
// add missing field of option
if (!setting.option) {
- setting.option = {};
+ setting.option = {}
}
if (setting.option.isExistingProcess === undefined) {
- setting.option.isExistingProcess = false;
+ setting.option.isExistingProcess = false
}
if (setting.option.setPermission === undefined) {
- setting.option.setPermission = false;
+ setting.option.setPermission = false
}
if (setting.option.isUserImpersonate === undefined) {
- setting.option.isUserImpersonate = false;
+ setting.option.isUserImpersonate = false
}
if (!($scope.getInterpreterRunningOption(settingId) === 'Per User' &&
$scope.getPerUserOption(settingId) === 'isolated')) {
- setting.option.isUserImpersonate = false;
+ setting.option.isUserImpersonate = false
}
if (setting.option.remote === undefined) {
// remote always true for now
- setting.option.remote = true;
+ setting.option.remote = true
}
- setting.option.users = angular.element('#' + setting.name + 'Users').val();
+ setting.option.users = angular.element('#' + setting.name + 'Users').val()
- var request = {
+ let request = {
option: angular.copy(setting.option),
properties: angular.copy(setting.properties),
dependencies: angular.copy(setting.dependencies)
- };
+ }
- thisConfirm.$modalFooter.find('button').addClass('disabled');
+ thisConfirm.$modalFooter.find('button').addClass('disabled')
thisConfirm.$modalFooter.find('button:contains("OK")')
- .html('<i class="fa fa-circle-o-notch fa-spin"></i> Saving Setting');
+ .html('<i class="fa fa-circle-o-notch fa-spin"></i> Saving Setting')
$http.put(baseUrlSrv.getRestApiBase() + '/interpreter/setting/' + settingId, request)
- .success(function(data, status, headers, config) {
- $scope.interpreterSettings[index] = data.body;
- removeTMPSettings(index);
- checkDownloadingDependencies();
- thisConfirm.close();
+ .success(function (data, status, headers, config) {
+ $scope.interpreterSettings[index] = data.body
+ removeTMPSettings(index)
+ checkDownloadingDependencies()
+ thisConfirm.close()
+ })
+ .error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ ngToast.danger({content: data.message, verticalPosition: 'bottom'})
+ form.$show()
+ thisConfirm.close()
})
- .error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- ngToast.danger({content: data.message, verticalPosition: 'bottom'});
- form.$show();
- thisConfirm.close();
- });
- return false;
+ return false
} else {
- form.$show();
+ form.$show()
}
}
- });
- };
+ })
+ }
- $scope.resetInterpreterSetting = function(settingId) {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
+ $scope.resetInterpreterSetting = function (settingId) {
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
// Set the old settings back
- $scope.interpreterSettings[index] = angular.copy(interpreterSettingsTmp[index]);
- removeTMPSettings(index);
- };
+ $scope.interpreterSettings[index] = angular.copy(interpreterSettingsTmp[index])
+ removeTMPSettings(index)
+ }
- $scope.removeInterpreterSetting = function(settingId) {
+ $scope.removeInterpreterSetting = function (settingId) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Do you want to delete this interpreter setting?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
$http.delete(baseUrlSrv.getRestApiBase() + '/interpreter/setting/' + settingId)
- .success(function(data, status, headers, config) {
-
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- $scope.interpreterSettings.splice(index, 1);
- }).error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- });
+ .success(function (data, status, headers, config) {
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ $scope.interpreterSettings.splice(index, 1)
+ }).error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ })
}
}
- });
- };
-
- $scope.newInterpreterGroupChange = function() {
- var el = _.pluck(_.filter($scope.availableInterpreters, {'name': $scope.newInterpreterSetting.group}),
- 'properties');
- var properties = {};
- for (var i = 0; i < el.length; i++) {
- var intpInfo = el[i];
- for (var key in intpInfo) {
+ })
+ }
+
+ $scope.newInterpreterGroupChange = function () {
+ let el = _.pluck(_.filter($scope.availableInterpreters, {'name': $scope.newInterpreterSetting.group}),
+ 'properties')
+ let properties = {}
+ for (let i = 0; i < el.length; i++) {
+ let intpInfo = el[i]
+ for (let key in intpInfo) {
properties[key] = {
value: intpInfo[key].defaultValue,
description: intpInfo[key].description
- };
+ }
}
}
- $scope.newInterpreterSetting.properties = properties;
- };
+ $scope.newInterpreterSetting.properties = properties
+ }
- $scope.restartInterpreterSetting = function(settingId) {
+ $scope.restartInterpreterSetting = function (settingId) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Do you want to restart this interpreter?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
$http.put(baseUrlSrv.getRestApiBase() + '/interpreter/setting/restart/' + settingId)
- .success(function(data, status, headers, config) {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- $scope.interpreterSettings[index] = data.body;
- ngToast.info('Interpreter stopped. Will be lazily started on next run.');
- }).error(function(data, status, headers, config) {
- var errorMsg = (data !== null) ? data.message : 'Could not connect to server.';
- console.log('Error %o %o', status, errorMsg);
- ngToast.danger(errorMsg);
- });
+ .success(function (data, status, headers, config) {
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ $scope.interpreterSettings[index] = data.body
+ ngToast.info('Interpreter stopped. Will be lazily started on next run.')
+ }).error(function (data, status, headers, config) {
+ let errorMsg = (data !== null) ? data.message : 'Could not connect to server.'
+ console.log('Error %o %o', status, errorMsg)
+ ngToast.danger(errorMsg)
+ })
}
}
- });
- };
+ })
+ }
- $scope.addNewInterpreterSetting = function() {
- //user input validation on interpreter creation
+ $scope.addNewInterpreterSetting = function () {
+ // user input validation on interpreter creation
if (!$scope.newInterpreterSetting.name ||
!$scope.newInterpreterSetting.name.trim() || !$scope.newInterpreterSetting.group) {
BootstrapDialog.alert({
closable: true,
title: 'Add interpreter',
message: 'Please fill in interpreter name and choose a group'
- });
- return;
+ })
+ return
}
if ($scope.newInterpreterSetting.name.indexOf('.') >= 0) {
@@ -454,8 +455,8 @@ function InterpreterCtrl($rootScope, $scope, $http, baseUrlSrv, ngToast, $timeou
closable: true,
title: 'Add interpreter',
message: '\'.\' is invalid for interpreter name'
- });
- return;
+ })
+ return
}
if (_.findIndex($scope.interpreterSettings, {'name': $scope.newInterpreterSetting.name}) >= 0) {
@@ -463,49 +464,49 @@ function InterpreterCtrl($rootScope, $scope, $http, baseUrlSrv, ngToast, $timeou
closable: true,
title: 'Add interpreter',
message: 'Name ' + $scope.newInterpreterSetting.name + ' already exists'
- });
- return;
+ })
+ return
}
- var newSetting = $scope.newInterpreterSetting;
+ let newSetting = $scope.newInterpreterSetting
if (newSetting.propertyKey !== '' || newSetting.propertyKey) {
- $scope.addNewInterpreterProperty();
+ $scope.addNewInterpreterProperty()
}
if (newSetting.depArtifact !== '' || newSetting.depArtifact) {
- $scope.addNewInterpreterDependency();
+ $scope.addNewInterpreterDependency()
}
if (newSetting.option.setPermission === undefined) {
- newSetting.option.setPermission = false;
+ newSetting.option.setPermission = false
}
- newSetting.option.users = angular.element('#newInterpreterUsers').val();
+ newSetting.option.users = angular.element('#newInterpreterUsers').val()
- var request = angular.copy($scope.newInterpreterSetting);
+ let request = angular.copy($scope.newInterpreterSetting)
// Change properties to proper request format
- var newProperties = {};
- for (var p in newSetting.properties) {
- newProperties[p] = newSetting.properties[p].value;
+ let newProperties = {}
+ for (let p in newSetting.properties) {
+ newProperties[p] = newSetting.properties[p].value
}
- request.properties = newProperties;
+ request.properties = newProperties
$http.post(baseUrlSrv.getRestApiBase() + '/interpreter/setting', request)
- .success(function(data, status, headers, config) {
- $scope.resetNewInterpreterSetting();
- getInterpreterSettings();
- $scope.showAddNewSetting = false;
- checkDownloadingDependencies();
- }).error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- ngToast.danger({content: data.message, verticalPosition: 'bottom'});
- });
- };
-
- $scope.cancelInterpreterSetting = function() {
- $scope.showAddNewSetting = false;
- $scope.resetNewInterpreterSetting();
- };
-
- $scope.resetNewInterpreterSetting = function() {
+ .success(function (data, status, headers, config) {
+ $scope.resetNewInterpreterSetting()
+ getInterpreterSettings()
+ $scope.showAddNewSetting = false
+ checkDownloadingDependencies()
+ }).error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ ngToast.danger({content: data.message, verticalPosition: 'bottom'})
+ })
+ }
+
+ $scope.cancelInterpreterSetting = function () {
+ $scope.showAddNewSetting = false
+ $scope.resetNewInterpreterSetting()
+ }
+
+ $scope.resetNewInterpreterSetting = function () {
$scope.newInterpreterSetting = {
name: undefined,
group: undefined,
@@ -519,110 +520,110 @@ function InterpreterCtrl($rootScope, $scope, $http, baseUrlSrv, ngToast, $timeou
process: false
}
- };
- emptyNewProperty($scope.newInterpreterSetting);
- };
+ }
+ emptyNewProperty($scope.newInterpreterSetting)
+ }
- $scope.removeInterpreterProperty = function(key, settingId) {
+ $scope.removeInterpreterProperty = function (key, settingId) {
if (settingId === undefined) {
- delete $scope.newInterpreterSetting.properties[key];
+ delete $scope.newInterpreterSetting.properties[key]
} else {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- delete $scope.interpreterSettings[index].properties[key];
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ delete $scope.interpreterSettings[index].properties[key]
}
- };
+ }
- $scope.removeInterpreterDependency = function(artifact, settingId) {
+ $scope.removeInterpreterDependency = function (artifact, settingId) {
if (settingId === undefined) {
$scope.newInterpreterSetting.dependencies = _.reject($scope.newInterpreterSetting.dependencies,
- function(el) {
- return el.groupArtifactVersion === artifact;
- });
+ function (el) {
+ return el.groupArtifactVersion === artifact
+ })
} else {
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
$scope.interpreterSettings[index].dependencies = _.reject($scope.interpreterSettings[index].dependencies,
- function(el) {
- return el.groupArtifactVersion === artifact;
- });
+ function (el) {
+ return el.groupArtifactVersion === artifact
+ })
}
- };
+ }
- $scope.addNewInterpreterProperty = function(settingId) {
+ $scope.addNewInterpreterProperty = function (settingId) {
if (settingId === undefined) {
// Add new property from create form
if (!$scope.newInterpreterSetting.propertyKey || $scope.newInterpreterSetting.propertyKey === '') {
- return;
+ return
}
$scope.newInterpreterSetting.properties[$scope.newInterpreterSetting.propertyKey] = {
value: $scope.newInterpreterSetting.propertyValue
- };
- emptyNewProperty($scope.newInterpreterSetting);
+ }
+ emptyNewProperty($scope.newInterpreterSetting)
} else {
// Add new property from edit form
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- var setting = $scope.interpreterSettings[index];
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ let setting = $scope.interpreterSettings[index]
if (!setting.propertyKey || setting.propertyKey === '') {
- return;
+ return
}
- setting.properties[setting.propertyKey] = setting.propertyValue;
- emptyNewProperty(setting);
+ setting.properties[setting.propertyKey] = setting.propertyValue
+ emptyNewProperty(setting)
}
- };
+ }
- $scope.addNewInterpreterDependency = function(settingId) {
+ $scope.addNewInterpreterDependency = function (settingId) {
if (settingId === undefined) {
// Add new dependency from create form
if (!$scope.newInterpreterSetting.depArtifact || $scope.newInterpreterSetting.depArtifact === '') {
- return;
+ return
}
// overwrite if artifact already exists
- var newSetting = $scope.newInterpreterSetting;
- for (var d in newSetting.dependencies) {
+ let newSetting = $scope.newInterpreterSetting
+ for (let d in newSetting.dependencies) {
if (newSetting.dependencies[d].groupArtifactVersion === newSetting.depArtifact) {
newSetting.dependencies[d] = {
'groupArtifactVersion': newSetting.depArtifact,
'exclusions': newSetting.depExclude
- };
- newSetting.dependencies.splice(d, 1);
+ }
+ newSetting.dependencies.splice(d, 1)
}
}
newSetting.dependencies.push({
'groupArtifactVersion': newSetting.depArtifact,
'exclusions': (newSetting.depExclude === '') ? [] : newSetting.depExclude
- });
- emptyNewDependency(newSetting);
+ })
+ emptyNewDependency(newSetting)
} else {
// Add new dependency from edit form
- var index = _.findIndex($scope.interpreterSettings, {'id': settingId});
- var setting = $scope.interpreterSettings[index];
+ let index = _.findIndex($scope.interpreterSettings, {'id': settingId})
+ let setting = $scope.interpreterSettings[index]
if (!setting.depArtifact || setting.depArtifact === '') {
- return;
+ return
}
// overwrite if artifact already exists
- for (var dep in setting.dependencies) {
+ for (let dep in setting.dependencies) {
if (setting.dependencies[dep].groupArtifactVersion === setting.depArtifact) {
setting.dependencies[dep] = {
'groupArtifactVersion': setting.depArtifact,
'exclusions': setting.depExclude
- };
- setting.dependencies.splice(dep, 1);
+ }
+ setting.dependencies.splice(dep, 1)
}
}
setting.dependencies.push({
'groupArtifactVersion': setting.depArtifact,
'exclusions': (setting.depExclude === '') ? [] : setting.depExclude
- });
- emptyNewDependency(setting);
+ })
+ emptyNewDependency(setting)
}
- };
+ }
- $scope.resetNewRepositorySetting = function() {
+ $scope.resetNewRepositorySetting = function () {
$scope.newRepoSetting = {
id: '',
url: '',
@@ -634,90 +635,89 @@ function InterpreterCtrl($rootScope, $scope, $http, baseUrlSrv, ngToast, $timeou
proxyPort: null,
proxyLogin: '',
proxyPassword: ''
- };
- };
+ }
+ }
- var getRepositories = function() {
+ let getRepositories = function () {
$http.get(baseUrlSrv.getRestApiBase() + '/interpreter/repository')
- .success(function(data, status, headers, config) {
- $scope.repositories = data.body;
- }).error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- });
- };
+ .success(function (data, status, headers, config) {
+ $scope.repositories = data.body
+ }).error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ })
+ }
- $scope.addNewRepository = function() {
- var request = angular.copy($scope.newRepoSetting);
+ $scope.addNewRepository = function () {
+ let request = angular.copy($scope.newRepoSetting)
$http.post(baseUrlSrv.getRestApiBase() + '/interpreter/repository', request)
- .success(function(data, status, headers, config) {
- getRepositories();
- $scope.resetNewRepositorySetting();
- angular.element('#repoModal').modal('hide');
- }).error(function(data, status, headers, config) {
- console.log('Error %o %o', headers, config);
- });
- };
-
- $scope.removeRepository = function(repoId) {
+ .success(function (data, status, headers, config) {
+ getRepositories()
+ $scope.resetNewRepositorySetting()
+ angular.element('#repoModal').modal('hide')
+ }).error(function (data, status, headers, config) {
+ console.log('Error %o %o', headers, config)
+ })
+ }
+
+ $scope.removeRepository = function (repoId) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Do you want to delete this repository?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
$http.delete(baseUrlSrv.getRestApiBase() + '/interpreter/repository/' + repoId)
- .success(function(data, status, headers, config) {
- var index = _.findIndex($scope.repositories, {'id': repoId});
- $scope.repositories.splice(index, 1);
- }).error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- });
+ .success(function (data, status, headers, config) {
+ let index = _.findIndex($scope.repositories, {'id': repoId})
+ $scope.repositories.splice(index, 1)
+ }).error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ })
}
}
- });
- };
+ })
+ }
- $scope.isDefaultRepository = function(repoId) {
+ $scope.isDefaultRepository = function (repoId) {
if (repoId === 'central' || repoId === 'local') {
- return true;
+ return true
} else {
- return false;
+ return false
}
- };
+ }
- $scope.showErrorMessage = function(setting) {
+ $scope.showErrorMessage = function (setting) {
BootstrapDialog.show({
title: 'Error downloading dependencies',
message: setting.errorReason
- });
- };
+ })
+ }
- var init = function() {
- $scope.resetNewInterpreterSetting();
- $scope.resetNewRepositorySetting();
+ let init = function () {
+ $scope.resetNewInterpreterSetting()
+ $scope.resetNewRepositorySetting()
- getInterpreterSettings();
- getAvailableInterpreters();
- getRepositories();
- };
+ getInterpreterSettings()
+ getAvailableInterpreters()
+ getRepositories()
+ }
- $scope.showSparkUI = function(settingId) {
+ $scope.showSparkUI = function (settingId) {
$http.get(baseUrlSrv.getRestApiBase() + '/interpreter/getmetainfos/' + settingId + '?propName=url')
- .success(function(data, status, headers, config) {
- var url = data.body.url;
+ .success(function (data, status, headers, config) {
+ let url = data.body.url
if (!url) {
BootstrapDialog.alert({
message: 'No spark application running'
- });
- return;
+ })
+ return
}
- window.open(url, '_blank');
- }).error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- });
- };
+ window.open(url, '_blank')
+ }).error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ })
+ }
- init();
+ init()
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/interpreter/interpreter.filter.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/interpreter/interpreter.filter.js b/zeppelin-web/src/app/interpreter/interpreter.filter.js
index c5f1572..3f42572 100644
--- a/zeppelin-web/src/app/interpreter/interpreter.filter.js
+++ b/zeppelin-web/src/app/interpreter/interpreter.filter.js
@@ -12,11 +12,11 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').filter('sortByKey', sortByKey);
+angular.module('zeppelinWebApp').filter('sortByKey', sortByKey)
-function sortByKey() {
- return function(properties) {
- var sortedKeys = properties ? Object.keys(properties) : [];
- return sortedKeys.sort();
- };
+function sortByKey () {
+ return function (properties) {
+ let sortedKeys = properties ? Object.keys(properties) : []
+ return sortedKeys.sort()
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/jobmanager/jobmanager.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/jobmanager/jobmanager.controller.js b/zeppelin-web/src/app/jobmanager/jobmanager.controller.js
index 5503be4..ec6f1ab 100644
--- a/zeppelin-web/src/app/jobmanager/jobmanager.controller.js
+++ b/zeppelin-web/src/app/jobmanager/jobmanager.controller.js
@@ -13,172 +13,169 @@
*/
angular.module('zeppelinWebApp')
- .controller('JobmanagerCtrl', JobmanagerCtrl);
+ .controller('JobmanagerCtrl', JobmanagerCtrl)
-function JobmanagerCtrl($scope, websocketMsgSrv, $interval, ngToast, $q, $timeout, jobManagerFilter) {
- 'ngInject';
+function JobmanagerCtrl ($scope, websocketMsgSrv, $interval, ngToast, $q, $timeout, jobManagerFilter) {
+ 'ngInject'
- ngToast.dismiss();
- var asyncNotebookJobFilter = function(jobInfomations, filterConfig) {
- return $q(function(resolve, reject) {
- $scope.JobInfomationsByFilter = $scope.jobTypeFilter(jobInfomations, filterConfig);
- resolve($scope.JobInfomationsByFilter);
- });
- };
+ ngToast.dismiss()
+ let asyncNotebookJobFilter = function (jobInfomations, filterConfig) {
+ return $q(function (resolve, reject) {
+ $scope.JobInfomationsByFilter = $scope.jobTypeFilter(jobInfomations, filterConfig)
+ resolve($scope.JobInfomationsByFilter)
+ })
+ }
- $scope.doFiltering = function(jobInfomations, filterConfig) {
+ $scope.doFiltering = function (jobInfomations, filterConfig) {
asyncNotebookJobFilter(jobInfomations, filterConfig).then(
- function() {
+ function () {
// success
- $scope.isLoadingFilter = false;
+ $scope.isLoadingFilter = false
},
- function() {
+ function () {
// failed
- });
- };
+ })
+ }
- $scope.filterValueToName = function(filterValue, maxStringLength) {
+ $scope.filterValueToName = function (filterValue, maxStringLength) {
if ($scope.activeInterpreters === undefined) {
- return;
+ return
}
- var index = _.findIndex($scope.activeInterpreters, {value: filterValue});
+ let index = _.findIndex($scope.activeInterpreters, {value: filterValue})
if ($scope.activeInterpreters[index].name !== undefined) {
if (maxStringLength !== undefined && maxStringLength > $scope.activeInterpreters[index].name) {
- return $scope.activeInterpreters[index].name.substr(0, maxStringLength - 3) + '...';
+ return $scope.activeInterpreters[index].name.substr(0, maxStringLength - 3) + '...'
}
- return $scope.activeInterpreters[index].name;
+ return $scope.activeInterpreters[index].name
} else {
- return 'Interpreter is not set';
+ return 'Interpreter is not set'
}
- };
-
- $scope.setFilterValue = function(filterValue) {
- $scope.filterConfig.filterValueInterpreter = filterValue;
- $scope.doFiltering($scope.jobInfomations, $scope.filterConfig);
- };
-
- $scope.onChangeRunJobToAlwaysTopToggle = function() {
- $scope.filterConfig.isRunningAlwaysTop = !$scope.filterConfig.isRunningAlwaysTop;
- $scope.doFiltering($scope.jobInfomations, $scope.filterConfig);
- };
-
- $scope.onChangeSortAsc = function() {
- $scope.filterConfig.isSortByAsc = !$scope.filterConfig.isSortByAsc;
- $scope.doFiltering($scope.jobInfomations, $scope.filterConfig);
- };
-
- $scope.doFilterInputTyping = function(keyEvent, jobInfomations, filterConfig) {
- var RETURN_KEY_CODE = 13;
- $timeout.cancel($scope.dofilterTimeoutObject);
- $scope.isActiveSearchTimer = true;
- $scope.dofilterTimeoutObject = $timeout(function() {
- $scope.doFiltering(jobInfomations, filterConfig);
- $scope.isActiveSearchTimer = false;
- }, 10000);
+ }
+
+ $scope.setFilterValue = function (filterValue) {
+ $scope.filterConfig.filterValueInterpreter = filterValue
+ $scope.doFiltering($scope.jobInfomations, $scope.filterConfig)
+ }
+
+ $scope.onChangeRunJobToAlwaysTopToggle = function () {
+ $scope.filterConfig.isRunningAlwaysTop = !$scope.filterConfig.isRunningAlwaysTop
+ $scope.doFiltering($scope.jobInfomations, $scope.filterConfig)
+ }
+
+ $scope.onChangeSortAsc = function () {
+ $scope.filterConfig.isSortByAsc = !$scope.filterConfig.isSortByAsc
+ $scope.doFiltering($scope.jobInfomations, $scope.filterConfig)
+ }
+
+ $scope.doFilterInputTyping = function (keyEvent, jobInfomations, filterConfig) {
+ let RETURN_KEY_CODE = 13
+ $timeout.cancel($scope.dofilterTimeoutObject)
+ $scope.isActiveSearchTimer = true
+ $scope.dofilterTimeoutObject = $timeout(function () {
+ $scope.doFiltering(jobInfomations, filterConfig)
+ $scope.isActiveSearchTimer = false
+ }, 10000)
if (keyEvent.which === RETURN_KEY_CODE) {
- $timeout.cancel($scope.dofilterTimeoutObject);
- $scope.doFiltering(jobInfomations, filterConfig);
- $scope.isActiveSearchTimer = false;
+ $timeout.cancel($scope.dofilterTimeoutObject)
+ $scope.doFiltering(jobInfomations, filterConfig)
+ $scope.isActiveSearchTimer = false
}
- };
-
- $scope.doForceFilterInputTyping = function(keyEvent, jobInfomations, filterConfig) {
- $timeout.cancel($scope.dofilterTimeoutObject);
- $scope.doFiltering(jobInfomations, filterConfig);
- $scope.isActiveSearchTimer = false;
- };
-
- $scope.init = function() {
- $scope.isLoadingFilter = true;
- $scope.jobInfomations = [];
- $scope.JobInfomationsByFilter = $scope.jobInfomations;
+ }
+
+ $scope.doForceFilterInputTyping = function (keyEvent, jobInfomations, filterConfig) {
+ $timeout.cancel($scope.dofilterTimeoutObject)
+ $scope.doFiltering(jobInfomations, filterConfig)
+ $scope.isActiveSearchTimer = false
+ }
+
+ $scope.init = function () {
+ $scope.isLoadingFilter = true
+ $scope.jobInfomations = []
+ $scope.JobInfomationsByFilter = $scope.jobInfomations
$scope.filterConfig = {
isRunningAlwaysTop: true,
filterValueNotebookName: '',
filterValueInterpreter: '*',
isSortByAsc: true
- };
- $scope.sortTooltipMsg = 'Switch to sort by desc';
- $scope.jobTypeFilter = jobManagerFilter;
+ }
+ $scope.sortTooltipMsg = 'Switch to sort by desc'
+ $scope.jobTypeFilter = jobManagerFilter
- websocketMsgSrv.getNoteJobsList();
+ websocketMsgSrv.getNoteJobsList()
$scope.$watch('filterConfig.isSortByAsc', function (value) {
if (value) {
- $scope.sortTooltipMsg = 'Switch to sort by desc';
+ $scope.sortTooltipMsg = 'Switch to sort by desc'
} else {
- $scope.sortTooltipMsg = 'Switch to sort by asc';
+ $scope.sortTooltipMsg = 'Switch to sort by asc'
}
- });
+ })
- $scope.$on('$destroy', function() {
- websocketMsgSrv.unsubscribeJobManager();
- });
- };
+ $scope.$on('$destroy', function () {
+ websocketMsgSrv.unsubscribeJobManager()
+ })
+ }
/*
** $scope.$on functions below
*/
- $scope.$on('setNoteJobs', function(event, responseData) {
- $scope.lastJobServerUnixTime = responseData.lastResponseUnixTime;
- $scope.jobInfomations = responseData.jobs;
- $scope.jobInfomationsIndexs = $scope.jobInfomations ? _.indexBy($scope.jobInfomations, 'noteId') : {};
- $scope.jobTypeFilter($scope.jobInfomations, $scope.filterConfig);
+ $scope.$on('setNoteJobs', function (event, responseData) {
+ $scope.lastJobServerUnixTime = responseData.lastResponseUnixTime
+ $scope.jobInfomations = responseData.jobs
+ $scope.jobInfomationsIndexs = $scope.jobInfomations ? _.indexBy($scope.jobInfomations, 'noteId') : {}
+ $scope.jobTypeFilter($scope.jobInfomations, $scope.filterConfig)
$scope.activeInterpreters = [
{
name: 'ALL',
value: '*'
}
- ];
- var interpreterLists = _.uniq(_.pluck($scope.jobInfomations, 'interpreter'), false);
- for (var index = 0, length = interpreterLists.length; index < length; index++) {
+ ]
+ let interpreterLists = _.uniq(_.pluck($scope.jobInfomations, 'interpreter'), false)
+ for (let index = 0, length = interpreterLists.length; index < length; index++) {
$scope.activeInterpreters.push({
name: interpreterLists[index],
value: interpreterLists[index]
- });
+ })
}
- $scope.doFiltering($scope.jobInfomations, $scope.filterConfig);
- });
-
- $scope.$on('setUpdateNoteJobs', function(event, responseData) {
- var jobInfomations = $scope.jobInfomations;
- var indexStore = $scope.jobInfomationsIndexs;
- $scope.lastJobServerUnixTime = responseData.lastResponseUnixTime;
- var notes = responseData.jobs;
- notes.map(function(changedItem) {
+ $scope.doFiltering($scope.jobInfomations, $scope.filterConfig)
+ })
+
+ $scope.$on('setUpdateNoteJobs', function (event, responseData) {
+ let jobInfomations = $scope.jobInfomations
+ let indexStore = $scope.jobInfomationsIndexs
+ $scope.lastJobServerUnixTime = responseData.lastResponseUnixTime
+ let notes = responseData.jobs
+ notes.map(function (changedItem) {
if (indexStore[changedItem.noteId] === undefined) {
- var newItem = angular.copy(changedItem);
- jobInfomations.push(newItem);
- indexStore[changedItem.noteId] = newItem;
+ let newItem = angular.copy(changedItem)
+ jobInfomations.push(newItem)
+ indexStore[changedItem.noteId] = newItem
} else {
- var changeOriginTarget = indexStore[changedItem.noteId];
+ let changeOriginTarget = indexStore[changedItem.noteId]
if (changedItem.isRemoved !== undefined && changedItem.isRemoved === true) {
-
// remove Item.
- var removeIndex = _.findIndex(indexStore, changedItem.noteId);
+ let removeIndex = _.findIndex(indexStore, changedItem.noteId)
if (removeIndex > -1) {
- indexStore.splice(removeIndex, 1);
+ indexStore.splice(removeIndex, 1)
}
- removeIndex = _.findIndex(jobInfomations, {'noteId': changedItem.noteId});
+ removeIndex = _.findIndex(jobInfomations, {'noteId': changedItem.noteId})
if (removeIndex) {
- jobInfomations.splice(removeIndex, 1);
+ jobInfomations.splice(removeIndex, 1)
}
-
} else {
// change value for item.
- changeOriginTarget.isRunningJob = changedItem.isRunningJob;
- changeOriginTarget.noteName = changedItem.noteName;
- changeOriginTarget.noteType = changedItem.noteType;
- changeOriginTarget.interpreter = changedItem.interpreter;
- changeOriginTarget.unixTimeLastRun = changedItem.unixTimeLastRun;
- changeOriginTarget.paragraphs = changedItem.paragraphs;
+ changeOriginTarget.isRunningJob = changedItem.isRunningJob
+ changeOriginTarget.noteName = changedItem.noteName
+ changeOriginTarget.noteType = changedItem.noteType
+ changeOriginTarget.interpreter = changedItem.interpreter
+ changeOriginTarget.unixTimeLastRun = changedItem.unixTimeLastRun
+ changeOriginTarget.paragraphs = changedItem.paragraphs
}
}
- });
- $scope.doFiltering(jobInfomations, $scope.filterConfig);
- });
+ })
+ $scope.doFiltering(jobInfomations, $scope.filterConfig)
+ })
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/jobmanager/jobmanager.filter.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/jobmanager/jobmanager.filter.js b/zeppelin-web/src/app/jobmanager/jobmanager.filter.js
index 05a1b6e..9211498 100644
--- a/zeppelin-web/src/app/jobmanager/jobmanager.filter.js
+++ b/zeppelin-web/src/app/jobmanager/jobmanager.filter.js
@@ -12,37 +12,36 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').filter('jobManager', jobManagerFilter);
+angular.module('zeppelinWebApp').filter('jobManager', jobManagerFilter)
-function jobManagerFilter() {
- function filterContext(jobItems, filterConfig) {
- var filterValueInterpreter = filterConfig.filterValueInterpreter;
- var filterValueNotebookName = filterConfig.filterValueNotebookName;
- var isSortByAsc = filterConfig.isSortByAsc;
- var filterItems = jobItems;
+function jobManagerFilter () {
+ function filterContext (jobItems, filterConfig) {
+ let filterValueInterpreter = filterConfig.filterValueInterpreter
+ let filterValueNotebookName = filterConfig.filterValueNotebookName
+ let isSortByAsc = filterConfig.isSortByAsc
+ let filterItems = jobItems
if (filterValueInterpreter === undefined) {
- filterItems = _.filter(filterItems, function(jobItem) {
- return jobItem.interpreter === undefined ? true : false;
- });
+ filterItems = _.filter(filterItems, function (jobItem) {
+ return jobItem.interpreter === undefined ? true : false
+ })
} else if (filterValueInterpreter !== '*') {
- filterItems = _.where(filterItems, {interpreter: filterValueInterpreter});
+ filterItems = _.where(filterItems, {interpreter: filterValueInterpreter})
}
if (filterValueNotebookName !== '') {
- filterItems = _.filter(filterItems, function(jobItem) {
- var lowerFilterValue = filterValueNotebookName.toLocaleLowerCase();
- var lowerNotebookName = jobItem.noteName.toLocaleLowerCase();
- return lowerNotebookName.match(new RegExp('.*' + lowerFilterValue + '.*'));
- });
+ filterItems = _.filter(filterItems, function (jobItem) {
+ let lowerFilterValue = filterValueNotebookName.toLocaleLowerCase()
+ let lowerNotebookName = jobItem.noteName.toLocaleLowerCase()
+ return lowerNotebookName.match(new RegExp('.*' + lowerFilterValue + '.*'))
+ })
}
- filterItems = _.sortBy(filterItems, function(sortItem) {
- return sortItem.noteName.toLowerCase();
- });
+ filterItems = _.sortBy(filterItems, function (sortItem) {
+ return sortItem.noteName.toLowerCase()
+ })
- return isSortByAsc ? filterItems : filterItems.reverse();
+ return isSortByAsc ? filterItems : filterItems.reverse()
}
- return filterContext;
+ return filterContext
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/jobmanager/jobs/job.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/jobmanager/jobs/job.controller.js b/zeppelin-web/src/app/jobmanager/jobs/job.controller.js
index 50f8d7a..e1ce02d 100644
--- a/zeppelin-web/src/app/jobmanager/jobs/job.controller.js
+++ b/zeppelin-web/src/app/jobmanager/jobs/job.controller.js
@@ -12,38 +12,38 @@
* limitations under the License.
*/
-import { ParagraphStatus, } from '../../notebook/paragraph/paragraph.status';
+import { ParagraphStatus, } from '../../notebook/paragraph/paragraph.status'
-angular.module('zeppelinWebApp').controller('JobCtrl', JobCtrl);
+angular.module('zeppelinWebApp').controller('JobCtrl', JobCtrl)
-function JobCtrl($scope, $http, baseUrlSrv) {
- 'ngInject';
+function JobCtrl ($scope, $http, baseUrlSrv) {
+ 'ngInject'
- $scope.init = function(jobInformation) {
- $scope.progressValue = 0;
- };
+ $scope.init = function (jobInformation) {
+ $scope.progressValue = 0
+ }
- $scope.getProgress = function() {
- var statusList = _.pluck($scope.notebookJob.paragraphs, 'status');
- var runningJob = _.countBy(statusList, function(status) {
+ $scope.getProgress = function () {
+ let statusList = _.pluck($scope.notebookJob.paragraphs, 'status')
+ let runningJob = _.countBy(statusList, function (status) {
if (status === ParagraphStatus.RUNNING || status === ParagraphStatus.FINISHED) {
- return 'matchCount';
+ return 'matchCount'
} else {
- return 'none';
+ return 'none'
}
- });
- var totalCount = statusList.length;
- var runningJobCount = runningJob.matchCount;
- var result = Math.ceil(runningJobCount / totalCount * 100);
- return isNaN(result) ? 0 : result;
- };
+ })
+ let totalCount = statusList.length
+ let runningJobCount = runningJob.matchCount
+ let result = Math.ceil(runningJobCount / totalCount * 100)
+ return isNaN(result) ? 0 : result
+ }
- $scope.runNotebookJob = function(notebookId) {
+ $scope.runNotebookJob = function (notebookId) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Run all paragraphs?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
$http({
method: 'POST',
@@ -51,30 +51,31 @@ function JobCtrl($scope, $http, baseUrlSrv) {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
- }).then(function successCallback(response) {
+ }).then(function successCallback (response) {
// success
- }, function errorCallback(errorResponse) {
- var errorText = 'SERVER ERROR';
+ }, function errorCallback (errorResponse) {
+ let errorText = 'SERVER ERROR'
+ // eslint-disable-next-line no-extra-boolean-cast
if (!!errorResponse.data.message) {
- errorText = errorResponse.data.message;
+ errorText = errorResponse.data.message
}
BootstrapDialog.alert({
closable: true,
title: 'Execution Failure',
message: errorText
- });
- });
+ })
+ })
}
}
- });
- };
+ })
+ }
- $scope.stopNotebookJob = function(notebookId) {
+ $scope.stopNotebookJob = function (notebookId) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Stop all paragraphs?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
$http({
method: 'DELETE',
@@ -82,28 +83,26 @@ function JobCtrl($scope, $http, baseUrlSrv) {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
- }).then(function successCallback(response) {
+ }).then(function successCallback (response) {
// success
- }, function errorCallback(errorResponse) {
- var errorText = 'SERVER ERROR';
+ }, function errorCallback (errorResponse) {
+ let errorText = 'SERVER ERROR'
+ // eslint-disable-next-line no-extra-boolean-cast
if (!!errorResponse.data.message) {
-
- errorText = errorResponse.data.message;
+ errorText = errorResponse.data.message
}
BootstrapDialog.alert({
closable: true,
title: 'Stop Failure',
message: errorText
- });
- });
+ })
+ })
}
}
- });
- };
-
- $scope.lastExecuteTime = function(unixtime) {
- return moment.unix(unixtime / 1000).fromNow();
- };
+ })
+ }
+ $scope.lastExecuteTime = function (unixtime) {
+ return moment.unix(unixtime / 1000).fromNow()
+ }
}
-
[5/8] zeppelin git commit: [ZEPPELIN-1940] lint rule set is NOT
applied at all.
Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.js b/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.js
index a453f16..1a92176 100644
--- a/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.js
+++ b/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.js
@@ -12,168 +12,180 @@
* limitations under the License.
*/
-import { SpellResult, } from '../../spell';
+import { SpellResult, } from '../../spell'
import {
ParagraphStatus, isParagraphRunning,
-} from './paragraph.status';
+} from './paragraph.status'
const ParagraphExecutor = {
SPELL: 'SPELL',
INTERPRETER: 'INTERPRETER',
NONE: '', /** meaning `DONE` */
-};
+}
-angular.module('zeppelinWebApp').controller('ParagraphCtrl', ParagraphCtrl);
+angular.module('zeppelinWebApp').controller('ParagraphCtrl', ParagraphCtrl)
-function ParagraphCtrl($scope, $rootScope, $route, $window, $routeParams, $location,
+function ParagraphCtrl ($scope, $rootScope, $route, $window, $routeParams, $location,
$timeout, $compile, $http, $q, websocketMsgSrv,
baseUrlSrv, ngToast, saveAsService, noteVarShareService,
heliumService) {
- 'ngInject';
+ 'ngInject'
- var ANGULAR_FUNCTION_OBJECT_NAME_PREFIX = '_Z_ANGULAR_FUNC_';
- $rootScope.keys = Object.keys;
- $scope.parentNote = null;
- $scope.paragraph = {};
- $scope.paragraph.results = {};
- $scope.paragraph.results.msg = [];
- $scope.originalText = '';
- $scope.editor = null;
+ let ANGULAR_FUNCTION_OBJECT_NAME_PREFIX = '_Z_ANGULAR_FUNC_'
+ $rootScope.keys = Object.keys
+ $scope.parentNote = null
+ $scope.paragraph = {}
+ $scope.paragraph.results = {}
+ $scope.paragraph.results.msg = []
+ $scope.originalText = ''
+ $scope.editor = null
// transactional info for spell execution
$scope.spellTransaction = {
- totalResultCount: 0, renderedResultCount: 0,
- propagated: false, resultsMsg: [], paragraphText: '',
- };
+ totalResultCount: 0,
+ renderedResultCount: 0,
+ propagated: false,
+ resultsMsg: [],
+ paragraphText: '',
+ }
- var editorSetting = {};
+ let editorSetting = {}
// flag that is used to set editor setting on paste percent sign
- var pastePercentSign = false;
+ let pastePercentSign = false
// flag that is used to set editor setting on save interpreter bindings
- var setInterpreterBindings = false;
- var paragraphScope = $rootScope.$new(true, $rootScope);
+ let setInterpreterBindings = false
+ let paragraphScope = $rootScope.$new(true, $rootScope)
// to keep backward compatibility
- $scope.compiledScope = paragraphScope;
+ $scope.compiledScope = paragraphScope
paragraphScope.z = {
// z.runParagraph('20150213-231621_168813393')
- runParagraph: function(paragraphId) {
+ runParagraph: function (paragraphId) {
if (paragraphId) {
- var filtered = $scope.parentNote.paragraphs.filter(function(x) {
- return x.id === paragraphId;});
+ let filtered = $scope.parentNote.paragraphs.filter(function (x) {
+ return x.id === paragraphId
+ })
if (filtered.length === 1) {
- var paragraph = filtered[0];
+ let paragraph = filtered[0]
websocketMsgSrv.runParagraph(paragraph.id, paragraph.title, paragraph.text,
- paragraph.config, paragraph.settings.params);
+ paragraph.config, paragraph.settings.params)
} else {
- ngToast.danger({content: 'Cannot find a paragraph with id \'' + paragraphId + '\'',
- verticalPosition: 'top', dismissOnTimeout: false});
+ ngToast.danger({
+ content: 'Cannot find a paragraph with id \'' + paragraphId + '\'',
+ verticalPosition: 'top',
+ dismissOnTimeout: false
+ })
}
} else {
ngToast.danger({
content: 'Please provide a \'paragraphId\' when calling z.runParagraph(paragraphId)',
- verticalPosition: 'top', dismissOnTimeout: false});
+ verticalPosition: 'top',
+ dismissOnTimeout: false
+ })
}
},
// Example: z.angularBind('my_var', 'Test Value', '20150213-231621_168813393')
- angularBind: function(varName, value, paragraphId) {
+ angularBind: function (varName, value, paragraphId) {
// Only push to server if there paragraphId is defined
if (paragraphId) {
- websocketMsgSrv.clientBindAngularObject($routeParams.noteId, varName, value, paragraphId);
+ websocketMsgSrv.clientBindAngularObject($routeParams.noteId, varName, value, paragraphId)
} else {
ngToast.danger({
content: 'Please provide a \'paragraphId\' when calling ' +
'z.angularBind(varName, value, \'PUT_HERE_PARAGRAPH_ID\')',
- verticalPosition: 'top', dismissOnTimeout: false});
+ verticalPosition: 'top',
+ dismissOnTimeout: false
+ })
}
},
// Example: z.angularUnBind('my_var', '20150213-231621_168813393')
- angularUnbind: function(varName, paragraphId) {
+ angularUnbind: function (varName, paragraphId) {
// Only push to server if paragraphId is defined
if (paragraphId) {
- websocketMsgSrv.clientUnbindAngularObject($routeParams.noteId, varName, paragraphId);
+ websocketMsgSrv.clientUnbindAngularObject($routeParams.noteId, varName, paragraphId)
} else {
ngToast.danger({
content: 'Please provide a \'paragraphId\' when calling ' +
'z.angularUnbind(varName, \'PUT_HERE_PARAGRAPH_ID\')',
- verticalPosition: 'top', dismissOnTimeout: false});
+ verticalPosition: 'top',
+ dismissOnTimeout: false})
}
}
- };
+ }
- var angularObjectRegistry = {};
+ let angularObjectRegistry = {}
// Controller init
- $scope.init = function(newParagraph, note) {
- $scope.paragraph = newParagraph;
- $scope.parentNote = note;
- $scope.originalText = angular.copy(newParagraph.text);
- $scope.chart = {};
- $scope.baseMapOption = ['Streets', 'Satellite', 'Hybrid', 'Topo', 'Gray', 'Oceans', 'Terrain'];
- $scope.colWidthOption = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
- $scope.paragraphFocused = false;
+ $scope.init = function (newParagraph, note) {
+ $scope.paragraph = newParagraph
+ $scope.parentNote = note
+ $scope.originalText = angular.copy(newParagraph.text)
+ $scope.chart = {}
+ $scope.baseMapOption = ['Streets', 'Satellite', 'Hybrid', 'Topo', 'Gray', 'Oceans', 'Terrain']
+ $scope.colWidthOption = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
+ $scope.paragraphFocused = false
if (newParagraph.focus) {
- $scope.paragraphFocused = true;
+ $scope.paragraphFocused = true
}
if (!$scope.paragraph.config) {
- $scope.paragraph.config = {};
+ $scope.paragraph.config = {}
}
- noteVarShareService.put($scope.paragraph.id + '_paragraphScope', paragraphScope);
+ noteVarShareService.put($scope.paragraph.id + '_paragraphScope', paragraphScope)
- initializeDefault($scope.paragraph.config);
- };
+ initializeDefault($scope.paragraph.config)
+ }
- var initializeDefault = function(config) {
- var forms = $scope.paragraph.settings.forms;
+ const initializeDefault = function (config) {
+ let forms = $scope.paragraph.settings.forms
if (!config.colWidth) {
- config.colWidth = 12;
+ config.colWidth = 12
}
if (config.enabled === undefined) {
- config.enabled = true;
+ config.enabled = true
}
- for (var idx in forms) {
+ for (let idx in forms) {
if (forms[idx]) {
if (forms[idx].options) {
if (config.runOnSelectionChange === undefined) {
- config.runOnSelectionChange = true;
+ config.runOnSelectionChange = true
}
}
}
}
if (!config.results) {
- config.results = {};
+ config.results = {}
}
if (!config.editorSetting) {
- config.editorSetting = {};
+ config.editorSetting = {}
} else if (config.editorSetting.editOnDblClick) {
- editorSetting.isOutputHidden = config.editorSetting.editOnDblClick;
+ editorSetting.isOutputHidden = config.editorSetting.editOnDblClick
}
- };
+ }
- $scope.$on('updateParagraphOutput', function(event, data) {
+ $scope.$on('updateParagraphOutput', function (event, data) {
if ($scope.paragraph.id === data.paragraphId) {
if (!$scope.paragraph.results) {
- $scope.paragraph.results = {};
+ $scope.paragraph.results = {}
}
if (!$scope.paragraph.results.msg) {
- $scope.paragraph.results.msg = [];
+ $scope.paragraph.results.msg = []
}
- var update = ($scope.paragraph.results.msg[data.index]) ? true : false;
+ let update = ($scope.paragraph.results.msg[data.index]) ? true : false
$scope.paragraph.results.msg[data.index] = {
data: data.data,
type: data.type
- };
+ }
if (update) {
$rootScope.$broadcast(
@@ -181,62 +193,62 @@ function ParagraphCtrl($scope, $rootScope, $route, $window, $routeParams, $locat
$scope.paragraph.results.msg[data.index],
$scope.paragraph.config.results[data.index],
$scope.paragraph,
- data.index);
+ data.index)
}
}
- });
+ })
- $scope.getIframeDimensions = function() {
+ $scope.getIframeDimensions = function () {
if ($scope.asIframe) {
- var paragraphid = '#' + $routeParams.paragraphId + '_container';
- var height = angular.element(paragraphid).height();
- return height;
+ let paragraphid = '#' + $routeParams.paragraphId + '_container'
+ let height = angular.element(paragraphid).height()
+ return height
}
- return 0;
- };
+ return 0
+ }
- $scope.$watch($scope.getIframeDimensions, function(newValue, oldValue) {
+ $scope.$watch($scope.getIframeDimensions, function (newValue, oldValue) {
if ($scope.asIframe && newValue) {
- var message = {};
- message.height = newValue;
- message.url = $location.$$absUrl;
- $window.parent.postMessage(angular.toJson(message), '*');
+ let message = {}
+ message.height = newValue
+ message.url = $location.$$absUrl
+ $window.parent.postMessage(angular.toJson(message), '*')
}
- });
+ })
- $scope.getEditor = function() {
- return $scope.editor;
- };
+ $scope.getEditor = function () {
+ return $scope.editor
+ }
- $scope.$watch($scope.getEditor, function(newValue, oldValue) {
+ $scope.$watch($scope.getEditor, function (newValue, oldValue) {
if (!$scope.editor) {
- return;
+ return
}
if (newValue === null || newValue === undefined) {
- console.log('editor isnt loaded yet, returning');
- return;
+ console.log('editor isnt loaded yet, returning')
+ return
}
if ($scope.revisionView === true) {
- $scope.editor.setReadOnly(true);
+ $scope.editor.setReadOnly(true)
} else {
- $scope.editor.setReadOnly(false);
+ $scope.editor.setReadOnly(false)
}
- });
+ })
- var isEmpty = function(object) {
- return !object;
- };
+ let isEmpty = function (object) {
+ return !object
+ }
- $scope.isRunning = function(paragraph) {
- return isParagraphRunning(paragraph);
- };
+ $scope.isRunning = function (paragraph) {
+ return isParagraphRunning(paragraph)
+ }
- $scope.cancelParagraph = function(paragraph) {
- console.log('Cancel %o', paragraph.id);
- websocketMsgSrv.cancelParagraphRun(paragraph.id);
- };
+ $scope.cancelParagraph = function (paragraph) {
+ console.log('Cancel %o', paragraph.id)
+ websocketMsgSrv.cancelParagraphRun(paragraph.id)
+ }
- $scope.propagateSpellResult = function(paragraphId, paragraphTitle,
+ $scope.propagateSpellResult = function (paragraphId, paragraphTitle,
paragraphText, paragraphResults,
paragraphStatus, paragraphErrorMessage,
paragraphConfig, paragraphSettingsParam) {
@@ -244,442 +256,443 @@ function ParagraphCtrl($scope, $rootScope, $route, $window, $routeParams, $locat
paragraphId, paragraphTitle,
paragraphText, paragraphResults,
paragraphStatus, paragraphErrorMessage,
- paragraphConfig, paragraphSettingsParam);
- };
+ paragraphConfig, paragraphSettingsParam)
+ }
- $scope.handleSpellError = function(paragraphText, error,
+ $scope.handleSpellError = function (paragraphText, error,
digestRequired, propagated) {
- const errorMessage = error.stack;
- $scope.paragraph.status = ParagraphStatus.ERROR;
- $scope.paragraph.errorMessage = errorMessage;
- console.error('Failed to execute interpret() in spell\n', error);
+ const errorMessage = error.stack
+ $scope.paragraph.status = ParagraphStatus.ERROR
+ $scope.paragraph.errorMessage = errorMessage
+ console.error('Failed to execute interpret() in spell\n', error)
if (!propagated) {
$scope.propagateSpellResult(
$scope.paragraph.id, $scope.paragraph.title,
paragraphText, [], $scope.paragraph.status, errorMessage,
- $scope.paragraph.config, $scope.paragraph.settings.params);
+ $scope.paragraph.config, $scope.paragraph.settings.params)
}
- };
+ }
- $scope.prepareSpellTransaction = function(resultsMsg, propagated, paragraphText) {
- $scope.spellTransaction.totalResultCount = resultsMsg.length;
- $scope.spellTransaction.renderedResultCount = 0;
- $scope.spellTransaction.propagated = propagated;
- $scope.spellTransaction.resultsMsg = resultsMsg;
- $scope.spellTransaction.paragraphText = paragraphText;
- };
+ $scope.prepareSpellTransaction = function (resultsMsg, propagated, paragraphText) {
+ $scope.spellTransaction.totalResultCount = resultsMsg.length
+ $scope.spellTransaction.renderedResultCount = 0
+ $scope.spellTransaction.propagated = propagated
+ $scope.spellTransaction.resultsMsg = resultsMsg
+ $scope.spellTransaction.paragraphText = paragraphText
+ }
/**
* - update spell transaction count and
* - check transaction is finished based on the result count
* @returns {boolean}
*/
- $scope.increaseSpellTransactionResultCount = function() {
- $scope.spellTransaction.renderedResultCount += 1;
+ $scope.increaseSpellTransactionResultCount = function () {
+ $scope.spellTransaction.renderedResultCount += 1
- const total = $scope.spellTransaction.totalResultCount;
- const current = $scope.spellTransaction.renderedResultCount;
- return total === current;
- };
+ const total = $scope.spellTransaction.totalResultCount
+ const current = $scope.spellTransaction.renderedResultCount
+ return total === current
+ }
- $scope.cleanupSpellTransaction = function() {
- const status = ParagraphStatus.FINISHED;
- $scope.paragraph.executor = ParagraphExecutor.NONE;
- $scope.paragraph.status = status;
- $scope.paragraph.results.code = status;
+ $scope.cleanupSpellTransaction = function () {
+ const status = ParagraphStatus.FINISHED
+ $scope.paragraph.executor = ParagraphExecutor.NONE
+ $scope.paragraph.status = status
+ $scope.paragraph.results.code = status
- const propagated = $scope.spellTransaction.propagated;
- const resultsMsg = $scope.spellTransaction.resultsMsg;
- const paragraphText = $scope.spellTransaction.paragraphText;
+ const propagated = $scope.spellTransaction.propagated
+ const resultsMsg = $scope.spellTransaction.resultsMsg
+ const paragraphText = $scope.spellTransaction.paragraphText
if (!propagated) {
- const propagable = SpellResult.createPropagable(resultsMsg);
+ const propagable = SpellResult.createPropagable(resultsMsg)
$scope.propagateSpellResult(
$scope.paragraph.id, $scope.paragraph.title,
paragraphText, propagable, status, '',
- $scope.paragraph.config, $scope.paragraph.settings.params);
+ $scope.paragraph.config, $scope.paragraph.settings.params)
}
- };
+ }
- $scope.runParagraphUsingSpell = function(paragraphText,
+ $scope.runParagraphUsingSpell = function (paragraphText,
magic, digestRequired, propagated) {
- $scope.paragraph.status = 'RUNNING';
- $scope.paragraph.executor = ParagraphExecutor.SPELL;
- $scope.paragraph.results = {};
- $scope.paragraph.errorMessage = '';
- if (digestRequired) { $scope.$digest(); }
+ $scope.paragraph.status = 'RUNNING'
+ $scope.paragraph.executor = ParagraphExecutor.SPELL
+ $scope.paragraph.results = {}
+ $scope.paragraph.errorMessage = ''
+ if (digestRequired) { $scope.$digest() }
try {
// remove magic from paragraphText
- const splited = paragraphText.split(magic);
+ const splited = paragraphText.split(magic)
// remove leading spaces
- const textWithoutMagic = splited[1].replace(/^\s+/g, '');
+ const textWithoutMagic = splited[1].replace(/^\s+/g, '')
// handle actual result message in promise
heliumService.executeSpell(magic, textWithoutMagic)
.then(resultsMsg => {
- $scope.prepareSpellTransaction(resultsMsg, propagated, paragraphText);
-
- $scope.paragraph.results.msg = resultsMsg;
- $scope.paragraph.config.tableHide = false;
+ $scope.prepareSpellTransaction(resultsMsg, propagated, paragraphText)
+ $scope.paragraph.results.msg = resultsMsg
+ $scope.paragraph.config.tableHide = false
})
.catch(error => {
$scope.handleSpellError(paragraphText, error,
- digestRequired, propagated);
- });
+ digestRequired, propagated)
+ })
} catch (error) {
$scope.handleSpellError(paragraphText, error,
- digestRequired, propagated);
+ digestRequired, propagated)
}
- };
+ }
- $scope.runParagraphUsingBackendInterpreter = function(paragraphText) {
+ $scope.runParagraphUsingBackendInterpreter = function (paragraphText) {
websocketMsgSrv.runParagraph($scope.paragraph.id, $scope.paragraph.title,
- paragraphText, $scope.paragraph.config, $scope.paragraph.settings.params);
- };
+ paragraphText, $scope.paragraph.config, $scope.paragraph.settings.params)
+ }
- $scope.saveParagraph = function(paragraph) {
- const dirtyText = paragraph.text;
+ $scope.saveParagraph = function (paragraph) {
+ const dirtyText = paragraph.text
if (dirtyText === undefined || dirtyText === $scope.originalText) {
- return;
+ return
}
- commitParagraph(paragraph);
- $scope.originalText = dirtyText;
- $scope.dirtyText = undefined;
- };
+ commitParagraph(paragraph)
+ $scope.originalText = dirtyText
+ $scope.dirtyText = undefined
+ }
- $scope.toggleEnableDisable = function(paragraph) {
- paragraph.config.enabled = !paragraph.config.enabled;
- commitParagraph(paragraph);
- };
+ $scope.toggleEnableDisable = function (paragraph) {
+ paragraph.config.enabled = !paragraph.config.enabled
+ commitParagraph(paragraph)
+ }
/**
* @param paragraphText to be parsed
* @param digestRequired true if calling `$digest` is required
* @param propagated true if update request is sent from other client
*/
- $scope.runParagraph = function(paragraphText, digestRequired, propagated) {
+ $scope.runParagraph = function (paragraphText, digestRequired, propagated) {
if (!paragraphText || $scope.isRunning($scope.paragraph)) {
- return;
+ return
}
- const magic = SpellResult.extractMagic(paragraphText);
+ const magic = SpellResult.extractMagic(paragraphText)
if (heliumService.getSpellByMagic(magic)) {
- $scope.runParagraphUsingSpell(paragraphText, magic, digestRequired, propagated);
+ $scope.runParagraphUsingSpell(paragraphText, magic, digestRequired, propagated)
} else {
- $scope.runParagraphUsingBackendInterpreter(paragraphText);
+ $scope.runParagraphUsingBackendInterpreter(paragraphText)
}
- $scope.originalText = angular.copy(paragraphText);
- $scope.dirtyText = undefined;
+ $scope.originalText = angular.copy(paragraphText)
+ $scope.dirtyText = undefined
if ($scope.paragraph.config.editorSetting.editOnDblClick) {
- closeEditorAndOpenTable($scope.paragraph);
+ closeEditorAndOpenTable($scope.paragraph)
} else if (editorSetting.isOutputHidden &&
!$scope.paragraph.config.editorSetting.editOnDblClick) {
// %md/%angular repl make output to be hidden by default after running
// so should open output if repl changed from %md/%angular to another
- openEditorAndOpenTable($scope.paragraph);
+ openEditorAndOpenTable($scope.paragraph)
}
- editorSetting.isOutputHidden = $scope.paragraph.config.editorSetting.editOnDblClick;
- };
+ editorSetting.isOutputHidden = $scope.paragraph.config.editorSetting.editOnDblClick
+ }
- $scope.runParagraphFromShortcut = function(paragraphText) {
+ $scope.runParagraphFromShortcut = function (paragraphText) {
// passing `digestRequired` as true to update view immediately
// without this, results cannot be rendered in view more than once
- $scope.runParagraph(paragraphText, true, false);
- };
+ $scope.runParagraph(paragraphText, true, false)
+ }
- $scope.runParagraphFromButton = function(paragraphText) {
+ $scope.runParagraphFromButton = function (paragraphText) {
// we come here from the view, so we don't need to call `$digest()`
$scope.runParagraph(paragraphText, false, false)
- };
+ }
$scope.turnOnAutoRun = function (paragraph) {
- paragraph.config.runOnSelectionChange = !paragraph.config.runOnSelectionChange;
- commitParagraph(paragraph);
- };
+ paragraph.config.runOnSelectionChange = !paragraph.config.runOnSelectionChange
+ commitParagraph(paragraph)
+ }
- $scope.moveUp = function(paragraph) {
- $scope.$emit('moveParagraphUp', paragraph);
- };
+ $scope.moveUp = function (paragraph) {
+ $scope.$emit('moveParagraphUp', paragraph)
+ }
- $scope.moveDown = function(paragraph) {
- $scope.$emit('moveParagraphDown', paragraph);
- };
+ $scope.moveDown = function (paragraph) {
+ $scope.$emit('moveParagraphDown', paragraph)
+ }
- $scope.insertNew = function(position) {
- $scope.$emit('insertParagraph', $scope.paragraph.id, position);
- };
+ $scope.insertNew = function (position) {
+ $scope.$emit('insertParagraph', $scope.paragraph.id, position)
+ }
- $scope.copyPara = function(position) {
- var editorValue = $scope.getEditorValue();
+ $scope.copyPara = function (position) {
+ let editorValue = $scope.getEditorValue()
if (editorValue) {
- $scope.copyParagraph(editorValue, position);
+ $scope.copyParagraph(editorValue, position)
}
- };
+ }
- $scope.copyParagraph = function(data, position) {
- var newIndex = -1;
- for (var i = 0; i < $scope.note.paragraphs.length; i++) {
+ $scope.copyParagraph = function (data, position) {
+ let newIndex = -1
+ for (let i = 0; i < $scope.note.paragraphs.length; i++) {
if ($scope.note.paragraphs[i].id === $scope.paragraph.id) {
- //determine position of where to add new paragraph; default is below
+ // determine position of where to add new paragraph; default is below
if (position === 'above') {
- newIndex = i;
+ newIndex = i
} else {
- newIndex = i + 1;
+ newIndex = i + 1
}
- break;
+ break
}
}
if (newIndex < 0 || newIndex > $scope.note.paragraphs.length) {
- return;
+ return
}
- var config = angular.copy($scope.paragraph.config);
- config.editorHide = false;
+ let config = angular.copy($scope.paragraph.config)
+ config.editorHide = false
websocketMsgSrv.copyParagraph(newIndex, $scope.paragraph.title, data,
- config, $scope.paragraph.settings.params);
- };
+ config, $scope.paragraph.settings.params)
+ }
- $scope.removeParagraph = function(paragraph) {
- var paragraphs = angular.element('div[id$="_paragraphColumn_main"]');
+ $scope.removeParagraph = function (paragraph) {
+ let paragraphs = angular.element('div[id$="_paragraphColumn_main"]')
if (paragraphs[paragraphs.length - 1].id.indexOf(paragraph.id) === 0) {
BootstrapDialog.alert({
closable: true,
message: 'The last paragraph can\'t be deleted.',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- $scope.editor.focus();
+ $scope.editor.focus()
}
}
- });
+ })
} else {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Do you want to delete this paragraph?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- console.log('Remove paragraph');
- websocketMsgSrv.removeParagraph(paragraph.id);
- $scope.$emit('moveFocusToNextParagraph', $scope.paragraph.id);
+ console.log('Remove paragraph')
+ websocketMsgSrv.removeParagraph(paragraph.id)
+ $scope.$emit('moveFocusToNextParagraph', $scope.paragraph.id)
}
}
- });
+ })
}
- };
+ }
- $scope.clearParagraphOutput = function(paragraph) {
- websocketMsgSrv.clearParagraphOutput(paragraph.id);
- };
+ $scope.clearParagraphOutput = function (paragraph) {
+ websocketMsgSrv.clearParagraphOutput(paragraph.id)
+ }
- $scope.toggleEditor = function(paragraph) {
+ $scope.toggleEditor = function (paragraph) {
if (paragraph.config.editorHide) {
- $scope.openEditor(paragraph);
+ $scope.openEditor(paragraph)
} else {
- $scope.closeEditor(paragraph);
- }
- };
-
- $scope.closeEditor = function(paragraph) {
- console.log('close the note');
- paragraph.config.editorHide = true;
- commitParagraph(paragraph);
- };
-
- $scope.openEditor = function(paragraph) {
- console.log('open the note');
- paragraph.config.editorHide = false;
- commitParagraph(paragraph);
- };
-
- $scope.closeTable = function(paragraph) {
- console.log('close the output');
- paragraph.config.tableHide = true;
- commitParagraph(paragraph);
- };
-
- $scope.openTable = function(paragraph) {
- console.log('open the output');
- paragraph.config.tableHide = false;
- commitParagraph(paragraph);
- };
-
- var openEditorAndCloseTable = function(paragraph) {
- manageEditorAndTableState(paragraph, false, true);
- };
-
- var closeEditorAndOpenTable = function(paragraph) {
- manageEditorAndTableState(paragraph, true, false);
- };
-
- var openEditorAndOpenTable = function(paragraph) {
- manageEditorAndTableState(paragraph, false, false);
- };
-
- var manageEditorAndTableState = function(paragraph, hideEditor, hideTable) {
- paragraph.config.editorHide = hideEditor;
- paragraph.config.tableHide = hideTable;
- commitParagraph(paragraph);
- };
-
- $scope.showTitle = function(paragraph) {
- paragraph.config.title = true;
- commitParagraph(paragraph);
- };
-
- $scope.hideTitle = function(paragraph) {
- paragraph.config.title = false;
- commitParagraph(paragraph);
- };
-
- $scope.setTitle = function(paragraph) {
- commitParagraph(paragraph);
- };
-
- $scope.showLineNumbers = function(paragraph) {
+ $scope.closeEditor(paragraph)
+ }
+ }
+
+ $scope.closeEditor = function (paragraph) {
+ console.log('close the note')
+ paragraph.config.editorHide = true
+ commitParagraph(paragraph)
+ }
+
+ $scope.openEditor = function (paragraph) {
+ console.log('open the note')
+ paragraph.config.editorHide = false
+ commitParagraph(paragraph)
+ }
+
+ $scope.closeTable = function (paragraph) {
+ console.log('close the output')
+ paragraph.config.tableHide = true
+ commitParagraph(paragraph)
+ }
+
+ $scope.openTable = function (paragraph) {
+ console.log('open the output')
+ paragraph.config.tableHide = false
+ commitParagraph(paragraph)
+ }
+
+ let openEditorAndCloseTable = function (paragraph) {
+ manageEditorAndTableState(paragraph, false, true)
+ }
+
+ const closeEditorAndOpenTable = function (paragraph) {
+ manageEditorAndTableState(paragraph, true, false)
+ }
+
+ const openEditorAndOpenTable = function (paragraph) {
+ manageEditorAndTableState(paragraph, false, false)
+ }
+
+ const manageEditorAndTableState = function (paragraph, hideEditor, hideTable) {
+ paragraph.config.editorHide = hideEditor
+ paragraph.config.tableHide = hideTable
+ commitParagraph(paragraph)
+ }
+
+ $scope.showTitle = function (paragraph) {
+ paragraph.config.title = true
+ commitParagraph(paragraph)
+ }
+
+ $scope.hideTitle = function (paragraph) {
+ paragraph.config.title = false
+ commitParagraph(paragraph)
+ }
+
+ $scope.setTitle = function (paragraph) {
+ commitParagraph(paragraph)
+ }
+
+ $scope.showLineNumbers = function (paragraph) {
if ($scope.editor) {
- paragraph.config.lineNumbers = true;
- $scope.editor.renderer.setShowGutter(true);
- commitParagraph(paragraph);
+ paragraph.config.lineNumbers = true
+ $scope.editor.renderer.setShowGutter(true)
+ commitParagraph(paragraph)
}
- };
+ }
- $scope.hideLineNumbers = function(paragraph) {
+ $scope.hideLineNumbers = function (paragraph) {
if ($scope.editor) {
- paragraph.config.lineNumbers = false;
- $scope.editor.renderer.setShowGutter(false);
- commitParagraph(paragraph);
+ paragraph.config.lineNumbers = false
+ $scope.editor.renderer.setShowGutter(false)
+ commitParagraph(paragraph)
}
- };
+ }
- $scope.columnWidthClass = function(n) {
+ $scope.columnWidthClass = function (n) {
if ($scope.asIframe) {
- return 'col-md-12';
+ return 'col-md-12'
} else {
- return 'paragraph-col col-md-' + n;
+ return 'paragraph-col col-md-' + n
}
- };
+ }
- $scope.changeColWidth = function(paragraph, width) {
- angular.element('.navbar-right.open').removeClass('open');
- paragraph.config.colWidth = width;
- commitParagraph(paragraph);
- };
+ $scope.changeColWidth = function (paragraph, width) {
+ angular.element('.navbar-right.open').removeClass('open')
+ paragraph.config.colWidth = width
+ commitParagraph(paragraph)
+ }
- $scope.toggleOutput = function(paragraph) {
- paragraph.config.tableHide = !paragraph.config.tableHide;
- commitParagraph(paragraph);
- };
+ $scope.toggleOutput = function (paragraph) {
+ paragraph.config.tableHide = !paragraph.config.tableHide
+ commitParagraph(paragraph)
+ }
- $scope.loadForm = function(formulaire, params) {
- var value = formulaire.defaultValue;
+ $scope.loadForm = function (formulaire, params) {
+ let value = formulaire.defaultValue
if (params[formulaire.name]) {
- value = params[formulaire.name];
+ value = params[formulaire.name]
}
- $scope.paragraph.settings.params[formulaire.name] = value;
- };
+ $scope.paragraph.settings.params[formulaire.name] = value
+ }
- $scope.toggleCheckbox = function(formulaire, option) {
- var idx = $scope.paragraph.settings.params[formulaire.name].indexOf(option.value);
+ $scope.toggleCheckbox = function (formulaire, option) {
+ let idx = $scope.paragraph.settings.params[formulaire.name].indexOf(option.value)
if (idx > -1) {
- $scope.paragraph.settings.params[formulaire.name].splice(idx, 1);
+ $scope.paragraph.settings.params[formulaire.name].splice(idx, 1)
} else {
- $scope.paragraph.settings.params[formulaire.name].push(option.value);
+ $scope.paragraph.settings.params[formulaire.name].push(option.value)
}
- };
+ }
- $scope.aceChanged = function(_, editor) {
- var session = editor.getSession();
- var dirtyText = session.getValue();
- $scope.dirtyText = dirtyText;
- $scope.startSaveTimer();
- setParagraphMode(session, dirtyText, editor.getCursorPosition());
- };
+ $scope.aceChanged = function (_, editor) {
+ let session = editor.getSession()
+ let dirtyText = session.getValue()
+ $scope.dirtyText = dirtyText
+ $scope.startSaveTimer()
+ setParagraphMode(session, dirtyText, editor.getCursorPosition())
+ }
- $scope.aceLoaded = function(_editor) {
- var langTools = ace.require('ace/ext/language_tools');
- var Range = ace.require('ace/range').Range;
+ $scope.aceLoaded = function (_editor) {
+ let langTools = ace.require('ace/ext/language_tools')
+ let Range = ace.require('ace/range').Range
- _editor.$blockScrolling = Infinity;
- $scope.editor = _editor;
- $scope.editor.on('input', $scope.aceChanged);
+ _editor.$blockScrolling = Infinity
+ $scope.editor = _editor
+ $scope.editor.on('input', $scope.aceChanged)
if (_editor.container.id !== '{{paragraph.id}}_editor') {
- $scope.editor.renderer.setShowGutter($scope.paragraph.config.lineNumbers);
- $scope.editor.setShowFoldWidgets(false);
- $scope.editor.setHighlightActiveLine(false);
- $scope.editor.setHighlightGutterLine(false);
- $scope.editor.getSession().setUseWrapMode(true);
- $scope.editor.setTheme('ace/theme/chrome');
- $scope.editor.setReadOnly($scope.isRunning($scope.paragraph));
+ $scope.editor.renderer.setShowGutter($scope.paragraph.config.lineNumbers)
+ $scope.editor.setShowFoldWidgets(false)
+ $scope.editor.setHighlightActiveLine(false)
+ $scope.editor.setHighlightGutterLine(false)
+ $scope.editor.getSession().setUseWrapMode(true)
+ $scope.editor.setTheme('ace/theme/chrome')
+ $scope.editor.setReadOnly($scope.isRunning($scope.paragraph))
if ($scope.paragraphFocused) {
- $scope.editor.focus();
- $scope.goToEnd($scope.editor);
+ $scope.editor.focus()
+ $scope.goToEnd($scope.editor)
}
- autoAdjustEditorHeight(_editor);
- angular.element(window).resize(function() {
- autoAdjustEditorHeight(_editor);
- });
+ autoAdjustEditorHeight(_editor)
+ angular.element(window).resize(function () {
+ autoAdjustEditorHeight(_editor)
+ })
if (navigator.appVersion.indexOf('Mac') !== -1) {
- $scope.editor.setKeyboardHandler('ace/keyboard/emacs');
- $rootScope.isMac = true;
+ $scope.editor.setKeyboardHandler('ace/keyboard/emacs')
+ $rootScope.isMac = true
} else if (navigator.appVersion.indexOf('Win') !== -1 ||
navigator.appVersion.indexOf('X11') !== -1 ||
navigator.appVersion.indexOf('Linux') !== -1) {
- $rootScope.isMac = false;
+ $rootScope.isMac = false
// not applying emacs key binding while the binding override Ctrl-v. default behavior of paste text on windows.
}
- var remoteCompleter = {
+ let remoteCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
- var langTools = ace.require('ace/ext/language_tools');
- var defaultKeywords = new Set();
- var getDefaultKeywords = function(err, completions) {
- if (completions !== undefined) {
- completions.forEach(function(c) {
- defaultKeywords.add(c.value);
- });
- }
+ let langTools = ace.require('ace/ext/language_tools')
+ let defaultKeywords = new Set()
+
+ // eslint-disable-next-line handle-callback-err
+ let getDefaultKeywords = function(err, completions) {
+ if (completions !== undefined) {
+ completions.forEach(function(c) {
+ defaultKeywords.add(c.value)
+ })
+ }
}
if (langTools.keyWordCompleter !== undefined) {
- langTools.keyWordCompleter.getCompletions(editor, session, pos, prefix, getDefaultKeywords);
+ langTools.keyWordCompleter.getCompletions(editor, session, pos, prefix, getDefaultKeywords)
}
if (!editor.isFocused()) {
- return;
+ return
}
- pos = session.getTextRange(new Range(0, 0, pos.row, pos.column)).length;
- var buf = session.getValue();
+ pos = session.getTextRange(new Range(0, 0, pos.row, pos.column)).length
+ let buf = session.getValue()
- websocketMsgSrv.completion($scope.paragraph.id, buf, pos);
+ websocketMsgSrv.completion($scope.paragraph.id, buf, pos)
$scope.$on('completionList', function(event, data) {
- var computeCaption = function(value, meta) {
- var metaLength = meta !== undefined ? meta.length : 0;
- var length = 42;
- var whitespaceLength = 3;
- var ellipses = '...';
- var maxLengthCaption = length - metaLength - whitespaceLength - ellipses.length;
+ let computeCaption = function(value, meta) {
+ let metaLength = meta !== undefined ? meta.length : 0
+ let length = 42
+ let whitespaceLength = 3
+ let ellipses = '...'
+ let maxLengthCaption = length - metaLength - whitespaceLength - ellipses.length
if (value !== undefined && value.length > maxLengthCaption) {
- return value.substr(0, maxLengthCaption) + ellipses;
+ return value.substr(0, maxLengthCaption) + ellipses
}
- return value;
+ return value
}
if (data.completions) {
- var completions = [];
- for (var c in data.completions) {
- var v = data.completions[c];
+ let completions = []
+ for (let c in data.completions) {
+ let v = data.completions[c]
if (v.meta !== undefined && v.meta === 'keyword' && defaultKeywords.has(v.value.trim())) {
- continue;
+ continue
}
completions.push({
name: v.name,
@@ -687,43 +700,43 @@ function ParagraphCtrl($scope, $rootScope, $route, $window, $routeParams, $locat
meta: v.meta,
caption: computeCaption(v.value, v.meta),
score: 300
- });
+ })
}
- callback(null, completions);
+ callback(null, completions)
}
- });
+ })
}
- };
+ }
langTools.setCompleters([remoteCompleter, langTools.keyWordCompleter, langTools.snippetCompleter,
- langTools.textCompleter]);
+ langTools.textCompleter])
$scope.editor.setOptions({
enableBasicAutocompletion: true,
enableSnippets: false,
enableLiveAutocompletion: false
- });
+ })
- $scope.editor.on('focus', function() {
- handleFocus(true);
- });
+ $scope.editor.on('focus', function () {
+ handleFocus(true)
+ })
- $scope.editor.on('blur', function() {
- handleFocus(false);
- $scope.saveParagraph($scope.paragraph);
- });
+ $scope.editor.on('blur', function () {
+ handleFocus(false)
+ $scope.saveParagraph($scope.paragraph)
+ })
- $scope.editor.on('paste', function(e) {
+ $scope.editor.on('paste', function (e) {
if (e.text.indexOf('%') === 0) {
- pastePercentSign = true;
+ pastePercentSign = true
}
- });
+ })
- $scope.editor.getSession().on('change', function(e, editSession) {
- autoAdjustEditorHeight(_editor);
- });
+ $scope.editor.getSession().on('change', function (e, editSession) {
+ autoAdjustEditorHeight(_editor)
+ })
- setParagraphMode($scope.editor.getSession(), $scope.editor.getSession().getValue());
+ setParagraphMode($scope.editor.getSession(), $scope.editor.getSession().getValue())
// autocomplete on '.'
/*
@@ -738,113 +751,113 @@ function ParagraphCtrl($scope, $rootScope, $route, $window, $routeParams, $locat
*/
// remove binding
- $scope.editor.commands.removeCommand('showSettingsMenu');
+ $scope.editor.commands.removeCommand('showSettingsMenu')
- var isOption = $rootScope.isMac? 'option' : 'alt';
+ let isOption = $rootScope.isMac ? 'option' : 'alt'
- $scope.editor.commands.bindKey('ctrl-' + isOption + '-n.', null);
- $scope.editor.commands.bindKey('ctrl-' + isOption + '-l', null);
- $scope.editor.commands.bindKey('ctrl-' + isOption + '-w', null);
- $scope.editor.commands.bindKey('ctrl-' + isOption + '-a', null);
- $scope.editor.commands.bindKey('ctrl-' + isOption + '-k', null);
- $scope.editor.commands.bindKey('ctrl-' + isOption + '-e', null);
- $scope.editor.commands.bindKey('ctrl-' + isOption + '-t', null);
- $scope.editor.commands.bindKey('ctrl-space', null);
+ $scope.editor.commands.bindKey('ctrl-' + isOption + '-n.', null)
+ $scope.editor.commands.bindKey('ctrl-' + isOption + '-l', null)
+ $scope.editor.commands.bindKey('ctrl-' + isOption + '-w', null)
+ $scope.editor.commands.bindKey('ctrl-' + isOption + '-a', null)
+ $scope.editor.commands.bindKey('ctrl-' + isOption + '-k', null)
+ $scope.editor.commands.bindKey('ctrl-' + isOption + '-e', null)
+ $scope.editor.commands.bindKey('ctrl-' + isOption + '-t', null)
+ $scope.editor.commands.bindKey('ctrl-space', null)
if ($rootScope.isMac) {
- $scope.editor.commands.bindKey('command-l', null);
+ $scope.editor.commands.bindKey('command-l', null)
} else {
- $scope.editor.commands.bindKey('ctrl-l', null);
+ $scope.editor.commands.bindKey('ctrl-l', null)
}
// autocomplete on 'ctrl+.'
- $scope.editor.commands.bindKey('ctrl-.', 'startAutocomplete');
+ $scope.editor.commands.bindKey('ctrl-.', 'startAutocomplete')
- var keyBindingEditorFocusAction = function(scrollValue) {
- var numRows = $scope.editor.getSession().getLength();
- var currentRow = $scope.editor.getCursorPosition().row;
+ let keyBindingEditorFocusAction = function (scrollValue) {
+ let numRows = $scope.editor.getSession().getLength()
+ let currentRow = $scope.editor.getCursorPosition().row
if (currentRow === 0 && scrollValue <= 0) {
// move focus to previous paragraph
- $scope.$emit('moveFocusToPreviousParagraph', $scope.paragraph.id);
+ $scope.$emit('moveFocusToPreviousParagraph', $scope.paragraph.id)
} else if (currentRow === numRows - 1 && scrollValue >= 0) {
- $scope.$emit('moveFocusToNextParagraph', $scope.paragraph.id);
+ $scope.$emit('moveFocusToNextParagraph', $scope.paragraph.id)
} else {
- $scope.scrollToCursor($scope.paragraph.id, scrollValue);
+ $scope.scrollToCursor($scope.paragraph.id, scrollValue)
}
- };
+ }
// handle cursor moves
- $scope.editor.keyBinding.origOnCommandKey = $scope.editor.keyBinding.onCommandKey;
- $scope.editor.keyBinding.onCommandKey = function(e, hashId, keyCode) {
+ $scope.editor.keyBinding.origOnCommandKey = $scope.editor.keyBinding.onCommandKey
+ $scope.editor.keyBinding.onCommandKey = function (e, hashId, keyCode) {
if ($scope.editor.completer && $scope.editor.completer.activated) { // if autocompleter is active
} else {
// fix ace editor focus issue in chrome (textarea element goes to top: -1000px after focused by cursor move)
if (parseInt(angular.element('#' + $scope.paragraph.id + '_editor > textarea')
.css('top').replace('px', '')) < 0) {
- var position = $scope.editor.getCursorPosition();
- var cursorPos = $scope.editor.renderer.$cursorLayer.getPixelPosition(position, true);
- angular.element('#' + $scope.paragraph.id + '_editor > textarea').css('top', cursorPos.top);
+ let position = $scope.editor.getCursorPosition()
+ let cursorPos = $scope.editor.renderer.$cursorLayer.getPixelPosition(position, true)
+ angular.element('#' + $scope.paragraph.id + '_editor > textarea').css('top', cursorPos.top)
}
- var ROW_UP = -1;
- var ROW_DOWN = 1;
+ let ROW_UP = -1
+ let ROW_DOWN = 1
switch (keyCode) {
case 38:
- keyBindingEditorFocusAction(ROW_UP);
- break;
+ keyBindingEditorFocusAction(ROW_UP)
+ break
case 80:
if (e.ctrlKey && !e.altKey) {
- keyBindingEditorFocusAction(ROW_UP);
+ keyBindingEditorFocusAction(ROW_UP)
}
- break;
+ break
case 40:
- keyBindingEditorFocusAction(ROW_DOWN);
- break;
+ keyBindingEditorFocusAction(ROW_DOWN)
+ break
case 78:
if (e.ctrlKey && !e.altKey) {
- keyBindingEditorFocusAction(ROW_DOWN);
+ keyBindingEditorFocusAction(ROW_DOWN)
}
- break;
+ break
}
}
- this.origOnCommandKey(e, hashId, keyCode);
- };
+ this.origOnCommandKey(e, hashId, keyCode)
+ }
}
- };
+ }
- var handleFocus = function(value, isDigestPass) {
- $scope.paragraphFocused = value;
+ const handleFocus = function (value, isDigestPass) {
+ $scope.paragraphFocused = value
if (isDigestPass === false || isDigestPass === undefined) {
// Protect against error in case digest is already running
- $timeout(function() {
+ $timeout(function () {
// Apply changes since they come from 3rd party library
- $scope.$digest();
- });
+ $scope.$digest()
+ })
}
- };
+ }
- var getEditorSetting = function(paragraph, interpreterName) {
- var deferred = $q.defer();
- websocketMsgSrv.getEditorSetting(paragraph.id, interpreterName);
+ let getEditorSetting = function (paragraph, interpreterName) {
+ let deferred = $q.defer()
+ websocketMsgSrv.getEditorSetting(paragraph.id, interpreterName)
$timeout(
- $scope.$on('editorSetting', function(event, data) {
- if (paragraph.id === data.paragraphId) {
- deferred.resolve(data);
- }
+ $scope.$on('editorSetting', function (event, data) {
+ if (paragraph.id === data.paragraphId) {
+ deferred.resolve(data)
}
- ), 1000);
- return deferred.promise;
- };
-
- var setEditorLanguage = function(session, language) {
- var mode = 'ace/mode/';
- mode += language;
- $scope.paragraph.config.editorMode = mode;
- session.setMode(mode);
- };
-
- var setParagraphMode = function(session, paragraphText, pos) {
+ }
+ ), 1000)
+ return deferred.promise
+ }
+
+ let setEditorLanguage = function (session, language) {
+ let mode = 'ace/mode/'
+ mode += language
+ $scope.paragraph.config.editorMode = mode
+ session.setMode(mode)
+ }
+
+ const setParagraphMode = function (session, paragraphText, pos) {
// Evaluate the mode only if the the position is undefined
// or the first 30 characters of the paragraph have been modified
// or cursor position is at beginning of second line.(in case user hit enter after typing %magic)
@@ -853,221 +866,220 @@ function ParagraphCtrl($scope, $rootScope, $route, $window, $routeParams, $locat
// If paragraph loading, use config value if exists
if ((typeof pos === 'undefined') && $scope.paragraph.config.editorMode &&
!setInterpreterBindings) {
- session.setMode($scope.paragraph.config.editorMode);
+ session.setMode($scope.paragraph.config.editorMode)
} else {
- var magic = getInterpreterName(paragraphText);
+ let magic = getInterpreterName(paragraphText)
if (editorSetting.magic !== magic) {
- editorSetting.magic = magic;
+ editorSetting.magic = magic
getEditorSetting($scope.paragraph, magic)
- .then(function(setting) {
- setEditorLanguage(session, setting.editor.language);
- _.merge($scope.paragraph.config.editorSetting, setting.editor);
- });
+ .then(function (setting) {
+ setEditorLanguage(session, setting.editor.language)
+ _.merge($scope.paragraph.config.editorSetting, setting.editor)
+ })
}
}
}
- pastePercentSign = false;
- setInterpreterBindings = false;
- };
+ pastePercentSign = false
+ setInterpreterBindings = false
+ }
- var getInterpreterName = function(paragraphText) {
- var intpNameRegexp = /^\s*%(.+?)(\s|\()/g;
- var match = intpNameRegexp.exec(paragraphText);
+ const getInterpreterName = function(paragraphText) {
+ let intpNameRegexp = /^\s*%(.+?)(\s|\()/g
+ let match = intpNameRegexp.exec(paragraphText)
if (match) {
- return match[1].trim();
+ return match[1].trim()
// get default interpreter name if paragraph text doesn't start with '%'
// TODO(mina): dig into the cause what makes interpreterBindings to have no element
} else if ($scope.$parent.interpreterBindings && $scope.$parent.interpreterBindings.length !== 0) {
- return $scope.$parent.interpreterBindings[0].name;
+ return $scope.$parent.interpreterBindings[0].name
}
- return '';
- };
+ return ''
+ }
- var autoAdjustEditorHeight = function(editor) {
- var height =
+ const autoAdjustEditorHeight = function (editor) {
+ let height =
editor.getSession().getScreenLength() *
editor.renderer.lineHeight +
- editor.renderer.scrollBar.getWidth();
+ editor.renderer.scrollBar.getWidth()
- angular.element('#' + editor.container.id).height(height.toString() + 'px');
- editor.resize();
- };
+ angular.element('#' + editor.container.id).height(height.toString() + 'px')
+ editor.resize()
+ }
- $rootScope.$on('scrollToCursor', function(event) {
+ $rootScope.$on('scrollToCursor', function (event) {
// scroll on 'scrollToCursor' event only when cursor is in the last paragraph
- var paragraphs = angular.element('div[id$="_paragraphColumn_main"]');
+ let paragraphs = angular.element('div[id$="_paragraphColumn_main"]')
if (paragraphs[paragraphs.length - 1].id.indexOf($scope.paragraph.id) === 0) {
- $scope.scrollToCursor($scope.paragraph.id, 0);
+ $scope.scrollToCursor($scope.paragraph.id, 0)
}
- });
+ })
/** scrollToCursor if it is necessary
* when cursor touches scrollTriggerEdgeMargin from the top (or bottom) of the screen, it autoscroll to place cursor around 1/3 of screen height from the top (or bottom)
* paragraphId : paragraph that has active cursor
* lastCursorMove : 1(down), 0, -1(up) last cursor move event
**/
- $scope.scrollToCursor = function(paragraphId, lastCursorMove) {
+ $scope.scrollToCursor = function (paragraphId, lastCursorMove) {
if (!$scope.editor || !$scope.editor.isFocused()) {
// only make sense when editor is focused
- return;
+ return
}
- var lineHeight = $scope.editor.renderer.lineHeight;
- var headerHeight = 103; // menubar, notebook titlebar
- var scrollTriggerEdgeMargin = 50;
+ let lineHeight = $scope.editor.renderer.lineHeight
+ let headerHeight = 103 // menubar, notebook titlebar
+ let scrollTriggerEdgeMargin = 50
- var documentHeight = angular.element(document).height();
- var windowHeight = angular.element(window).height(); // actual viewport height
+ let documentHeight = angular.element(document).height()
+ let windowHeight = angular.element(window).height() // actual viewport height
- var scrollPosition = angular.element(document).scrollTop();
- var editorPosition = angular.element('#' + paragraphId + '_editor').offset();
- var position = $scope.editor.getCursorPosition();
- var lastCursorPosition = $scope.editor.renderer.$cursorLayer.getPixelPosition(position, true);
+ let scrollPosition = angular.element(document).scrollTop()
+ let editorPosition = angular.element('#' + paragraphId + '_editor').offset()
+ let position = $scope.editor.getCursorPosition()
+ let lastCursorPosition = $scope.editor.renderer.$cursorLayer.getPixelPosition(position, true)
- var calculatedCursorPosition = editorPosition.top + lastCursorPosition.top + lineHeight * lastCursorMove;
+ let calculatedCursorPosition = editorPosition.top + lastCursorPosition.top + lineHeight * lastCursorMove
- var scrollTargetPos;
+ let scrollTargetPos
if (calculatedCursorPosition < scrollPosition + headerHeight + scrollTriggerEdgeMargin) {
- scrollTargetPos = calculatedCursorPosition - headerHeight - ((windowHeight - headerHeight) / 3);
+ scrollTargetPos = calculatedCursorPosition - headerHeight - ((windowHeight - headerHeight) / 3)
if (scrollTargetPos < 0) {
- scrollTargetPos = 0;
+ scrollTargetPos = 0
}
} else if (calculatedCursorPosition > scrollPosition + scrollTriggerEdgeMargin + windowHeight - headerHeight) {
- scrollTargetPos = calculatedCursorPosition - headerHeight - ((windowHeight - headerHeight) * 2 / 3);
+ scrollTargetPos = calculatedCursorPosition - headerHeight - ((windowHeight - headerHeight) * 2 / 3)
if (scrollTargetPos > documentHeight) {
- scrollTargetPos = documentHeight;
+ scrollTargetPos = documentHeight
}
}
// cancel previous scroll animation
- var bodyEl = angular.element('body');
- bodyEl.stop();
- bodyEl.finish();
+ let bodyEl = angular.element('body')
+ bodyEl.stop()
+ bodyEl.finish()
// scroll to scrollTargetPos
- bodyEl.scrollTo(scrollTargetPos, {axis: 'y', interrupt: true, duration: 100});
- };
+ bodyEl.scrollTo(scrollTargetPos, {axis: 'y', interrupt: true, duration: 100})
+ }
- $scope.getEditorValue = function() {
- return !$scope.editor ? $scope.paragraph.text : $scope.editor.getValue();
- };
+ $scope.getEditorValue = function () {
+ return !$scope.editor ? $scope.paragraph.text : $scope.editor.getValue()
+ }
- $scope.getProgress = function() {
- return $scope.currentProgress || 0;
- };
+ $scope.getProgress = function () {
+ return $scope.currentProgress || 0
+ }
- $scope.getExecutionTime = function(pdata) {
- var timeMs = Date.parse(pdata.dateFinished) - Date.parse(pdata.dateStarted);
+ $scope.getExecutionTime = function (pdata) {
+ let timeMs = Date.parse(pdata.dateFinished) - Date.parse(pdata.dateStarted)
if (isNaN(timeMs) || timeMs < 0) {
if ($scope.isResultOutdated(pdata)) {
- return 'outdated';
+ return 'outdated'
}
- return '';
+ return ''
}
- var user = (pdata.user === undefined || pdata.user === null) ? 'anonymous' : pdata.user;
- var desc = 'Took ' + moment.duration((timeMs / 1000), 'seconds').format('h [hrs] m [min] s [sec]') +
- '. Last updated by ' + user + ' at ' + moment(pdata.dateFinished).format('MMMM DD YYYY, h:mm:ss A') + '.';
+ let user = (pdata.user === undefined || pdata.user === null) ? 'anonymous' : pdata.user
+ let desc = 'Took ' + moment.duration((timeMs / 1000), 'seconds').format('h [hrs] m [min] s [sec]') +
+ '. Last updated by ' + user + ' at ' + moment(pdata.dateFinished).format('MMMM DD YYYY, h:mm:ss A') + '.'
if ($scope.isResultOutdated(pdata)) {
- desc += ' (outdated)';
+ desc += ' (outdated)'
}
- return desc;
- };
+ return desc
+ }
- $scope.getElapsedTime = function(paragraph) {
- return 'Started ' + moment(paragraph.dateStarted).fromNow() + '.';
- };
+ $scope.getElapsedTime = function (paragraph) {
+ return 'Started ' + moment(paragraph.dateStarted).fromNow() + '.'
+ }
- $scope.isResultOutdated = function(pdata) {
+ $scope.isResultOutdated = function (pdata) {
if (pdata.dateUpdated !== undefined && Date.parse(pdata.dateUpdated) > Date.parse(pdata.dateStarted)) {
- return true;
+ return true
}
- return false;
- };
+ return false
+ }
- $scope.goToEnd = function(editor) {
- editor.navigateFileEnd();
- };
+ $scope.goToEnd = function (editor) {
+ editor.navigateFileEnd()
+ }
- $scope.parseTableCell = function(cell) {
+ $scope.parseTableCell = function (cell) {
if (!isNaN(cell)) {
if (cell.length === 0 || Number(cell) > Number.MAX_SAFE_INTEGER || Number(cell) < Number.MIN_SAFE_INTEGER) {
- return cell;
+ return cell
} else {
- return Number(cell);
+ return Number(cell)
}
}
- var d = moment(cell);
+ let d = moment(cell)
if (d.isValid()) {
- return d;
+ return d
}
- return cell;
- };
+ return cell
+ }
- var commitParagraph = function(paragraph) {
+ const commitParagraph = function (paragraph) {
const {
id,
title,
text,
config,
settings: {params},
- } = paragraph;
+ } = paragraph
- websocketMsgSrv.commitParagraph(id, title, text, config, params);
- };
+ websocketMsgSrv.commitParagraph(id, title, text, config, params)
+ }
/** Utility function */
- $scope.goToSingleParagraph = function() {
- var noteId = $route.current.pathParams.noteId;
- var redirectToUrl = location.protocol + '//' + location.host + location.pathname + '#/notebook/' + noteId +
- '/paragraph/' + $scope.paragraph.id + '?asIframe';
- $window.open(redirectToUrl);
- };
-
- $scope.showScrollDownIcon = function(id) {
- var doc = angular.element('#p' + id + '_text');
+ $scope.goToSingleParagraph = function () {
+ let noteId = $route.current.pathParams.noteId
+ let redirectToUrl = location.protocol + '//' + location.host + location.pathname + '#/notebook/' + noteId +
+ '/paragraph/' + $scope.paragraph.id + '?asIframe'
+ $window.open(redirectToUrl)
+ }
+
+ $scope.showScrollDownIcon = function (id) {
+ let doc = angular.element('#p' + id + '_text')
if (doc[0]) {
- return doc[0].scrollHeight > doc.innerHeight();
+ return doc[0].scrollHeight > doc.innerHeight()
}
- return false;
- };
+ return false
+ }
- $scope.scrollParagraphDown = function(id) {
- var doc = angular.element('#p' + id + '_text');
- doc.animate({scrollTop: doc[0].scrollHeight}, 500);
- $scope.keepScrollDown = true;
- };
+ $scope.scrollParagraphDown = function (id) {
+ let doc = angular.element('#p' + id + '_text')
+ doc.animate({scrollTop: doc[0].scrollHeight}, 500)
+ $scope.keepScrollDown = true
+ }
- $scope.showScrollUpIcon = function(id) {
+ $scope.showScrollUpIcon = function (id) {
if (angular.element('#p' + id + '_text')[0]) {
- return angular.element('#p' + id + '_text')[0].scrollTop !== 0;
+ return angular.element('#p' + id + '_text')[0].scrollTop !== 0
}
- return false;
-
- };
+ return false
+ }
- $scope.scrollParagraphUp = function(id) {
- var doc = angular.element('#p' + id + '_text');
- doc.animate({scrollTop: 0}, 500);
- $scope.keepScrollDown = false;
- };
+ $scope.scrollParagraphUp = function (id) {
+ let doc = angular.element('#p' + id + '_text')
+ doc.animate({scrollTop: 0}, 500)
+ $scope.keepScrollDown = false
+ }
- $scope.$on('angularObjectUpdate', function(event, data) {
- var noteId = $route.current.pathParams.noteId;
+ $scope.$on('angularObjectUpdate', function (event, data) {
+ let noteId = $route.current.pathParams.noteId
if (!data.noteId || data.noteId === noteId) {
- var scope;
- var registry;
+ let scope
+ let registry
if (!data.paragraphId || data.paragraphId === $scope.paragraph.id) {
- scope = paragraphScope;
- registry = angularObjectRegistry;
+ scope = paragraphScope
+ registry = angularObjectRegistry
} else {
- return;
+ return
}
- var varName = data.angularObject.name;
+ let varName = data.angularObject.name
if (angular.equals(data.angularObject.object, scope[varName])) {
// return when update has no change
- return;
+ return
}
if (!registry[varName]) {
@@ -1075,87 +1087,89 @@ function ParagraphCtrl($scope, $rootScope, $route, $window, $routeParams, $locat
interpreterGroupId: data.interpreterGroupId,
noteId: data.noteId,
paragraphId: data.paragraphId
- };
+ }
} else {
- registry[varName].noteId = registry[varName].noteId || data.noteId;
- registry[varName].paragraphId = registry[varName].paragraphId || data.paragraphId;
+ registry[varName].noteId = registry[varName].noteId || data.noteId
+ registry[varName].paragraphId = registry[varName].paragraphId || data.paragraphId
}
- registry[varName].skipEmit = true;
+ registry[varName].skipEmit = true
if (!registry[varName].clearWatcher) {
- registry[varName].clearWatcher = scope.$watch(varName, function(newValue, oldValue) {
- console.log('angular object (paragraph) updated %o %o', varName, registry[varName]);
+ registry[varName].clearWatcher = scope.$watch(varName, function (newValue, oldValue) {
+ console.log('angular object (paragraph) updated %o %o', varName, registry[varName])
if (registry[varName].skipEmit) {
- registry[varName].skipEmit = false;
- return;
+ registry[varName].skipEmit = false
+ return
}
websocketMsgSrv.updateAngularObject(
registry[varName].noteId,
registry[varName].paragraphId,
varName,
newValue,
- registry[varName].interpreterGroupId);
- });
+ registry[varName].interpreterGroupId)
+ })
}
- console.log('angular object (paragraph) created %o', varName);
- scope[varName] = data.angularObject.object;
+ console.log('angular object (paragraph) created %o', varName)
+ scope[varName] = data.angularObject.object
// create proxy for AngularFunction
if (varName.indexOf(ANGULAR_FUNCTION_OBJECT_NAME_PREFIX) === 0) {
- var funcName = varName.substring((ANGULAR_FUNCTION_OBJECT_NAME_PREFIX).length);
- scope[funcName] = function() {
- scope[varName] = arguments;
- console.log('angular function (paragraph) invoked %o', arguments);
- };
+ let funcName = varName.substring((ANGULAR_FUNCTION_OBJECT_NAME_PREFIX).length)
+ scope[funcName] = function () {
+ // eslint-disable-next-line prefer-rest-params
+ scope[varName] = arguments
+ // eslint-disable-next-line prefer-rest-params
+ console.log('angular function (paragraph) invoked %o', arguments)
+ }
- console.log('angular function (paragraph) created %o', scope[funcName]);
+ console.log('angular function (paragraph) created %o', scope[funcName])
}
}
- });
+ })
- $scope.$on('updateParaInfos', function(event, data) {
+ $scope.$on('updateParaInfos', function (event, data) {
if (data.id === $scope.paragraph.id) {
- $scope.paragraph.runtimeInfos = data.infos;
+ $scope.paragraph.runtimeInfos = data.infos
}
- });
+ })
- $scope.$on('angularObjectRemove', function(event, data) {
- var noteId = $route.current.pathParams.noteId;
+ $scope.$on('angularObjectRemove', function (event, data) {
+ let noteId = $route.current.pathParams.noteId
if (!data.noteId || data.noteId === noteId) {
- var scope;
- var registry;
+ let scope
+ let registry
if (!data.paragraphId || data.paragraphId === $scope.paragraph.id) {
- scope = paragraphScope;
- registry = angularObjectRegistry;
+ scope = paragraphScope
+ registry = angularObjectRegistry
} else {
- return;
+ return
}
- var varName = data.name;
+ let varName = data.name
// clear watcher
if (registry[varName]) {
- registry[varName].clearWatcher();
- registry[varName] = undefined;
+ registry[varName].clearWatcher()
+ registry[varName] = undefined
}
// remove scope variable
- scope[varName] = undefined;
+ scope[varName] = undefined
// remove proxy for AngularFunction
if (varName.indexOf(ANGULAR_FUNCTION_OBJECT_NAME_PREFIX) === 0) {
- var funcName = varName.substring((ANGULAR_FUNCTION_OBJECT_NAME_PREFIX).length);
- scope[funcName] = undefined;
+ let funcName = varName.substring((ANGULAR_FUNCTION_OBJECT_NAME_PREFIX).length)
+ scope[funcName] = undefined
}
}
- });
+ })
/**
* @returns {boolean} true if updated is needed
*/
- function isUpdateRequired(oldPara, newPara) {
+ function isUpdateRequired (oldPara, newPara) {
return (newPara.id === oldPara.id &&
(newPara.dateCreated !== oldPara.dateCreated ||
newPara.text !== oldPara.text ||
@@ -1172,287 +1186,285 @@ function ParagraphCtrl($scope, $rootScope, $route, $window, $routeParams, $locat
!angular.equals(newPara.runtimeInfos, oldPara.runtimeInfos)))
}
- $scope.updateAllScopeTexts = function(oldPara, newPara) {
+ $scope.updateAllScopeTexts = function (oldPara, newPara) {
if (oldPara.text !== newPara.text) {
if ($scope.dirtyText) { // check if editor has local update
if ($scope.dirtyText === newPara.text) { // when local update is the same from remote, clear local update
- $scope.paragraph.text = newPara.text;
- $scope.dirtyText = undefined;
- $scope.originalText = angular.copy(newPara.text);
-
+ $scope.paragraph.text = newPara.text
+ $scope.dirtyText = undefined
+ $scope.originalText = angular.copy(newPara.text)
} else { // if there're local update, keep it.
- $scope.paragraph.text = newPara.text;
+ $scope.paragraph.text = newPara.text
}
} else {
- $scope.paragraph.text = newPara.text;
- $scope.originalText = angular.copy(newPara.text);
+ $scope.paragraph.text = newPara.text
+ $scope.originalText = angular.copy(newPara.text)
}
}
- };
+ }
- $scope.updateParagraphObjectWhenUpdated = function(newPara) {
+ $scope.updateParagraphObjectWhenUpdated = function (newPara) {
// resize col width
if ($scope.paragraph.config.colWidth !== newPara.colWidth) {
- $rootScope.$broadcast('paragraphResized', $scope.paragraph.id);
+ $rootScope.$broadcast('paragraphResized', $scope.paragraph.id)
}
/** push the rest */
- $scope.paragraph.aborted = newPara.aborted;
- $scope.paragraph.user = newPara.user;
- $scope.paragraph.dateUpdated = newPara.dateUpdated;
- $scope.paragraph.dateCreated = newPara.dateCreated;
- $scope.paragraph.dateFinished = newPara.dateFinished;
- $scope.paragraph.dateStarted = newPara.dateStarted;
- $scope.paragraph.errorMessage = newPara.errorMessage;
- $scope.paragraph.jobName = newPara.jobName;
- $scope.paragraph.title = newPara.title;
- $scope.paragraph.lineNumbers = newPara.lineNumbers;
- $scope.paragraph.status = newPara.status;
+ $scope.paragraph.aborted = newPara.aborted
+ $scope.paragraph.user = newPara.user
+ $scope.paragraph.dateUpdated = newPara.dateUpdated
+ $scope.paragraph.dateCreated = newPara.dateCreated
+ $scope.paragraph.dateFinished = newPara.dateFinished
+ $scope.paragraph.dateStarted = newPara.dateStarted
+ $scope.paragraph.errorMessage = newPara.errorMessage
+ $scope.paragraph.jobName = newPara.jobName
+ $scope.paragraph.title = newPara.title
+ $scope.paragraph.lineNumbers = newPara.lineNumbers
+ $scope.paragraph.status = newPara.status
if (newPara.status !== ParagraphStatus.RUNNING) {
- $scope.paragraph.results = newPara.results;
+ $scope.paragraph.results = newPara.results
}
- $scope.paragraph.settings = newPara.settings;
- $scope.paragraph.runtimeInfos = newPara.runtimeInfos;
+ $scope.paragraph.settings = newPara.settings
+ $scope.paragraph.runtimeInfos = newPara.runtimeInfos
if ($scope.editor) {
- $scope.editor.setReadOnly($scope.isRunning(newPara));
+ $scope.editor.setReadOnly($scope.isRunning(newPara))
}
if (!$scope.asIframe) {
- $scope.paragraph.config = newPara.config;
- initializeDefault(newPara.config);
- } else {
- newPara.config.editorHide = true;
- newPara.config.tableHide = false;
- $scope.paragraph.config = newPara.config;
- }
- };
-
- $scope.updateParagraph = function(oldPara, newPara, updateCallback) {
+ $scope.paragraph.config = newPara.config
+ initializeDefault(newPara.config)
+ } else {
+ newPara.config.editorHide = true
+ newPara.config.tableHide = false
+ $scope.paragraph.config = newPara.config
+ }
+ }
+
+ $scope.updateParagraph = function (oldPara, newPara, updateCallback) {
// 1. get status, refreshed
- const statusChanged = (newPara.status !== oldPara.status);
- const resultRefreshed = (newPara.dateFinished !== oldPara.dateFinished) ||
+ const statusChanged = (newPara.status !== oldPara.status)
+ const resultRefreshed = (newPara.dateFinished !== oldPara.dateFinished) ||
isEmpty(newPara.results) !== isEmpty(oldPara.results) ||
newPara.status === ParagraphStatus.ERROR ||
- (newPara.status === ParagraphStatus.FINISHED && statusChanged);
+ (newPara.status === ParagraphStatus.FINISHED && statusChanged)
// 2. update texts managed by $scope
- $scope.updateAllScopeTexts(oldPara, newPara);
+ $scope.updateAllScopeTexts(oldPara, newPara)
// 3. execute callback to update result
- updateCallback();
+ updateCallback()
// 4. update remaining paragraph objects
- $scope.updateParagraphObjectWhenUpdated(newPara);
+ $scope.updateParagraphObjectWhenUpdated(newPara)
// 5. handle scroll down by key properly if new paragraph is added
- if (statusChanged || resultRefreshed) {
+ if (statusChanged || resultRefreshed) {
// when last paragraph runs, zeppelin automatically appends new paragraph.
// this broadcast will focus to the newly inserted paragraph
- const paragraphs = angular.element('div[id$="_paragraphColumn_main"]');
- if (paragraphs.length >= 2 && paragraphs[paragraphs.length - 2].id.indexOf($scope.paragraph.id) === 0) {
+ const paragraphs = angular.element('div[id$="_paragraphColumn_main"]')
+ if (paragraphs.length >= 2 && paragraphs[paragraphs.length - 2].id.indexOf($scope.paragraph.id) === 0) {
// rendering output can took some time. So delay scrolling event firing for sometime.
- setTimeout(() => { $rootScope.$broadcast('scrollToCursor'); }, 500);
- }
- }
- };
+ setTimeout(() => { $rootScope.$broadcast('scrollToCursor') }, 500)
+ }
+ }
+ }
/** $scope.$on */
- $scope.$on('runParagraphUsingSpell', function(event, data) {
- const oldPara = $scope.paragraph;
- let newPara = data.paragraph;
+ $scope.$on('runParagraphUsingSpell', function (event, data) {
+ const oldPara = $scope.paragraph
+ let newPara = data.paragraph
const updateCallback = () => {
- $scope.runParagraph(newPara.text, true, true);
- };
+ $scope.runParagraph(newPara.text, true, true)
+ }
if (!isUpdateRequired(oldPara, newPara)) {
- return;
+ return
}
$scope.updateParagraph(oldPara, newPara, updateCallback)
- });
+ })
- $scope.$on('updateParagraph', function(event, data) {
- const oldPara = $scope.paragraph;
- const newPara = data.paragraph;
+ $scope.$on('updateParagraph', function (event, data) {
+ const oldPara = $scope.paragraph
+ const newPara = data.paragraph
if (!isUpdateRequired(oldPara, newPara)) {
- return;
+ return
}
const updateCallback = () => {
// broadcast `updateResult` message to trigger result update
if (newPara.results && newPara.results.msg) {
for (let i in newPara.results.msg) {
- const newResult = newPara.results.msg ? newPara.results.msg[i] : {};
- const oldResult = (oldPara.results && oldPara.results.msg) ?
- oldPara.results.msg[i] : {};
- const newConfig = newPara.config.results ? newPara.config.results[i] : {};
- const oldConfig = oldPara.config.results ? oldPara.config.results[i] : {};
+ const newResult = newPara.results.msg ? newPara.results.msg[i] : {}
+ const oldResult = (oldPara.results && oldPara.results.msg)
+ ? oldPara.results.msg[i] : {}
+ const newConfig = newPara.config.results ? newPara.config.results[i] : {}
+ const oldConfig = oldPara.config.results ? oldPara.config.results[i] : {}
if (!angular.equals(newResult, oldResult) ||
!angular.equals(newConfig, oldConfig)) {
- $rootScope.$broadcast('updateResult', newResult, newConfig, newPara, parseInt(i));
+ $rootScope.$broadcast('updateResult', newResult, newConfig, newPara, parseInt(i))
}
}
}
- };
+ }
$scope.updateParagraph(oldPara, newPara, updateCallback)
- });
+ })
- $scope.$on('updateProgress', function(event, data) {
+ $scope.$on('updateProgress', function (event, data) {
if (data.id === $scope.paragraph.id) {
- $scope.currentProgress = data.progress;
+ $scope.currentProgress = data.progress
}
- });
+ })
- $scope.$on('keyEvent', function(event, keyEvent) {
+ $scope.$on('keyEvent', function (event, keyEvent) {
if ($scope.paragraphFocused) {
-
- var paragraphId = $scope.paragraph.id;
- var keyCode = keyEvent.keyCode;
- var noShortcutDefined = false;
- var editorHide = $scope.paragraph.config.editorHide;
+ let paragraphId = $scope.paragraph.id
+ let keyCode = keyEvent.keyCode
+ let noShortcutDefined = false
+ let editorHide = $scope.paragraph.config.editorHide
if (editorHide && (keyCode === 38 || (keyCode === 80 && keyEvent.ctrlKey && !keyEvent.altKey))) { // up
// move focus to previous paragraph
- $scope.$emit('moveFocusToPreviousParagraph', paragraphId);
+ $scope.$emit('moveFocusToPreviousParagraph', paragraphId)
} else if (editorHide && (keyCode === 40 || (keyCode === 78 && keyEvent.ctrlKey && !keyEvent.altKey))) { // down
// move focus to next paragraph
- $scope.$emit('moveFocusToNextParagraph', paragraphId);
+ $scope.$emit('moveFocusToNextParagraph', paragraphId)
} else if (keyEvent.shiftKey && keyCode === 13) { // Shift + Enter
- $scope.runParagraphFromShortcut($scope.getEditorValue());
+ $scope.runParagraphFromShortcut($scope.getEditorValue())
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 67) { // Ctrl + Alt + c
- $scope.cancelParagraph($scope.paragraph);
+ $scope.cancelParagraph($scope.paragraph)
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 68) { // Ctrl + Alt + d
- $scope.removeParagraph($scope.paragraph);
+ $scope.removeParagraph($scope.paragraph)
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 75) { // Ctrl + Alt + k
- $scope.moveUp($scope.paragraph);
+ $scope.moveUp($scope.paragraph)
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 74) { // Ctrl + Alt + j
- $scope.moveDown($scope.paragraph);
+ $scope.moveDown($scope.paragraph)
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 65) { // Ctrl + Alt + a
- $scope.insertNew('above');
+ $scope.insertNew('above')
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 66) { // Ctrl + Alt + b
- $scope.insertNew('below');
+ $scope.insertNew('below')
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 79) { // Ctrl + Alt + o
- $scope.toggleOutput($scope.paragraph);
+ $scope.toggleOutput($scope.paragraph)
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 82) { // Ctrl + Alt + r
- $scope.toggleEnableDisable($scope.paragraph);
+ $scope.toggleEnableDisable($scope.paragraph)
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 69) { // Ctrl + Alt + e
- $scope.toggleEditor($scope.paragraph);
+ $scope.toggleEditor($scope.paragraph)
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 77) { // Ctrl + Alt + m
if ($scope.paragraph.config.lineNumbers) {
- $scope.hideLineNumbers($scope.paragraph);
+ $scope.hideLineNumbers($scope.paragraph)
} else {
- $scope.showLineNumbers($scope.paragraph);
+ $scope.showLineNumbers($scope.paragraph)
}
} else if (keyEvent.ctrlKey && keyEvent.shiftKey && keyCode === 189) { // Ctrl + Shift + -
- $scope.changeColWidth($scope.paragraph, Math.max(1, $scope.paragraph.config.colWidth - 1));
+ $scope.changeColWidth($scope.paragraph, Math.max(1, $scope.paragraph.config.colWidth - 1))
} else if (keyEvent.ctrlKey && keyEvent.shiftKey && keyCode === 187) { // Ctrl + Shift + =
- $scope.changeColWidth($scope.paragraph, Math.min(12, $scope.paragraph.config.colWidth + 1));
+ $scope.changeColWidth($scope.paragraph, Math.min(12, $scope.paragraph.config.colWidth + 1))
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 84) { // Ctrl + Alt + t
if ($scope.paragraph.config.title) {
- $scope.hideTitle($scope.paragraph);
+ $scope.hideTitle($scope.paragraph)
} else {
- $scope.showTitle($scope.paragraph);
+ $scope.showTitle($scope.paragraph)
}
} else if (keyEvent.ctrlKey && keyEvent.shiftKey && keyCode === 67) { // Ctrl + Alt + c
- $scope.copyPara('below');
+ $scope.copyPara('below')
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 76) { // Ctrl + Alt + l
- $scope.clearParagraphOutput($scope.paragraph);
+ $scope.clearParagraphOutput($scope.paragraph)
} else if (keyEvent.ctrlKey && keyEvent.altKey && keyCode === 87) { // Ctrl + Alt + w
- $scope.goToSingleParagraph();
+ $scope.goToSingleParagraph()
} else {
- noShortcutDefined = true;
+ noShortcutDefined = true
}
if (!noShortcutDefined) {
- keyEvent.preventDefault();
+ keyEvent.preventDefault()
}
}
- });
+ })
- $scope.$on('focusParagraph', function(event, paragraphId, cursorPos, mouseEvent) {
+ $scope.$on('focusParagraph', function (event, paragraphId, cursorPos, mouseEvent) {
if ($scope.paragraph.id === paragraphId) {
// focus editor
if (!$scope.paragraph.config.editorHide) {
if (!mouseEvent) {
- $scope.editor.focus();
+ $scope.editor.focus()
// move cursor to the first row (or the last row)
- var row;
+ let row
if (cursorPos >= 0) {
- row = cursorPos;
- $scope.editor.gotoLine(row, 0);
+ row = cursorPos
+ $scope.editor.gotoLine(row, 0)
} else {
- row = $scope.editor.session.getLength();
- $scope.editor.gotoLine(row, 0);
+ row = $scope.editor.session.getLength()
+ $scope.editor.gotoLine(row, 0)
}
- $scope.scrollToCursor($scope.paragraph.id, 0);
+ $scope.scrollToCursor($scope.paragraph.id, 0)
}
}
- handleFocus(true);
+ handleFocus(true)
} else {
if ($scope.editor !== undefined && $scope.editor !== null) {
- $scope.editor.blur();
+ $scope.editor.blur()
}
- var isDigestPass = true;
- handleFocus(false, isDigestPass);
+ let isDigestPass = true
+ handleFocus(false, isDigestPass)
}
- });
+ })
- $scope.$on('saveInterpreterBindings', function(event, paragraphId) {
+ $scope.$on('saveInterpreterBindings', function (event, paragraphId) {
if ($scope.paragraph.id === paragraphId && $scope.editor) {
- setInterpreterBindings = true;
- setParagraphMode($scope.editor.getSession(), $scope.editor.getSession().getValue());
+ setInterpreterBindings = true
+ setParagraphMode($scope.editor.getSession(), $scope.editor.getSession().getValue())
}
- });
+ })
- $scope.$on('doubleClickParagraph', function(event, paragraphId) {
+ $scope.$on('doubleClickParagraph', function (event, paragraphId) {
if ($scope.paragraph.id === paragraphId && $scope.paragraph.config.editorHide &&
$scope.paragraph.config.editorSetting.editOnDblClick && $scope.revisionView !== true) {
- var deferred = $q.defer();
- openEditorAndCloseTable($scope.paragraph);
+ let deferred = $q.defer()
+ openEditorAndCloseTable($scope.paragraph)
$timeout(
- $scope.$on('updateParagraph', function(event, data) {
- deferred.resolve(data);
- }
- ), 1000);
+ $scope.$on('updateParagraph', function (event, data) {
+ deferred.resolve(data)
+ }
+ ), 1000)
- deferred.promise.then(function(data) {
+ deferred.promise.then(function (data) {
if ($scope.editor) {
- $scope.editor.focus();
- $scope.goToEnd($scope.editor);
+ $scope.editor.focus()
+ $scope.goToEnd($scope.editor)
}
- });
+ })
}
- });
+ })
- $scope.$on('openEditor', function(event) {
- $scope.openEditor($scope.paragraph);
- });
+ $scope.$on('openEditor', function (event) {
+ $scope.openEditor($scope.paragraph)
+ })
- $scope.$on('closeEditor', function(event) {
- $scope.closeEditor($scope.paragraph);
- });
+ $scope.$on('closeEditor', function (event) {
+ $scope.closeEditor($scope.paragraph)
+ })
- $scope.$on('openTable', function(event) {
- $scope.openTable($scope.paragraph);
- });
+ $scope.$on('openTable', function (event) {
+ $scope.openTable($scope.paragraph)
+ })
- $scope.$on('closeTable', function(event) {
- $scope.closeTable($scope.paragraph);
- });
+ $scope.$on('closeTable', function (event) {
+ $scope.closeTable($scope.paragraph)
+ })
- $scope.$on('resultRendered', function(event, paragraphId) {
+ $scope.$on('resultRendered', function (event, paragraphId) {
if ($scope.paragraph.id !== paragraphId) {
- return;
+ return
}
/** increase spell result count and return if not finished */
if (!$scope.increaseSpellTransactionResultCount()) {
- return;
+ return
}
- $scope.cleanupSpellTransaction();
- });
+ $scope.cleanupSpellTransaction()
+ })
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.test.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.test.js b/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.test.js
index f8a1f63..29b203c 100644
--- a/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.test.js
+++ b/zeppelin-web/src/app/notebook/paragraph/paragraph.controller.test.js
@@ -1,54 +1,53 @@
-describe('Controller: ParagraphCtrl', function() {
+describe('Controller: ParagraphCtrl', function () {
+ beforeEach(angular.mock.module('zeppelinWebApp'))
- beforeEach(angular.mock.module('zeppelinWebApp'));
-
- var scope;
- var websocketMsgSrvMock = {};
- var paragraphMock = {
+ let scope
+ let websocketMsgSrvMock = {}
+ let paragraphMock = {
config: {},
settings: {
forms: {}
}
- };
- var route = {
+ }
+ let route = {
current: {
pathParams: {
noteId: 'noteId'
}
}
- };
+ }
- beforeEach(inject(function($controller, $rootScope) {
- scope = $rootScope.$new();
- $rootScope.notebookScope = $rootScope.$new(true, $rootScope);
+ beforeEach(inject(function ($controller, $rootScope) {
+ scope = $rootScope.$new()
+ $rootScope.notebookScope = $rootScope.$new(true, $rootScope)
$controller('ParagraphCtrl', {
$scope: scope,
websocketMsgSrv: websocketMsgSrvMock,
$element: {},
$route: route
- });
+ })
- scope.init(paragraphMock);
- }));
+ scope.init(paragraphMock)
+ }))
- var functions = ['isRunning', 'getIframeDimensions', 'cancelParagraph', 'runParagraph', 'saveParagraph',
+ let functions = ['isRunning', 'getIframeDimensions', 'cancelParagraph', 'runParagraph', 'saveParagraph',
'moveUp', 'moveDown', 'insertNew', 'removeParagraph', 'toggleEditor', 'closeEditor', 'openEditor',
'closeTable', 'openTable', 'showTitle', 'hideTitle', 'setTitle', 'showLineNumbers', 'hideLineNumbers',
'changeColWidth', 'columnWidthClass', 'toggleOutput', 'loadForm',
- 'aceChanged', 'aceLoaded', 'getEditorValue', 'getProgress', 'getExecutionTime', 'isResultOutdated'];
-
- functions.forEach(function(fn) {
- it('check for scope functions to be defined : ' + fn, function() {
- expect(scope[fn]).toBeDefined();
- });
- });
-
- it('should have this array of values for "colWidthOption"', function() {
- expect(scope.colWidthOption).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
- });
-
- it('should set default value of "paragraphFocused" as false', function() {
- expect(scope.paragraphFocused).toEqual(false);
- });
-});
+ 'aceChanged', 'aceLoaded', 'getEditorValue', 'getProgress', 'getExecutionTime', 'isResultOutdated']
+
+ functions.forEach(function (fn) {
+ it('check for scope functions to be defined : ' + fn, function () {
+ expect(scope[fn]).toBeDefined()
+ })
+ })
+
+ it('should have this array of values for "colWidthOption"', function () {
+ expect(scope.colWidthOption).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
+ })
+
+ it('should set default value of "paragraphFocused" as false', function () {
+ expect(scope.paragraphFocused).toEqual(false)
+ })
+})
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/notebook/paragraph/paragraph.status.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/notebook/paragraph/paragraph.status.js b/zeppelin-web/src/app/notebook/paragraph/paragraph.status.js
index c2e9027..f839eee 100644
--- a/zeppelin-web/src/app/notebook/paragraph/paragraph.status.js
+++ b/zeppelin-web/src/app/notebook/paragraph/paragraph.status.js
@@ -19,12 +19,12 @@ export const ParagraphStatus = {
FINISHED: 'FINISHED',
ABORT: 'ABORT',
ERROR: 'ERROR',
-};
+}
-export function isParagraphRunning(paragraph) {
- if (!paragraph) { return false; }
- const status = paragraph.status;
- if (!status) { return false; }
+export function isParagraphRunning (paragraph) {
+ if (!paragraph) { return false }
+ const status = paragraph.status
+ if (!status) { return false }
- return status === ParagraphStatus.PENDING || status === ParagraphStatus.RUNNING;
+ return status === ParagraphStatus.PENDING || status === ParagraphStatus.RUNNING
}
[4/8] zeppelin git commit: [ZEPPELIN-1940] lint rule set is NOT
applied at all.
Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/notebook/paragraph/result/result.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/notebook/paragraph/result/result.controller.js b/zeppelin-web/src/app/notebook/paragraph/result/result.controller.js
index 5708339..71104b5 100644
--- a/zeppelin-web/src/app/notebook/paragraph/result/result.controller.js
+++ b/zeppelin-web/src/app/notebook/paragraph/result/result.controller.js
@@ -12,25 +12,25 @@
* limitations under the License.
*/
-import TableData from '../../../tabledata/tabledata';
-import TableVisualization from '../../../visualization/builtins/visualization-table';
-import BarchartVisualization from '../../../visualization/builtins/visualization-barchart';
-import PiechartVisualization from '../../../visualization/builtins/visualization-piechart';
-import AreachartVisualization from '../../../visualization/builtins/visualization-areachart';
-import LinechartVisualization from '../../../visualization/builtins/visualization-linechart';
-import ScatterchartVisualization from '../../../visualization/builtins/visualization-scatterchart';
+import TableData from '../../../tabledata/tabledata'
+import TableVisualization from '../../../visualization/builtins/visualization-table'
+import BarchartVisualization from '../../../visualization/builtins/visualization-barchart'
+import PiechartVisualization from '../../../visualization/builtins/visualization-piechart'
+import AreachartVisualization from '../../../visualization/builtins/visualization-areachart'
+import LinechartVisualization from '../../../visualization/builtins/visualization-linechart'
+import ScatterchartVisualization from '../../../visualization/builtins/visualization-scatterchart'
import {
DefaultDisplayType,
SpellResult,
} from '../../../spell'
-import { ParagraphStatus, } from '../paragraph.status';
+import { ParagraphStatus, } from '../paragraph.status'
-angular.module('zeppelinWebApp').controller('ResultCtrl', ResultCtrl);
+angular.module('zeppelinWebApp').controller('ResultCtrl', ResultCtrl)
-function ResultCtrl($scope, $rootScope, $route, $window, $routeParams, $location,
+function ResultCtrl ($scope, $rootScope, $route, $window, $routeParams, $location,
$timeout, $compile, $http, $q, $templateRequest, $sce, websocketMsgSrv,
baseUrlSrv, ngToast, saveAsService, noteVarShareService, heliumService) {
- 'ngInject';
+ 'ngInject'
/**
* Built-in visualizations
@@ -70,12 +70,12 @@ function ResultCtrl($scope, $rootScope, $route, $window, $routeParams, $location
name: 'Scatter Chart',
icon: '<i class="cf cf-scatter-chart"></i>'
}
- ];
+ ]
/**
* Holds class and actual runtime instance and related infos of built-in visualizations
*/
- var builtInVisualizations = {
+ let builtInVisualizations = {
'table': {
class: TableVisualization,
instance: undefined // created from setGraphMode()
@@ -100,95 +100,95 @@ function ResultCtrl($scope, $rootScope, $route, $window, $routeParams, $location
class: ScatterchartVisualization,
instance: undefined
}
- };
+ }
// type
- $scope.type;
+ $scope.type = null
// Data of the result
- var data;
+ let data
// config
- $scope.config;
+ $scope.config = null
// resultId = paragraph.id + index
- $scope.id;
+ $scope.id = null
// referece to paragraph
- var paragraph;
+ let paragraph
// index of the result
- var resultIndex;
+ let resultIndex
// TableData instance
- var tableData;
+ let tableData
// available columns in tabledata
- $scope.tableDataColumns = [];
+ $scope.tableDataColumns = []
// enable helium
- var enableHelium = false;
+ let enableHelium = false
// graphMode
- $scope.graphMode;
+ $scope.graphMode = null
// image data
- $scope.imageData;
+ $scope.imageData = null
// queue for append output
- const textResultQueueForAppend = [];
+ const textResultQueueForAppend = []
- $scope.init = function(result, config, paragraph, index) {
+ $scope.init = function (result, config, paragraph, index) {
// register helium plugin vis
- var visBundles = heliumService.getVisualizationBundles();
- visBundles.forEach(function(vis) {
+ let visBundles = heliumService.getVisualizationBundles()
+ visBundles.forEach(function (vis) {
$scope.builtInTableDataVisualizationList.push({
id: vis.id,
name: vis.name,
icon: $sce.trustAsHtml(vis.icon)
- });
+ })
builtInVisualizations[vis.id] = {
class: vis.class
- };
- });
+ }
+ })
- updateData(result, config, paragraph, index);
- renderResult($scope.type);
- };
+ updateData(result, config, paragraph, index)
+ renderResult($scope.type)
+ }
- function isDOMLoaded(targetElemId) {
- const elem = angular.element(`#${targetElemId}`);
- return elem.length;
+ function isDOMLoaded (targetElemId) {
+ const elem = angular.element(`#${targetElemId}`)
+ return elem.length
}
- function retryUntilElemIsLoaded(targetElemId, callback) {
- function retry() {
+ function retryUntilElemIsLoaded (targetElemId, callback) {
+ function retry () {
if (!isDOMLoaded(targetElemId)) {
- $timeout(retry, 10);
- return;
+ $timeout(retry, 10)
+ return
}
- const elem = angular.element(`#${targetElemId}`);
- callback(elem);
+ const elem = angular.element(`#${targetElemId}`)
+ callback(elem)
}
- $timeout(retry);
+ $timeout(retry)
}
- $scope.$on('updateResult', function(event, result, newConfig, paragraphRef, index) {
+ $scope.$on('updateResult', function (event, result, newConfig, paragraphRef, index) {
if (paragraph.id !== paragraphRef.id || index !== resultIndex) {
- return;
+ return
}
- var refresh = !angular.equals(newConfig, $scope.config) ||
+ let refresh = !angular.equals(newConfig, $scope.config) ||
!angular.equals(result.type, $scope.type) ||
- !angular.equals(result.data, data);
+ !angular.equals(result.data, data)
- updateData(result, newConfig, paragraph, resultIndex);
- renderResult($scope.type, refresh);
- });
+ updateData(result, newConfig, paragraph, resultIndex)
+ renderResult($scope.type, refresh)
+ })
- $scope.$on('appendParagraphOutput', function(event, data) {
+ $scope.$on('appendParagraphOutput', function (event, data) {
/* It has been observed that append events
* can be errorneously called even if paragraph
* execution has ended, and in that case, no append
@@ -200,159 +200,158 @@ function ResultCtrl($scope, $rootScope, $route, $window, $routeParams, $location
if (paragraph.id === data.paragraphId &&
resultIndex === data.index &&
(paragraph.status === ParagraphStatus.PENDING || paragraph.status === ParagraphStatus.RUNNING)) {
-
if (DefaultDisplayType.TEXT !== $scope.type) {
- $scope.type = DefaultDisplayType.TEXT;
+ $scope.type = DefaultDisplayType.TEXT
}
- appendTextOutput(data.data);
+ appendTextOutput(data.data)
}
- });
+ })
- var updateData = function(result, config, paragraphRef, index) {
- data = result.data;
- paragraph = paragraphRef;
- resultIndex = parseInt(index);
+ const updateData = function (result, config, paragraphRef, index) {
+ data = result.data
+ paragraph = paragraphRef
+ resultIndex = parseInt(index)
- $scope.id = paragraph.id + '_' + index;
- $scope.type = result.type;
- config = config ? config : {};
+ $scope.id = paragraph.id + '_' + index
+ $scope.type = result.type
+ config = config ? config : {}
// initialize default config values
if (!config.graph) {
- config.graph = {};
+ config.graph = {}
}
if (!config.graph.mode) {
- config.graph.mode = 'table';
+ config.graph.mode = 'table'
}
if (!config.graph.height) {
- config.graph.height = 300;
+ config.graph.height = 300
}
if (!config.graph.optionOpen) {
- config.graph.optionOpen = false;
+ config.graph.optionOpen = false
}
- $scope.graphMode = config.graph.mode;
- $scope.config = angular.copy(config);
+ $scope.graphMode = config.graph.mode
+ $scope.config = angular.copy(config)
// enable only when it is last result
- enableHelium = (index === paragraphRef.results.msg.length - 1);
+ enableHelium = (index === paragraphRef.results.msg.length - 1)
if ($scope.type === 'TABLE') {
- tableData = new TableData();
- tableData.loadParagraphResult({type: $scope.type, msg: data});
- $scope.tableDataColumns = tableData.columns;
- $scope.tableDataComment = tableData.comment;
+ tableData = new TableData()
+ tableData.loadParagraphResult({type: $scope.type, msg: data})
+ $scope.tableDataColumns = tableData.columns
+ $scope.tableDataComment = tableData.comment
} else if ($scope.type === 'IMG') {
- $scope.imageData = data;
+ $scope.imageData = data
}
- };
+ }
- $scope.createDisplayDOMId = function(baseDOMId, type) {
+ $scope.createDisplayDOMId = function (baseDOMId, type) {
if (type === DefaultDisplayType.TABLE) {
- return `${baseDOMId}_graph`;
+ return `${baseDOMId}_graph`
} else if (type === DefaultDisplayType.HTML) {
- return `${baseDOMId}_html`;
+ return `${baseDOMId}_html`
} else if (type === DefaultDisplayType.ANGULAR) {
- return `${baseDOMId}_angular`;
+ return `${baseDOMId}_angular`
} else if (type === DefaultDisplayType.TEXT) {
- return `${baseDOMId}_text`;
+ return `${baseDOMId}_text`
} else if (type === DefaultDisplayType.ELEMENT) {
- return `${baseDOMId}_elem`;
+ return `${baseDOMId}_elem`
} else {
- console.error(`Cannot create display DOM Id due to unknown display type: ${type}`);
+ console.error(`Cannot create display DOM Id due to unknown display type: ${type}`)
}
- };
+ }
- $scope.renderDefaultDisplay = function(targetElemId, type, data, refresh) {
+ $scope.renderDefaultDisplay = function (targetElemId, type, data, refresh) {
const afterLoaded = () => {
if (type === DefaultDisplayType.TABLE) {
- renderGraph(targetElemId, $scope.graphMode, refresh);
+ renderGraph(targetElemId, $scope.graphMode, refresh)
} else if (type === DefaultDisplayType.HTML) {
- renderHtml(targetElemId, data);
+ renderHtml(targetElemId, data)
} else if (type === DefaultDisplayType.ANGULAR) {
- renderAngular(targetElemId, data);
+ renderAngular(targetElemId, data)
} else if (type === DefaultDisplayType.TEXT) {
- renderText(targetElemId, data);
+ renderText(targetElemId, data)
} else if (type === DefaultDisplayType.ELEMENT) {
- renderElem(targetElemId, data);
+ renderElem(targetElemId, data)
} else {
- console.error(`Unknown Display Type: ${type}`);
+ console.error(`Unknown Display Type: ${type}`)
}
}
- retryUntilElemIsLoaded(targetElemId, afterLoaded);
+ retryUntilElemIsLoaded(targetElemId, afterLoaded)
// send message to parent that this result is rendered
- const paragraphId = $scope.$parent.paragraph.id;
- $scope.$emit('resultRendered', paragraphId);
- };
+ const paragraphId = $scope.$parent.paragraph.id
+ $scope.$emit('resultRendered', paragraphId)
+ }
- const renderResult = function(type, refresh) {
- let activeApp;
+ const renderResult = function (type, refresh) {
+ let activeApp
if (enableHelium) {
- getSuggestions();
- getApplicationStates();
- activeApp = _.get($scope.config, 'helium.activeApp');
+ getSuggestions()
+ getApplicationStates()
+ activeApp = _.get($scope.config, 'helium.activeApp')
}
if (activeApp) {
- const appState = _.find($scope.apps, {id: activeApp});
- renderApp(`p${appState.id}`, appState);
+ const appState = _.find($scope.apps, {id: activeApp})
+ renderApp(`p${appState.id}`, appState)
} else {
if (!DefaultDisplayType[type]) {
- $scope.renderCustomDisplay(type, data);
+ $scope.renderCustomDisplay(type, data)
} else {
- const targetElemId = $scope.createDisplayDOMId(`p${$scope.id}`, type);
- $scope.renderDefaultDisplay(targetElemId, type, data, refresh);
+ const targetElemId = $scope.createDisplayDOMId(`p${$scope.id}`, type)
+ $scope.renderDefaultDisplay(targetElemId, type, data, refresh)
}
}
- };
+ }
- $scope.isDefaultDisplay = function() {
- return DefaultDisplayType[$scope.type];
- };
+ $scope.isDefaultDisplay = function () {
+ return DefaultDisplayType[$scope.type]
+ }
/**
* Render multiple sub results for custom display
*/
- $scope.renderCustomDisplay = function(type, data) {
+ $scope.renderCustomDisplay = function (type, data) {
// get result from intp
if (!heliumService.getSpellByMagic(type)) {
- console.error(`Can't execute spell due to unknown display type: ${type}`);
- return;
+ console.error(`Can't execute spell due to unknown display type: ${type}`)
+ return
}
// custom display result can include multiple subset results
heliumService.executeSpellAsDisplaySystem(type, data)
.then(dataWithTypes => {
- const containerDOMId = `p${$scope.id}_custom`;
+ const containerDOMId = `p${$scope.id}_custom`
const afterLoaded = () => {
- const containerDOM = angular.element(`#${containerDOMId}`);
+ const containerDOM = angular.element(`#${containerDOMId}`)
// Spell.interpret() can create multiple outputs
- for(let i = 0; i < dataWithTypes.length; i++) {
- const dt = dataWithTypes[i];
- const data = dt.data;
- const type = dt.type;
+ for (let i = 0; i < dataWithTypes.length; i++) {
+ const dt = dataWithTypes[i]
+ const data = dt.data
+ const type = dt.type
// prepare each DOM to be filled
- const subResultDOMId = $scope.createDisplayDOMId(`p${$scope.id}_custom_${i}`, type);
- const subResultDOM = document.createElement('div');
- containerDOM.append(subResultDOM);
- subResultDOM.setAttribute('id', subResultDOMId);
+ const subResultDOMId = $scope.createDisplayDOMId(`p${$scope.id}_custom_${i}`, type)
+ const subResultDOM = document.createElement('div')
+ containerDOM.append(subResultDOM)
+ subResultDOM.setAttribute('id', subResultDOMId)
- $scope.renderDefaultDisplay(subResultDOMId, type, data, true);
+ $scope.renderDefaultDisplay(subResultDOMId, type, data, true)
}
- };
+ }
- retryUntilElemIsLoaded(containerDOMId, afterLoaded);
+ retryUntilElemIsLoaded(containerDOMId, afterLoaded)
})
.catch(error => {
- console.error(`Failed to render custom display: ${$scope.type}\n` + error);
- });
- };
+ console.error(`Failed to render custom display: ${$scope.type}\n` + error)
+ })
+ }
/**
* generates actually object which will be consumed from `data` property
@@ -364,271 +363,269 @@ function ResultCtrl($scope, $rootScope, $route, $window, $routeParams, $location
* @param successCallback
* @param failureCallback
*/
- const handleData = function(data, type, successCallback, failureCallback) {
+ const handleData = function (data, type, successCallback, failureCallback) {
if (SpellResult.isFunction(data)) {
try {
- successCallback(data());
+ successCallback(data())
} catch (error) {
- failureCallback(error);
- console.error(`Failed to handle ${type} type, function data\n`, error);
+ failureCallback(error)
+ console.error(`Failed to handle ${type} type, function data\n`, error)
}
} else if (SpellResult.isObject(data)) {
try {
- successCallback(data);
+ successCallback(data)
} catch (error) {
- console.error(`Failed to handle ${type} type, object data\n`, error);
+ console.error(`Failed to handle ${type} type, object data\n`, error)
}
}
- };
+ }
- const renderElem = function(targetElemId, data) {
- const elem = angular.element(`#${targetElemId}`);
+ const renderElem = function (targetElemId, data) {
+ const elem = angular.element(`#${targetElemId}`)
handleData(() => { data(targetElemId) }, DefaultDisplayType.ELEMENT,
() => {}, /** HTML element will be filled with data. thus pass empty success callback */
- (error) => { elem.html(`${error.stack}`); }
- );
- };
+ (error) => { elem.html(`${error.stack}`) }
+ )
+ }
- const renderHtml = function(targetElemId, data) {
- const elem = angular.element(`#${targetElemId}`);
+ const renderHtml = function (targetElemId, data) {
+ const elem = angular.element(`#${targetElemId}`)
handleData(data, DefaultDisplayType.HTML,
(generated) => {
- elem.html(generated);
- elem.find('pre code').each(function(i, e) {
- hljs.highlightBlock(e);
- });
- /*eslint new-cap: [2, {"capIsNewExceptions": ["MathJax.Hub.Queue"]}]*/
- MathJax.Hub.Queue(['Typeset', MathJax.Hub, elem[0]]);
+ elem.html(generated)
+ elem.find('pre code').each(function (i, e) {
+ hljs.highlightBlock(e)
+ })
+ /* eslint new-cap: [2, {"capIsNewExceptions": ["MathJax.Hub.Queue"]}] */
+ MathJax.Hub.Queue(['Typeset', MathJax.Hub, elem[0]])
},
- (error) => { elem.html(`${error.stack}`); }
- );
- };
+ (error) => { elem.html(`${error.stack}`) }
+ )
+ }
- const renderAngular = function(targetElemId, data) {
- const elem = angular.element(`#${targetElemId}`);
- const paragraphScope = noteVarShareService.get(`${paragraph.id}_paragraphScope`);
+ const renderAngular = function (targetElemId, data) {
+ const elem = angular.element(`#${targetElemId}`)
+ const paragraphScope = noteVarShareService.get(`${paragraph.id}_paragraphScope`)
handleData(data, DefaultDisplayType.ANGULAR,
(generated) => {
- elem.html(generated);
- $compile(elem.contents())(paragraphScope);
+ elem.html(generated)
+ $compile(elem.contents())(paragraphScope)
},
- (error) => { elem.html(`${error.stack}`); }
- );
- };
+ (error) => { elem.html(`${error.stack}`) }
+ )
+ }
const getTextResultElemId = function (resultId) {
- return `p${resultId}_text`;
- };
+ return `p${resultId}_text`
+ }
- const renderText = function(targetElemId, data) {
- const elem = angular.element(`#${targetElemId}`);
+ const renderText = function (targetElemId, data) {
+ const elem = angular.element(`#${targetElemId}`)
handleData(data, DefaultDisplayType.TEXT,
(generated) => {
// clear all lines before render
- removeChildrenDOM(targetElemId);
+ removeChildrenDOM(targetElemId)
if (generated) {
- const divDOM = angular.element('<div></div>').text(generated);
- elem.append(divDOM);
+ const divDOM = angular.element('<div></div>').text(generated)
+ elem.append(divDOM)
}
- elem.bind('mousewheel', (e) => { $scope.keepScrollDown = false; });
+ elem.bind('mousewheel', (e) => { $scope.keepScrollDown = false })
},
- (error) => { elem.html(`${error.stack}`); }
- );
- };
+ (error) => { elem.html(`${error.stack}`) }
+ )
+ }
- const removeChildrenDOM = function(targetElemId) {
- const elem = angular.element(`#${targetElemId}`);
+ const removeChildrenDOM = function (targetElemId) {
+ const elem = angular.element(`#${targetElemId}`)
if (elem.length) {
- elem.children().remove();
+ elem.children().remove()
}
- };
+ }
- function appendTextOutput(data) {
- const elemId = getTextResultElemId($scope.id);
- textResultQueueForAppend.push(data);
+ function appendTextOutput (data) {
+ const elemId = getTextResultElemId($scope.id)
+ textResultQueueForAppend.push(data)
// if DOM is not loaded, just push data and return
if (!isDOMLoaded(elemId)) {
- return;
+ return
}
- const elem = angular.element(`#${elemId}`);
+ const elem = angular.element(`#${elemId}`)
// pop all stacked data and append to the DOM
while (textResultQueueForAppend.length > 0) {
- const line = textResultQueueForAppend.pop();
- elem.append(angular.element('<div></div>').text(line));
+ const line = textResultQueueForAppend.pop()
+ elem.append(angular.element('<div></div>').text(line))
if ($scope.keepScrollDown) {
- const doc = angular.element(`#${elemId}`);
- doc[0].scrollTop = doc[0].scrollHeight;
+ const doc = angular.element(`#${elemId}`)
+ doc[0].scrollTop = doc[0].scrollHeight
}
}
}
- const getTrSettingElem = function(scopeId, graphMode) {
+ const getTrSettingElem = function (scopeId, graphMode) {
return angular.element('#trsetting' + scopeId + '_' + graphMode)
}
- const getVizSettingElem = function(scopeId, graphMode) {
+ const getVizSettingElem = function (scopeId, graphMode) {
return angular.element('#vizsetting' + scopeId + '_' + graphMode)
}
- const renderGraph = function(graphElemId, graphMode, refresh) {
+ const renderGraph = function (graphElemId, graphMode, refresh) {
// set graph height
- const height = $scope.config.graph.height;
- const graphElem = angular.element(`#${graphElemId}`);
- graphElem.height(height);
+ const height = $scope.config.graph.height
+ const graphElem = angular.element(`#${graphElemId}`)
+ graphElem.height(height)
- if (!graphMode) { graphMode = 'table'; }
+ if (!graphMode) { graphMode = 'table' }
- const builtInViz = builtInVisualizations[graphMode];
- if (!builtInViz) { return; }
+ const builtInViz = builtInVisualizations[graphMode]
+ if (!builtInViz) { return }
// deactive previsouly active visualization
for (let t in builtInVisualizations) {
- const v = builtInVisualizations[t].instance;
+ const v = builtInVisualizations[t].instance
if (t !== graphMode && v && v.isActive()) {
- v.deactivate();
- break;
+ v.deactivate()
+ break
}
}
- let afterLoaded = function() { /** will be overwritten */ };
+ let afterLoaded = function () { /** will be overwritten */ }
if (!builtInViz.instance) { // not instantiated yet
// render when targetEl is available
- afterLoaded = function(loadedElem) {
+ afterLoaded = function (loadedElem) {
try {
const transformationSettingTargetEl = getTrSettingElem($scope.id, graphMode)
const visualizationSettingTargetEl = getVizSettingElem($scope.id, graphMode)
// set height
- loadedElem.height(height);
+ loadedElem.height(height)
// instantiate visualization
- const config = getVizConfig(graphMode);
- const Visualization = builtInViz.class;
- builtInViz.instance = new Visualization(loadedElem, config);
+ const config = getVizConfig(graphMode)
+ const Visualization = builtInViz.class
+ builtInViz.instance = new Visualization(loadedElem, config)
// inject emitter, $templateRequest
- const emitter = function(graphSetting) {
- commitVizConfigChange(graphSetting, graphMode);
- };
- builtInViz.instance._emitter = emitter;
- builtInViz.instance._compile = $compile;
- builtInViz.instance._createNewScope = createNewScope;
- const transformation = builtInViz.instance.getTransformation();
- transformation._emitter = emitter;
- transformation._templateRequest = $templateRequest;
- transformation._compile = $compile;
- transformation._createNewScope = createNewScope;
+ const emitter = function (graphSetting) {
+ commitVizConfigChange(graphSetting, graphMode)
+ }
+ builtInViz.instance._emitter = emitter
+ builtInViz.instance._compile = $compile
+ builtInViz.instance._createNewScope = createNewScope
+ const transformation = builtInViz.instance.getTransformation()
+ transformation._emitter = emitter
+ transformation._templateRequest = $templateRequest
+ transformation._compile = $compile
+ transformation._createNewScope = createNewScope
// render
- const transformed = transformation.transform(tableData);
- transformation.renderSetting(transformationSettingTargetEl);
- builtInViz.instance.render(transformed);
- builtInViz.instance.renderSetting(visualizationSettingTargetEl);
- builtInViz.instance.activate();
+ const transformed = transformation.transform(tableData)
+ transformation.renderSetting(transformationSettingTargetEl)
+ builtInViz.instance.render(transformed)
+ builtInViz.instance.renderSetting(visualizationSettingTargetEl)
+ builtInViz.instance.activate()
angular.element(window).resize(() => {
- builtInViz.instance.resize();
- });
+ builtInViz.instance.resize()
+ })
} catch (err) {
- console.error('Graph drawing error %o', err);
+ console.error('Graph drawing error %o', err)
}
- };
-
+ }
} else if (refresh) {
// when graph options or data are changed
- console.log('Refresh data %o', tableData);
+ console.log('Refresh data %o', tableData)
- afterLoaded = function(loadedElem) {
+ afterLoaded = function (loadedElem) {
const transformationSettingTargetEl = getTrSettingElem($scope.id, graphMode)
const visualizationSettingTargetEl = getVizSettingElem($scope.id, graphMode)
- const config = getVizConfig(graphMode);
- loadedElem.height(height);
- const transformation = builtInViz.instance.getTransformation();
- transformation.setConfig(config);
- const transformed = transformation.transform(tableData);
- transformation.renderSetting(transformationSettingTargetEl);
- builtInViz.instance.setConfig(config);
- builtInViz.instance.render(transformed);
- builtInViz.instance.renderSetting(visualizationSettingTargetEl);
- };
-
+ const config = getVizConfig(graphMode)
+ loadedElem.height(height)
+ const transformation = builtInViz.instance.getTransformation()
+ transformation.setConfig(config)
+ const transformed = transformation.transform(tableData)
+ transformation.renderSetting(transformationSettingTargetEl)
+ builtInViz.instance.setConfig(config)
+ builtInViz.instance.render(transformed)
+ builtInViz.instance.renderSetting(visualizationSettingTargetEl)
+ }
} else {
- afterLoaded = function(loadedElem) {
- loadedElem.height(height);
- builtInViz.instance.activate();
- };
+ afterLoaded = function (loadedElem) {
+ loadedElem.height(height)
+ builtInViz.instance.activate()
+ }
}
- const tableElemId = `p${$scope.id}_${graphMode}`;
- retryUntilElemIsLoaded(tableElemId, afterLoaded);
- };
+ const tableElemId = `p${$scope.id}_${graphMode}`
+ retryUntilElemIsLoaded(tableElemId, afterLoaded)
+ }
- $scope.switchViz = function(newMode) {
- var newConfig = angular.copy($scope.config);
- var newParams = angular.copy(paragraph.settings.params);
+ $scope.switchViz = function (newMode) {
+ let newConfig = angular.copy($scope.config)
+ let newParams = angular.copy(paragraph.settings.params)
// graph options
- newConfig.graph.mode = newMode;
+ newConfig.graph.mode = newMode
// see switchApp()
- _.set(newConfig, 'helium.activeApp', undefined);
+ _.set(newConfig, 'helium.activeApp', undefined)
- commitParagraphResult(paragraph.title, paragraph.text, newConfig, newParams);
- };
+ commitParagraphResult(paragraph.title, paragraph.text, newConfig, newParams)
+ }
- var createNewScope = function() {
- return $rootScope.$new(true);
- };
+ const createNewScope = function () {
+ return $rootScope.$new(true)
+ }
- var commitParagraphResult = function(title, text, config, params) {
- var newParagraphConfig = angular.copy(paragraph.config);
- newParagraphConfig.results = newParagraphConfig.results || [];
- newParagraphConfig.results[resultIndex] = config;
+ const commitParagraphResult = function (title, text, config, params) {
+ let newParagraphConfig = angular.copy(paragraph.config)
+ newParagraphConfig.results = newParagraphConfig.results || []
+ newParagraphConfig.results[resultIndex] = config
if ($scope.revisionView === true) {
// local update without commit
updateData({
type: $scope.type,
data: data
- }, newParagraphConfig.results[resultIndex], paragraph, resultIndex);
- renderResult($scope.type, true);
+ }, newParagraphConfig.results[resultIndex], paragraph, resultIndex)
+ renderResult($scope.type, true)
} else {
- websocketMsgSrv.commitParagraph(paragraph.id, title, text, newParagraphConfig, params);
+ websocketMsgSrv.commitParagraph(paragraph.id, title, text, newParagraphConfig, params)
}
- };
+ }
- $scope.toggleGraphSetting = function() {
- var newConfig = angular.copy($scope.config);
+ $scope.toggleGraphSetting = function () {
+ let newConfig = angular.copy($scope.config)
if (newConfig.graph.optionOpen) {
- newConfig.graph.optionOpen = false;
+ newConfig.graph.optionOpen = false
} else {
- newConfig.graph.optionOpen = true;
+ newConfig.graph.optionOpen = true
}
- var newParams = angular.copy(paragraph.settings.params);
+ let newParams = angular.copy(paragraph.settings.params)
- commitParagraphResult(paragraph.title, paragraph.text, newConfig, newParams);
- };
+ commitParagraphResult(paragraph.title, paragraph.text, newConfig, newParams)
+ }
- var getVizConfig = function(vizId) {
- var config;
- var graph = $scope.config.graph;
+ const getVizConfig = function (vizId) {
+ let config
+ let graph = $scope.config.graph
if (graph) {
// copy setting for vizId
if (graph.setting) {
- config = angular.copy(graph.setting[vizId]);
+ config = angular.copy(graph.setting[vizId])
}
if (!config) {
- config = {};
+ config = {}
}
// copy common setting
- config.common = angular.copy(graph.commonSetting) || {};
+ config.common = angular.copy(graph.commonSetting) || {}
// copy pivot setting
if (graph.keys) {
@@ -636,300 +633,300 @@ function ResultCtrl($scope, $rootScope, $route, $window, $routeParams, $location
keys: angular.copy(graph.keys),
groups: angular.copy(graph.groups),
values: angular.copy(graph.values)
- };
+ }
}
}
- console.log('getVizConfig', config);
- return config;
- };
+ console.log('getVizConfig', config)
+ return config
+ }
- var commitVizConfigChange = function(config, vizId) {
- var newConfig = angular.copy($scope.config);
+ const commitVizConfigChange = function (config, vizId) {
+ let newConfig = angular.copy($scope.config)
if (!newConfig.graph) {
- newConfig.graph = {};
+ newConfig.graph = {}
}
// copy setting for vizId
if (!newConfig.graph.setting) {
- newConfig.graph.setting = {};
+ newConfig.graph.setting = {}
}
- newConfig.graph.setting[vizId] = angular.copy(config);
+ newConfig.graph.setting[vizId] = angular.copy(config)
// copy common setting
if (newConfig.graph.setting[vizId]) {
- newConfig.graph.commonSetting = newConfig.graph.setting[vizId].common;
- delete newConfig.graph.setting[vizId].common;
+ newConfig.graph.commonSetting = newConfig.graph.setting[vizId].common
+ delete newConfig.graph.setting[vizId].common
}
// copy pivot setting
if (newConfig.graph.commonSetting && newConfig.graph.commonSetting.pivot) {
- newConfig.graph.keys = newConfig.graph.commonSetting.pivot.keys;
- newConfig.graph.groups = newConfig.graph.commonSetting.pivot.groups;
- newConfig.graph.values = newConfig.graph.commonSetting.pivot.values;
- delete newConfig.graph.commonSetting.pivot;
- }
- console.log('committVizConfig', newConfig);
- var newParams = angular.copy(paragraph.settings.params);
- commitParagraphResult(paragraph.title, paragraph.text, newConfig, newParams);
- };
+ newConfig.graph.keys = newConfig.graph.commonSetting.pivot.keys
+ newConfig.graph.groups = newConfig.graph.commonSetting.pivot.groups
+ newConfig.graph.values = newConfig.graph.commonSetting.pivot.values
+ delete newConfig.graph.commonSetting.pivot
+ }
+ console.log('committVizConfig', newConfig)
+ let newParams = angular.copy(paragraph.settings.params)
+ commitParagraphResult(paragraph.title, paragraph.text, newConfig, newParams)
+ }
- $scope.$on('paragraphResized', function(event, paragraphId) {
+ $scope.$on('paragraphResized', function (event, paragraphId) {
// paragraph col width changed
if (paragraphId === paragraph.id) {
- var builtInViz = builtInVisualizations[$scope.graphMode];
+ let builtInViz = builtInVisualizations[$scope.graphMode]
if (builtInViz && builtInViz.instance) {
- builtInViz.instance.resize();
+ builtInViz.instance.resize()
}
}
- });
+ })
- $scope.resize = function(width, height) {
- $timeout(function() {
- changeHeight(width, height);
- }, 200);
- };
+ $scope.resize = function (width, height) {
+ $timeout(function () {
+ changeHeight(width, height)
+ }, 200)
+ }
- var changeHeight = function(width, height) {
- var newParams = angular.copy(paragraph.settings.params);
- var newConfig = angular.copy($scope.config);
+ const changeHeight = function (width, height) {
+ let newParams = angular.copy(paragraph.settings.params)
+ let newConfig = angular.copy($scope.config)
- newConfig.graph.height = height;
- paragraph.config.colWidth = width;
+ newConfig.graph.height = height
+ paragraph.config.colWidth = width
- commitParagraphResult(paragraph.title, paragraph.text, newConfig, newParams);
- };
+ commitParagraphResult(paragraph.title, paragraph.text, newConfig, newParams)
+ }
- $scope.exportToDSV = function(delimiter) {
- var dsv = '';
- var dateFinished = moment(paragraph.dateFinished).format('YYYY-MM-DD hh:mm:ss A');
- var exportedFileName = paragraph.title ? paragraph.title + '_' + dateFinished : 'data_' + dateFinished;
+ $scope.exportToDSV = function (delimiter) {
+ let dsv = ''
+ let dateFinished = moment(paragraph.dateFinished).format('YYYY-MM-DD hh:mm:ss A')
+ let exportedFileName = paragraph.title ? paragraph.title + '_' + dateFinished : 'data_' + dateFinished
- for (var titleIndex in tableData.columns) {
- dsv += tableData.columns[titleIndex].name + delimiter;
+ for (let titleIndex in tableData.columns) {
+ dsv += tableData.columns[titleIndex].name + delimiter
}
- dsv = dsv.substring(0, dsv.length - 1) + '\n';
- for (var r in tableData.rows) {
- var row = tableData.rows[r];
- var dsvRow = '';
- for (var index in row) {
- var stringValue = (row[index]).toString();
+ dsv = dsv.substring(0, dsv.length - 1) + '\n'
+ for (let r in tableData.rows) {
+ let row = tableData.rows[r]
+ let dsvRow = ''
+ for (let index in row) {
+ let stringValue = (row[index]).toString()
if (stringValue.indexOf(delimiter) > -1) {
- dsvRow += '"' + stringValue + '"' + delimiter;
+ dsvRow += '"' + stringValue + '"' + delimiter
} else {
- dsvRow += row[index] + delimiter;
+ dsvRow += row[index] + delimiter
}
}
- dsv += dsvRow.substring(0, dsvRow.length - 1) + '\n';
+ dsv += dsvRow.substring(0, dsvRow.length - 1) + '\n'
}
- var extension = '';
+ let extension = ''
if (delimiter === '\t') {
- extension = 'tsv';
+ extension = 'tsv'
} else if (delimiter === ',') {
- extension = 'csv';
+ extension = 'csv'
}
- saveAsService.saveAs(dsv, exportedFileName, extension);
- };
+ saveAsService.saveAs(dsv, exportedFileName, extension)
+ }
- $scope.getBase64ImageSrc = function(base64Data) {
- return 'data:image/png;base64,' + base64Data;
- };
+ $scope.getBase64ImageSrc = function (base64Data) {
+ return 'data:image/png;base64,' + base64Data
+ }
// Helium ----------------
- var ANGULAR_FUNCTION_OBJECT_NAME_PREFIX = '_Z_ANGULAR_FUNC_';
+ let ANGULAR_FUNCTION_OBJECT_NAME_PREFIX = '_Z_ANGULAR_FUNC_'
// app states
- $scope.apps = [];
+ $scope.apps = []
// suggested apps
- $scope.suggestion = {};
+ $scope.suggestion = {}
- $scope.switchApp = function(appId) {
- var newConfig = angular.copy($scope.config);
- var newParams = angular.copy(paragraph.settings.params);
+ $scope.switchApp = function (appId) {
+ let newConfig = angular.copy($scope.config)
+ let newParams = angular.copy(paragraph.settings.params)
// 'helium.activeApp' can be cleared by switchViz()
- _.set(newConfig, 'helium.activeApp', appId);
+ _.set(newConfig, 'helium.activeApp', appId)
- commitConfig(newConfig, newParams);
- };
+ commitConfig(newConfig, newParams)
+ }
- $scope.loadApp = function(heliumPackage) {
- var noteId = $route.current.pathParams.noteId;
+ $scope.loadApp = function (heliumPackage) {
+ let noteId = $route.current.pathParams.noteId
$http.post(baseUrlSrv.getRestApiBase() + '/helium/load/' + noteId + '/' + paragraph.id, heliumPackage)
- .success(function(data, status, headers, config) {
- console.log('Load app %o', data);
+ .success(function (data, status, headers, config) {
+ console.log('Load app %o', data)
+ })
+ .error(function (err, status, headers, config) {
+ console.log('Error %o', err)
})
- .error(function(err, status, headers, config) {
- console.log('Error %o', err);
- });
- };
+ }
- var commitConfig = function(config, params) {
- commitParagraphResult(paragraph.title, paragraph.text, config, params);
- };
+ const commitConfig = function (config, params) {
+ commitParagraphResult(paragraph.title, paragraph.text, config, params)
+ }
- var getApplicationStates = function() {
- var appStates = [];
+ const getApplicationStates = function () {
+ let appStates = []
// Display ApplicationState
if (paragraph.apps) {
- _.forEach(paragraph.apps, function(app) {
+ _.forEach(paragraph.apps, function (app) {
appStates.push({
id: app.id,
pkg: app.pkg,
status: app.status,
output: app.output
- });
- });
+ })
+ })
}
// update or remove app states no longer exists
- _.forEach($scope.apps, function(currentAppState, idx) {
- var newAppState = _.find(appStates, {id: currentAppState.id});
+ _.forEach($scope.apps, function (currentAppState, idx) {
+ let newAppState = _.find(appStates, {id: currentAppState.id})
if (newAppState) {
- angular.extend($scope.apps[idx], newAppState);
+ angular.extend($scope.apps[idx], newAppState)
} else {
- $scope.apps.splice(idx, 1);
+ $scope.apps.splice(idx, 1)
}
- });
+ })
// add new app states
- _.forEach(appStates, function(app, idx) {
+ _.forEach(appStates, function (app, idx) {
if ($scope.apps.length <= idx || $scope.apps[idx].id !== app.id) {
- $scope.apps.splice(idx, 0, app);
+ $scope.apps.splice(idx, 0, app)
}
- });
- };
+ })
+ }
- var getSuggestions = function() {
+ const getSuggestions = function () {
// Get suggested apps
- var noteId = $route.current.pathParams.noteId;
+ let noteId = $route.current.pathParams.noteId
if (!noteId) {
- return;
+ return
}
$http.get(baseUrlSrv.getRestApiBase() + '/helium/suggest/' + noteId + '/' + paragraph.id)
- .success(function(data, status, headers, config) {
- $scope.suggestion = data.body;
+ .success(function (data, status, headers, config) {
+ $scope.suggestion = data.body
})
- .error(function(err, status, headers, config) {
- console.log('Error %o', err);
- });
- };
+ .error(function (err, status, headers, config) {
+ console.log('Error %o', err)
+ })
+ }
- const renderApp = function(targetElemId, appState) {
+ const renderApp = function (targetElemId, appState) {
const afterLoaded = (loadedElem) => {
try {
- console.log('renderApp %o', appState);
- loadedElem.html(appState.output);
- $compile(loadedElem.contents())(getAppScope(appState));
+ console.log('renderApp %o', appState)
+ loadedElem.html(appState.output)
+ $compile(loadedElem.contents())(getAppScope(appState))
} catch (err) {
- console.log('App rendering error %o', err);
+ console.log('App rendering error %o', err)
}
- };
- retryUntilElemIsLoaded(targetElemId, afterLoaded);
- };
+ }
+ retryUntilElemIsLoaded(targetElemId, afterLoaded)
+ }
/*
** $scope.$on functions below
*/
- $scope.$on('appendAppOutput', function(event, data) {
+ $scope.$on('appendAppOutput', function (event, data) {
if (paragraph.id === data.paragraphId) {
- var app = _.find($scope.apps, {id: data.appId});
+ let app = _.find($scope.apps, {id: data.appId})
if (app) {
- app.output += data.data;
+ app.output += data.data
- var paragraphAppState = _.find(paragraph.apps, {id: data.appId});
- paragraphAppState.output = app.output;
+ let paragraphAppState = _.find(paragraph.apps, {id: data.appId})
+ paragraphAppState.output = app.output
- var targetEl = angular.element(document.getElementById('p' + app.id));
- targetEl.html(app.output);
- $compile(targetEl.contents())(getAppScope(app));
- console.log('append app output %o', $scope.apps);
+ let targetEl = angular.element(document.getElementById('p' + app.id))
+ targetEl.html(app.output)
+ $compile(targetEl.contents())(getAppScope(app))
+ console.log('append app output %o', $scope.apps)
}
}
- });
+ })
- $scope.$on('updateAppOutput', function(event, data) {
+ $scope.$on('updateAppOutput', function (event, data) {
if (paragraph.id === data.paragraphId) {
- var app = _.find($scope.apps, {id: data.appId});
+ let app = _.find($scope.apps, {id: data.appId})
if (app) {
- app.output = data.data;
+ app.output = data.data
- var paragraphAppState = _.find(paragraph.apps, {id: data.appId});
- paragraphAppState.output = app.output;
+ let paragraphAppState = _.find(paragraph.apps, {id: data.appId})
+ paragraphAppState.output = app.output
- var targetEl = angular.element(document.getElementById('p' + app.id));
- targetEl.html(app.output);
- $compile(targetEl.contents())(getAppScope(app));
- console.log('append app output');
+ let targetEl = angular.element(document.getElementById('p' + app.id))
+ targetEl.html(app.output)
+ $compile(targetEl.contents())(getAppScope(app))
+ console.log('append app output')
}
}
- });
+ })
- $scope.$on('appLoad', function(event, data) {
+ $scope.$on('appLoad', function (event, data) {
if (paragraph.id === data.paragraphId) {
- var app = _.find($scope.apps, {id: data.appId});
+ let app = _.find($scope.apps, {id: data.appId})
if (!app) {
app = {
id: data.appId,
pkg: data.pkg,
status: 'UNLOADED',
output: ''
- };
+ }
- $scope.apps.push(app);
- paragraph.apps.push(app);
- $scope.switchApp(app.id);
+ $scope.apps.push(app)
+ paragraph.apps.push(app)
+ $scope.switchApp(app.id)
}
}
- });
+ })
- $scope.$on('appStatusChange', function(event, data) {
+ $scope.$on('appStatusChange', function (event, data) {
if (paragraph.id === data.paragraphId) {
- var app = _.find($scope.apps, {id: data.appId});
+ let app = _.find($scope.apps, {id: data.appId})
if (app) {
- app.status = data.status;
- var paragraphAppState = _.find(paragraph.apps, {id: data.appId});
- paragraphAppState.status = app.status;
+ app.status = data.status
+ let paragraphAppState = _.find(paragraph.apps, {id: data.appId})
+ paragraphAppState.status = app.status
}
}
- });
+ })
- var getAppRegistry = function(appState) {
+ let getAppRegistry = function (appState) {
if (!appState.registry) {
- appState.registry = {};
+ appState.registry = {}
}
- return appState.registry;
- };
+ return appState.registry
+ }
- var getAppScope = function(appState) {
+ const getAppScope = function (appState) {
if (!appState.scope) {
- appState.scope = $rootScope.$new(true, $rootScope);
+ appState.scope = $rootScope.$new(true, $rootScope)
}
- return appState.scope;
- };
+ return appState.scope
+ }
- $scope.$on('angularObjectUpdate', function(event, data) {
- var noteId = $route.current.pathParams.noteId;
+ $scope.$on('angularObjectUpdate', function (event, data) {
+ let noteId = $route.current.pathParams.noteId
if (!data.noteId || data.noteId === noteId) {
- var scope;
- var registry;
+ let scope
+ let registry
- var app = _.find($scope.apps, {id: data.paragraphId});
+ let app = _.find($scope.apps, {id: data.paragraphId})
if (app) {
- scope = getAppScope(app);
- registry = getAppRegistry(app);
+ scope = getAppScope(app)
+ registry = getAppRegistry(app)
} else {
// no matching app in this paragraph
- return;
+ return
}
- var varName = data.angularObject.name;
+ let varName = data.angularObject.name
if (angular.equals(data.angularObject.object, scope[varName])) {
// return when update has no change
- return;
+ return
}
if (!registry[varName]) {
@@ -937,76 +934,78 @@ function ResultCtrl($scope, $rootScope, $route, $window, $routeParams, $location
interpreterGroupId: data.interpreterGroupId,
noteId: data.noteId,
paragraphId: data.paragraphId
- };
+ }
} else {
- registry[varName].noteId = registry[varName].noteId || data.noteId;
- registry[varName].paragraphId = registry[varName].paragraphId || data.paragraphId;
+ registry[varName].noteId = registry[varName].noteId || data.noteId
+ registry[varName].paragraphId = registry[varName].paragraphId || data.paragraphId
}
- registry[varName].skipEmit = true;
+ registry[varName].skipEmit = true
if (!registry[varName].clearWatcher) {
- registry[varName].clearWatcher = scope.$watch(varName, function(newValue, oldValue) {
- console.log('angular object (paragraph) updated %o %o', varName, registry[varName]);
+ registry[varName].clearWatcher = scope.$watch(varName, function (newValue, oldValue) {
+ console.log('angular object (paragraph) updated %o %o', varName, registry[varName])
if (registry[varName].skipEmit) {
- registry[varName].skipEmit = false;
- return;
+ registry[varName].skipEmit = false
+ return
}
websocketMsgSrv.updateAngularObject(
registry[varName].noteId,
registry[varName].paragraphId,
varName,
newValue,
- registry[varName].interpreterGroupId);
- });
+ registry[varName].interpreterGroupId)
+ })
}
- console.log('angular object (paragraph) created %o', varName);
- scope[varName] = data.angularObject.object;
+ console.log('angular object (paragraph) created %o', varName)
+ scope[varName] = data.angularObject.object
// create proxy for AngularFunction
if (varName.indexOf(ANGULAR_FUNCTION_OBJECT_NAME_PREFIX) === 0) {
- var funcName = varName.substring((ANGULAR_FUNCTION_OBJECT_NAME_PREFIX).length);
- scope[funcName] = function() {
- scope[varName] = arguments;
- console.log('angular function (paragraph) invoked %o', arguments);
- };
+ let funcName = varName.substring((ANGULAR_FUNCTION_OBJECT_NAME_PREFIX).length)
+ scope[funcName] = function () {
+ // eslint-disable-next-line prefer-rest-params
+ scope[varName] = arguments
+ // eslint-disable-next-line prefer-rest-params
+ console.log('angular function (paragraph) invoked %o', arguments)
+ }
- console.log('angular function (paragraph) created %o', scope[funcName]);
+ console.log('angular function (paragraph) created %o', scope[funcName])
}
}
- });
+ })
- $scope.$on('angularObjectRemove', function(event, data) {
- var noteId = $route.current.pathParams.noteId;
+ $scope.$on('angularObjectRemove', function (event, data) {
+ let noteId = $route.current.pathParams.noteId
if (!data.noteId || data.noteId === noteId) {
- var scope;
- var registry;
+ let scope
+ let registry
- var app = _.find($scope.apps, {id: data.paragraphId});
+ let app = _.find($scope.apps, {id: data.paragraphId})
if (app) {
- scope = getAppScope(app);
- registry = getAppRegistry(app);
+ scope = getAppScope(app)
+ registry = getAppRegistry(app)
} else {
// no matching app in this paragraph
- return;
+ return
}
- var varName = data.name;
+ let varName = data.name
// clear watcher
if (registry[varName]) {
- registry[varName].clearWatcher();
- registry[varName] = undefined;
+ registry[varName].clearWatcher()
+ registry[varName] = undefined
}
// remove scope variable
- scope[varName] = undefined;
+ scope[varName] = undefined
// remove proxy for AngularFunction
if (varName.indexOf(ANGULAR_FUNCTION_OBJECT_NAME_PREFIX) === 0) {
- var funcName = varName.substring((ANGULAR_FUNCTION_OBJECT_NAME_PREFIX).length);
- scope[funcName] = undefined;
+ let funcName = varName.substring((ANGULAR_FUNCTION_OBJECT_NAME_PREFIX).length)
+ scope[funcName] = undefined
}
}
- });
+ })
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/notebookRepos/notebookRepos.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/notebookRepos/notebookRepos.controller.js b/zeppelin-web/src/app/notebookRepos/notebookRepos.controller.js
index 14357fd..2e35338 100644
--- a/zeppelin-web/src/app/notebookRepos/notebookRepos.controller.js
+++ b/zeppelin-web/src/app/notebookRepos/notebookRepos.controller.js
@@ -12,77 +12,76 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('NotebookReposCtrl', NotebookReposCtrl);
+angular.module('zeppelinWebApp').controller('NotebookReposCtrl', NotebookReposCtrl)
-function NotebookReposCtrl($http, baseUrlSrv, ngToast) {
- 'ngInject';
+function NotebookReposCtrl ($http, baseUrlSrv, ngToast) {
+ 'ngInject'
- var vm = this;
- vm.notebookRepos = [];
- vm.showDropdownSelected = showDropdownSelected;
- vm.saveNotebookRepo = saveNotebookRepo;
+ let vm = this
+ vm.notebookRepos = []
+ vm.showDropdownSelected = showDropdownSelected
+ vm.saveNotebookRepo = saveNotebookRepo
- _init();
+ _init()
// Public functions
- function saveNotebookRepo(valueform, repo, data) {
- console.log('data %o', data);
+ function saveNotebookRepo (valueform, repo, data) {
+ console.log('data %o', data)
$http.put(baseUrlSrv.getRestApiBase() + '/notebook-repositories', {
'name': repo.className,
'settings': data
- }).success(function(data) {
- var index = _.findIndex(vm.notebookRepos, {'className': repo.className});
+ }).success(function (data) {
+ let index = _.findIndex(vm.notebookRepos, {'className': repo.className})
if (index >= 0) {
- vm.notebookRepos[index] = data.body;
- console.log('repos %o, data %o', vm.notebookRepos, data.body);
+ vm.notebookRepos[index] = data.body
+ console.log('repos %o, data %o', vm.notebookRepos, data.body)
}
- valueform.$show();
- }).error(function() {
+ valueform.$show()
+ }).error(function () {
ngToast.danger({
content: 'We couldn\'t save that NotebookRepo\'s settings',
verticalPosition: 'bottom',
timeout: '3000'
- });
- valueform.$show();
- });
+ })
+ valueform.$show()
+ })
- return 'manual';
+ return 'manual'
}
- function showDropdownSelected(setting) {
- var index = _.findIndex(setting.value, {'value': setting.selected});
+ function showDropdownSelected (setting) {
+ let index = _.findIndex(setting.value, {'value': setting.selected})
if (index < 0) {
- return 'No value';
+ return 'No value'
} else {
- return setting.value[index].name;
+ return setting.value[index].name
}
}
// Private functions
- function _getInterpreterSettings() {
+ function _getInterpreterSettings () {
$http.get(baseUrlSrv.getRestApiBase() + '/notebook-repositories')
- .success(function(data, status, headers, config) {
- vm.notebookRepos = data.body;
- console.log('ya notebookRepos %o', vm.notebookRepos);
- }).error(function(data, status, headers, config) {
- if (status === 401) {
- ngToast.danger({
- content: 'You don\'t have permission on this page',
- verticalPosition: 'bottom',
- timeout: '3000'
- });
- setTimeout(function() {
- window.location.replace('/');
- }, 3000);
- }
- console.log('Error %o %o', status, data.message);
- });
+ .success(function (data, status, headers, config) {
+ vm.notebookRepos = data.body
+ console.log('ya notebookRepos %o', vm.notebookRepos)
+ }).error(function (data, status, headers, config) {
+ if (status === 401) {
+ ngToast.danger({
+ content: 'You don\'t have permission on this page',
+ verticalPosition: 'bottom',
+ timeout: '3000'
+ })
+ setTimeout(function () {
+ window.location.replace('/')
+ }, 3000)
+ }
+ console.log('Error %o %o', status, data.message)
+ })
}
- function _init() {
- _getInterpreterSettings();
- };
+ function _init () {
+ _getInterpreterSettings()
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/search/result-list.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/search/result-list.controller.js b/zeppelin-web/src/app/search/result-list.controller.js
index f3ceb6a..cd7542d 100644
--- a/zeppelin-web/src/app/search/result-list.controller.js
+++ b/zeppelin-web/src/app/search/result-list.controller.js
@@ -12,108 +12,107 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('SearchResultCtrl', SearchResultCtrl);
+angular.module('zeppelinWebApp').controller('SearchResultCtrl', SearchResultCtrl)
-function SearchResultCtrl($scope, $routeParams, searchService) {
- 'ngInject';
+function SearchResultCtrl ($scope, $routeParams, searchService) {
+ 'ngInject'
- $scope.isResult = true ;
- $scope.searchTerm = $routeParams.searchTerm;
- var results = searchService.search({'q': $routeParams.searchTerm}).query();
+ $scope.isResult = true
+ $scope.searchTerm = $routeParams.searchTerm
+ let results = searchService.search({'q': $routeParams.searchTerm}).query()
- results.$promise.then(function(result) {
- $scope.notes = result.body.map(function(note) {
+ results.$promise.then(function (result) {
+ $scope.notes = result.body.map(function (note) {
// redirect to notebook when search result is a notebook itself,
// not a paragraph
if (!/\/paragraph\//.test(note.id)) {
- return note;
+ return note
}
note.id = note.id.replace('paragraph/', '?paragraph=') +
- '&term=' + $routeParams.searchTerm;
+ '&term=' + $routeParams.searchTerm
- return note;
- });
+ return note
+ })
if ($scope.notes.length === 0) {
- $scope.isResult = false;
+ $scope.isResult = false
} else {
- $scope.isResult = true;
+ $scope.isResult = true
}
- $scope.$on('$routeChangeStart', function(event, next, current) {
+ $scope.$on('$routeChangeStart', function (event, next, current) {
if (next.originalPath !== '/search/:searchTerm') {
- searchService.searchTerm = '';
+ searchService.searchTerm = ''
}
- });
- });
+ })
+ })
- $scope.page = 0;
- $scope.allResults = false;
+ $scope.page = 0
+ $scope.allResults = false
- $scope.highlightSearchResults = function(note) {
- return function(_editor) {
- function getEditorMode(text) {
- var editorModes = {
+ $scope.highlightSearchResults = function (note) {
+ return function (_editor) {
+ function getEditorMode (text) {
+ let editorModes = {
'ace/mode/scala': /^%(\w*\.)?spark/,
'ace/mode/python': /^%(\w*\.)?(pyspark|python)/,
'ace/mode/r': /^%(\w*\.)?(r|sparkr|knitr)/,
'ace/mode/sql': /^%(\w*\.)?\wql/,
'ace/mode/markdown': /^%md/,
'ace/mode/sh': /^%sh/
- };
+ }
- return Object.keys(editorModes).reduce(function(res, mode) {
- return editorModes[mode].test(text) ? mode : res;
- }, 'ace/mode/scala');
+ return Object.keys(editorModes).reduce(function (res, mode) {
+ return editorModes[mode].test(text) ? mode : res
+ }, 'ace/mode/scala')
}
- var Range = ace.require('ace/range').Range;
+ let Range = ace.require('ace/range').Range
- _editor.setOption('highlightActiveLine', false);
- _editor.$blockScrolling = Infinity;
- _editor.setReadOnly(true);
- _editor.renderer.setShowGutter(false);
- _editor.setTheme('ace/theme/chrome');
- _editor.getSession().setMode(getEditorMode(note.text));
+ _editor.setOption('highlightActiveLine', false)
+ _editor.$blockScrolling = Infinity
+ _editor.setReadOnly(true)
+ _editor.renderer.setShowGutter(false)
+ _editor.setTheme('ace/theme/chrome')
+ _editor.getSession().setMode(getEditorMode(note.text))
- function getIndeces(term) {
- return function(str) {
- var indeces = [];
- var i = -1;
+ function getIndeces (term) {
+ return function (str) {
+ let indeces = []
+ let i = -1
while ((i = str.indexOf(term, i + 1)) >= 0) {
- indeces.push(i);
+ indeces.push(i)
}
- return indeces;
- };
+ return indeces
+ }
}
- var result = '';
+ let result = ''
if (note.header !== '') {
- result = note.header + '\n\n' + note.snippet;
+ result = note.header + '\n\n' + note.snippet
} else {
- result = note.snippet;
+ result = note.snippet
}
- var lines = result
+ let lines = result
.split('\n')
- .map(function(line, row) {
-
- var match = line.match(/<B>(.+?)<\/B>/);
+ .map(function (line, row) {
+ let match = line.match(/<B>(.+?)<\/B>/)
// return early if nothing to highlight
if (!match) {
- return line;
+ return line
}
- var term = match[1];
- var __line = line
+ let term = match[1]
+ let __line = line
.replace(/<B>/g, '')
- .replace(/<\/B>/g, '');
+ .replace(/<\/B>/g, '')
- var indeces = getIndeces(term)(__line);
+ let indeces = getIndeces(term)(__line)
- indeces.forEach(function(start) {
- var end = start + term.length;
+ indeces.forEach(function (start) {
+ let end = start + term.length
if (note.header !== '' && row === 0) {
_editor
.getSession()
@@ -121,14 +120,14 @@ function SearchResultCtrl($scope, $routeParams, searchService) {
new Range(row, 0, row, line.length),
'search-results-highlight-header',
'background'
- );
+ )
_editor
.getSession()
.addMarker(
new Range(row, start, row, end),
'search-results-highlight',
'line'
- );
+ )
} else {
_editor
.getSession()
@@ -136,21 +135,19 @@ function SearchResultCtrl($scope, $routeParams, searchService) {
new Range(row, start, row, end),
'search-results-highlight',
'line'
- );
+ )
}
- });
- return __line;
- });
+ })
+ return __line
+ })
// resize editor based on content length
_editor.setOption(
'maxLines',
- lines.reduce(function(len, line) {return len + line.length;}, 0)
- );
-
- _editor.getSession().setValue(lines.join('\n'));
+ lines.reduce(function (len, line) { return len + line.length }, 0)
+ )
- };
- };
+ _editor.getSession().setValue(lines.join('\n'))
+ }
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/spell/index.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/spell/index.js b/zeppelin-web/src/app/spell/index.js
index 8ec4753..ac4343c 100644
--- a/zeppelin-web/src/app/spell/index.js
+++ b/zeppelin-web/src/app/spell/index.js
@@ -18,8 +18,8 @@
export {
DefaultDisplayType,
SpellResult,
-} from './spell-result';
+} from './spell-result'
export {
SpellBase,
-} from './spell-base';
+} from './spell-base'
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/spell/spell-base.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/spell/spell-base.js b/zeppelin-web/src/app/spell/spell-base.js
index 6dcb576..0b4216f 100644
--- a/zeppelin-web/src/app/spell/spell-base.js
+++ b/zeppelin-web/src/app/spell/spell-base.js
@@ -15,16 +15,16 @@
* limitations under the License.
*/
-/*eslint-disable no-unused-vars */
+/* eslint-disable no-unused-vars */
import {
DefaultDisplayType,
SpellResult,
-} from './spell-result';
-/*eslint-enable no-unused-vars */
+} from './spell-result'
+/* eslint-enable no-unused-vars */
export class SpellBase {
- constructor(magic) {
- this.magic = magic;
+ constructor (magic) {
+ this.magic = magic
}
/**
@@ -34,8 +34,8 @@ export class SpellBase {
* @param config {Object}
* @return {SpellResult}
*/
- interpret(paragraphText, config) {
- throw new Error('SpellBase.interpret() should be overrided');
+ interpret (paragraphText, config) {
+ throw new Error('SpellBase.interpret() should be overrided')
}
/**
@@ -43,7 +43,7 @@ export class SpellBase {
* (e.g `%flowchart`)
* @return {string}
*/
- getMagic() {
- return this.magic;
+ getMagic () {
+ return this.magic
}
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/spell/spell-result.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/spell/spell-result.js b/zeppelin-web/src/app/spell/spell-result.js
index d62e97a..e8e2a0a 100644
--- a/zeppelin-web/src/app/spell/spell-result.js
+++ b/zeppelin-web/src/app/spell/spell-result.js
@@ -21,7 +21,7 @@ export const DefaultDisplayType = {
HTML: 'HTML',
ANGULAR: 'ANGULAR',
TEXT: 'TEXT',
-};
+}
export const DefaultDisplayMagic = {
'%element': DefaultDisplayType.ELEMENT,
@@ -29,12 +29,12 @@ export const DefaultDisplayMagic = {
'%html': DefaultDisplayType.HTML,
'%angular': DefaultDisplayType.ANGULAR,
'%text': DefaultDisplayType.TEXT,
-};
+}
export class DataWithType {
- constructor(data, type, magic, text) {
- this.data = data;
- this.type = type;
+ constructor (data, type, magic, text) {
+ this.data = data
+ this.type = type
/**
* keep for `DefaultDisplayType.ELEMENT` (function data type)
@@ -44,29 +44,29 @@ export class DataWithType {
* since they don't have context where they are created.
*/
- this.magic = magic;
- this.text = text;
+ this.magic = magic
+ this.text = text
}
- static handleDefaultMagic(m) {
+ static handleDefaultMagic (m) {
// let's use default display type instead of magic in case of default
// to keep consistency with backend interpreter
if (DefaultDisplayMagic[m]) {
- return DefaultDisplayMagic[m];
+ return DefaultDisplayMagic[m]
} else {
- return m;
+ return m
}
}
- static createPropagable(dataWithType) {
+ static createPropagable (dataWithType) {
if (!SpellResult.isFunction(dataWithType.data)) {
- return dataWithType;
+ return dataWithType
}
- const data = dataWithType.getText();
- const type = dataWithType.getMagic();
+ const data = dataWithType.getText()
+ const type = dataWithType.getMagic()
- return new DataWithType(data, type);
+ return new DataWithType(data, type)
}
/**
@@ -75,45 +75,45 @@ export class DataWithType {
* @param customDisplayType
* @return {Array<DataWithType>}
*/
- static parseStringData(data, customDisplayMagic) {
- function availableMagic(magic) {
- return magic && (DefaultDisplayMagic[magic] || customDisplayMagic[magic]);
+ static parseStringData (data, customDisplayMagic) {
+ function availableMagic (magic) {
+ return magic && (DefaultDisplayMagic[magic] || customDisplayMagic[magic])
}
- const splited = data.split('\n');
+ const splited = data.split('\n')
- const gensWithTypes = [];
- let mergedGens = [];
- let previousMagic = DefaultDisplayType.TEXT;
+ const gensWithTypes = []
+ let mergedGens = []
+ let previousMagic = DefaultDisplayType.TEXT
// create `DataWithType` whenever see available display type.
- for(let i = 0; i < splited.length; i++) {
- const g = splited[i];
- const magic = SpellResult.extractMagic(g);
+ for (let i = 0; i < splited.length; i++) {
+ const g = splited[i]
+ const magic = SpellResult.extractMagic(g)
// create `DataWithType` only if see new magic
if (availableMagic(magic) && mergedGens.length > 0) {
- gensWithTypes.push(new DataWithType(mergedGens.join(''), previousMagic));
- mergedGens = [];
+ gensWithTypes.push(new DataWithType(mergedGens.join(''), previousMagic))
+ mergedGens = []
}
// accumulate `data` to mergedGens
if (availableMagic(magic)) {
- const withoutMagic = g.split(magic)[1];
- mergedGens.push(`${withoutMagic}\n`);
- previousMagic = DataWithType.handleDefaultMagic(magic);
+ const withoutMagic = g.split(magic)[1]
+ mergedGens.push(`${withoutMagic}\n`)
+ previousMagic = DataWithType.handleDefaultMagic(magic)
} else {
- mergedGens.push(`${g}\n`);
+ mergedGens.push(`${g}\n`)
}
}
// cleanup the last `DataWithType`
if (mergedGens.length > 0) {
- previousMagic = DataWithType.handleDefaultMagic(previousMagic);
- gensWithTypes.push(new DataWithType(mergedGens.join(''), previousMagic));
+ previousMagic = DataWithType.handleDefaultMagic(previousMagic)
+ gensWithTypes.push(new DataWithType(mergedGens.join(''), previousMagic))
}
- return gensWithTypes;
+ return gensWithTypes
}
/**
@@ -126,45 +126,44 @@ export class DataWithType {
* @param textWithoutMagic
* @return {Promise<Array<DataWithType>>}
*/
- static produceMultipleData(dataWithType, customDisplayType,
+ static produceMultipleData (dataWithType, customDisplayType,
magic, textWithoutMagic) {
- const data = dataWithType.getData();
- const type = dataWithType.getType();
+ const data = dataWithType.getData()
+ const type = dataWithType.getType()
// if the type is specified, just return it
// handle non-specified dataWithTypes only
if (type) {
- return new Promise((resolve) => { resolve([dataWithType]); });
+ return new Promise((resolve) => { resolve([dataWithType]) })
}
- let wrapped;
+ let wrapped
if (SpellResult.isFunction(data)) {
// if data is a function, we consider it as ELEMENT type.
wrapped = new Promise((resolve) => {
const dt = new DataWithType(
- data, DefaultDisplayType.ELEMENT, magic, textWithoutMagic);
- const result = [dt];
- return resolve(result);
- });
+ data, DefaultDisplayType.ELEMENT, magic, textWithoutMagic)
+ const result = [dt]
+ return resolve(result)
+ })
} else if (SpellResult.isPromise(data)) {
// if data is a promise,
wrapped = data.then(generated => {
const result =
- DataWithType.parseStringData(generated, customDisplayType);
- return result;
+ DataWithType.parseStringData(generated, customDisplayType)
+ return result
})
-
} else {
// if data is a object, parse it to multiples
wrapped = new Promise((resolve) => {
const result =
- DataWithType.parseStringData(data, customDisplayType);
- return resolve(result);
- });
+ DataWithType.parseStringData(data, customDisplayType)
+ return resolve(result)
+ })
}
- return wrapped;
+ return wrapped
}
/**
@@ -176,8 +175,8 @@ export class DataWithType {
* will be called in `then()` of this promise.
* @returns {*} `data` which can be object, function or promise.
*/
- getData() {
- return this.data;
+ getData () {
+ return this.data
}
/**
@@ -186,66 +185,66 @@ export class DataWithType {
* by `SpellResult.parseStringData()`
* @returns {string}
*/
- getType() {
- return this.type;
+ getType () {
+ return this.type
}
- getMagic() {
- return this.magic;
+ getMagic () {
+ return this.magic
}
- getText() {
- return this.text;
+ getText () {
+ return this.text
}
}
export class SpellResult {
- constructor(resultData, resultType) {
- this.dataWithTypes = [];
- this.add(resultData, resultType);
+ constructor (resultData, resultType) {
+ this.dataWithTypes = []
+ this.add(resultData, resultType)
}
- static isFunction(data) {
- return (data && typeof data === 'function');
+ static isFunction (data) {
+ return (data && typeof data === 'function')
}
- static isPromise(data) {
- return (data && typeof data.then === 'function');
+ static isPromise (data) {
+ return (data && typeof data.then === 'function')
}
- static isObject(data) {
+ static isObject (data) {
return (data &&
!SpellResult.isFunction(data) &&
- !SpellResult.isPromise(data));
+ !SpellResult.isPromise(data))
}
- static extractMagic(allParagraphText) {
- const pattern = /^\s*%(\S+)\s*/g;
+ static extractMagic (allParagraphText) {
+ const pattern = /^\s*%(\S+)\s*/g
try {
- let match = pattern.exec(allParagraphText);
+ let match = pattern.exec(allParagraphText)
if (match) {
- return `%${match[1].trim()}`;
+ return `%${match[1].trim()}`
}
} catch (error) {
// failed to parse, ignore
}
- return undefined;
+ return undefined
}
- static createPropagable(resultMsg) {
+ static createPropagable (resultMsg) {
return resultMsg.map(dt => {
- return DataWithType.createPropagable(dt);
+ return DataWithType.createPropagable(dt)
})
}
- add(resultData, resultType) {
+ add (resultData, resultType) {
if (resultData) {
this.dataWithTypes.push(
- new DataWithType(resultData, resultType));
+ new DataWithType(resultData, resultType))
}
- return this;
+ return this
}
/**
@@ -253,23 +252,23 @@ export class SpellResult {
* @param textWithoutMagic
* @return {Promise<Array<DataWithType>>}
*/
- getAllParsedDataWithTypes(customDisplayType, magic, textWithoutMagic) {
+ getAllParsedDataWithTypes (customDisplayType, magic, textWithoutMagic) {
const promises = this.dataWithTypes.map(dt => {
return DataWithType.produceMultipleData(
- dt, customDisplayType, magic, textWithoutMagic);
- });
+ dt, customDisplayType, magic, textWithoutMagic)
+ })
// some promises can include an array so we need to flatten them
const flatten = Promise.all(promises).then(values => {
return values.reduce((acc, cur) => {
if (Array.isArray(cur)) {
- return acc.concat(cur);
+ return acc.concat(cur)
} else {
- return acc.concat([cur]);
+ return acc.concat([cur])
}
})
- });
+ })
- return flatten;
+ return flatten
}
}
[2/8] zeppelin git commit: [ZEPPELIN-1940] lint rule set is NOT
applied at all.
Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/visualization/builtins/visualization-nvd3chart.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/visualization/builtins/visualization-nvd3chart.js b/zeppelin-web/src/app/visualization/builtins/visualization-nvd3chart.js
index 930e435..f99fa3d 100644
--- a/zeppelin-web/src/app/visualization/builtins/visualization-nvd3chart.js
+++ b/zeppelin-web/src/app/visualization/builtins/visualization-nvd3chart.js
@@ -12,233 +12,232 @@
* limitations under the License.
*/
-import Visualization from '../visualization';
+import Visualization from '../visualization'
/**
* Visualize data in table format
*/
export default class Nvd3ChartVisualization extends Visualization {
- constructor(targetEl, config) {
- super(targetEl, config);
- this.targetEl.append('<svg></svg>');
- };
+ constructor (targetEl, config) {
+ super(targetEl, config)
+ this.targetEl.append('<svg></svg>')
+ }
- refresh() {
+ refresh () {
if (this.chart) {
- this.chart.update();
+ this.chart.update()
}
- };
+ }
- render(data) {
- var type = this.type();
- var d3g = data.d3g;
+ render (data) {
+ let type = this.type()
+ let d3g = data.d3g
if (!this.chart) {
- this.chart = nv.models[type]();
+ this.chart = nv.models[type]()
}
- this.configureChart(this.chart);
+ this.configureChart(this.chart)
- var animationDuration = 300;
- var numberOfDataThreshold = 150;
- var height = this.targetEl.height();
+ let animationDuration = 300
+ let numberOfDataThreshold = 150
+ let height = this.targetEl.height()
// turn off animation when dataset is too large. (for performance issue)
// still, since dataset is large, the chart content sequentially appears like animated
try {
if (d3g[0].values.length > numberOfDataThreshold) {
- animationDuration = 0;
+ animationDuration = 0
}
- } catch (ignoreErr) {
- }
+ } catch (err) { /** ignore */ }
d3.select('#' + this.targetEl[0].id + ' svg')
.attr('height', height)
.datum(d3g)
.transition()
.duration(animationDuration)
- .call(this.chart);
- d3.select('#' + this.targetEl[0].id + ' svg').style.height = height + 'px';
- };
+ .call(this.chart)
+ d3.select('#' + this.targetEl[0].id + ' svg').style.height = height + 'px'
+ }
- type() {
+ type () {
// override this and return chart type
- };
+ }
- configureChart(chart) {
+ configureChart (chart) {
// override this to configure chart
- };
+ }
- groupedThousandsWith3DigitsFormatter(x) {
- return d3.format(',')(d3.round(x, 3));
- };
+ groupedThousandsWith3DigitsFormatter (x) {
+ return d3.format(',')(d3.round(x, 3))
+ }
- customAbbrevFormatter(x) {
- var s = d3.format('.3s')(x);
+ customAbbrevFormatter (x) {
+ let s = d3.format('.3s')(x)
switch (s[s.length - 1]) {
- case 'G': return s.slice(0, -1) + 'B';
+ case 'G': return s.slice(0, -1) + 'B'
}
- return s;
- };
+ return s
+ }
- defaultY() {
- return 0;
- };
+ defaultY () {
+ return 0
+ }
- xAxisTickFormat(d, xLabels) {
+ xAxisTickFormat (d, xLabels) {
if (xLabels[d] && (isNaN(parseFloat(xLabels[d])) || !isFinite(xLabels[d]))) { // to handle string type xlabel
- return xLabels[d];
+ return xLabels[d]
} else {
- return d;
+ return d
}
- };
+ }
- yAxisTickFormat(d) {
- if (Math.abs(d) >= Math.pow(10,6)) {
- return this.customAbbrevFormatter(d);
+ yAxisTickFormat (d) {
+ if (Math.abs(d) >= Math.pow(10, 6)) {
+ return this.customAbbrevFormatter(d)
}
- return this.groupedThousandsWith3DigitsFormatter(d);
- };
+ return this.groupedThousandsWith3DigitsFormatter(d)
+ }
- d3DataFromPivot(
+ d3DataFromPivot (
schema, rows, keys, groups, values, allowTextXAxis, fillMissingValues, multiBarChart) {
- var self = this;
+ let self = this
// construct table data
- var d3g = [];
+ let d3g = []
- var concat = function(o, n) {
+ let concat = function (o, n) {
if (!o) {
- return n;
+ return n
} else {
- return o + '.' + n;
+ return o + '.' + n
}
- };
+ }
- var getSchemaUnderKey = function(key, s) {
- for (var c in key.children) {
- s[c] = {};
- getSchemaUnderKey(key.children[c], s[c]);
+ const getSchemaUnderKey = function (key, s) {
+ for (let c in key.children) {
+ s[c] = {}
+ getSchemaUnderKey(key.children[c], s[c])
}
- };
+ }
- var traverse = function(sKey, s, rKey, r, func, rowName, rowValue, colName) {
- //console.log("TRAVERSE sKey=%o, s=%o, rKey=%o, r=%o, rowName=%o, rowValue=%o, colName=%o", sKey, s, rKey, r, rowName, rowValue, colName);
+ const traverse = function (sKey, s, rKey, r, func, rowName, rowValue, colName) {
+ // console.log("TRAVERSE sKey=%o, s=%o, rKey=%o, r=%o, rowName=%o, rowValue=%o, colName=%o", sKey, s, rKey, r, rowName, rowValue, colName);
if (s.type === 'key') {
- rowName = concat(rowName, sKey);
- rowValue = concat(rowValue, rKey);
+ rowName = concat(rowName, sKey)
+ rowValue = concat(rowValue, rKey)
} else if (s.type === 'group') {
- colName = concat(colName, rKey);
+ colName = concat(colName, rKey)
} else if (s.type === 'value' && sKey === rKey || valueOnly) {
- colName = concat(colName, rKey);
- func(rowName, rowValue, colName, r);
+ colName = concat(colName, rKey)
+ func(rowName, rowValue, colName, r)
}
- for (var c in s.children) {
+ for (let c in s.children) {
if (fillMissingValues && s.children[c].type === 'group' && r[c] === undefined) {
- var cs = {};
- getSchemaUnderKey(s.children[c], cs);
- traverse(c, s.children[c], c, cs, func, rowName, rowValue, colName);
- continue;
+ let cs = {}
+ getSchemaUnderKey(s.children[c], cs)
+ traverse(c, s.children[c], c, cs, func, rowName, rowValue, colName)
+ continue
}
- for (var j in r) {
+ for (let j in r) {
if (s.children[c].type === 'key' || c === j) {
- traverse(c, s.children[c], j, r[j], func, rowName, rowValue, colName);
+ traverse(c, s.children[c], j, r[j], func, rowName, rowValue, colName)
}
}
}
- };
+ }
- var valueOnly = (keys.length === 0 && groups.length === 0 && values.length > 0);
- var noKey = (keys.length === 0);
- var isMultiBarChart = multiBarChart;
+ const valueOnly = (keys.length === 0 && groups.length === 0 && values.length > 0)
+ let noKey = (keys.length === 0)
+ let isMultiBarChart = multiBarChart
- var sKey = Object.keys(schema)[0];
+ let sKey = Object.keys(schema)[0]
- var rowNameIndex = {};
- var rowIdx = 0;
- var colNameIndex = {};
- var colIdx = 0;
- var rowIndexValue = {};
+ let rowNameIndex = {}
+ let rowIdx = 0
+ let colNameIndex = {}
+ let colIdx = 0
+ let rowIndexValue = {}
- for (var k in rows) {
- traverse(sKey, schema[sKey], k, rows[k], function(rowName, rowValue, colName, value) {
- //console.log("RowName=%o, row=%o, col=%o, value=%o", rowName, rowValue, colName, value);
+ for (let k in rows) {
+ traverse(sKey, schema[sKey], k, rows[k], function (rowName, rowValue, colName, value) {
+ // console.log("RowName=%o, row=%o, col=%o, value=%o", rowName, rowValue, colName, value);
if (rowNameIndex[rowValue] === undefined) {
- rowIndexValue[rowIdx] = rowValue;
- rowNameIndex[rowValue] = rowIdx++;
+ rowIndexValue[rowIdx] = rowValue
+ rowNameIndex[rowValue] = rowIdx++
}
if (colNameIndex[colName] === undefined) {
- colNameIndex[colName] = colIdx++;
+ colNameIndex[colName] = colIdx++
}
- var i = colNameIndex[colName];
+ let i = colNameIndex[colName]
if (noKey && isMultiBarChart) {
- i = 0;
+ i = 0
}
if (!d3g[i]) {
d3g[i] = {
values: [],
key: (noKey && isMultiBarChart) ? 'values' : colName
- };
+ }
}
- var xVar = isNaN(rowValue) ? ((allowTextXAxis) ? rowValue : rowNameIndex[rowValue]) : parseFloat(rowValue);
- var yVar = self.defaultY();
- if (xVar === undefined) { xVar = colName; }
+ let xVar = isNaN(rowValue) ? ((allowTextXAxis) ? rowValue : rowNameIndex[rowValue]) : parseFloat(rowValue)
+ let yVar = self.defaultY()
+ if (xVar === undefined) { xVar = colName }
if (value !== undefined) {
- yVar = isNaN(value.value) ? self.defaultY() : parseFloat(value.value) / parseFloat(value.count);
+ yVar = isNaN(value.value) ? self.defaultY() : parseFloat(value.value) / parseFloat(value.count)
}
d3g[i].values.push({
x: xVar,
y: yVar
- });
- });
+ })
+ })
}
// clear aggregation name, if possible
- var namesWithoutAggr = {};
- var colName;
- var withoutAggr;
+ let namesWithoutAggr = {}
+ let colName
+ let withoutAggr
// TODO - This part could use som refactoring - Weird if/else with similar actions and variable names
for (colName in colNameIndex) {
- withoutAggr = colName.substring(0, colName.lastIndexOf('('));
+ withoutAggr = colName.substring(0, colName.lastIndexOf('('))
if (!namesWithoutAggr[withoutAggr]) {
- namesWithoutAggr[withoutAggr] = 1;
+ namesWithoutAggr[withoutAggr] = 1
} else {
- namesWithoutAggr[withoutAggr]++;
+ namesWithoutAggr[withoutAggr]++
}
}
if (valueOnly) {
- for (var valueIndex = 0; valueIndex < d3g[0].values.length; valueIndex++) {
- colName = d3g[0].values[valueIndex].x;
+ for (let valueIndex = 0; valueIndex < d3g[0].values.length; valueIndex++) {
+ colName = d3g[0].values[valueIndex].x
if (!colName) {
- continue;
+ continue
}
- withoutAggr = colName.substring(0, colName.lastIndexOf('('));
+ withoutAggr = colName.substring(0, colName.lastIndexOf('('))
if (namesWithoutAggr[withoutAggr] <= 1) {
- d3g[0].values[valueIndex].x = withoutAggr;
+ d3g[0].values[valueIndex].x = withoutAggr
}
}
} else {
- for (var d3gIndex = 0; d3gIndex < d3g.length; d3gIndex++) {
- colName = d3g[d3gIndex].key;
- withoutAggr = colName.substring(0, colName.lastIndexOf('('));
+ for (let d3gIndex = 0; d3gIndex < d3g.length; d3gIndex++) {
+ colName = d3g[d3gIndex].key
+ withoutAggr = colName.substring(0, colName.lastIndexOf('('))
if (namesWithoutAggr[withoutAggr] <= 1) {
- d3g[d3gIndex].key = withoutAggr;
+ d3g[d3gIndex].key = withoutAggr
}
}
// use group name instead of group.value as a column name, if there're only one group and one value selected.
if (groups.length === 1 && values.length === 1) {
- for (d3gIndex = 0; d3gIndex < d3g.length; d3gIndex++) {
- colName = d3g[d3gIndex].key;
- colName = colName.split('.').slice(0, -1).join('.');
- d3g[d3gIndex].key = colName;
+ for (let d3gIndex = 0; d3gIndex < d3g.length; d3gIndex++) {
+ colName = d3g[d3gIndex].key
+ colName = colName.split('.').slice(0, -1).join('.')
+ d3g[d3gIndex].key = colName
}
}
}
@@ -246,17 +245,17 @@ export default class Nvd3ChartVisualization extends Visualization {
return {
xLabels: rowIndexValue,
d3g: d3g
- };
- };
+ }
+ }
/**
* method will be invoked when visualization need to be destroyed.
* Don't need to destroy this.targetEl.
*/
- destroy() {
+ destroy () {
if (this.chart) {
- d3.selectAll('#' + this.targetEl[0].id + ' svg > *').remove();
- this.chart = undefined;
+ d3.selectAll('#' + this.targetEl[0].id + ' svg > *').remove()
+ this.chart = undefined
}
- };
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/visualization/builtins/visualization-piechart.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/visualization/builtins/visualization-piechart.js b/zeppelin-web/src/app/visualization/builtins/visualization-piechart.js
index f74ecd0..4f80654 100644
--- a/zeppelin-web/src/app/visualization/builtins/visualization-piechart.js
+++ b/zeppelin-web/src/app/visualization/builtins/visualization-piechart.js
@@ -12,29 +12,29 @@
* limitations under the License.
*/
-import Nvd3ChartVisualization from './visualization-nvd3chart';
-import PivotTransformation from '../../tabledata/pivot';
+import Nvd3ChartVisualization from './visualization-nvd3chart'
+import PivotTransformation from '../../tabledata/pivot'
/**
* Visualize data in pie chart
*/
export default class PiechartVisualization extends Nvd3ChartVisualization {
- constructor(targetEl, config) {
- super(targetEl, config);
- this.pivot = new PivotTransformation(config);
- };
+ constructor (targetEl, config) {
+ super(targetEl, config)
+ this.pivot = new PivotTransformation(config)
+ }
- type() {
- return 'pieChart';
- };
+ type () {
+ return 'pieChart'
+ }
- getTransformation() {
- return this.pivot;
- };
+ getTransformation () {
+ return this.pivot
+ }
- render(pivot) {
+ render (pivot) {
// [ZEPPELIN-2253] New chart function will be created each time inside super.render()
- this.chart = null;
+ this.chart = null
const d3Data = this.d3DataFromPivot(
pivot.schema,
pivot.rows,
@@ -43,41 +43,41 @@ export default class PiechartVisualization extends Nvd3ChartVisualization {
pivot.values,
true,
false,
- false);
- const d = d3Data.d3g;
+ false)
+ const d = d3Data.d3g
- let generateLabel;
+ let generateLabel
// data is grouped
if (pivot.groups && pivot.groups.length > 0) {
- generateLabel = (suffix, prefix) => `${prefix}.${suffix}`;
+ generateLabel = (suffix, prefix) => `${prefix}.${suffix}`
} else { // data isn't grouped
- generateLabel = suffix => suffix;
+ generateLabel = suffix => suffix
}
let d3g = d.map(group => {
return group.values.map(row => ({
label: generateLabel(row.x, group.key),
value: row.y
- }));
- });
+ }))
+ })
// the map function returns d3g as a nested array
// [].concat flattens it, http://stackoverflow.com/a/10865042/5154397
- d3g = [].concat.apply([], d3g);
- super.render({d3g: d3g});
- };
+ d3g = [].concat.apply([], d3g) // eslint-disable-line prefer-spread
+ super.render({d3g: d3g})
+ }
/**
* Set new config
*/
- setConfig(config) {
- super.setConfig(config);
- this.pivot.setConfig(config);
- };
+ setConfig (config) {
+ super.setConfig(config)
+ this.pivot.setConfig(config)
+ }
- configureChart(chart) {
- chart.x(function(d) { return d.label;})
- .y(function(d) { return d.value;})
- .showLabels(false)
- .showTooltipPercent(true);
- };
+ configureChart (chart) {
+ chart.x(function (d) { return d.label })
+ .y(function (d) { return d.value })
+ .showLabels(false)
+ .showTooltipPercent(true)
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/visualization/builtins/visualization-scatterchart.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/visualization/builtins/visualization-scatterchart.js b/zeppelin-web/src/app/visualization/builtins/visualization-scatterchart.js
index 6161b3c..2c8ba3e 100644
--- a/zeppelin-web/src/app/visualization/builtins/visualization-scatterchart.js
+++ b/zeppelin-web/src/app/visualization/builtins/visualization-scatterchart.js
@@ -12,15 +12,15 @@
* limitations under the License.
*/
-import Nvd3ChartVisualization from './visualization-nvd3chart';
-import ColumnselectorTransformation from '../../tabledata/columnselector';
+import Nvd3ChartVisualization from './visualization-nvd3chart'
+import ColumnselectorTransformation from '../../tabledata/columnselector'
/**
* Visualize data in scatter char
*/
export default class ScatterchartVisualization extends Nvd3ChartVisualization {
- constructor(targetEl, config) {
- super(targetEl, config);
+ constructor (targetEl, config) {
+ super(targetEl, config)
this.columnselectorProps = [
{
@@ -41,198 +41,196 @@ export default class ScatterchartVisualization extends Nvd3ChartVisualization {
or the number of distinct values are bigger than 5% of total number of values.</li>
<li>Size field button turns to grey when the option you chose is not valid.</li>`
}
- ];
- this.columnselector = new ColumnselectorTransformation(config, this.columnselectorProps);
- };
-
- type() {
- return 'scatterChart';
- };
-
- getTransformation() {
- return this.columnselector;
- };
-
- render(tableData) {
- this.tableData = tableData;
- this.selectDefault();
- var d3Data = this.setScatterChart(tableData, true);
- this.xLabels = d3Data.xLabels;
- this.yLabels = d3Data.yLabels;
-
- super.render(d3Data);
- };
-
- configureChart(chart) {
- var self = this;
-
- chart.xAxis.tickFormat(function(d) { // TODO remove round after bump to nvd3 > 1.8.5
- return self.xAxisTickFormat(Math.round(d * 1e3)/1e3, self.xLabels);
- });
-
- chart.yAxis.tickFormat(function(d) { // TODO remove round after bump to nvd3 > 1.8.5
- return self.yAxisTickFormat(Math.round(d * 1e3)/1e3, self.yLabels);
- });
-
- chart.showDistX(true).showDistY(true);
- //handle the problem of tooltip not showing when muliple points have same value.
- };
-
- yAxisTickFormat(d, yLabels){
- if (yLabels[d] && (isNaN(parseFloat(yLabels[d])) || !isFinite(yLabels[d]))) { // to handle string type xlabel
- return yLabels[d];
- } else {
- return super.yAxisTickFormat(d);
- }
- }
-
- selectDefault() {
+ ]
+ this.columnselector = new ColumnselectorTransformation(config, this.columnselectorProps)
+ }
+
+ type () {
+ return 'scatterChart'
+ }
+
+ getTransformation () {
+ return this.columnselector
+ }
+
+ render (tableData) {
+ this.tableData = tableData
+ this.selectDefault()
+ let d3Data = this.setScatterChart(tableData, true)
+ this.xLabels = d3Data.xLabels
+ this.yLabels = d3Data.yLabels
+
+ super.render(d3Data)
+ }
+
+ configureChart (chart) {
+ let self = this
+
+ chart.xAxis.tickFormat(function (d) { // TODO remove round after bump to nvd3 > 1.8.5
+ return self.xAxisTickFormat(Math.round(d * 1e3) / 1e3, self.xLabels)
+ })
+
+ chart.yAxis.tickFormat(function (d) { // TODO remove round after bump to nvd3 > 1.8.5
+ return self.yAxisTickFormat(Math.round(d * 1e3) / 1e3, self.yLabels)
+ })
+
+ chart.showDistX(true).showDistY(true)
+ // handle the problem of tooltip not showing when muliple points have same value.
+ }
+
+ yAxisTickFormat (d, yLabels) {
+ if (yLabels[d] && (isNaN(parseFloat(yLabels[d])) || !isFinite(yLabels[d]))) { // to handle string type xlabel
+ return yLabels[d]
+ } else {
+ return super.yAxisTickFormat(d)
+ }
+ }
+
+ selectDefault () {
if (!this.config.xAxis && !this.config.yAxis) {
if (this.tableData.columns.length > 1) {
- this.config.xAxis = this.tableData.columns[0];
- this.config.yAxis = this.tableData.columns[1];
+ this.config.xAxis = this.tableData.columns[0]
+ this.config.yAxis = this.tableData.columns[1]
} else if (this.tableData.columns.length === 1) {
- this.config.xAxis = this.tableData.columns[0];
+ this.config.xAxis = this.tableData.columns[0]
}
}
- };
-
- setScatterChart(data, refresh) {
- var xAxis = this.config.xAxis;
- var yAxis = this.config.yAxis;
- var group = this.config.group;
- var size = this.config.size;
-
- var xValues = [];
- var yValues = [];
- var rows = {};
- var d3g = [];
-
- var rowNameIndex = {};
- var colNameIndex = {};
- var grpNameIndex = {};
- var rowIndexValue = {};
- var colIndexValue = {};
- var grpIndexValue = {};
- var rowIdx = 0;
- var colIdx = 0;
- var grpIdx = 0;
- var grpName = '';
-
- var xValue;
- var yValue;
- var row;
+ }
+
+ setScatterChart (data, refresh) {
+ let xAxis = this.config.xAxis
+ let yAxis = this.config.yAxis
+ let group = this.config.group
+ let size = this.config.size
+
+ let xValues = []
+ let yValues = []
+ let rows = {}
+ let d3g = []
+
+ let rowNameIndex = {}
+ let colNameIndex = {}
+ let grpNameIndex = {}
+ let rowIndexValue = {}
+ let colIndexValue = {}
+ let grpIndexValue = {}
+ let rowIdx = 0
+ let colIdx = 0
+ let grpIdx = 0
+ let grpName = ''
+
+ let xValue
+ let yValue
+ let row
if (!xAxis && !yAxis) {
return {
d3g: []
- };
+ }
}
-
-
-
- for (var i = 0; i < data.rows.length; i++) {
- row = data.rows[i];
+ for (let i = 0; i < data.rows.length; i++) {
+ row = data.rows[i]
if (xAxis) {
- xValue = row[xAxis.index];
- xValues[i] = xValue;
+ xValue = row[xAxis.index]
+ xValues[i] = xValue
}
if (yAxis) {
- yValue = row[yAxis.index];
- yValues[i] = yValue;
+ yValue = row[yAxis.index]
+ yValues[i] = yValue
}
}
- var isAllDiscrete = ((xAxis && yAxis && this.isDiscrete(xValues) && this.isDiscrete(yValues)) ||
+ let isAllDiscrete = ((xAxis && yAxis && this.isDiscrete(xValues) && this.isDiscrete(yValues)) ||
(!xAxis && this.isDiscrete(yValues)) ||
- (!yAxis && this.isDiscrete(xValues)));
+ (!yAxis && this.isDiscrete(xValues)))
if (isAllDiscrete) {
- rows = this.setDiscreteScatterData(data);
+ rows = this.setDiscreteScatterData(data)
} else {
- rows = data.rows;
+ rows = data.rows
}
if (!group && isAllDiscrete) {
- grpName = 'count';
+ grpName = 'count'
} else if (!group && !size) {
if (xAxis && yAxis) {
- grpName = '(' + xAxis.name + ', ' + yAxis.name + ')';
+ grpName = '(' + xAxis.name + ', ' + yAxis.name + ')'
} else if (xAxis && !yAxis) {
- grpName = xAxis.name;
+ grpName = xAxis.name
} else if (!xAxis && yAxis) {
- grpName = yAxis.name;
+ grpName = yAxis.name
}
} else if (!group && size) {
- grpName = size.name;
+ grpName = size.name
}
- var epsilon = 1e-4; // TODO remove after bump to nvd3 > 1.8.5
+ let epsilon = 1e-4 // TODO remove after bump to nvd3 > 1.8.5
- for (i = 0; i < rows.length; i++) {
- row = rows[i];
+ for (let i = 0; i < rows.length; i++) {
+ row = rows[i]
if (xAxis) {
- xValue = row[xAxis.index];
+ xValue = row[xAxis.index]
}
if (yAxis) {
- yValue = row[yAxis.index];
+ yValue = row[yAxis.index]
}
if (group) {
- grpName = row[group.index];
+ grpName = row[group.index]
}
- var sz = (isAllDiscrete) ? row[row.length - 1] : ((size) ? row[size.index] : 1);
+ let sz = (isAllDiscrete) ? row[row.length - 1] : ((size) ? row[size.index] : 1)
if (grpNameIndex[grpName] === undefined) {
- grpIndexValue[grpIdx] = grpName;
- grpNameIndex[grpName] = grpIdx++;
+ grpIndexValue[grpIdx] = grpName
+ grpNameIndex[grpName] = grpIdx++
}
if (xAxis && rowNameIndex[xValue] === undefined) {
- rowIndexValue[rowIdx] = xValue;
- rowNameIndex[xValue] = rowIdx++;
+ rowIndexValue[rowIdx] = xValue
+ rowNameIndex[xValue] = rowIdx++
}
if (yAxis && colNameIndex[yValue] === undefined) {
- colIndexValue[colIdx] = yValue;
- colNameIndex[yValue] = colIdx++;
+ colIndexValue[colIdx] = yValue
+ colNameIndex[yValue] = colIdx++
}
if (!d3g[grpNameIndex[grpName]]) {
d3g[grpNameIndex[grpName]] = {
key: grpName,
values: []
- };
+ }
}
-
// TODO remove epsilon jitter after bump to nvd3 > 1.8.5
- var xval, yval = 0;
- if ( xAxis ){
- xval = (isNaN(xValue) ? rowNameIndex[xValue] : parseFloat(xValue)) + Math.random() * epsilon;
+ let xval = 0
+ let yval = 0
+ if (xAxis) {
+ xval = (isNaN(xValue) ? rowNameIndex[xValue] : parseFloat(xValue)) + Math.random() * epsilon
}
- if ( yAxis ){
- yval = (isNaN(yValue) ? colNameIndex[yValue] : parseFloat(yValue)) + Math.random() * epsilon;
+ if (yAxis) {
+ yval = (isNaN(yValue) ? colNameIndex[yValue] : parseFloat(yValue)) + Math.random() * epsilon
}
d3g[grpNameIndex[grpName]].values.push({
x: xval,
y: yval,
size: isNaN(parseFloat(sz)) ? 1 : parseFloat(sz)
- });
+ })
}
// TODO remove sort and dedup after bump to nvd3 > 1.8.5
- var d3gvalues = d3g[grpNameIndex[grpName]].values;
- d3gvalues.sort(function(a,b){
- return ((a['x'] - b['x']) || (a['y'] - b['y']))});
-
- for (var i = 0; i < d3gvalues.length - 1; ){
- if ( (Math.abs(d3gvalues[i]['x'] - d3gvalues[i+1]['x']) < epsilon) &&
- (Math.abs(d3gvalues[i]['y'] - d3gvalues[i+1]['y']) < epsilon) ){
- d3gvalues.splice(i+1,1);
- } else{
- i++;
+ let d3gvalues = d3g[grpNameIndex[grpName]].values
+ d3gvalues.sort(function (a, b) {
+ return ((a['x'] - b['x']) || (a['y'] - b['y']))
+ })
+
+ for (let i = 0; i < d3gvalues.length - 1;) {
+ if ((Math.abs(d3gvalues[i]['x'] - d3gvalues[i + 1]['x']) < epsilon) &&
+ (Math.abs(d3gvalues[i]['y'] - d3gvalues[i + 1]['y']) < epsilon)) {
+ d3gvalues.splice(i + 1, 1)
+ } else {
+ i++
}
}
@@ -240,33 +238,33 @@ export default class ScatterchartVisualization extends Nvd3ChartVisualization {
xLabels: rowIndexValue,
yLabels: colIndexValue,
d3g: d3g
- };
- };
+ }
+ }
- setDiscreteScatterData(data) {
- var xAxis = this.config.xAxis;
- var yAxis = this.config.yAxis;
- var group = this.config.group;
+ setDiscreteScatterData (data) {
+ let xAxis = this.config.xAxis
+ let yAxis = this.config.yAxis
+ let group = this.config.group
- var xValue;
- var yValue;
- var grp;
+ let xValue
+ let yValue
+ let grp
- var rows = {};
+ let rows = {}
- for (var i = 0; i < data.rows.length; i++) {
- var row = data.rows[i];
+ for (let i = 0; i < data.rows.length; i++) {
+ let row = data.rows[i]
if (xAxis) {
- xValue = row[xAxis.index];
+ xValue = row[xAxis.index]
}
if (yAxis) {
- yValue = row[yAxis.index];
+ yValue = row[yAxis.index]
}
if (group) {
- grp = row[group.index];
+ grp = row[group.index]
}
- var key = xValue + ',' + yValue + ',' + grp;
+ let key = xValue + ',' + yValue + ',' + grp
if (!rows[key]) {
rows[key] = {
@@ -274,89 +272,89 @@ export default class ScatterchartVisualization extends Nvd3ChartVisualization {
y: yValue,
group: grp,
size: 1
- };
+ }
} else {
- rows[key].size++;
+ rows[key].size++
}
}
// change object into array
- var newRows = [];
- for (var r in rows) {
- var newRow = [];
- if (xAxis) { newRow[xAxis.index] = rows[r].x; }
- if (yAxis) { newRow[yAxis.index] = rows[r].y; }
- if (group) { newRow[group.index] = rows[r].group; }
- newRow[data.rows[0].length] = rows[r].size;
- newRows.push(newRow);
+ let newRows = []
+ for (let r in rows) {
+ let newRow = []
+ if (xAxis) { newRow[xAxis.index] = rows[r].x }
+ if (yAxis) { newRow[yAxis.index] = rows[r].y }
+ if (group) { newRow[group.index] = rows[r].group }
+ newRow[data.rows[0].length] = rows[r].size
+ newRows.push(newRow)
}
- return newRows;
- };
-
- isDiscrete(field) {
- var getUnique = function(f) {
- var uniqObj = {};
- var uniqArr = [];
- var j = 0;
- for (var i = 0; i < f.length; i++) {
- var item = f[i];
+ return newRows
+ }
+
+ isDiscrete (field) {
+ let getUnique = function (f) {
+ let uniqObj = {}
+ let uniqArr = []
+ let j = 0
+ for (let i = 0; i < f.length; i++) {
+ let item = f[i]
if (uniqObj[item] !== 1) {
- uniqObj[item] = 1;
- uniqArr[j++] = item;
+ uniqObj[item] = 1
+ uniqArr[j++] = item
}
}
- return uniqArr;
- };
+ return uniqArr
+ }
- for (var i = 0; i < field.length; i++) {
+ for (let i = 0; i < field.length; i++) {
if (isNaN(parseFloat(field[i])) &&
(typeof field[i] === 'string' || field[i] instanceof String)) {
- return true;
+ return true
}
}
- var threshold = 0.05;
- var unique = getUnique(field);
+ let threshold = 0.05
+ let unique = getUnique(field)
if (unique.length / field.length < threshold) {
- return true;
+ return true
} else {
- return false;
+ return false
}
- };
+ }
- isValidSizeOption(options) {
- var xValues = [];
- var yValues = [];
- var rows = this.tableData.rows;
+ isValidSizeOption (options) {
+ let xValues = []
+ let yValues = []
+ let rows = this.tableData.rows
- for (var i = 0; i < rows.length; i++) {
- var row = rows[i];
- var size = row[options.size.index];
+ for (let i = 0; i < rows.length; i++) {
+ let row = rows[i]
+ let size = row[options.size.index]
- //check if the field is numeric
+ // check if the field is numeric
if (isNaN(parseFloat(size)) || !isFinite(size)) {
- return false;
+ return false
}
if (options.xAxis) {
- var x = row[options.xAxis.index];
- xValues[i] = x;
+ let x = row[options.xAxis.index]
+ xValues[i] = x
}
if (options.yAxis) {
- var y = row[options.yAxis.index];
- yValues[i] = y;
+ let y = row[options.yAxis.index]
+ yValues[i] = y
}
}
- //check if all existing fields are discrete
- var isAllDiscrete = ((options.xAxis && options.yAxis && this.isDiscrete(xValues) && this.isDiscrete(yValues)) ||
+ // check if all existing fields are discrete
+ let isAllDiscrete = ((options.xAxis && options.yAxis && this.isDiscrete(xValues) && this.isDiscrete(yValues)) ||
(!options.xAxis && this.isDiscrete(yValues)) ||
- (!options.yAxis && this.isDiscrete(xValues)));
+ (!options.yAxis && this.isDiscrete(xValues)))
if (isAllDiscrete) {
- return false;
+ return false
}
- return true;
- };
+ return true
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/visualization/builtins/visualization-table.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/visualization/builtins/visualization-table.js b/zeppelin-web/src/app/visualization/builtins/visualization-table.js
index 0c58407..3192ee6 100644
--- a/zeppelin-web/src/app/visualization/builtins/visualization-table.js
+++ b/zeppelin-web/src/app/visualization/builtins/visualization-table.js
@@ -12,51 +12,52 @@
* limitations under the License.
*/
-import Visualization from '../visualization';
-import PassthroughTransformation from '../../tabledata/passthrough';
-import HandsonHelper from '../../handsontable/handsonHelper';
+import Visualization from '../visualization'
+import PassthroughTransformation from '../../tabledata/passthrough'
+import HandsonHelper from '../../handsontable/handsonHelper'
/**
* Visualize data in table format
*/
export default class TableVisualization extends Visualization {
- constructor(targetEl, config) {
- super(targetEl, config);
- console.log('Init table viz');
- targetEl.addClass('table');
- this.passthrough = new PassthroughTransformation(config);
- };
-
- refresh() {
- this.hot.render();
- };
-
- render(tableData) {
- var height = this.targetEl.height();
- var container = this.targetEl.css('height', height).get(0);
- var resultRows = tableData.rows;
- var columnNames = _.pluck(tableData.columns, 'name');
- var columns = Array.apply(null, Array(tableData.columns.length)).map(function() {
- return {type: 'text'};
- });
+ constructor (targetEl, config) {
+ super(targetEl, config)
+ console.log('Init table viz')
+ targetEl.addClass('table')
+ this.passthrough = new PassthroughTransformation(config)
+ }
+
+ refresh () {
+ this.hot.render()
+ }
+
+ render (tableData) {
+ let height = this.targetEl.height()
+ let container = this.targetEl.css('height', height).get(0)
+ let resultRows = tableData.rows
+ let columnNames = _.pluck(tableData.columns, 'name')
+ // eslint-disable-next-line prefer-spread
+ let columns = Array.apply(null, Array(tableData.columns.length)).map(function () {
+ return {type: 'text'}
+ })
if (this.hot) {
- this.hot.destroy();
+ this.hot.destroy()
}
- var handsonHelper = new HandsonHelper();
+ let handsonHelper = new HandsonHelper()
this.hot = new Handsontable(container, handsonHelper.getHandsonTableConfig(
- columns, columnNames, resultRows));
- this.hot.validateCells(null);
- };
+ columns, columnNames, resultRows))
+ this.hot.validateCells(null)
+ }
- destroy() {
+ destroy () {
if (this.hot) {
- this.hot.destroy();
+ this.hot.destroy()
}
- };
+ }
- getTransformation() {
- return this.passthrough;
- };
+ getTransformation () {
+ return this.passthrough
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/visualization/visualization.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/visualization/visualization.js b/zeppelin-web/src/app/visualization/visualization.js
index ec7ce96..ec89882 100644
--- a/zeppelin-web/src/app/visualization/visualization.js
+++ b/zeppelin-web/src/app/visualization/visualization.js
@@ -16,42 +16,42 @@
* Base class for visualization
*/
export default class Visualization {
- constructor(targetEl, config) {
- this.targetEl = targetEl;
- this.config = config;
- this._dirty = false;
- this._active = false;
- this._emitter;
- };
+ constructor (targetEl, config) {
+ this.targetEl = targetEl
+ this.config = config
+ this._dirty = false
+ this._active = false
+ this._emitter = () => {}
+ }
/**
* get transformation
*/
- getTransformation() {
+ getTransformation () {
// override this
- };
+ }
/**
* Method will be invoked when data or configuration changed
*/
- render(tableData) {
+ render (tableData) {
// override this
- };
+ }
/**
* Refresh visualization.
*/
- refresh() {
+ refresh () {
// override this
- };
+ }
/**
* method will be invoked when visualization need to be destroyed.
* Don't need to destroy this.targetEl.
*/
- destroy() {
+ destroy () {
// override this
- };
+ }
/**
* return {
@@ -59,113 +59,113 @@ export default class Visualization {
* scope : an object to bind to template scope
* }
*/
- getSetting() {
+ getSetting () {
// override this
- };
+ }
/**
* Activate. invoked when visualization is selected
*/
- activate() {
+ activate () {
if (!this._active || this._dirty) {
- this.refresh();
- this._dirty = false;
+ this.refresh()
+ this._dirty = false
}
- this._active = true;
- };
+ this._active = true
+ }
/**
* Activate. invoked when visualization is de selected
*/
- deactivate() {
- this._active = false;
- };
+ deactivate () {
+ this._active = false
+ }
/**
* Is active
*/
- isActive() {
- return this._active;
- };
+ isActive () {
+ return this._active
+ }
/**
* When window or paragraph is resized
*/
- resize() {
+ resize () {
if (this.isActive()) {
- this.refresh();
+ this.refresh()
} else {
- this._dirty = true;
+ this._dirty = true
}
- };
+ }
/**
* Set new config
*/
- setConfig(config) {
- this.config = config;
+ setConfig (config) {
+ this.config = config
if (this.isActive()) {
- this.refresh();
+ this.refresh()
} else {
- this._dirty = true;
+ this._dirty = true
}
- };
+ }
/**
* Emit config. config will sent to server and saved.
*/
- emitConfig(config) {
- this._emitter(config);
- };
+ emitConfig (config) {
+ this._emitter(config)
+ }
/**
* render setting
*/
- renderSetting(targetEl) {
- var setting = this.getSetting();
+ renderSetting (targetEl) {
+ let setting = this.getSetting()
if (!setting) {
- return;
+ return
}
// already readered
if (this._scope) {
- var self = this;
- this._scope.$apply(function() {
- for (var k in setting.scope) {
- self._scope[k] = setting.scope[k];
+ let self = this
+ this._scope.$apply(function () {
+ for (let k in setting.scope) {
+ self._scope[k] = setting.scope[k]
}
- for (var k in self._prevSettingScope) {
+ for (let k in self._prevSettingScope) {
if (!setting.scope[k]) {
- self._scope[k] = setting.scope[k];
+ self._scope[k] = setting.scope[k]
}
}
- });
- return;
+ })
+ return
} else {
- this._prevSettingScope = setting.scope;
+ this._prevSettingScope = setting.scope
}
- var scope = this._createNewScope();
- for (var k in setting.scope) {
- scope[k] = setting.scope[k];
+ let scope = this._createNewScope()
+ for (let k in setting.scope) {
+ scope[k] = setting.scope[k]
}
- var template = setting.template;
+ let template = setting.template
if (template.split('\n').length === 1 &&
template.endsWith('.html')) { // template is url
this._templateRequest(template).then(t =>
_renderSetting(this, targetEl, t, scope)
- );
+ )
} else {
- _renderSetting(this, targetEl, template, scope);
+ _renderSetting(this, targetEl, template, scope)
}
- };
+ }
}
-function _renderSetting(instance, targetEl, template, scope) {
- instance._targetEl = targetEl;
- targetEl.html(template);
- instance._compile(targetEl.contents())(scope);
- instance._scope = scope;
-};
+function _renderSetting (instance, targetEl, template, scope) {
+ instance._targetEl = targetEl
+ targetEl.html(template)
+ instance._compile(targetEl.contents())(scope)
+ instance._scope = scope
+}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/arrayOrderingSrv/arrayOrdering.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/arrayOrderingSrv/arrayOrdering.service.js b/zeppelin-web/src/components/arrayOrderingSrv/arrayOrdering.service.js
index 70d9f6a..6e2fe33 100644
--- a/zeppelin-web/src/components/arrayOrderingSrv/arrayOrdering.service.js
+++ b/zeppelin-web/src/components/arrayOrderingSrv/arrayOrdering.service.js
@@ -12,26 +12,25 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').service('arrayOrderingSrv', arrayOrderingSrv);
+angular.module('zeppelinWebApp').service('arrayOrderingSrv', arrayOrderingSrv)
-function arrayOrderingSrv(TRASH_FOLDER_ID) {
- 'ngInject';
+function arrayOrderingSrv (TRASH_FOLDER_ID) {
+ 'ngInject'
- var arrayOrderingSrv = this;
+ let arrayOrderingSrv = this
- this.noteListOrdering = function(note) {
+ this.noteListOrdering = function (note) {
if (note.id === TRASH_FOLDER_ID) {
- return '\uFFFF';
+ return '\uFFFF'
}
- return arrayOrderingSrv.getNoteName(note);
- };
+ return arrayOrderingSrv.getNoteName(note)
+ }
- this.getNoteName = function(note) {
+ this.getNoteName = function (note) {
if (note.name === undefined || note.name.trim() === '') {
- return 'Note ' + note.id;
+ return 'Note ' + note.id
} else {
- return note.name;
+ return note.name
}
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/baseUrl/baseUrl.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/baseUrl/baseUrl.service.js b/zeppelin-web/src/components/baseUrl/baseUrl.service.js
index 4ad1eab..fb2ecfb 100644
--- a/zeppelin-web/src/components/baseUrl/baseUrl.service.js
+++ b/zeppelin-web/src/components/baseUrl/baseUrl.service.js
@@ -12,38 +12,37 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').service('baseUrlSrv', baseUrlSrv);
+angular.module('zeppelinWebApp').service('baseUrlSrv', baseUrlSrv)
-function baseUrlSrv() {
- this.getPort = function() {
- var port = Number(location.port);
+function baseUrlSrv () {
+ this.getPort = function () {
+ let port = Number(location.port)
if (!port) {
- port = 80;
+ port = 80
if (location.protocol === 'https:') {
- port = 443;
+ port = 443
}
}
- //Exception for when running locally via grunt
+ // Exception for when running locally via grunt
if (port === process.env.WEB_PORT) {
- port = process.env.SERVER_PORT;
+ port = process.env.SERVER_PORT
}
- return port;
- };
+ return port
+ }
- this.getWebsocketUrl = function() {
- var wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
+ this.getWebsocketUrl = function () {
+ let wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
return wsProtocol + '//' + location.hostname + ':' + this.getPort() +
- skipTrailingSlash(location.pathname) + '/ws';
- };
+ skipTrailingSlash(location.pathname) + '/ws'
+ }
- this.getRestApiBase = function() {
+ this.getRestApiBase = function () {
return location.protocol + '//' + location.hostname + ':' +
this.getPort() + skipTrailingSlash(location.pathname) +
- '/api';
- };
+ '/api'
+ }
- var skipTrailingSlash = function(path) {
- return path.replace(/\/$/, '');
- };
+ const skipTrailingSlash = function (path) {
+ return path.replace(/\/$/, '')
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/browser-detect/browserDetect.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/browser-detect/browserDetect.service.js b/zeppelin-web/src/components/browser-detect/browserDetect.service.js
index 2fda717..2223d5f 100644
--- a/zeppelin-web/src/components/browser-detect/browserDetect.service.js
+++ b/zeppelin-web/src/components/browser-detect/browserDetect.service.js
@@ -12,29 +12,28 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').service('browserDetectService', browserDetectService);
+angular.module('zeppelinWebApp').service('browserDetectService', browserDetectService)
-function browserDetectService() {
- this.detectIE = function() {
- var ua = window.navigator.userAgent;
- var msie = ua.indexOf('MSIE ');
+function browserDetectService () {
+ this.detectIE = function () {
+ let ua = window.navigator.userAgent
+ let msie = ua.indexOf('MSIE ')
if (msie > 0) {
// IE 10 or older => return version number
- return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
+ return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10)
}
- var trident = ua.indexOf('Trident/');
+ let trident = ua.indexOf('Trident/')
if (trident > 0) {
// IE 11 => return version number
- var rv = ua.indexOf('rv:');
- return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
+ let rv = ua.indexOf('rv:')
+ return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10)
}
- var edge = ua.indexOf('Edge/');
+ let edge = ua.indexOf('Edge/')
if (edge > 0) {
// IE 12 (aka Edge) => return version number
- return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
+ return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10)
}
// other browser
- return false;
- };
+ return false
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/clipboard/clipboard.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/clipboard/clipboard.controller.js b/zeppelin-web/src/components/clipboard/clipboard.controller.js
index 685f04e..c4a9e42 100644
--- a/zeppelin-web/src/components/clipboard/clipboard.controller.js
+++ b/zeppelin-web/src/components/clipboard/clipboard.controller.js
@@ -11,24 +11,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('clipboardCtrl', clipboardCtrl);
+angular.module('zeppelinWebApp').controller('clipboardCtrl', clipboardCtrl)
-function clipboardCtrl($scope) {
- 'ngInject';
+function clipboardCtrl ($scope) {
+ 'ngInject'
- $scope.complete = function(e) {
- $scope.copied = true;
- $scope.tooltip = 'Copied!';
- setTimeout(function() {
- $scope.tooltip = 'Copy to clipboard';
- }, 400);
- };
- $scope.$watch('input', function() {
- $scope.copied = false;
- $scope.tooltip = 'Copy to clipboard';
- });
- $scope.clipError = function(e) {
- console.log('Error: ' + e.name + ' - ' + e.message);
- $scope.tooltip = 'Not supported browser';
- };
+ $scope.complete = function (e) {
+ $scope.copied = true
+ $scope.tooltip = 'Copied!'
+ setTimeout(function () {
+ $scope.tooltip = 'Copy to clipboard'
+ }, 400)
+ }
+ $scope.$watch('input', function () {
+ $scope.copied = false
+ $scope.tooltip = 'Copy to clipboard'
+ })
+ $scope.clipError = function (e) {
+ console.log('Error: ' + e.name + ' - ' + e.message)
+ $scope.tooltip = 'Not supported browser'
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/dropdowninput/dropdowninput.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/dropdowninput/dropdowninput.directive.js b/zeppelin-web/src/components/dropdowninput/dropdowninput.directive.js
index a690aed..cdc74f3 100644
--- a/zeppelin-web/src/components/dropdowninput/dropdowninput.directive.js
+++ b/zeppelin-web/src/components/dropdowninput/dropdowninput.directive.js
@@ -12,16 +12,15 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('dropdownInput', dropdownInput);
+angular.module('zeppelinWebApp').directive('dropdownInput', dropdownInput)
-function dropdownInput() {
+function dropdownInput () {
return {
restrict: 'A',
- link: function(scope, element) {
- element.bind('click', function(event) {
- event.stopPropagation();
- });
+ link: function (scope, element) {
+ element.bind('click', function (event) {
+ event.stopPropagation()
+ })
}
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/editor/codeEditor.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/editor/codeEditor.directive.js b/zeppelin-web/src/components/editor/codeEditor.directive.js
index 09ef21f..b8e1b6a 100644
--- a/zeppelin-web/src/components/editor/codeEditor.directive.js
+++ b/zeppelin-web/src/components/editor/codeEditor.directive.js
@@ -12,9 +12,9 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('codeEditor', codeEditor);
+angular.module('zeppelinWebApp').directive('codeEditor', codeEditor)
-function codeEditor($templateRequest, $compile) {
+function codeEditor ($templateRequest, $compile) {
return {
restrict: 'AE',
scope: {
@@ -25,15 +25,14 @@ function codeEditor($templateRequest, $compile) {
onLoad: '=onLoad',
revisionView: '=revisionView'
},
- link: function(scope, element, attrs, controller) {
- $templateRequest('components/editor/ace.editor.directive.html').then(function(editorHtml) {
- var editor = angular.element(editorHtml);
- editor.attr('id', scope.paragraphId + '_editor');
- element.append(editor);
- $compile(editor)(scope);
- console.log('codeEditor directive revision view is ' + scope.revisionView);
- });
+ link: function (scope, element, attrs, controller) {
+ $templateRequest('components/editor/ace.editor.directive.html').then(function (editorHtml) {
+ let editor = angular.element(editorHtml)
+ editor.attr('id', scope.paragraphId + '_editor')
+ element.append(editor)
+ $compile(editor)(scope)
+ console.log('codeEditor directive revision view is ' + scope.revisionView)
+ })
}
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/elasticInputCtrl/elasticInput.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/elasticInputCtrl/elasticInput.controller.js b/zeppelin-web/src/components/elasticInputCtrl/elasticInput.controller.js
index f56c172..507b2f6 100644
--- a/zeppelin-web/src/components/elasticInputCtrl/elasticInput.controller.js
+++ b/zeppelin-web/src/components/elasticInputCtrl/elasticInput.controller.js
@@ -12,11 +12,10 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('ElasticInputCtrl', ElasticInputCtrl);
+angular.module('zeppelinWebApp').controller('ElasticInputCtrl', ElasticInputCtrl)
-function ElasticInputCtrl() {
- var vm = this;
- vm.showEditor = false;
- vm.value = '';
+function ElasticInputCtrl () {
+ let vm = this
+ vm.showEditor = false
+ vm.value = ''
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/expandCollapse/expandCollapse.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/expandCollapse/expandCollapse.directive.js b/zeppelin-web/src/components/expandCollapse/expandCollapse.directive.js
index 1f73f64..9e28098 100644
--- a/zeppelin-web/src/components/expandCollapse/expandCollapse.directive.js
+++ b/zeppelin-web/src/components/expandCollapse/expandCollapse.directive.js
@@ -12,27 +12,26 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('expandCollapse', expandCollapse);
+angular.module('zeppelinWebApp').directive('expandCollapse', expandCollapse)
-function expandCollapse() {
+function expandCollapse () {
return {
restrict: 'EA',
- link: function(scope, element, attrs) {
- angular.element(element).click(function(event) {
+ link: function (scope, element, attrs) {
+ angular.element(element).click(function (event) {
if (angular.element(element).find('.expandable:visible').length > 1) {
- angular.element(element).find('.expandable:visible').slideUp('slow');
- angular.element(element).find('i.icon-folder-alt').toggleClass('icon-folder icon-folder-alt');
+ angular.element(element).find('.expandable:visible').slideUp('slow')
+ angular.element(element).find('i.icon-folder-alt').toggleClass('icon-folder icon-folder-alt')
} else {
- angular.element(element).find('.expandable').first().slideToggle('200',function() {
+ angular.element(element).find('.expandable').first().slideToggle('200', function () {
// do not toggle trash folder
if (angular.element(element).find('.fa-trash-o').length === 0) {
- angular.element(element).find('i').first().toggleClass('icon-folder icon-folder-alt');
+ angular.element(element).find('i').first().toggleClass('icon-folder icon-folder-alt')
}
- });
+ })
}
- event.stopPropagation();
- });
+ event.stopPropagation()
+ })
}
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/helium/helium-conf.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/helium/helium-conf.js b/zeppelin-web/src/components/helium/helium-conf.js
index a93f6f0..10ca18a 100644
--- a/zeppelin-web/src/components/helium/helium-conf.js
+++ b/zeppelin-web/src/components/helium/helium-conf.js
@@ -16,81 +16,84 @@ export const HeliumConfFieldType = {
NUMBER: 'number',
JSON: 'json',
STRING: 'string',
-};
+}
/**
* @param persisted <Object> including `type`, `description`, `defaultValue` for each conf key
* @param spec <Object> including `value` for each conf key
*/
-export function mergePersistedConfWithSpec(persisted, spec) {
- const confs = [];
+export function mergePersistedConfWithSpec (persisted, spec) {
+ const confs = []
- for(let name in spec) {
- const specField = spec[name];
- const persistedValue = persisted[name];
+ for (let name in spec) {
+ const specField = spec[name]
+ const persistedValue = persisted[name]
- const value = (persistedValue) ? persistedValue : specField.defaultValue;
+ const value = (persistedValue) ? persistedValue : specField.defaultValue
const merged = {
- name: name, type: specField.type, description: specField.description,
- value: value, defaultValue: specField.defaultValue,
- };
+ name: name,
+ type: specField.type,
+ description: specField.description,
+ value: value,
+ defaultValue: specField.defaultValue,
+ }
- confs.push(merged);
+ confs.push(merged)
}
- return confs;
+ return confs
}
-export function createAllPackageConfigs(defaultPackages, persistedConfs) {
- let packageConfs = {};
+export function createAllPackageConfigs (defaultPackages, persistedConfs) {
+ let packageConfs = {}
for (let name in defaultPackages) {
- const pkgSearchResult = defaultPackages[name];
+ const pkgSearchResult = defaultPackages[name]
- const spec = pkgSearchResult.pkg.config;
- if (!spec) { continue; }
+ const spec = pkgSearchResult.pkg.config
+ if (!spec) { continue }
- const artifact = pkgSearchResult.pkg.artifact;
- if (!artifact) { continue; }
+ const artifact = pkgSearchResult.pkg.artifact
+ if (!artifact) { continue }
- let persistedConf = {};
+ let persistedConf = {}
if (persistedConfs[artifact]) {
- persistedConf = persistedConfs[artifact];
+ persistedConf = persistedConfs[artifact]
}
- const confs = mergePersistedConfWithSpec(persistedConf, spec);
- packageConfs[name] = confs;
+ const confs = mergePersistedConfWithSpec(persistedConf, spec)
+ packageConfs[name] = confs
}
- return packageConfs;
+ return packageConfs
}
-export function parseConfigValue(type, stringified) {
- let value = stringified;
+export function parseConfigValue (type, stringified) {
+ let value = stringified
try {
if (HeliumConfFieldType.NUMBER === type) {
- value = parseFloat(stringified);
+ value = parseFloat(stringified)
} else if (HeliumConfFieldType.JSON === type) {
- value = JSON.parse(stringified);
+ value = JSON.parse(stringified)
}
- } catch(error) {
+ } catch (error) {
// return just the stringified one
- console.error(`Failed to parse conf type ${type}, value ${value}`);
+ console.error(`Failed to parse conf type ${type}, value ${value}`)
}
- return value;
+ return value
}
/**
* persist key-value only
* since other info (e.g type, desc) can be provided by default config
*/
-export function createPersistableConfig(currentConfs) {
+export function createPersistableConfig (currentConfs) {
const filtered = currentConfs.reduce((acc, c) => {
- acc[c.name] = parseConfigValue(c.type, c.value);
- return acc;
- }, {});
+ acc[c.name] = parseConfigValue(c.type, c.value)
+ return acc
+ }, {})
- return filtered;
+ return filtered
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/helium/helium-package.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/helium/helium-package.js b/zeppelin-web/src/components/helium/helium-package.js
index 8192a6a..88d191a 100644
--- a/zeppelin-web/src/components/helium/helium-package.js
+++ b/zeppelin-web/src/components/helium/helium-package.js
@@ -12,20 +12,20 @@
* limitations under the License.
*/
-export function createDefaultPackage(pkgSearchResult, sce) {
+export function createDefaultPackage (pkgSearchResult, sce) {
for (let pkgIdx in pkgSearchResult) {
- const pkg = pkgSearchResult[pkgIdx];
- pkg.pkg.icon = sce.trustAsHtml(pkg.pkg.icon);
+ const pkg = pkgSearchResult[pkgIdx]
+ pkg.pkg.icon = sce.trustAsHtml(pkg.pkg.icon)
if (pkg.enabled) {
- pkgSearchResult.splice(pkgIdx, 1);
- return pkg;
+ pkgSearchResult.splice(pkgIdx, 1)
+ return pkg
}
}
// show first available version if package is not enabled
- const result = pkgSearchResult[0];
- pkgSearchResult.splice(0, 1);
- return result;
+ const result = pkgSearchResult[0]
+ pkgSearchResult.splice(0, 1)
+ return result
}
/**
@@ -35,13 +35,13 @@ export function createDefaultPackage(pkgSearchResult, sce) {
* @param sce angular `$sce` object
* @returns {Object} including {name, pkgInfo}
*/
-export function createDefaultPackages(pkgSearchResults, sce) {
- const defaultPackages = {};
+export function createDefaultPackages (pkgSearchResults, sce) {
+ const defaultPackages = {}
// show enabled version if any version of package is enabled
for (let name in pkgSearchResults) {
- const pkgSearchResult = pkgSearchResults[name];
+ const pkgSearchResult = pkgSearchResults[name]
defaultPackages[name] = createDefaultPackage(pkgSearchResult, sce)
}
- return defaultPackages;
+ return defaultPackages
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/helium/helium.service.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/helium/helium.service.js b/zeppelin-web/src/components/helium/helium.service.js
index 34520e1..c26f95b 100644
--- a/zeppelin-web/src/components/helium/helium.service.js
+++ b/zeppelin-web/src/components/helium/helium.service.js
@@ -12,26 +12,26 @@
* limitations under the License.
*/
-import { HeliumType, } from './helium-type';
+import { HeliumType, } from './helium-type'
import {
createAllPackageConfigs,
createPersistableConfig,
mergePersistedConfWithSpec,
-} from './helium-conf';
+} from './helium-conf'
import {
createDefaultPackages,
-} from './helium-package';
+} from './helium-package'
-angular.module('zeppelinWebApp').service('heliumService', heliumService);
+angular.module('zeppelinWebApp').service('heliumService', heliumService)
-export default function heliumService($http, $sce, baseUrlSrv) {
- 'ngInject';
+export default function heliumService ($http, $sce, baseUrlSrv) {
+ 'ngInject'
- let visualizationBundles = [];
+ let visualizationBundles = []
// name `heliumBundles` should be same as `HeliumBundleFactory.HELIUM_BUNDLES_VAR`
- let heliumBundles = [];
+ let heliumBundles = []
// map for `{ magic: interpreter }`
- let spellPerMagic = {};
+ let spellPerMagic = {}
// map for `{ magic: package-name }`
let pkgNamePerMagic = {}
@@ -39,211 +39,211 @@ export default function heliumService($http, $sce, baseUrlSrv) {
* @param magic {string} e.g `%flowchart`
* @returns {SpellBase} undefined if magic is not registered
*/
- this.getSpellByMagic = function(magic) {
- return spellPerMagic[magic];
- };
+ this.getSpellByMagic = function (magic) {
+ return spellPerMagic[magic]
+ }
- this.executeSpell = function(magic, textWithoutMagic) {
+ this.executeSpell = function (magic, textWithoutMagic) {
const promisedConf = this.getSinglePackageConfigUsingMagic(magic)
- .then(confs => createPersistableConfig(confs));
+ .then(confs => createPersistableConfig(confs))
return promisedConf.then(conf => {
- const spell = this.getSpellByMagic(magic);
- const spellResult = spell.interpret(textWithoutMagic, conf);
+ const spell = this.getSpellByMagic(magic)
+ const spellResult = spell.interpret(textWithoutMagic, conf)
const parsed = spellResult.getAllParsedDataWithTypes(
- spellPerMagic, magic, textWithoutMagic);
+ spellPerMagic, magic, textWithoutMagic)
- return parsed;
- });
- };
+ return parsed
+ })
+ }
- this.executeSpellAsDisplaySystem = function(magic, textWithoutMagic) {
+ this.executeSpellAsDisplaySystem = function (magic, textWithoutMagic) {
const promisedConf = this.getSinglePackageConfigUsingMagic(magic)
- .then(confs => createPersistableConfig(confs));
+ .then(confs => createPersistableConfig(confs))
return promisedConf.then(conf => {
- const spell = this.getSpellByMagic(magic);
- const spellResult = spell.interpret(textWithoutMagic.trim(), conf);
- const parsed = spellResult.getAllParsedDataWithTypes(spellPerMagic);
+ const spell = this.getSpellByMagic(magic)
+ const spellResult = spell.interpret(textWithoutMagic.trim(), conf)
+ const parsed = spellResult.getAllParsedDataWithTypes(spellPerMagic)
- return parsed;
- });
- };
+ return parsed
+ })
+ }
- this.getVisualizationBundles = function() {
- return visualizationBundles;
- };
+ this.getVisualizationBundles = function () {
+ return visualizationBundles
+ }
/**
* @returns {Promise} which returns bundleOrder
*/
- this.getVisualizationPackageOrder = function() {
+ this.getVisualizationPackageOrder = function () {
return $http.get(baseUrlSrv.getRestApiBase() + '/helium/order/visualization')
- .then(function(response, status) {
- return response.data.body;
+ .then(function (response, status) {
+ return response.data.body
+ })
+ .catch(function (error) {
+ console.error('Can not get bundle order', error)
})
- .catch(function(error) {
- console.error('Can not get bundle order', error);
- });
- };
+ }
- this.setVisualizationPackageOrder = function(list) {
- return $http.post(baseUrlSrv.getRestApiBase() + '/helium/order/visualization', list);
- };
+ this.setVisualizationPackageOrder = function (list) {
+ return $http.post(baseUrlSrv.getRestApiBase() + '/helium/order/visualization', list)
+ }
- this.enable = function(name, artifact) {
- return $http.post(baseUrlSrv.getRestApiBase() + '/helium/enable/' + name, artifact);
- };
+ this.enable = function (name, artifact) {
+ return $http.post(baseUrlSrv.getRestApiBase() + '/helium/enable/' + name, artifact)
+ }
- this.disable = function(name) {
- return $http.post(baseUrlSrv.getRestApiBase() + '/helium/disable/' + name);
- };
+ this.disable = function (name) {
+ return $http.post(baseUrlSrv.getRestApiBase() + '/helium/disable/' + name)
+ }
- this.saveConfig = function(pkg , defaultPackageConfig, closeConfigPanelCallback) {
+ this.saveConfig = function (pkg, defaultPackageConfig, closeConfigPanelCallback) {
// in case of local package, it will include `/`
- const pkgArtifact = encodeURIComponent(pkg.artifact);
- const pkgName = pkg.name;
- const filtered = createPersistableConfig(defaultPackageConfig);
+ const pkgArtifact = encodeURIComponent(pkg.artifact)
+ const pkgName = pkg.name
+ const filtered = createPersistableConfig(defaultPackageConfig)
- if (!pkgName || !pkgArtifact|| !filtered) {
+ if (!pkgName || !pkgArtifact || !filtered) {
console.error(
- `Can't save config for helium package '${pkgArtifact}'`, filtered);
- return;
+ `Can't save config for helium package '${pkgArtifact}'`, filtered)
+ return
}
- const url = `${baseUrlSrv.getRestApiBase()}/helium/config/${pkgName}/${pkgArtifact}`;
+ const url = `${baseUrlSrv.getRestApiBase()}/helium/config/${pkgName}/${pkgArtifact}`
return $http.post(url, filtered)
.then(() => {
- if (closeConfigPanelCallback) { closeConfigPanelCallback(); }
+ if (closeConfigPanelCallback) { closeConfigPanelCallback() }
}).catch((error) => {
- console.error(`Failed to save config for ${pkgArtifact}`, error);
- });
- };
+ console.error(`Failed to save config for ${pkgArtifact}`, error)
+ })
+ }
/**
* @returns {Promise<Object>} which including {name, Array<package info for artifact>}
*/
- this.getAllPackageInfo = function() {
+ this.getAllPackageInfo = function () {
return $http.get(`${baseUrlSrv.getRestApiBase()}/helium/package`)
- .then(function(response, status) {
- return response.data.body;
+ .then(function (response, status) {
+ return response.data.body
})
- .catch(function(error) {
- console.error('Failed to get all package infos', error);
- });
- };
+ .catch(function (error) {
+ console.error('Failed to get all package infos', error)
+ })
+ }
- this.getAllEnabledPackages = function() {
+ this.getAllEnabledPackages = function () {
return $http.get(`${baseUrlSrv.getRestApiBase()}/helium/enabledPackage`)
- .then(function(response, status) {
- return response.data.body;
+ .then(function (response, status) {
+ return response.data.body
})
- .catch(function(error) {
- console.error('Failed to get all enabled package infos', error);
- });
- };
+ .catch(function (error) {
+ console.error('Failed to get all enabled package infos', error)
+ })
+ }
- this.getSingleBundle = function(pkgName) {
+ this.getSingleBundle = function (pkgName) {
let url = `${baseUrlSrv.getRestApiBase()}/helium/bundle/load/${pkgName}`
if (process.env.HELIUM_BUNDLE_DEV) {
- url = url + '?refresh=true';
+ url = url + '?refresh=true'
}
return $http.get(url)
- .then(function(response, status) {
+ .then(function (response, status) {
const bundle = response.data
if (bundle.substring(0, 'ERROR:'.length) === 'ERROR:') {
- console.error(`Failed to get bundle: ${pkgName}`, bundle);
+ console.error(`Failed to get bundle: ${pkgName}`, bundle)
return '' // empty bundle will be filtered later
}
return bundle
})
- .catch(function(error) {
- console.error(`Failed to get single bundle: ${pkgName}`, error);
- });
+ .catch(function (error) {
+ console.error(`Failed to get single bundle: ${pkgName}`, error)
+ })
}
- this.getDefaultPackages = function() {
+ this.getDefaultPackages = function () {
return this.getAllPackageInfo()
.then(pkgSearchResults => {
- return createDefaultPackages(pkgSearchResults, $sce);
- });
- };
+ return createDefaultPackages(pkgSearchResults, $sce)
+ })
+ }
- this.getAllPackageInfoAndDefaultPackages = function() {
+ this.getAllPackageInfoAndDefaultPackages = function () {
return this.getAllPackageInfo()
.then(pkgSearchResults => {
return {
pkgSearchResults: pkgSearchResults,
defaultPackages: createDefaultPackages(pkgSearchResults, $sce),
- };
- });
- };
+ }
+ })
+ }
/**
* get all package configs.
* @return { Promise<{name, Array<Object>}> }
*/
- this.getAllPackageConfigs = function() {
- const promisedDefaultPackages = this.getDefaultPackages();
+ this.getAllPackageConfigs = function () {
+ const promisedDefaultPackages = this.getDefaultPackages()
const promisedPersistedConfs =
$http.get(`${baseUrlSrv.getRestApiBase()}/helium/config`)
- .then(function(response, status) {
- return response.data.body;
- });
+ .then(function (response, status) {
+ return response.data.body
+ })
return Promise.all([promisedDefaultPackages, promisedPersistedConfs])
.then(values => {
- const defaultPackages = values[0];
- const persistedConfs = values[1];
+ const defaultPackages = values[0]
+ const persistedConfs = values[1]
- return createAllPackageConfigs(defaultPackages, persistedConfs);
+ return createAllPackageConfigs(defaultPackages, persistedConfs)
+ })
+ .catch(function (error) {
+ console.error('Failed to get all package configs', error)
})
- .catch(function(error) {
- console.error('Failed to get all package configs', error);
- });
- };
+ }
/**
* get the package config which is persisted in server.
* @return { Promise<Array<Object>> }
*/
- this.getSinglePackageConfigs = function(pkg) {
- const pkgName = pkg.name;
+ this.getSinglePackageConfigs = function (pkg) {
+ const pkgName = pkg.name
// in case of local package, it will include `/`
- const pkgArtifact = encodeURIComponent(pkg.artifact);
+ const pkgArtifact = encodeURIComponent(pkg.artifact)
if (!pkgName || !pkgArtifact) {
- console.error('Failed to fetch config for\n', pkg);
- return Promise.resolve([]);
+ console.error('Failed to fetch config for\n', pkg)
+ return Promise.resolve([])
}
- const confUrl = `${baseUrlSrv.getRestApiBase()}/helium/config/${pkgName}/${pkgArtifact}`;
+ const confUrl = `${baseUrlSrv.getRestApiBase()}/helium/config/${pkgName}/${pkgArtifact}`
const promisedConf = $http.get(confUrl)
- .then(function(response, status) {
- return response.data.body;
- });
+ .then(function (response, status) {
+ return response.data.body
+ })
return promisedConf.then(({confSpec, confPersisted}) => {
const merged = mergePersistedConfWithSpec(confPersisted, confSpec)
- return merged;
- });
- };
+ return merged
+ })
+ }
- this.getSinglePackageConfigUsingMagic = function(magic) {
- const pkgName = pkgNamePerMagic[magic];
+ this.getSinglePackageConfigUsingMagic = function (magic) {
+ const pkgName = pkgNamePerMagic[magic]
- const confUrl = `${baseUrlSrv.getRestApiBase()}/helium/spell/config/${pkgName}`;
+ const confUrl = `${baseUrlSrv.getRestApiBase()}/helium/spell/config/${pkgName}`
const promisedConf = $http.get(confUrl)
- .then(function(response, status) {
- return response.data.body;
- });
+ .then(function (response, status) {
+ return response.data.body
+ })
return promisedConf.then(({confSpec, confPersisted}) => {
const merged = mergePersistedConfWithSpec(confPersisted, confSpec)
- return merged;
- });
+ return merged
+ })
}
const p = this.getAllEnabledPackages()
@@ -260,15 +260,15 @@ export default function heliumService($http, $sce, baseUrlSrv) {
// filter out empty bundle
if (b === '') { return acc }
acc.push(b)
- return acc;
+ return acc
}, [])
})
// load should be promise
this.load = p.then(availableBundles => {
-
// evaluate bundles
availableBundles.map(b => {
+ // eslint-disable-next-line no-eval
eval(b)
})
@@ -284,5 +284,4 @@ export default function heliumService($http, $sce, baseUrlSrv) {
}
})
})
-
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/interpreter/interpreter.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/interpreter/interpreter.directive.js b/zeppelin-web/src/components/interpreter/interpreter.directive.js
index 0ec6353..7080760 100644
--- a/zeppelin-web/src/components/interpreter/interpreter.directive.js
+++ b/zeppelin-web/src/components/interpreter/interpreter.directive.js
@@ -12,21 +12,20 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('interpreterDirective', interpreterDirective);
+angular.module('zeppelinWebApp').directive('interpreterDirective', interpreterDirective)
-function interpreterDirective($timeout) {
- 'ngInject';
+function interpreterDirective ($timeout) {
+ 'ngInject'
return {
restrict: 'A',
- link: function(scope, element, attr) {
+ link: function (scope, element, attr) {
if (scope.$last === true) {
- $timeout(function() {
- var id = 'ngRenderFinished';
- scope.$emit(id);
- });
+ $timeout(function () {
+ let id = 'ngRenderFinished'
+ scope.$emit(id)
+ })
}
}
- };
+ }
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/login/login.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/login/login.controller.js b/zeppelin-web/src/components/login/login.controller.js
index 370466e..9190950 100644
--- a/zeppelin-web/src/components/login/login.controller.js
+++ b/zeppelin-web/src/components/login/login.controller.js
@@ -12,16 +12,15 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('LoginCtrl', LoginCtrl);
+angular.module('zeppelinWebApp').controller('LoginCtrl', LoginCtrl)
-function LoginCtrl($scope, $rootScope, $http, $httpParamSerializer, baseUrlSrv, $location, $timeout) {
- 'ngInject';
+function LoginCtrl ($scope, $rootScope, $http, $httpParamSerializer, baseUrlSrv, $location, $timeout) {
+ 'ngInject'
- $scope.SigningIn = false;
- $scope.loginParams = {};
- $scope.login = function() {
-
- $scope.SigningIn = true;
+ $scope.SigningIn = false
+ $scope.loginParams = {}
+ $scope.login = function () {
+ $scope.SigningIn = true
$http({
method: 'POST',
url: baseUrlSrv.getRestApiBase() + '/login',
@@ -32,57 +31,54 @@ function LoginCtrl($scope, $rootScope, $http, $httpParamSerializer, baseUrlSrv,
'userName': $scope.loginParams.userName,
'password': $scope.loginParams.password
})
- }).then(function successCallback(response) {
- $rootScope.ticket = response.data.body;
- angular.element('#loginModal').modal('toggle');
- $rootScope.$broadcast('loginSuccess', true);
- $rootScope.userName = $scope.loginParams.userName;
- $scope.SigningIn = false;
+ }).then(function successCallback (response) {
+ $rootScope.ticket = response.data.body
+ angular.element('#loginModal').modal('toggle')
+ $rootScope.$broadcast('loginSuccess', true)
+ $rootScope.userName = $scope.loginParams.userName
+ $scope.SigningIn = false
- //redirect to the page from where the user originally was
+ // redirect to the page from where the user originally was
if ($location.search() && $location.search()['ref']) {
- $timeout(function() {
- var redirectLocation = $location.search()['ref'];
- $location.$$search = {};
- $location.path(redirectLocation);
- }, 100);
-
+ $timeout(function () {
+ let redirectLocation = $location.search()['ref']
+ $location.$$search = {}
+ $location.path(redirectLocation)
+ }, 100)
}
- }, function errorCallback(errorResponse) {
- $scope.loginParams.errorText = 'The username and password that you entered don\'t match.';
- $scope.SigningIn = false;
- });
-
- };
+ }, function errorCallback (errorResponse) {
+ $scope.loginParams.errorText = 'The username and password that you entered don\'t match.'
+ $scope.SigningIn = false
+ })
+ }
- var initValues = function() {
+ let initValues = function () {
$scope.loginParams = {
userName: '',
password: ''
- };
- };
+ }
+ }
- //handle session logout message received from WebSocket
- $rootScope.$on('session_logout', function(event, data) {
+ // handle session logout message received from WebSocket
+ $rootScope.$on('session_logout', function (event, data) {
if ($rootScope.userName !== '') {
- $rootScope.userName = '';
- $rootScope.ticket = undefined;
+ $rootScope.userName = ''
+ $rootScope.ticket = undefined
- setTimeout(function() {
- $scope.loginParams = {};
- $scope.loginParams.errorText = data.info;
- angular.element('.nav-login-btn').click();
- }, 1000);
- var locationPath = $location.path();
- $location.path('/').search('ref', locationPath);
+ setTimeout(function () {
+ $scope.loginParams = {}
+ $scope.loginParams.errorText = data.info
+ angular.element('.nav-login-btn').click()
+ }, 1000)
+ let locationPath = $location.path()
+ $location.path('/').search('ref', locationPath)
}
- });
+ })
/*
** $scope.$on functions below
*/
- $scope.$on('initLoginValues', function() {
- initValues();
- });
+ $scope.$on('initLoginValues', function () {
+ initValues()
+ })
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/navbar/navbar.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/navbar/navbar.controller.js b/zeppelin-web/src/components/navbar/navbar.controller.js
index a7a7cde..a2ca20a 100644
--- a/zeppelin-web/src/components/navbar/navbar.controller.js
+++ b/zeppelin-web/src/components/navbar/navbar.controller.js
@@ -12,142 +12,142 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('NavCtrl', NavCtrl);
+angular.module('zeppelinWebApp').controller('NavCtrl', NavCtrl)
-function NavCtrl($scope, $rootScope, $http, $routeParams, $location,
+function NavCtrl ($scope, $rootScope, $http, $routeParams, $location,
noteListDataFactory, baseUrlSrv, websocketMsgSrv,
arrayOrderingSrv, searchService, TRASH_FOLDER_ID) {
- 'ngInject';
+ 'ngInject'
- var vm = this;
- vm.arrayOrderingSrv = arrayOrderingSrv;
- vm.connected = websocketMsgSrv.isConnected();
- vm.isActive = isActive;
- vm.logout = logout;
- vm.notes = noteListDataFactory;
- vm.search = search;
- vm.searchForm = searchService;
- vm.showLoginWindow = showLoginWindow;
- vm.TRASH_FOLDER_ID = TRASH_FOLDER_ID;
- vm.isFilterNote = isFilterNote;
+ let vm = this
+ vm.arrayOrderingSrv = arrayOrderingSrv
+ vm.connected = websocketMsgSrv.isConnected()
+ vm.isActive = isActive
+ vm.logout = logout
+ vm.notes = noteListDataFactory
+ vm.search = search
+ vm.searchForm = searchService
+ vm.showLoginWindow = showLoginWindow
+ vm.TRASH_FOLDER_ID = TRASH_FOLDER_ID
+ vm.isFilterNote = isFilterNote
- $scope.query = {q: ''};
+ $scope.query = {q: ''}
- initController();
+ initController()
- function getZeppelinVersion() {
+ function getZeppelinVersion () {
$http.get(baseUrlSrv.getRestApiBase() + '/version').success(
- function(data, status, headers, config) {
- $rootScope.zeppelinVersion = data.body;
+ function (data, status, headers, config) {
+ $rootScope.zeppelinVersion = data.body
}).error(
- function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- });
+ function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ })
}
- function initController() {
- $scope.isDrawNavbarNoteList = false;
- angular.element('#notebook-list').perfectScrollbar({suppressScrollX: true});
+ function initController () {
+ $scope.isDrawNavbarNoteList = false
+ angular.element('#notebook-list').perfectScrollbar({suppressScrollX: true})
- angular.element(document).click(function() {
- $scope.query.q = '';
- });
+ angular.element(document).click(function () {
+ $scope.query.q = ''
+ })
- getZeppelinVersion();
- loadNotes();
+ getZeppelinVersion()
+ loadNotes()
}
- function isFilterNote(note) {
+ function isFilterNote (note) {
if (!$scope.query.q) {
- return true;
+ return true
}
- var noteName = note.name;
+ let noteName = note.name
if (noteName.toLowerCase().indexOf($scope.query.q.toLowerCase()) > -1) {
- return true;
+ return true
}
- return false;
+ return false
}
- function isActive(noteId) {
- return ($routeParams.noteId === noteId);
+ function isActive (noteId) {
+ return ($routeParams.noteId === noteId)
}
- function listConfigurations() {
- websocketMsgSrv.listConfigurations();
+ function listConfigurations () {
+ websocketMsgSrv.listConfigurations()
}
- function loadNotes() {
- websocketMsgSrv.getNoteList();
+ function loadNotes () {
+ websocketMsgSrv.getNoteList()
}
- function getHomeNote(){
- websocketMsgSrv.getHomeNote();
+ function getHomeNote () {
+ websocketMsgSrv.getHomeNote()
}
- function logout() {
- var logoutURL = baseUrlSrv.getRestApiBase() + '/login/logout';
-
- //for firefox and safari
- logoutURL = logoutURL.replace('//', '//false:false@');
- $http.post(logoutURL).error(function() {
- //force authcBasic (if configured) to logout
- $http.post(logoutURL).error(function() {
- $rootScope.userName = '';
- $rootScope.ticket.principal = '';
- $rootScope.ticket.ticket = '';
- $rootScope.ticket.roles = '';
+ function logout () {
+ let logoutURL = baseUrlSrv.getRestApiBase() + '/login/logout'
+
+ // for firefox and safari
+ logoutURL = logoutURL.replace('//', '//false:false@')
+ $http.post(logoutURL).error(function () {
+ // force authcBasic (if configured) to logout
+ $http.post(logoutURL).error(function () {
+ $rootScope.userName = ''
+ $rootScope.ticket.principal = ''
+ $rootScope.ticket.ticket = ''
+ $rootScope.ticket.roles = ''
BootstrapDialog.show({
message: 'Logout Success'
- });
- setTimeout(function() {
- window.location.replace('/');
- }, 1000);
- });
- });
+ })
+ setTimeout(function () {
+ window.location.replace('/')
+ }, 1000)
+ })
+ })
}
- function search(searchTerm) {
- $location.path('/search/' + searchTerm);
+ function search (searchTerm) {
+ $location.path('/search/' + searchTerm)
}
- function showLoginWindow() {
- setTimeout(function() {
- angular.element('#userName').focus();
- }, 500);
+ function showLoginWindow () {
+ setTimeout(function () {
+ angular.element('#userName').focus()
+ }, 500)
}
/*
** $scope.$on functions below
*/
- $scope.$on('setNoteMenu', function(event, notes) {
- noteListDataFactory.setNotes(notes);
- initNotebookListEventListener();
- });
+ $scope.$on('setNoteMenu', function (event, notes) {
+ noteListDataFactory.setNotes(notes)
+ initNotebookListEventListener()
+ })
- $scope.$on('setConnectedStatus', function(event, param) {
- vm.connected = param;
- });
+ $scope.$on('setConnectedStatus', function (event, param) {
+ vm.connected = param
+ })
- $scope.$on('loginSuccess', function(event, param) {
- listConfigurations();
- loadNotes();
- getHomeNote();
- });
+ $scope.$on('loginSuccess', function (event, param) {
+ listConfigurations()
+ loadNotes()
+ getHomeNote()
+ })
/*
** Performance optimization for Browser Render.
*/
- function initNotebookListEventListener() {
- angular.element(document).ready(function() {
- angular.element('.notebook-list-dropdown').on('show.bs.dropdown', function() {
- $scope.isDrawNavbarNoteList = true;
- });
-
- angular.element('.notebook-list-dropdown').on('hide.bs.dropdown', function() {
- $scope.isDrawNavbarNoteList = false;
- });
- });
+ function initNotebookListEventListener () {
+ angular.element(document).ready(function () {
+ angular.element('.notebook-list-dropdown').on('show.bs.dropdown', function () {
+ $scope.isDrawNavbarNoteList = true
+ })
+
+ angular.element('.notebook-list-dropdown').on('hide.bs.dropdown', function () {
+ $scope.isDrawNavbarNoteList = false
+ })
+ })
}
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/navbar/navbar.controller.test.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/navbar/navbar.controller.test.js b/zeppelin-web/src/components/navbar/navbar.controller.test.js
index 07a5945..bf29b84 100644
--- a/zeppelin-web/src/components/navbar/navbar.controller.test.js
+++ b/zeppelin-web/src/components/navbar/navbar.controller.test.js
@@ -1,18 +1,18 @@
-describe('Controller: NavCtrl', function() {
+describe('Controller: NavCtrl', function () {
// load the controller's module
- beforeEach(angular.mock.module('zeppelinWebApp'));
- var NavCtrl;
- var scope;
+ beforeEach(angular.mock.module('zeppelinWebApp'))
+ let NavCtrl
+ let scope
// Initialize the controller and a mock scope
- beforeEach(inject(function($controller, $rootScope) {
- scope = $rootScope.$new();
+ beforeEach(inject(function ($controller, $rootScope) {
+ scope = $rootScope.$new()
NavCtrl = $controller('NavCtrl', {
$scope: scope
- });
+ })
- it('NavCtrl to toBeDefined', function() {
- expect(NavCtrl).toBeDefined();
- expect(NavCtrl.loadNotes).toBeDefined();
- });
- }));
-});
+ it('NavCtrl to toBeDefined', function () {
+ expect(NavCtrl).toBeDefined()
+ expect(NavCtrl.loadNotes).toBeDefined()
+ })
+ }))
+})
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/components/ngenter/ngenter.directive.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/components/ngenter/ngenter.directive.js b/zeppelin-web/src/components/ngenter/ngenter.directive.js
index 8b4fe8b..57ec01c 100644
--- a/zeppelin-web/src/components/ngenter/ngenter.directive.js
+++ b/zeppelin-web/src/components/ngenter/ngenter.directive.js
@@ -12,20 +12,19 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').directive('ngEnter', ngEnter);
+angular.module('zeppelinWebApp').directive('ngEnter', ngEnter)
-function ngEnter() {
- return function(scope, element, attrs) {
- element.bind('keydown keypress', function(event) {
+function ngEnter () {
+ return function (scope, element, attrs) {
+ element.bind('keydown keypress', function (event) {
if (event.which === 13) {
if (!event.shiftKey) {
- scope.$apply(function() {
- scope.$eval(attrs.ngEnter);
- });
+ scope.$apply(function () {
+ scope.$eval(attrs.ngEnter)
+ })
}
- event.preventDefault();
+ event.preventDefault()
}
- });
- };
+ })
+ }
}
-
[3/8] zeppelin git commit: [ZEPPELIN-1940] lint rule set is NOT
applied at all.
Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/tabledata/advanced-transformation-util.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/tabledata/advanced-transformation-util.js b/zeppelin-web/src/app/tabledata/advanced-transformation-util.js
index 0bcefb6..0d1c2f6 100644
--- a/zeppelin-web/src/app/tabledata/advanced-transformation-util.js
+++ b/zeppelin-web/src/app/tabledata/advanced-transformation-util.js
@@ -13,7 +13,7 @@
*/
export function getCurrentChart(config) {
- return config.chart.current;
+ return config.chart.current
}
export function getCurrentChartTransform(config) {
@@ -43,7 +43,7 @@ export function useSharedAxis(config, chart) {
export function serializeSharedAxes(config) {
const availableCharts = getAvailableChartNames(config.spec.charts)
for (let i = 0; i < availableCharts.length; i++) {
- const chartName = availableCharts[i];
+ const chartName = availableCharts[i]
if (useSharedAxis(config, chartName)) {
/** use reference :) in case of sharedAxis */
config.axis[chartName] = config.sharedAxis
@@ -59,19 +59,19 @@ export const Widget = {
}
export function isInputWidget(paramSpec) {
- return (paramSpec && !paramSpec.widget) || (paramSpec && paramSpec.widget === Widget.INPUT);
+ return (paramSpec && !paramSpec.widget) || (paramSpec && paramSpec.widget === Widget.INPUT)
}
export function isOptionWidget(paramSpec) {
- return paramSpec && paramSpec.widget === Widget.OPTION;
+ return paramSpec && paramSpec.widget === Widget.OPTION
}
export function isCheckboxWidget(paramSpec) {
- return paramSpec && paramSpec.widget === Widget.CHECKBOX;
+ return paramSpec && paramSpec.widget === Widget.CHECKBOX
}
export function isTextareaWidget(paramSpec) {
- return paramSpec && paramSpec.widget === Widget.TEXTAREA;
+ return paramSpec && paramSpec.widget === Widget.TEXTAREA
}
export const ParameterValueType = {
@@ -86,37 +86,29 @@ export function parseParameter(paramSpecs, param) {
/** copy original params */
const parsed = JSON.parse(JSON.stringify(param))
- for (let i = 0 ; i < paramSpecs.length; i++) {
+ for (let i = 0; i < paramSpecs.length; i++) {
const paramSpec = paramSpecs[i]
const name = paramSpec.name
if (paramSpec.valueType === ParameterValueType.INT &&
typeof parsed[name] !== 'number') {
-
- try { parsed[name] = parseInt(parsed[name]); }
- catch (error) { parsed[name] = paramSpec.defaultValue; }
- }
- else if (paramSpec.valueType === ParameterValueType.FLOAT &&
+ try { parsed[name] = parseInt(parsed[name]) } catch (error) { parsed[name] = paramSpec.defaultValue }
+ } else if (paramSpec.valueType === ParameterValueType.FLOAT &&
typeof parsed[name] !== 'number') {
-
- try { parsed[name] = parseFloat(parsed[name]); }
- catch (error) { parsed[name] = paramSpec.defaultValue; }
- }
- else if (paramSpec.valueType === ParameterValueType.BOOLEAN) {
+ try { parsed[name] = parseFloat(parsed[name]) } catch (error) { parsed[name] = paramSpec.defaultValue }
+ } else if (paramSpec.valueType === ParameterValueType.BOOLEAN) {
if (parsed[name] === 'false') {
- parsed[name] = false;
+ parsed[name] = false
} else if (parsed[name] === 'true') {
- parsed[name] = true;
+ parsed[name] = true
} else if (typeof parsed[name] !== 'boolean') {
- parsed[name] = paramSpec.defaultValue;
+ parsed[name] = paramSpec.defaultValue
}
- }
- else if (paramSpec.valueType === ParameterValueType.JSON) {
+ } else if (paramSpec.valueType === ParameterValueType.JSON) {
if (parsed[name] !== null && typeof parsed[name] !== 'object') {
- try { parsed[name] = JSON.parse(parsed[name]); }
- catch (error) { parsed[name] = paramSpec.defaultValue; }
+ try { parsed[name] = JSON.parse(parsed[name]) } catch (error) { parsed[name] = paramSpec.defaultValue }
} else if (parsed[name] === null) {
- parsed[name] = paramSpec.defaultValue;
+ parsed[name] = paramSpec.defaultValue
}
}
}
@@ -150,12 +142,12 @@ export function isSingleDimensionAxis(axisSpec) {
* add the `name` field while converting to array to easily manipulate
*/
export function getSpecs(specObject) {
- const specs = [];
+ const specs = []
for (let name in specObject) {
- const singleSpec = specObject[name];
+ const singleSpec = specObject[name]
if (!singleSpec) { continue }
- singleSpec.name = name;
- specs.push(singleSpec);
+ singleSpec.name = name
+ specs.push(singleSpec)
}
return specs
@@ -163,7 +155,7 @@ export function getSpecs(specObject) {
export function getAvailableChartNames(charts) {
const available = []
- for (var name in charts) {
+ for (let name in charts) {
available.push(name)
}
@@ -172,11 +164,11 @@ export function getAvailableChartNames(charts) {
export function applyMaxAxisCount(config, axisSpec) {
if (isSingleDimensionAxis(axisSpec) || typeof axisSpec.maxAxisCount === 'undefined') {
- return;
+ return
}
const columns = getCurrentChartAxis(config)[axisSpec.name]
- if (columns.length <= axisSpec.maxAxisCount) { return; }
+ if (columns.length <= axisSpec.maxAxisCount) { return }
const sliced = columns.slice(1)
getCurrentChartAxis(config)[axisSpec.name] = sliced
@@ -213,23 +205,23 @@ export function initAxisConfig(config) {
const spec = config.spec
const availableCharts = getAvailableChartNames(spec.charts)
- if (!config.axisSpecs) { config.axisSpecs = {}; }
+ if (!config.axisSpecs) { config.axisSpecs = {} }
for (let i = 0; i < availableCharts.length; i++) {
- const chartName = availableCharts[i];
+ const chartName = availableCharts[i]
if (!config.axis[chartName]) {
- config.axis[chartName] = {};
+ config.axis[chartName] = {}
}
const axisSpecs = getSpecs(spec.charts[chartName].axis)
if (!config.axisSpecs[chartName]) {
- config.axisSpecs[chartName] = axisSpecs;
+ config.axisSpecs[chartName] = axisSpecs
}
/** initialize multi-dimension axes */
for (let i = 0; i < axisSpecs.length; i++) {
const axisSpec = axisSpecs[i]
if (isSingleDimensionAxis(axisSpec)) {
- continue;
+ continue
}
/** intentionally nested if-stmt is used because order of conditions matter here */
@@ -268,18 +260,18 @@ export function initParameterConfig(config) {
const spec = config.spec
const availableCharts = getAvailableChartNames(spec.charts)
- if (!config.paramSpecs) { config.paramSpecs = {}; }
+ if (!config.paramSpecs) { config.paramSpecs = {} }
for (let i = 0; i < availableCharts.length; i++) {
- const chartName = availableCharts[i];
+ const chartName = availableCharts[i]
- if (!config.parameter[chartName]) { config.parameter[chartName] = {}; }
+ if (!config.parameter[chartName]) { config.parameter[chartName] = {} }
const paramSpecs = getSpecs(spec.charts[chartName].parameter)
- if (!config.paramSpecs[chartName]) { config.paramSpecs[chartName] = paramSpecs; }
+ if (!config.paramSpecs[chartName]) { config.paramSpecs[chartName] = paramSpecs }
for (let i = 0; i < paramSpecs.length; i++) {
- const paramSpec = paramSpecs[i];
+ const paramSpec = paramSpecs[i]
if (!config.parameter[chartName][paramSpec.name]) {
- config.parameter[chartName][paramSpec.name] = paramSpec.defaultValue;
+ config.parameter[chartName][paramSpec.name] = paramSpec.defaultValue
}
}
}
@@ -295,7 +287,7 @@ export function getSpecVersion(availableCharts, spec) {
const paramHash = {}
for (let i = 0; i < availableCharts.length; i++) {
- const chartName = availableCharts[i];
+ const chartName = availableCharts[i]
const axisSpecs = getSpecs(spec.charts[chartName].axis)
axisHash[chartName] = axisSpecs
@@ -318,7 +310,6 @@ export function initializeConfig(config, spec) {
if (!config.spec || !config.spec.version ||
!config.spec.version.axis ||
config.spec.version.axis !== axisVersion) {
-
spec.initialized = true
updated = true
@@ -332,7 +323,6 @@ export function initializeConfig(config, spec) {
if (!config.spec || !config.spec.version ||
!config.spec.version.parameter ||
config.spec.version.parameter !== paramVersion) {
-
updated = true
clearParameterConfig(config)
@@ -343,12 +333,12 @@ export function initializeConfig(config, spec) {
spec.version.axis = axisVersion
spec.version.parameter = paramVersion
- if (!config.spec || updated) { config.spec = spec; }
+ if (!config.spec || updated) { config.spec = spec }
if (!config.chart) {
- config.chart = {};
- config.chart.current = availableCharts[0];
- config.chart.available = availableCharts;
+ config.chart = {}
+ config.chart.current = availableCharts[0]
+ config.chart.available = availableCharts
}
/** initialize config.axis, config.axisSpecs for each chart */
@@ -363,8 +353,8 @@ export function getColumnsForMultipleAxes(axisType, axisSpecs, axis) {
const axisNames = []
let column = {}
- for(let i = 0; i < axisSpecs.length; i++) {
- const axisSpec = axisSpecs[i];
+ for (let i = 0; i < axisSpecs.length; i++) {
+ const axisSpec = axisSpecs[i]
if (axisType === AxisType.KEY && isKeyAxis(axisSpec)) {
axisNames.push(axisSpec.name)
@@ -375,8 +365,8 @@ export function getColumnsForMultipleAxes(axisType, axisSpecs, axis) {
}
}
- for(let axisName of axisNames) {
- const columns = axis[axisName];
+ for (let axisName of axisNames) {
+ const columns = axis[axisName]
if (typeof axis[axisName] === 'undefined') { continue }
if (!column[axisName]) { column[axisName] = [] }
column[axisName] = column[axisName].concat(columns)
@@ -386,35 +376,39 @@ export function getColumnsForMultipleAxes(axisType, axisSpecs, axis) {
}
export function getColumnsFromAxis(axisSpecs, axis) {
- const keyAxisNames = [];
- const groupAxisNames = [];
- const aggrAxisNames = [];
-
- for(let i = 0; i < axisSpecs.length; i++) {
- const axisSpec = axisSpecs[i];
-
- if (isKeyAxis(axisSpec)) { keyAxisNames.push(axisSpec.name); }
- else if (isGroupAxis(axisSpec)) { groupAxisNames.push(axisSpec.name); }
- else if (isAggregatorAxis(axisSpec)) { aggrAxisNames.push(axisSpec.name); }
+ const keyAxisNames = []
+ const groupAxisNames = []
+ const aggrAxisNames = []
+
+ for (let i = 0; i < axisSpecs.length; i++) {
+ const axisSpec = axisSpecs[i]
+
+ if (isKeyAxis(axisSpec)) {
+ keyAxisNames.push(axisSpec.name)
+ } else if (isGroupAxis(axisSpec)) {
+ groupAxisNames.push(axisSpec.name)
+ } else if (isAggregatorAxis(axisSpec)) {
+ aggrAxisNames.push(axisSpec.name)
+ }
}
- let keyColumns = [];
- let groupColumns = [];
- let aggregatorColumns = [];
- let customColumn = {};
+ let keyColumns = []
+ let groupColumns = []
+ let aggregatorColumns = []
+ let customColumn = {}
- for(let axisName in axis) {
- const columns = axis[axisName];
+ for (let axisName in axis) {
+ const columns = axis[axisName]
if (keyAxisNames.includes(axisName)) {
- keyColumns = keyColumns.concat(columns);
+ keyColumns = keyColumns.concat(columns)
} else if (groupAxisNames.includes(axisName)) {
- groupColumns = groupColumns.concat(columns);
+ groupColumns = groupColumns.concat(columns)
} else if (aggrAxisNames.includes(axisName)) {
- aggregatorColumns = aggregatorColumns.concat(columns);
+ aggregatorColumns = aggregatorColumns.concat(columns)
} else {
const axisType = axisSpecs.filter(s => s.name === axisName)[0].axisType
- if (!customColumn[axisType]) { customColumn[axisType] = []; }
- customColumn[axisType] = customColumn[axisType].concat(columns);
+ if (!customColumn[axisType]) { customColumn[axisType] = [] }
+ customColumn[axisType] = customColumn[axisType].concat(columns)
}
}
@@ -466,10 +460,10 @@ export function getTransformer(conf, rows, axisSpecs, axis) {
const method = transformSpec.method
- const columns = getColumnsFromAxis(axisSpecs, axis);
- const keyColumns = columns.key;
- const groupColumns = columns.group;
- const aggregatorColumns = columns.aggregator;
+ const columns = getColumnsFromAxis(axisSpecs, axis)
+ const keyColumns = columns.key
+ const groupColumns = columns.group
+ const aggregatorColumns = columns.aggregator
const customColumns = columns.custom
let column = {
@@ -477,10 +471,10 @@ export function getTransformer(conf, rows, axisSpecs, axis) {
}
if (method === TransformMethod.RAW) {
- transformer = () => { return rows; }
+ transformer = () => { return rows }
} else if (method === TransformMethod.OBJECT) {
transformer = () => {
- const { cube, schema, keyColumnName, keyNames, groupNameSet, selectorNameWithIndex, } =
+ const { cube, schema, keyColumnName, keyNames, groupNameSet, selectorNameWithIndex, } =
getKGACube(rows, keyColumns, groupColumns, aggregatorColumns)
const {
@@ -489,7 +483,8 @@ export function getTransformer(conf, rows, axisSpecs, axis) {
keyColumnName, keyNames, groupNameSet, selectorNameWithIndex)
return {
- rows: transformed, keyColumnName,
+ rows: transformed,
+ keyColumnName,
keyNames,
groupNames: groupNames,
selectors: sortedSelectors,
@@ -506,7 +501,8 @@ export function getTransformer(conf, rows, axisSpecs, axis) {
keyColumnName, keyNames, groupNameSet, selectorNameWithIndex)
return {
- rows: transformed, keyColumnName,
+ rows: transformed,
+ keyColumnName,
keyNames,
groupNames: groupNames,
selectors: sortedSelectors,
@@ -524,8 +520,7 @@ export function getTransformer(conf, rows, axisSpecs, axis) {
for (let axisName in keyAxisColumn) {
if (i === 2) { break }
- if (i === 0) { key1Columns = keyAxisColumn[axisName] }
- else if (i === 1) { key2Columns = keyAxisColumn[axisName] }
+ if (i === 0) { key1Columns = keyAxisColumn[axisName] } else if (i === 1) { key2Columns = keyAxisColumn[axisName] }
i++
}
@@ -553,8 +548,7 @@ export function getTransformer(conf, rows, axisSpecs, axis) {
selectors: sortedSelectors,
}
}
- }
- else if (method === TransformMethod.DRILL_DOWN) {
+ } else if (method === TransformMethod.DRILL_DOWN) {
transformer = () => {
const { cube, schema, keyColumnName, keyNames, groupNameSet, selectorNameWithIndex, } =
getKAGCube(rows, keyColumns, groupColumns, aggregatorColumns)
@@ -565,7 +559,9 @@ export function getTransformer(conf, rows, axisSpecs, axis) {
keyColumnName, keyNames, groupNameSet, selectorNameWithIndex)
return {
- rows: transformed, keyColumnName, keyNames,
+ rows: transformed,
+ keyColumnName,
+ keyNames,
groupNames: groupNames,
selectors: sortedSelectors,
}
@@ -577,31 +573,31 @@ export function getTransformer(conf, rows, axisSpecs, axis) {
const AggregatorFunctions = {
sum: function(a, b) {
- const varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0;
- const varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0;
- return varA + varB;
+ const varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0
+ const varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0
+ return varA + varB
},
count: function(a, b) {
- const varA = (a !== undefined) ? parseInt(a) : 0;
- const varB = (b !== undefined) ? 1 : 0;
- return varA + varB;
+ const varA = (a !== undefined) ? parseInt(a) : 0
+ const varB = (b !== undefined) ? 1 : 0
+ return varA + varB
},
min: function(a, b) {
- const varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0;
- const varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0;
- return Math.min(varA,varB);
+ const varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0
+ const varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0
+ return Math.min(varA, varB)
},
max: function(a, b) {
- const varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0;
- const varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0;
- return Math.max(varA,varB);
+ const varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0
+ const varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0
+ return Math.max(varA, varB)
},
avg: function(a, b, c) {
- const varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0;
- const varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0;
- return varA + varB;
+ const varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0
+ const varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0
+ return varA + varB
}
-};
+}
const AggregatorFunctionDiv = {
sum: false,
@@ -609,7 +605,7 @@ const AggregatorFunctionDiv = {
max: false,
count: false,
avg: true
-};
+}
/** nested cube `(key) -> (group) -> aggregator` */
export function getKGACube(rows, keyColumns, groupColumns, aggrColumns) {
@@ -617,7 +613,7 @@ export function getKGACube(rows, keyColumns, groupColumns, aggrColumns) {
key: keyColumns.length !== 0,
group: groupColumns.length !== 0,
aggregator: aggrColumns.length !== 0,
- };
+ }
let cube = {}
const entry = {}
@@ -629,12 +625,12 @@ export function getKGACube(rows, keyColumns, groupColumns, aggrColumns) {
let indexCounter = 0
for (let i = 0; i < rows.length; i++) {
- const row = rows[i];
- let e = entry;
- let c = cube;
+ const row = rows[i]
+ let e = entry
+ let c = cube
// key: add to entry
- let mergedKeyName = undefined
+ let mergedKeyName
if (schema.key) {
mergedKeyName = keyColumns.map(c => row[c.index]).join('.')
if (!e[mergedKeyName]) { e[mergedKeyName] = { children: {}, } }
@@ -646,7 +642,7 @@ export function getKGACube(rows, keyColumns, groupColumns, aggrColumns) {
keyNameSet.add(mergedKeyName)
}
- let mergedGroupName = undefined
+ let mergedGroupName
if (schema.group) {
mergedGroupName = groupColumns.map(c => row[c.index]).join('.')
@@ -690,13 +686,12 @@ export function getKGACube(rows, keyColumns, groupColumns, aggrColumns) {
} else {
const value = AggregatorFunctions[aggrColumn.aggr](
c[aggrName].value, row[aggrColumn.index], c[aggrName].count + 1)
- const count = (AggregatorFunctionDiv[aggrColumn.aggr]) ?
- c[aggrName].count + 1 : c[aggrName].count
+ const count = (AggregatorFunctionDiv[aggrColumn.aggr])
+ ? c[aggrName].count + 1 : c[aggrName].count
c[aggrName].value = value
c[aggrName].count = count
}
-
} /** end loop for aggrColumns */
}
@@ -725,7 +720,7 @@ export function getKAGCube(rows, keyColumns, groupColumns, aggrColumns) {
key: keyColumns.length !== 0,
group: groupColumns.length !== 0,
aggregator: aggrColumns.length !== 0,
- };
+ }
let cube = {}
@@ -736,11 +731,11 @@ export function getKAGCube(rows, keyColumns, groupColumns, aggrColumns) {
let indexCounter = 0
for (let i = 0; i < rows.length; i++) {
- const row = rows[i];
- let c = cube;
+ const row = rows[i]
+ let c = cube
// key: add to entry
- let mergedKeyName = undefined
+ let mergedKeyName
if (schema.key) {
mergedKeyName = keyColumns.map(c => row[c.index]).join('.')
// key: add to row
@@ -750,7 +745,7 @@ export function getKAGCube(rows, keyColumns, groupColumns, aggrColumns) {
keyNameSet.add(mergedKeyName)
}
- let mergedGroupName = undefined
+ let mergedGroupName
if (schema.group) {
mergedGroupName = groupColumns.map(c => row[c.index]).join('.')
groupNameSet.add(mergedGroupName)
@@ -781,8 +776,8 @@ export function getKAGCube(rows, keyColumns, groupColumns, aggrColumns) {
} else {
const value = AggregatorFunctions[aggrColumn.aggr](
c[aggrName].value, row[aggrColumn.index], c[aggrName].count + 1)
- const count = (AggregatorFunctionDiv[aggrColumn.aggr]) ?
- c[aggrName].count + 1 : c[aggrName].count
+ const count = (AggregatorFunctionDiv[aggrColumn.aggr])
+ ? c[aggrName].count + 1 : c[aggrName].count
c[aggrName].value = value
c[aggrName].count = count
@@ -800,15 +795,13 @@ export function getKAGCube(rows, keyColumns, groupColumns, aggrColumns) {
const drillDownedCount = c[aggrName].children[mergedGroupName].count
const value = AggregatorFunctions[aggrColumn.aggr](
drillDownedValue, row[aggrColumn.index], drillDownedCount + 1)
- const count = (AggregatorFunctionDiv[aggrColumn.aggr]) ?
- drillDownedCount + 1 : drillDownedCount
+ const count = (AggregatorFunctionDiv[aggrColumn.aggr])
+ ? drillDownedCount + 1 : drillDownedCount
c[aggrName].children[mergedGroupName].value = value
c[aggrName].children[mergedGroupName].count = count
}
-
}
-
} /** end loop for aggrColumns */
}
@@ -837,7 +830,7 @@ export function getKKGACube(rows, key1Columns, key2Columns, groupColumns, aggrCo
key2: key2Columns.length !== 0,
group: groupColumns.length !== 0,
aggregator: aggrColumns.length !== 0,
- };
+ }
let cube = {}
const entry = {}
@@ -851,12 +844,12 @@ export function getKKGACube(rows, key1Columns, key2Columns, groupColumns, aggrCo
let indexCounter = 0
for (let i = 0; i < rows.length; i++) {
- const row = rows[i];
- let e = entry;
- let c = cube;
+ const row = rows[i]
+ let e = entry
+ let c = cube
// key1: add to entry
- let mergedKey1Name = undefined
+ let mergedKey1Name
if (schema.key1) {
mergedKey1Name = key1Columns.map(c => row[c.index]).join('.')
if (!e[mergedKey1Name]) { e[mergedKey1Name] = { children: {}, } }
@@ -869,7 +862,7 @@ export function getKKGACube(rows, key1Columns, key2Columns, groupColumns, aggrCo
}
// key2: add to entry
- let mergedKey2Name = undefined
+ let mergedKey2Name
if (schema.key2) {
mergedKey2Name = key2Columns.map(c => row[c.index]).join('.')
if (!e[mergedKey2Name]) { e[mergedKey2Name] = { children: {}, } }
@@ -881,7 +874,7 @@ export function getKKGACube(rows, key1Columns, key2Columns, groupColumns, aggrCo
if (!key2NameSet[mergedKey2Name]) { key2NameSet[mergedKey2Name] = true }
}
- let mergedGroupName = undefined
+ let mergedGroupName
if (schema.group) {
mergedGroupName = groupColumns.map(c => row[c.index]).join('.')
@@ -925,13 +918,12 @@ export function getKKGACube(rows, key1Columns, key2Columns, groupColumns, aggrCo
} else {
const value = AggregatorFunctions[aggrColumn.aggr](
c[aggrName].value, row[aggrColumn.index], c[aggrName].count + 1)
- const count = (AggregatorFunctionDiv[aggrColumn.aggr]) ?
- c[aggrName].count + 1 : c[aggrName].count
+ const count = (AggregatorFunctionDiv[aggrColumn.aggr])
+ ? c[aggrName].count + 1 : c[aggrName].count
c[aggrName].value = value
c[aggrName].count = count
}
-
} /** end loop for aggrColumns */
}
@@ -954,8 +946,8 @@ export function getSelectorName(mergedGroupName, aggrColumnLength, aggrColumnNam
if (!mergedGroupName) {
return aggrColumnName
} else {
- return (aggrColumnLength > 1) ?
- `${mergedGroupName} / ${aggrColumnName}` : mergedGroupName
+ return (aggrColumnLength > 1)
+ ? `${mergedGroupName} / ${aggrColumnName}` : mergedGroupName
}
}
@@ -990,7 +982,6 @@ export function getNameWithIndex(names) {
export function getArrayRowsFromKKGACube(cube, schema, aggregatorColumns,
key1Names, key2Names, groupNameSet, selectorNameWithIndex) {
-
const sortedSelectors = Object.keys(selectorNameWithIndex).sort()
const sortedSelectorNameWithIndex = getNameWithIndex(sortedSelectors)
@@ -1015,7 +1006,6 @@ export function getArrayRowsFromKKGACube(cube, schema, aggregatorColumns,
export function fillSelectorRows(schema, cube, selectorRows,
aggrColumns, selectorNameWithIndex,
key1Names, key2Names) {
-
function fill(grouped, mergedGroupName, key1Name, key2Name) {
// should iterate aggrColumns in the most nested loop to utilize memory locality
for (let aggrColumn of aggrColumns) {
@@ -1083,14 +1073,13 @@ export function fillSelectorRows(schema, cube, selectorRows,
export function getArrayRowsFromKGACube(cube, schema, aggregatorColumns,
keyColumnName, keyNames, groupNameSet,
selectorNameWithIndex) {
-
const sortedSelectors = Object.keys(selectorNameWithIndex).sort()
const sortedSelectorNameWithIndex = getNameWithIndex(sortedSelectors)
const keyArrowRows = new Array(sortedSelectors.length)
const keyNameWithIndex = getNameWithIndex(keyNames)
- for(let i = 0; i < keyNames.length; i++) {
+ for (let i = 0; i < keyNames.length; i++) {
const key = keyNames[i]
const obj = cube[key]
@@ -1110,7 +1099,6 @@ export function getArrayRowsFromKGACube(cube, schema, aggregatorColumns,
export function fillArrayRow(schema, aggrColumns, obj,
groupNameSet, selectorNameWithIndex,
keyName, keyNames, keyArrayRows, keyNameWithIndex) {
-
function fill(target, mergedGroupName, aggr, aggrName) {
const value = getCubeValue(target, aggr, aggrName)
const selector = getSelectorName(mergedGroupName, aggrColumns.length, aggrName)
@@ -1127,13 +1115,13 @@ export function fillArrayRow(schema, aggrColumns, obj,
/** when group is empty */
if (!schema.group) {
- for(let i = 0; i < aggrColumns.length; i++) {
+ for (let i = 0; i < aggrColumns.length; i++) {
const aggrColumn = aggrColumns[i]
const aggrName = `${aggrColumn.name}(${aggrColumn.aggr})`
fill(obj, undefined, aggrColumn.aggr, aggrName)
}
} else {
- for(let i = 0; i < aggrColumns.length; i++) {
+ for (let i = 0; i < aggrColumns.length; i++) {
const aggrColumn = aggrColumns[i]
const aggrName = `${aggrColumn.name}(${aggrColumn.aggr})`
@@ -1148,7 +1136,6 @@ export function fillArrayRow(schema, aggrColumns, obj,
export function getObjectRowsFromKGACube(cube, schema, aggregatorColumns,
keyColumnName, keyNames, groupNameSet,
selectorNameWithIndex) {
-
const rows = keyNames.reduce((acc, key) => {
const obj = cube[key]
const row = getObjectRow(schema, aggregatorColumns, obj, groupNameSet)
@@ -1177,7 +1164,7 @@ export function getObjectRow(schema, aggrColumns, obj, groupNameSet) {
/** when group is empty */
if (!schema.group) {
- for(let i = 0; i < aggrColumns.length; i++) {
+ for (let i = 0; i < aggrColumns.length; i++) {
const aggrColumn = aggrColumns[i]
const aggrName = `${aggrColumn.name}(${aggrColumn.aggr})`
@@ -1188,7 +1175,7 @@ export function getObjectRow(schema, aggrColumns, obj, groupNameSet) {
}
/** when group is specified */
- for(let i = 0; i < aggrColumns.length; i++) {
+ for (let i = 0; i < aggrColumns.length; i++) {
const aggrColumn = aggrColumns[i]
const aggrName = `${aggrColumn.name}(${aggrColumn.aggr})`
@@ -1206,7 +1193,6 @@ export function getObjectRow(schema, aggrColumns, obj, groupNameSet) {
export function getDrilldownRowsFromKAGCube(cube, schema, aggregatorColumns,
keyColumnName, keyNames, groupNameSet, selectorNameWithIndex) {
-
const sortedSelectors = Object.keys(selectorNameWithIndex).sort()
const sortedSelectorNameWithIndex = getNameWithIndex(sortedSelectors)
@@ -1232,7 +1218,7 @@ export function getDrilldownRowsFromKAGCube(cube, schema, aggregatorColumns,
export function fillDrillDownRow(schema, obj, rows, key,
selectorNameWithIndex, aggrColumns, groupNames) {
/** when group is empty */
- for(let i = 0; i < aggrColumns.length; i++) {
+ for (let i = 0; i < aggrColumns.length; i++) {
const row = {}
const aggrColumn = aggrColumns[i]
const aggrName = `${aggrColumn.name}(${aggrColumn.aggr})`
@@ -1248,7 +1234,7 @@ export function fillDrillDownRow(schema, obj, rows, key,
if (schema.group) {
row.drillDown = []
- for(let groupName of groupNames) {
+ for (let groupName of groupNames) {
const value = getCubeValue(obj[aggrName].children, aggrColumn.aggr, groupName)
row.drillDown.push({ group: groupName, value: value, })
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/tabledata/advanced-transformation-util.test.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/tabledata/advanced-transformation-util.test.js b/zeppelin-web/src/app/tabledata/advanced-transformation-util.test.js
index 6fde659..90f569f 100644
--- a/zeppelin-web/src/app/tabledata/advanced-transformation-util.test.js
+++ b/zeppelin-web/src/app/tabledata/advanced-transformation-util.test.js
@@ -50,7 +50,6 @@ const MockAxis4 = {
'groupAxis': { dimension: 'multiple', axisType: 'group', },
}
-
// test spec for axis, param, widget
const MockSpec = {
charts: {
@@ -138,23 +137,23 @@ const MockSpec2 = {
/* eslint-disable max-len */
const MockTableDataColumn = [
- {'name': 'age', 'index': 0, 'aggr': 'sum',},
- {'name': 'job', 'index': 1, 'aggr': 'sum',},
- {'name': 'marital', 'index': 2, 'aggr': 'sum',},
- {'name': 'education', 'index': 3, 'aggr': 'sum',},
- {'name': 'default', 'index': 4, 'aggr': 'sum',},
- {'name': 'balance', 'index': 5, 'aggr': 'sum',},
- {'name': 'housing', 'index': 6, 'aggr': 'sum',},
- {'name': 'loan', 'index': 7, 'aggr': 'sum',},
- {'name': 'contact', 'index': 8, 'aggr': 'sum',},
- {'name': 'day', 'index': 9, 'aggr': 'sum',},
- {'name': 'month', 'index': 10, 'aggr': 'sum',},
- {'name': 'duration', 'index': 11, 'aggr': 'sum',},
- {'name': 'campaign', 'index': 12, 'aggr': 'sum',},
- {'name': 'pdays', 'index': 13, 'aggr': 'sum',},
- {'name': 'previous', 'index': 14, 'aggr': 'sum',},
- {'name': 'poutcome', 'index': 15, 'aggr': 'sum',},
- {'name': 'y', 'index': 16, 'aggr': 'sum',}
+ {'name': 'age', 'index': 0, 'aggr': 'sum', },
+ {'name': 'job', 'index': 1, 'aggr': 'sum', },
+ {'name': 'marital', 'index': 2, 'aggr': 'sum', },
+ {'name': 'education', 'index': 3, 'aggr': 'sum', },
+ {'name': 'default', 'index': 4, 'aggr': 'sum', },
+ {'name': 'balance', 'index': 5, 'aggr': 'sum', },
+ {'name': 'housing', 'index': 6, 'aggr': 'sum', },
+ {'name': 'loan', 'index': 7, 'aggr': 'sum', },
+ {'name': 'contact', 'index': 8, 'aggr': 'sum', },
+ {'name': 'day', 'index': 9, 'aggr': 'sum', },
+ {'name': 'month', 'index': 10, 'aggr': 'sum', },
+ {'name': 'duration', 'index': 11, 'aggr': 'sum', },
+ {'name': 'campaign', 'index': 12, 'aggr': 'sum', },
+ {'name': 'pdays', 'index': 13, 'aggr': 'sum', },
+ {'name': 'previous', 'index': 14, 'aggr': 'sum', },
+ {'name': 'poutcome', 'index': 15, 'aggr': 'sum', },
+ {'name': 'y', 'index': 16, 'aggr': 'sum', }
]
const MockTableDataRows1 = [
@@ -169,7 +168,7 @@ const MockTableDataRows1 = [
describe('advanced-transformation-util', () => {
describe('getCurrent* funcs', () => {
it('should set return proper value of the current chart', () => {
- const config = {}
+ const config = {}
const spec = JSON.parse(JSON.stringify(MockSpec))
Util.initializeConfig(config, spec)
expect(Util.getCurrentChart(config)).toEqual('object-chart')
@@ -183,7 +182,7 @@ describe('advanced-transformation-util', () => {
describe('useSharedAxis', () => {
it('should set chartChanged for initial drawing', () => {
- const config = {}
+ const config = {}
const spec = JSON.parse(JSON.stringify(MockSpec))
Util.initializeConfig(config, spec)
expect(Util.useSharedAxis(config, 'object-chart')).toEqual(true)
@@ -194,7 +193,7 @@ describe('advanced-transformation-util', () => {
})
describe('initializeConfig', () => {
- const config = {}
+ const config = {}
const spec = JSON.parse(JSON.stringify(MockSpec))
Util.initializeConfig(config, spec)
@@ -269,7 +268,6 @@ describe('advanced-transformation-util', () => {
// it's ok not to set single dimension axis
expect(config.axis['raw-chart']).toEqual({ customAxis2: [], })
})
-
})
describe('axis', () => {
@@ -354,7 +352,6 @@ describe('advanced-transformation-util', () => {
expect(typeof parsed.stringParam).toBe('string')
expect(parsed.stringParam).toBe('example')
})
-
})
describe('removeDuplicatedColumnsInMultiDimensionAxis', () => {
@@ -472,7 +469,6 @@ describe('advanced-transformation-util', () => {
// it's hard to test all methods for transformation.
// so let's do behavioral (black-box) test instead of
describe('getTransformer', () => {
-
describe('method: raw', () => {
let config = {}
const spec = JSON.parse(JSON.stringify(MockSpec2))
@@ -935,8 +931,8 @@ describe('advanced-transformation-util', () => {
expect(groupNames).toEqual([ 'age(sum)', ])
expect(selectors).toEqual([ 'age(sum)', ])
expect(rows).toEqual([
- { 'age(sum)': 82, marital: 'married', },
- { 'age(sum)': 77, marital: 'single', },
+ { 'age(sum)': 82, 'marital': 'married', },
+ { 'age(sum)': 77, 'marital': 'single', },
])
})
@@ -1021,7 +1017,7 @@ describe('advanced-transformation-util', () => {
expect(groupNames).toEqual([ 'age(sum)', ])
expect(selectors).toEqual([ 'age(sum)', ])
expect(rows).toEqual([
- { selector: 'age(sum)', value: 44 + 43 + 39 + 33, drillDown: [ ], },
+ { selector: 'age(sum)', value: 44 + 43 + 39 + 33, drillDown: [ ], },
])
})
@@ -1035,7 +1031,7 @@ describe('advanced-transformation-util', () => {
const { rows, } = transformer()
expect(rows).toEqual([
- { selector: 'age(count)', value: 4, drillDown: [ ], },
+ { selector: 'age(count)', value: 4, drillDown: [ ], },
])
})
@@ -1049,7 +1045,7 @@ describe('advanced-transformation-util', () => {
const { rows, } = transformer()
expect(rows).toEqual([
- { selector: 'age(avg)', value: (44 + 43 + 39 + 33) / 4.0, drillDown: [ ], },
+ { selector: 'age(avg)', value: (44 + 43 + 39 + 33) / 4.0, drillDown: [ ], },
])
})
@@ -1063,7 +1059,7 @@ describe('advanced-transformation-util', () => {
const { rows, } = transformer()
expect(rows).toEqual([
- { selector: 'age(max)', value: 44, drillDown: [ ], },
+ { selector: 'age(max)', value: 44, drillDown: [ ], },
])
})
@@ -1077,7 +1073,7 @@ describe('advanced-transformation-util', () => {
const { rows, } = transformer()
expect(rows).toEqual([
- { selector: 'age(min)', value: 33, drillDown: [ ], },
+ { selector: 'age(min)', value: 33, drillDown: [ ], },
])
})
@@ -1098,8 +1094,8 @@ describe('advanced-transformation-util', () => {
expect(groupNames).toEqual([ 'age(sum)', 'balance(sum)', ])
expect(selectors).toEqual([ 'age(sum)', 'balance(sum)', ])
expect(rows).toEqual([
- { selector: 'age(sum)', value: 159, drillDown: [ ], },
- { selector: 'balance(sum)', value: 14181, drillDown: [ ], },
+ { selector: 'age(sum)', value: 159, drillDown: [ ], },
+ { selector: 'balance(sum)', value: 14181, drillDown: [ ], },
])
})
@@ -1212,8 +1208,8 @@ describe('advanced-transformation-util', () => {
expect(groupNames).toEqual([ 'age(sum)', ])
expect(selectors).toEqual([ 'married', 'single', ])
expect(rows).toEqual([
- { selector: 'married', value: 82, drillDown: [ ], },
- { selector: 'single', value: 77, drillDown: [ ], },
+ { selector: 'married', value: 82, drillDown: [ ], },
+ { selector: 'single', value: 77, drillDown: [ ], },
])
})
@@ -1234,9 +1230,9 @@ describe('advanced-transformation-util', () => {
expect(groupNames).toEqual([ 'age(sum)', ])
expect(selectors).toEqual([ 'married.primary', 'married.secondary', 'single.tertiary', ])
expect(rows).toEqual([
- { selector: 'married.primary', value: '43', drillDown: [ ], },
- { selector: 'married.secondary', value: '39', drillDown: [ ], },
- { selector: 'single.tertiary', value: 77, drillDown: [ ], },
+ { selector: 'married.primary', value: '43', drillDown: [ ], },
+ { selector: 'married.secondary', value: '39', drillDown: [ ], },
+ { selector: 'single.tertiary', value: 77, drillDown: [ ], },
])
})
@@ -1738,9 +1734,6 @@ describe('advanced-transformation-util', () => {
},
])
})
-
}) // end: describe('method: array:2-key')
-
}) // end: describe('getTransformer')
})
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/tabledata/advanced-transformation.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/tabledata/advanced-transformation.js b/zeppelin-web/src/app/tabledata/advanced-transformation.js
index d754f4d..051bb99 100644
--- a/zeppelin-web/src/app/tabledata/advanced-transformation.js
+++ b/zeppelin-web/src/app/tabledata/advanced-transformation.js
@@ -12,7 +12,7 @@
* limitations under the License.
*/
-import Transformation from './transformation';
+import Transformation from './transformation'
import {
getCurrentChart, getCurrentChartAxis, getCurrentChartParam,
@@ -23,19 +23,19 @@ import {
removeDuplicatedColumnsInMultiDimensionAxis, applyMaxAxisCount,
isInputWidget, isOptionWidget, isCheckboxWidget, isTextareaWidget, parseParameter,
getTransformer,
-} from './advanced-transformation-util';
+} from './advanced-transformation-util'
-const SETTING_TEMPLATE = 'app/tabledata/advanced-transformation-setting.html';
+const SETTING_TEMPLATE = 'app/tabledata/advanced-transformation-setting.html'
export default class AdvancedTransformation extends Transformation {
constructor(config, spec) {
- super(config);
+ super(config)
- this.columns = []; /** [{ name, index, comment }] */
- this.props = {};
+ this.columns = [] /** [{ name, index, comment }] */
+ this.props = {}
this.spec = spec
- initializeConfig(config, spec);
+ initializeConfig(config, spec)
}
emitConfigChange(conf) {
@@ -57,8 +57,8 @@ export default class AdvancedTransformation extends Transformation {
}
getSetting() {
- const self = this; /** for closure */
- const configInstance = self.config; /** for closure */
+ const self = this /** for closure */
+ const configInstance = self.config /** for closure */
if (self.spec.initialized) {
self.spec.initialized = false
@@ -111,7 +111,7 @@ export default class AdvancedTransformation extends Transformation {
let comment = ''
if (minAxisCount) { comment = `min: ${minAxisCount}` }
- if (minAxisCount && maxAxisCount) { comment = `${comment}, `}
+ if (minAxisCount && maxAxisCount) { comment = `${comment}, ` }
if (maxAxisCount) { comment = `${comment}max: ${maxAxisCount}` }
if (comment !== '') {
@@ -123,13 +123,13 @@ export default class AdvancedTransformation extends Transformation {
getAxisTypeAnnotationColor: (axisSpec) => {
if (isAggregatorAxis(axisSpec)) {
- return { 'background-color': '#5782bd' };
+ return { 'background-color': '#5782bd' }
} else if (isGroupAxis(axisSpec)) {
- return { 'background-color': '#cd5c5c' };
+ return { 'background-color': '#cd5c5c' }
} else if (isKeyAxis(axisSpec)) {
- return { 'background-color': '#906ebd' };
+ return { 'background-color': '#906ebd' }
} else {
- return { 'background-color': '#62bda9' };
+ return { 'background-color': '#62bda9' }
}
},
@@ -179,14 +179,13 @@ export default class AdvancedTransformation extends Transformation {
isTextareaWidget: function(paramSpec) { return isTextareaWidget(paramSpec) },
parameterChanged: (paramSpec) => {
-
configInstance.chartChanged = false
configInstance.parameterChanged = true
self.emitParameterChange(configInstance)
},
parameterOnKeyDown: function(event, paramSpec) {
- const code = event.keyCode || event.which;
+ const code = event.keyCode || event.which
if (code === 13 && isInputWidget(paramSpec)) {
self.emitParameterChange(configInstance)
} else if (code === 13 && event.shiftKey && isTextareaWidget(paramSpec)) {
@@ -201,7 +200,7 @@ export default class AdvancedTransformation extends Transformation {
}
transform(tableData) {
- this.columns = tableData.columns; /** used in `getSetting` */
+ this.columns = tableData.columns /** used in `getSetting` */
/** initialize in `transform` instead of `getSetting` because this method is called before */
serializeSharedAxes(this.config)
@@ -213,7 +212,7 @@ export default class AdvancedTransformation extends Transformation {
const paramSpecs = getCurrentChartParamSpecs(conf)
const parsedParam = parseParameter(paramSpecs, param)
- let { transformer, column, } = getTransformer(conf, tableData.rows, axisSpecs, axis)
+ let { transformer, column, } = getTransformer(conf, tableData.rows, axisSpecs, axis)
return {
chartChanged: conf.chartChanged,
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/tabledata/columnselector.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/tabledata/columnselector.js b/zeppelin-web/src/app/tabledata/columnselector.js
index 4b9180a..9fcf2f1 100644
--- a/zeppelin-web/src/app/tabledata/columnselector.js
+++ b/zeppelin-web/src/app/tabledata/columnselector.js
@@ -12,7 +12,7 @@
* limitations under the License.
*/
-import Transformation from './transformation';
+import Transformation from './transformation'
/**
* select columns
@@ -26,57 +26,57 @@ import Transformation from './transformation';
* ]
*/
export default class ColumnselectorTransformation extends Transformation {
- constructor(config, columnSelectorProp) {
- super(config);
- this.props = columnSelectorProp;
- };
+ constructor (config, columnSelectorProp) {
+ super(config)
+ this.props = columnSelectorProp
+ }
- getSetting() {
- var self = this;
- var configObj = self.config;
+ getSetting () {
+ let self = this
+ let configObj = self.config
return {
template: 'app/tabledata/columnselector_settings.html',
scope: {
config: self.config,
props: self.props,
tableDataColumns: self.tableDataColumns,
- save: function() {
- self.emitConfig(configObj);
+ save: function () {
+ self.emitConfig(configObj)
},
- remove: function(selectorName) {
- configObj[selectorName] = null;
- self.emitConfig(configObj);
+ remove: function (selectorName) {
+ configObj[selectorName] = null
+ self.emitConfig(configObj)
}
}
- };
- };
+ }
+ }
/**
* Method will be invoked when tableData or config changes
*/
- transform(tableData) {
- this.tableDataColumns = tableData.columns;
- this.removeUnknown();
- return tableData;
- };
+ transform (tableData) {
+ this.tableDataColumns = tableData.columns
+ this.removeUnknown()
+ return tableData
+ }
- removeUnknown() {
- var fields = this.config;
- for (var f in fields) {
+ removeUnknown () {
+ let fields = this.config
+ for (let f in fields) {
if (fields[f]) {
- var found = false;
- for (var i = 0; i < this.tableDataColumns.length; i++) {
- var a = fields[f];
- var b = this.tableDataColumns[i];
+ let found = false
+ for (let i = 0; i < this.tableDataColumns.length; i++) {
+ let a = fields[f]
+ let b = this.tableDataColumns[i]
if (a.index === b.index && a.name === b.name) {
- found = true;
- break;
+ found = true
+ break
}
}
if (!found && (fields[f] instanceof Object) && !(fields[f] instanceof Array)) {
- fields[f] = null;
+ fields[f] = null
}
}
}
- };
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/tabledata/passthrough.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/tabledata/passthrough.js b/zeppelin-web/src/app/tabledata/passthrough.js
index b2d6ec4..e376c43 100644
--- a/zeppelin-web/src/app/tabledata/passthrough.js
+++ b/zeppelin-web/src/app/tabledata/passthrough.js
@@ -12,20 +12,21 @@
* limitations under the License.
*/
-import Transformation from './transformation';
+import Transformation from './transformation'
/**
* passthough the data
*/
export default class PassthroughTransformation extends Transformation {
- constructor(config) {
- super(config);
- };
+ // eslint-disable-next-line no-useless-constructor
+ constructor (config) {
+ super(config)
+ }
/**
* Method will be invoked when tableData or config changes
*/
- transform(tableData) {
- return tableData;
- };
+ transform (tableData) {
+ return tableData
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/tabledata/pivot.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/tabledata/pivot.js b/zeppelin-web/src/app/tabledata/pivot.js
index 366efee..1c938ea 100644
--- a/zeppelin-web/src/app/tabledata/pivot.js
+++ b/zeppelin-web/src/app/tabledata/pivot.js
@@ -12,174 +12,175 @@
* limitations under the License.
*/
-import Transformation from './transformation';
+import Transformation from './transformation'
/**
* pivot table data and return d3 chart data
*/
export default class PivotTransformation extends Transformation {
- constructor(config) {
- super(config);
- };
+ // eslint-disable-next-line no-useless-constructor
+ constructor (config) {
+ super(config)
+ }
- getSetting() {
- var self = this;
+ getSetting () {
+ let self = this
- var configObj = self.config;
- console.log('getSetting', configObj);
+ let configObj = self.config
+ console.log('getSetting', configObj)
return {
template: 'app/tabledata/pivot_settings.html',
scope: {
config: configObj.common.pivot,
tableDataColumns: self.tableDataColumns,
- save: function() {
- self.emitConfig(configObj);
+ save: function () {
+ self.emitConfig(configObj)
},
- removeKey: function(idx) {
- configObj.common.pivot.keys.splice(idx, 1);
- self.emitConfig(configObj);
+ removeKey: function (idx) {
+ configObj.common.pivot.keys.splice(idx, 1)
+ self.emitConfig(configObj)
},
- removeGroup: function(idx) {
- configObj.common.pivot.groups.splice(idx, 1);
- self.emitConfig(configObj);
+ removeGroup: function (idx) {
+ configObj.common.pivot.groups.splice(idx, 1)
+ self.emitConfig(configObj)
},
- removeValue: function(idx) {
- configObj.common.pivot.values.splice(idx, 1);
- self.emitConfig(configObj);
+ removeValue: function (idx) {
+ configObj.common.pivot.values.splice(idx, 1)
+ self.emitConfig(configObj)
},
- setValueAggr: function(idx, aggr) {
- configObj.common.pivot.values[idx].aggr = aggr;
- self.emitConfig(configObj);
+ setValueAggr: function (idx, aggr) {
+ configObj.common.pivot.values[idx].aggr = aggr
+ self.emitConfig(configObj)
}
}
- };
- };
+ }
+ }
/**
* Method will be invoked when tableData or config changes
*/
- transform(tableData) {
- this.tableDataColumns = tableData.columns;
- this.config.common = this.config.common || {};
- this.config.common.pivot = this.config.common.pivot || {};
- var config = this.config.common.pivot;
- var firstTime = (!config.keys && !config.groups && !config.values);
+ transform (tableData) {
+ this.tableDataColumns = tableData.columns
+ this.config.common = this.config.common || {}
+ this.config.common.pivot = this.config.common.pivot || {}
+ let config = this.config.common.pivot
+ let firstTime = (!config.keys && !config.groups && !config.values)
- config.keys = config.keys || [];
- config.groups = config.groups || [];
- config.values = config.values || [];
+ config.keys = config.keys || []
+ config.groups = config.groups || []
+ config.values = config.values || []
- this.removeUnknown();
+ this.removeUnknown()
if (firstTime) {
- this.selectDefault();
+ this.selectDefault()
}
return this.pivot(
tableData,
config.keys,
config.groups,
- config.values);
- };
+ config.values)
+ }
- removeUnknown() {
- var config = this.config.common.pivot;
- var tableDataColumns = this.tableDataColumns;
- var unique = function(list) {
- for (var i = 0; i < list.length; i++) {
- for (var j = i + 1; j < list.length; j++) {
+ removeUnknown () {
+ let config = this.config.common.pivot
+ let tableDataColumns = this.tableDataColumns
+ let unique = function (list) {
+ for (let i = 0; i < list.length; i++) {
+ for (let j = i + 1; j < list.length; j++) {
if (angular.equals(list[i], list[j])) {
- list.splice(j, 1);
+ list.splice(j, 1)
}
}
}
- };
+ }
- var removeUnknown = function(list) {
- for (var i = 0; i < list.length; i++) {
+ let removeUnknown = function (list) {
+ for (let i = 0; i < list.length; i++) {
// remove non existing column
- var found = false;
- for (var j = 0; j < tableDataColumns.length; j++) {
- var a = list[i];
- var b = tableDataColumns[j];
+ let found = false
+ for (let j = 0; j < tableDataColumns.length; j++) {
+ let a = list[i]
+ let b = tableDataColumns[j]
if (a.index === b.index && a.name === b.name) {
- found = true;
- break;
+ found = true
+ break
}
}
if (!found) {
- list.splice(i, 1);
+ list.splice(i, 1)
}
}
- };
+ }
- unique(config.keys);
- removeUnknown(config.keys);
- unique(config.groups);
- removeUnknown(config.groups);
- removeUnknown(config.values);
- };
+ unique(config.keys)
+ removeUnknown(config.keys)
+ unique(config.groups)
+ removeUnknown(config.groups)
+ removeUnknown(config.values)
+ }
- selectDefault() {
- var config = this.config.common.pivot;
+ selectDefault () {
+ let config = this.config.common.pivot
if (config.keys.length === 0 &&
config.groups.length === 0 &&
config.values.length === 0) {
if (config.keys.length === 0 && this.tableDataColumns.length > 0) {
- config.keys.push(this.tableDataColumns[0]);
+ config.keys.push(this.tableDataColumns[0])
}
if (config.values.length === 0 && this.tableDataColumns.length > 1) {
- config.values.push(this.tableDataColumns[1]);
+ config.values.push(this.tableDataColumns[1])
}
}
- };
+ }
- pivot(data, keys, groups, values) {
- var aggrFunc = {
- sum: function(a, b) {
- var varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0;
- var varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0;
- return varA + varB;
+ pivot (data, keys, groups, values) {
+ let aggrFunc = {
+ sum: function (a, b) {
+ let varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0
+ let varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0
+ return varA + varB
},
- count: function(a, b) {
- var varA = (a !== undefined) ? parseInt(a) : 0;
- var varB = (b !== undefined) ? 1 : 0;
- return varA + varB;
+ count: function (a, b) {
+ let varA = (a !== undefined) ? parseInt(a) : 0
+ let varB = (b !== undefined) ? 1 : 0
+ return varA + varB
},
- min: function(a, b) {
- var varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0;
- var varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0;
- return Math.min(varA,varB);
+ min: function (a, b) {
+ let varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0
+ let varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0
+ return Math.min(varA, varB)
},
- max: function(a, b) {
- var varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0;
- var varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0;
- return Math.max(varA,varB);
+ max: function (a, b) {
+ let varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0
+ let varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0
+ return Math.max(varA, varB)
},
- avg: function(a, b, c) {
- var varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0;
- var varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0;
- return varA + varB;
+ avg: function (a, b, c) {
+ let varA = (a !== undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0
+ let varB = (b !== undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0
+ return varA + varB
}
- };
+ }
- var aggrFuncDiv = {
+ let aggrFuncDiv = {
sum: false,
count: false,
min: false,
max: false,
avg: true
- };
+ }
- var schema = {};
- var rows = {};
+ let schema = {}
+ let rows = {}
- for (var i = 0; i < data.rows.length; i++) {
- var row = data.rows[i];
- var s = schema;
- var p = rows;
+ for (let i = 0; i < data.rows.length; i++) {
+ let row = data.rows[i]
+ let s = schema
+ let p = rows
- for (var k = 0; k < keys.length; k++) {
- var key = keys[k];
+ for (let k = 0; k < keys.length; k++) {
+ let key = keys[k]
// add key to schema
if (!s[key.name]) {
@@ -188,21 +189,21 @@ export default class PivotTransformation extends Transformation {
index: key.index,
type: 'key',
children: {}
- };
+ }
}
- s = s[key.name].children;
+ s = s[key.name].children
// add key to row
- var keyKey = row[key.index];
+ let keyKey = row[key.index]
if (!p[keyKey]) {
- p[keyKey] = {};
+ p[keyKey] = {}
}
- p = p[keyKey];
+ p = p[keyKey]
}
- for (var g = 0; g < groups.length; g++) {
- var group = groups[g];
- var groupKey = row[group.index];
+ for (let g = 0; g < groups.length; g++) {
+ let group = groups[g]
+ let groupKey = row[group.index]
// add group to schema
if (!s[groupKey]) {
@@ -211,20 +212,20 @@ export default class PivotTransformation extends Transformation {
index: group.index,
type: 'group',
children: {}
- };
+ }
}
- s = s[groupKey].children;
+ s = s[groupKey].children
// add key to row
if (!p[groupKey]) {
- p[groupKey] = {};
+ p[groupKey] = {}
}
- p = p[groupKey];
+ p = p[groupKey]
}
- for (var v = 0; v < values.length; v++) {
- var value = values[v];
- var valueKey = value.name + '(' + value.aggr + ')';
+ for (let v = 0; v < values.length; v++) {
+ let value = values[v]
+ let valueKey = value.name + '(' + value.aggr + ')'
// add value to schema
if (!s[valueKey]) {
@@ -232,7 +233,7 @@ export default class PivotTransformation extends Transformation {
type: 'value',
order: v,
index: value.index
- };
+ }
}
// add value to row
@@ -240,23 +241,23 @@ export default class PivotTransformation extends Transformation {
p[valueKey] = {
value: (value.aggr !== 'count') ? row[value.index] : 1,
count: 1
- };
+ }
} else {
p[valueKey] = {
value: aggrFunc[value.aggr](p[valueKey].value, row[value.index], p[valueKey].count + 1),
- count: (aggrFuncDiv[value.aggr]) ? p[valueKey].count + 1 : p[valueKey].count
- };
+ count: (aggrFuncDiv[value.aggr]) ? p[valueKey].count + 1 : p[valueKey].count
+ }
}
}
}
- //console.log('schema=%o, rows=%o', schema, rows);
+ // console.log('schema=%o, rows=%o', schema, rows);
return {
keys: keys,
groups: groups,
values: values,
schema: schema,
rows: rows
- };
- };
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/tabledata/tabledata.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/tabledata/tabledata.js b/zeppelin-web/src/app/tabledata/tabledata.js
index 950f456..8e4e6b6 100644
--- a/zeppelin-web/src/app/tabledata/tabledata.js
+++ b/zeppelin-web/src/app/tabledata/tabledata.js
@@ -16,58 +16,58 @@
* Create table data object from paragraph table type result
*/
export default class TableData {
- constructor(columns, rows, comment) {
- this.columns = columns || [];
- this.rows = rows || [];
- this.comment = comment || '';
- };
+ constructor (columns, rows, comment) {
+ this.columns = columns || []
+ this.rows = rows || []
+ this.comment = comment || ''
+ }
- loadParagraphResult(paragraphResult) {
+ loadParagraphResult (paragraphResult) {
if (!paragraphResult || paragraphResult.type !== 'TABLE') {
- console.log('Can not load paragraph result');
- return;
+ console.log('Can not load paragraph result')
+ return
}
- var columnNames = [];
- var rows = [];
- var array = [];
- var textRows = paragraphResult.msg.split('\n');
- var comment = '';
- var commentRow = false;
+ let columnNames = []
+ let rows = []
+ let array = []
+ let textRows = paragraphResult.msg.split('\n')
+ let comment = ''
+ let commentRow = false
- for (var i = 0; i < textRows.length; i++) {
- var textRow = textRows[i];
+ for (let i = 0; i < textRows.length; i++) {
+ let textRow = textRows[i]
if (commentRow) {
- comment += textRow;
- continue;
+ comment += textRow
+ continue
}
if (textRow === '' || textRow === '<!--TABLE_COMMENT-->') {
if (rows.length > 0) {
- commentRow = true;
+ commentRow = true
}
- continue;
+ continue
}
- var textCols = textRow.split('\t');
- var cols = [];
- var cols2 = [];
- for (var j = 0; j < textCols.length; j++) {
- var col = textCols[j];
+ let textCols = textRow.split('\t')
+ let cols = []
+ let cols2 = []
+ for (let j = 0; j < textCols.length; j++) {
+ let col = textCols[j]
if (i === 0) {
- columnNames.push({name: col, index: j, aggr: 'sum'});
+ columnNames.push({name: col, index: j, aggr: 'sum'})
} else {
- cols.push(col);
- cols2.push({key: (columnNames[i]) ? columnNames[i].name : undefined, value: col});
+ cols.push(col)
+ cols2.push({key: (columnNames[i]) ? columnNames[i].name : undefined, value: col})
}
}
if (i !== 0) {
- rows.push(cols);
- array.push(cols2);
+ rows.push(cols)
+ array.push(cols2)
}
}
- this.comment = comment;
- this.columns = columnNames;
- this.rows = rows;
- };
+ this.comment = comment
+ this.columns = columnNames
+ this.rows = rows
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/tabledata/tabledata.test.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/tabledata/tabledata.test.js b/zeppelin-web/src/app/tabledata/tabledata.test.js
index 64dd915..7e41de4 100644
--- a/zeppelin-web/src/app/tabledata/tabledata.test.js
+++ b/zeppelin-web/src/app/tabledata/tabledata.test.js
@@ -12,30 +12,30 @@
* limitations under the License.
*/
-import TableData from './tabledata.js';
+import TableData from './tabledata.js'
-describe('TableData build', function() {
- var td;
+describe('TableData build', function () {
+ let td
- beforeEach(function() {
- console.log(TableData);
- td = new TableData();
- });
+ beforeEach(function () {
+ console.log(TableData)
+ td = new TableData()
+ })
- it('should initialize the default value', function() {
- expect(td.columns.length).toBe(0);
- expect(td.rows.length).toBe(0);
- expect(td.comment).toBe('');
- });
+ it('should initialize the default value', function () {
+ expect(td.columns.length).toBe(0)
+ expect(td.rows.length).toBe(0)
+ expect(td.comment).toBe('')
+ })
- it('should able to create Tabledata from paragraph result', function() {
+ it('should able to create Tabledata from paragraph result', function () {
td.loadParagraphResult({
type: 'TABLE',
msg: 'key\tvalue\na\t10\nb\t20\n\nhello'
- });
+ })
- expect(td.columns.length).toBe(2);
- expect(td.rows.length).toBe(2);
- expect(td.comment).toBe('hello');
- });
-});
+ expect(td.columns.length).toBe(2)
+ expect(td.rows.length).toBe(2)
+ expect(td.comment).toBe('hello')
+ })
+})
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/tabledata/transformation.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/tabledata/transformation.js b/zeppelin-web/src/app/tabledata/transformation.js
index bdd620b..f142618 100644
--- a/zeppelin-web/src/app/tabledata/transformation.js
+++ b/zeppelin-web/src/app/tabledata/transformation.js
@@ -16,10 +16,10 @@
* Base class for visualization
*/
export default class Transformation {
- constructor(config) {
- this.config = config;
- this._emitter;
- };
+ constructor (config) {
+ this.config = config
+ this._emitter = () => {}
+ }
/**
* return {
@@ -27,77 +27,77 @@ export default class Transformation {
* scope : an object to bind to template scope
* }
*/
- getSetting() {
+ getSetting () {
// override this
- };
+ }
/**
* Method will be invoked when tableData or config changes
*/
- transform(tableData) {
+ transform (tableData) {
// override this
- };
+ }
/**
* render setting
*/
- renderSetting(targetEl) {
- var setting = this.getSetting();
+ renderSetting (targetEl) {
+ let setting = this.getSetting()
if (!setting) {
- return;
+ return
}
// already readered
if (this._scope) {
- var self = this;
- this._scope.$apply(function() {
- for (var k in setting.scope) {
- self._scope[k] = setting.scope[k];
+ let self = this
+ this._scope.$apply(function () {
+ for (let k in setting.scope) {
+ self._scope[k] = setting.scope[k]
}
- for (var k in self._prevSettingScope) {
+ for (let k in self._prevSettingScope) {
if (!setting.scope[k]) {
- self._scope[k] = setting.scope[k];
+ self._scope[k] = setting.scope[k]
}
}
- });
- return;
+ })
+ return
} else {
- this._prevSettingScope = setting.scope;
+ this._prevSettingScope = setting.scope
}
- var scope = this._createNewScope();
- for (var k in setting.scope) {
- scope[k] = setting.scope[k];
+ let scope = this._createNewScope()
+ for (let k in setting.scope) {
+ scope[k] = setting.scope[k]
}
- var template = setting.template;
+ let template = setting.template
if (template.split('\n').length === 1 &&
template.endsWith('.html')) { // template is url
- var self = this;
- this._templateRequest(template).then(function(t) {
- self._render(targetEl, t, scope);
- });
+ let self = this
+ this._templateRequest(template).then(function (t) {
+ self._render(targetEl, t, scope)
+ })
} else {
- this._render(targetEl, template, scope);
+ this._render(targetEl, template, scope)
}
- };
+ }
- _render(targetEl, template, scope) {
- this._targetEl = targetEl;
- targetEl.html(template);
- this._compile(targetEl.contents())(scope);
- this._scope = scope;
- };
+ _render (targetEl, template, scope) {
+ this._targetEl = targetEl
+ targetEl.html(template)
+ this._compile(targetEl.contents())(scope)
+ this._scope = scope
+ }
- setConfig(config) {
- this.config = config;
- };
+ setConfig (config) {
+ this.config = config
+ }
/**
* Emit config. config will sent to server and saved.
*/
- emitConfig(config) {
- this._emitter(config);
- };
+ emitConfig (config) {
+ this._emitter(config)
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/visualization/builtins/visualization-areachart.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/visualization/builtins/visualization-areachart.js b/zeppelin-web/src/app/visualization/builtins/visualization-areachart.js
index 4e0d318..900f0f4 100644
--- a/zeppelin-web/src/app/visualization/builtins/visualization-areachart.js
+++ b/zeppelin-web/src/app/visualization/builtins/visualization-areachart.js
@@ -12,29 +12,29 @@
* limitations under the License.
*/
-import Nvd3ChartVisualization from './visualization-nvd3chart';
-import PivotTransformation from '../../tabledata/pivot';
+import Nvd3ChartVisualization from './visualization-nvd3chart'
+import PivotTransformation from '../../tabledata/pivot'
/**
* Visualize data in area chart
*/
export default class AreachartVisualization extends Nvd3ChartVisualization {
- constructor(targetEl, config) {
- super(targetEl, config);
+ constructor (targetEl, config) {
+ super(targetEl, config)
- this.pivot = new PivotTransformation(config);
- };
+ this.pivot = new PivotTransformation(config)
+ }
- type() {
- return 'stackedAreaChart';
- };
+ type () {
+ return 'stackedAreaChart'
+ }
- getTransformation() {
- return this.pivot;
- };
+ getTransformation () {
+ return this.pivot
+ }
- render(pivot) {
- var d3Data = this.d3DataFromPivot(
+ render (pivot) {
+ let d3Data = this.d3DataFromPivot(
pivot.schema,
pivot.rows,
pivot.keys,
@@ -42,37 +42,36 @@ export default class AreachartVisualization extends Nvd3ChartVisualization {
pivot.values,
false,
true,
- false);
+ false)
- this.xLabels = d3Data.xLabels;
- super.render(d3Data);
- };
+ this.xLabels = d3Data.xLabels
+ super.render(d3Data)
+ }
/**
* Set new config
*/
- setConfig(config) {
- super.setConfig(config);
- this.pivot.setConfig(config);
- };
+ setConfig (config) {
+ super.setConfig(config)
+ this.pivot.setConfig(config)
+ }
- configureChart(chart) {
- var self = this;
- chart.xAxis.tickFormat(function(d) {return self.xAxisTickFormat(d, self.xLabels);});
- chart.yAxis.tickFormat(function(d) {return self.yAxisTickFormat(d);});
- chart.yAxis.axisLabelDistance(50);
- chart.useInteractiveGuideline(true); // for better UX and performance issue. (https://github.com/novus/nvd3/issues/691)
+ configureChart (chart) {
+ let self = this
+ chart.xAxis.tickFormat(function (d) { return self.xAxisTickFormat(d, self.xLabels) })
+ chart.yAxis.tickFormat(function (d) { return self.yAxisTickFormat(d) })
+ chart.yAxis.axisLabelDistance(50)
+ chart.useInteractiveGuideline(true) // for better UX and performance issue. (https://github.com/novus/nvd3/issues/691)
- this.chart.style(this.config.style || 'stack');
+ this.chart.style(this.config.style || 'stack')
- var self = this;
- this.chart.dispatch.on('stateChange', function(s) {
- self.config.style = s.style;
+ this.chart.dispatch.on('stateChange', function (s) {
+ self.config.style = s.style
// give some time to animation finish
- setTimeout(function() {
- self.emitConfig(self.config);
- }, 500);
- });
- };
+ setTimeout(function () {
+ self.emitConfig(self.config)
+ }, 500)
+ })
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/visualization/builtins/visualization-barchart.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/visualization/builtins/visualization-barchart.js b/zeppelin-web/src/app/visualization/builtins/visualization-barchart.js
index 15f0337..258fcce 100644
--- a/zeppelin-web/src/app/visualization/builtins/visualization-barchart.js
+++ b/zeppelin-web/src/app/visualization/builtins/visualization-barchart.js
@@ -12,29 +12,29 @@
* limitations under the License.
*/
-import Nvd3ChartVisualization from './visualization-nvd3chart';
-import PivotTransformation from '../../tabledata/pivot';
+import Nvd3ChartVisualization from './visualization-nvd3chart'
+import PivotTransformation from '../../tabledata/pivot'
/**
* Visualize data in bar char
*/
export default class BarchartVisualization extends Nvd3ChartVisualization {
- constructor(targetEl, config) {
- super(targetEl, config);
+ constructor (targetEl, config) {
+ super(targetEl, config)
- this.pivot = new PivotTransformation(config);
- };
+ this.pivot = new PivotTransformation(config)
+ }
- type() {
- return 'multiBarChart';
- };
+ type () {
+ return 'multiBarChart'
+ }
- getTransformation() {
- return this.pivot;
- };
+ getTransformation () {
+ return this.pivot
+ }
- render(pivot) {
- var d3Data = this.d3DataFromPivot(
+ render (pivot) {
+ let d3Data = this.d3DataFromPivot(
pivot.schema,
pivot.rows,
pivot.keys,
@@ -42,79 +42,77 @@ export default class BarchartVisualization extends Nvd3ChartVisualization {
pivot.values,
true,
true,
- true);
+ true)
- super.render(d3Data);
- this.config.changeXLabel(this.config.xLabelStatus);
- };
+ super.render(d3Data)
+ this.config.changeXLabel(this.config.xLabelStatus)
+ }
/**
* Set new config
*/
- setConfig(config) {
- super.setConfig(config);
- this.pivot.setConfig(config);
- };
+ setConfig (config) {
+ super.setConfig(config)
+ this.pivot.setConfig(config)
+ }
- configureChart(chart) {
- var self = this;
- var configObj = self.config;
+ configureChart (chart) {
+ let self = this
+ let configObj = self.config
- chart.yAxis.axisLabelDistance(50);
- chart.yAxis.tickFormat(function(d) {return self.yAxisTickFormat(d);});
+ chart.yAxis.axisLabelDistance(50)
+ chart.yAxis.tickFormat(function (d) { return self.yAxisTickFormat(d) })
- self.chart.stacked(this.config.stacked);
+ self.chart.stacked(this.config.stacked)
self.config.changeXLabel = function(type) {
switch (type) {
case 'default':
- self.chart._options['showXAxis'] = true;
- self.chart._options['margin'] = {bottom: 50};
- self.chart.xAxis.rotateLabels(0);
- configObj.xLabelStatus = 'default';
- break;
+ self.chart._options['showXAxis'] = true
+ self.chart._options['margin'] = {bottom: 50}
+ self.chart.xAxis.rotateLabels(0)
+ configObj.xLabelStatus = 'default'
+ break
case 'rotate':
- self.chart._options['showXAxis'] = true;
- self.chart._options['margin'] = {bottom: 140};
- self.chart.xAxis.rotateLabels(-45);
- configObj.xLabelStatus = 'rotate';
- break;
+ self.chart._options['showXAxis'] = true
+ self.chart._options['margin'] = {bottom: 140}
+ self.chart.xAxis.rotateLabels(-45)
+ configObj.xLabelStatus = 'rotate'
+ break
case 'hide':
- self.chart._options['showXAxis'] = false;
- self.chart._options['margin'] = {bottom: 50};
- d3.select('#' + self.targetEl[0].id + '> svg').select('g.nv-axis.nv-x').selectAll('*').remove();
- configObj.xLabelStatus = 'hide';
- break;
+ self.chart._options['showXAxis'] = false
+ self.chart._options['margin'] = {bottom: 50}
+ d3.select('#' + self.targetEl[0].id + '> svg').select('g.nv-axis.nv-x').selectAll('*').remove()
+ configObj.xLabelStatus = 'hide'
+ break
}
- };
+ }
self.config.isXLabelStatus = function(type) {
if (configObj.xLabelStatus === type) {
- return true;
+ return true
} else {
- return false;
+ return false
}
- };
+ }
this.chart.dispatch.on('stateChange', function(s) {
- configObj.stacked = s.stacked;
+ configObj.stacked = s.stacked
// give some time to animation finish
setTimeout(function() {
- self.emitConfig(configObj);
- }, 500);
- });
- };
-
-
+ self.emitConfig(configObj)
+ }, 500)
+ })
+ }
getSetting(chart) {
- var self = this;
- var configObj = self.config;
+ let self = this
+ let configObj = self.config
// default to visualize xLabel
- if (typeof(configObj.xLabelStatus) === 'undefined') {
- configObj.changeXLabel('default');
+ if (typeof (configObj.xLabelStatus) === 'undefined') {
+ configObj.changeXLabel('default')
}
return {
@@ -147,10 +145,10 @@ export default class BarchartVisualization extends Nvd3ChartVisualization {
scope: {
config: configObj,
save: function(type) {
- configObj.changeXLabel(type);
- self.emitConfig(configObj);
+ configObj.changeXLabel(type)
+ self.emitConfig(configObj)
}
}
- };
- };
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/visualization/builtins/visualization-linechart.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/visualization/builtins/visualization-linechart.js b/zeppelin-web/src/app/visualization/builtins/visualization-linechart.js
index 577001f..31da47b 100644
--- a/zeppelin-web/src/app/visualization/builtins/visualization-linechart.js
+++ b/zeppelin-web/src/app/visualization/builtins/visualization-linechart.js
@@ -12,33 +12,33 @@
* limitations under the License.
*/
-import Nvd3ChartVisualization from './visualization-nvd3chart';
-import PivotTransformation from '../../tabledata/pivot';
+import Nvd3ChartVisualization from './visualization-nvd3chart'
+import PivotTransformation from '../../tabledata/pivot'
/**
* Visualize data in line chart
*/
export default class LinechartVisualization extends Nvd3ChartVisualization {
- constructor(targetEl, config) {
- super(targetEl, config);
+ constructor (targetEl, config) {
+ super(targetEl, config)
- this.pivot = new PivotTransformation(config);
- };
+ this.pivot = new PivotTransformation(config)
+ }
- type() {
+ type () {
if (this.config.lineWithFocus) {
- return 'lineWithFocusChart';
+ return 'lineWithFocusChart'
} else {
- return 'lineChart';
+ return 'lineChart'
}
- };
+ }
- getTransformation() {
- return this.pivot;
- };
+ getTransformation () {
+ return this.pivot
+ }
- render(pivot) {
- var d3Data = this.d3DataFromPivot(
+ render (pivot) {
+ let d3Data = this.d3DataFromPivot(
pivot.schema,
pivot.rows,
pivot.keys,
@@ -46,49 +46,49 @@ export default class LinechartVisualization extends Nvd3ChartVisualization {
pivot.values,
false,
true,
- false);
+ false)
- this.xLabels = d3Data.xLabels;
- super.render(d3Data);
- };
+ this.xLabels = d3Data.xLabels
+ super.render(d3Data)
+ }
/**
* Set new config
*/
- setConfig(config) {
- super.setConfig(config);
- this.pivot.setConfig(config);
+ setConfig (config) {
+ super.setConfig(config)
+ this.pivot.setConfig(config)
// change mode
if (this.currentMode !== config.lineWithFocus) {
- super.destroy();
- this.currentMode = config.lineWithFocus;
+ super.destroy()
+ this.currentMode = config.lineWithFocus
}
- };
+ }
- configureChart(chart) {
- var self = this;
- chart.xAxis.tickFormat(function(d) {return self.xAxisTickFormat(d, self.xLabels);});
- chart.yAxis.tickFormat(function(d) {
+ configureChart (chart) {
+ let self = this
+ chart.xAxis.tickFormat(function (d) { return self.xAxisTickFormat(d, self.xLabels) })
+ chart.yAxis.tickFormat(function (d) {
if (d === undefined) {
- return 'N/A';
+ return 'N/A'
}
- return self.yAxisTickFormat(d, self.xLabels);
- });
- chart.yAxis.axisLabelDistance(50);
+ return self.yAxisTickFormat(d, self.xLabels)
+ })
+ chart.yAxis.axisLabelDistance(50)
if (chart.useInteractiveGuideline) { // lineWithFocusChart hasn't got useInteractiveGuideline
- chart.useInteractiveGuideline(true); // for better UX and performance issue. (https://github.com/novus/nvd3/issues/691)
+ chart.useInteractiveGuideline(true) // for better UX and performance issue. (https://github.com/novus/nvd3/issues/691)
}
if (this.config.forceY) {
- chart.forceY([0]); // force y-axis minimum to 0 for line chart.
+ chart.forceY([0]) // force y-axis minimum to 0 for line chart.
} else {
- chart.forceY([]);
+ chart.forceY([])
}
- };
+ }
- getSetting(chart) {
- var self = this;
- var configObj = self.config;
+ getSetting (chart) {
+ let self = this
+ let configObj = self.config
return {
template: `<div>
@@ -109,14 +109,14 @@ export default class LinechartVisualization extends Nvd3ChartVisualization {
</div>`,
scope: {
config: configObj,
- save: function() {
- self.emitConfig(configObj);
+ save: function () {
+ self.emitConfig(configObj)
}
}
- };
- };
+ }
+ }
- defaultY() {
- return undefined;
- };
+ defaultY () {
+ return undefined
+ }
}
[6/8] zeppelin git commit: [ZEPPELIN-1940] lint rule set is NOT
applied at all.
Posted by ah...@apache.org.
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/notebook/notebook.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/notebook/notebook.controller.js b/zeppelin-web/src/app/notebook/notebook.controller.js
index 1322419..e481e9b 100644
--- a/zeppelin-web/src/app/notebook/notebook.controller.js
+++ b/zeppelin-web/src/app/notebook/notebook.controller.js
@@ -12,25 +12,25 @@
* limitations under the License.
*/
-import { isParagraphRunning, } from './paragraph/paragraph.status';
+import { isParagraphRunning, } from './paragraph/paragraph.status'
-angular.module('zeppelinWebApp').controller('NotebookCtrl', NotebookCtrl);
+angular.module('zeppelinWebApp').controller('NotebookCtrl', NotebookCtrl)
-function NotebookCtrl($scope, $route, $routeParams, $location, $rootScope,
+function NotebookCtrl ($scope, $route, $routeParams, $location, $rootScope,
$http, websocketMsgSrv, baseUrlSrv, $timeout, saveAsService,
ngToast, noteActionSrv, noteVarShareService, TRASH_FOLDER_ID,
heliumService) {
- 'ngInject';
+ 'ngInject'
- ngToast.dismiss();
+ ngToast.dismiss()
- $scope.note = null;
- $scope.moment = moment;
- $scope.editorToggled = false;
- $scope.tableToggled = false;
- $scope.viewOnly = false;
- $scope.showSetting = false;
- $scope.looknfeelOption = ['default', 'simple', 'report'];
+ $scope.note = null
+ $scope.moment = moment
+ $scope.editorToggled = false
+ $scope.tableToggled = false
+ $scope.viewOnly = false
+ $scope.showSetting = false
+ $scope.looknfeelOption = ['default', 'simple', 'report']
$scope.cronOption = [
{name: 'None', value: undefined},
{name: '1m', value: '0 0/1 * * * ?'},
@@ -40,50 +40,50 @@ function NotebookCtrl($scope, $route, $routeParams, $location, $rootScope,
{name: '6h', value: '0 0 0/6 * * ?'},
{name: '12h', value: '0 0 0/12 * * ?'},
{name: '1d', value: '0 0 0 * * ?'}
- ];
+ ]
- $scope.interpreterSettings = [];
- $scope.interpreterBindings = [];
- $scope.isNoteDirty = null;
- $scope.saveTimer = null;
+ $scope.interpreterSettings = []
+ $scope.interpreterBindings = []
+ $scope.isNoteDirty = null
+ $scope.saveTimer = null
- var connectedOnce = false;
- var isRevisionPath = function(path) {
- var pattern = new RegExp('^.*\/notebook\/[a-zA-Z0-9_]*\/revision\/[a-zA-Z0-9_]*');
- return pattern.test(path);
- };
+ let connectedOnce = false
+ let isRevisionPath = function (path) {
+ let pattern = new RegExp('^.*\/notebook\/[a-zA-Z0-9_]*\/revision\/[a-zA-Z0-9_]*')
+ return pattern.test(path)
+ }
- $scope.noteRevisions = [];
- $scope.currentRevision = 'Head';
- $scope.revisionView = isRevisionPath($location.path());
+ $scope.noteRevisions = []
+ $scope.currentRevision = 'Head'
+ $scope.revisionView = isRevisionPath($location.path())
- $scope.$on('setConnectedStatus', function(event, param) {
+ $scope.$on('setConnectedStatus', function (event, param) {
if (connectedOnce && param) {
- initNotebook();
+ initNotebook()
}
- connectedOnce = true;
- });
+ connectedOnce = true
+ })
- $scope.getCronOptionNameFromValue = function(value) {
+ $scope.getCronOptionNameFromValue = function (value) {
if (!value) {
- return '';
+ return ''
}
- for (var o in $scope.cronOption) {
+ for (let o in $scope.cronOption) {
if ($scope.cronOption[o].value === value) {
- return $scope.cronOption[o].name;
+ return $scope.cronOption[o].name
}
}
- return value;
- };
+ return value
+ }
- $scope.blockAnonUsers = function() {
- var zeppelinVersion = $rootScope.zeppelinVersion;
- var url = 'https://zeppelin.apache.org/docs/' + zeppelinVersion + '/security/notebook_authorization.html';
- var content = 'Only authenticated user can set the permission.' +
+ $scope.blockAnonUsers = function () {
+ let zeppelinVersion = $rootScope.zeppelinVersion
+ let url = 'https://zeppelin.apache.org/docs/' + zeppelinVersion + '/security/notebook_authorization.html'
+ let content = 'Only authenticated user can set the permission.' +
'<a data-toggle="tooltip" data-placement="top" title="Learn more" target="_blank" href=' + url + '>' +
'<i class="icon-question" />' +
- '</a>';
+ '</a>'
BootstrapDialog.show({
closable: false,
closeByBackdrop: false,
@@ -92,187 +92,189 @@ function NotebookCtrl($scope, $route, $routeParams, $location, $rootScope,
message: content,
buttons: [{
label: 'Close',
- action: function(dialog) {
- dialog.close();
+ action: function (dialog) {
+ dialog.close()
}
}]
- });
- };
+ })
+ }
/** Init the new controller */
- var initNotebook = function() {
- noteVarShareService.clear();
+ const initNotebook = function () {
+ noteVarShareService.clear()
if ($routeParams.revisionId) {
- websocketMsgSrv.getNoteByRevision($routeParams.noteId, $routeParams.revisionId);
+ websocketMsgSrv.getNoteByRevision($routeParams.noteId, $routeParams.revisionId)
} else {
- websocketMsgSrv.getNote($routeParams.noteId);
+ websocketMsgSrv.getNote($routeParams.noteId)
}
- websocketMsgSrv.listRevisionHistory($routeParams.noteId);
- var currentRoute = $route.current;
+ websocketMsgSrv.listRevisionHistory($routeParams.noteId)
+ let currentRoute = $route.current
if (currentRoute) {
setTimeout(
- function() {
- var routeParams = currentRoute.params;
- var $id = angular.element('#' + routeParams.paragraph + '_container');
+ function () {
+ let routeParams = currentRoute.params
+ let $id = angular.element('#' + routeParams.paragraph + '_container')
if ($id.length > 0) {
// adjust for navbar
- var top = $id.offset().top - 103;
- angular.element('html, body').scrollTo({top: top, left: 0});
+ let top = $id.offset().top - 103
+ angular.element('html, body').scrollTo({top: top, left: 0})
}
},
1000
- );
+ )
}
- };
+ }
- initNotebook();
+ initNotebook()
- $scope.focusParagraphOnClick = function(clickEvent) {
+ $scope.focusParagraphOnClick = function (clickEvent) {
if (!$scope.note) {
- return;
+ return
}
- for (var i = 0; i < $scope.note.paragraphs.length; i++) {
- var paragraphId = $scope.note.paragraphs[i].id;
+ for (let i = 0; i < $scope.note.paragraphs.length; i++) {
+ let paragraphId = $scope.note.paragraphs[i].id
if (jQuery.contains(angular.element('#' + paragraphId + '_container')[0], clickEvent.target)) {
- $scope.$broadcast('focusParagraph', paragraphId, 0, true);
- break;
+ $scope.$broadcast('focusParagraph', paragraphId, 0, true)
+ break
}
}
- };
+ }
// register mouseevent handler for focus paragraph
- document.addEventListener('click', $scope.focusParagraphOnClick);
+ document.addEventListener('click', $scope.focusParagraphOnClick)
- $scope.keyboardShortcut = function(keyEvent) {
+ $scope.keyboardShortcut = function (keyEvent) {
// handle keyevent
if (!$scope.viewOnly && !$scope.revisionView) {
- $scope.$broadcast('keyEvent', keyEvent);
+ $scope.$broadcast('keyEvent', keyEvent)
}
- };
+ }
// register mouseevent handler for focus paragraph
- document.addEventListener('keydown', $scope.keyboardShortcut);
+ document.addEventListener('keydown', $scope.keyboardShortcut)
- $scope.paragraphOnDoubleClick = function(paragraphId) {
- $scope.$broadcast('doubleClickParagraph', paragraphId);
- };
+ $scope.paragraphOnDoubleClick = function (paragraphId) {
+ $scope.$broadcast('doubleClickParagraph', paragraphId)
+ }
// Move the note to trash and go back to the main page
- $scope.moveNoteToTrash = function(noteId) {
- noteActionSrv.moveNoteToTrash(noteId, true);
- };
+ $scope.moveNoteToTrash = function (noteId) {
+ noteActionSrv.moveNoteToTrash(noteId, true)
+ }
// Remove the note permanently if it's in the trash
- $scope.removeNote = function(noteId) {
- noteActionSrv.removeNote(noteId, true);
- };
-
- $scope.isTrash = function(note) {
- return note ? note.name.split('/')[0] === TRASH_FOLDER_ID : false;
- };
-
- //Export notebook
- $scope.exportNote = function() {
- var jsonContent = JSON.stringify($scope.note);
- saveAsService.saveAs(jsonContent, $scope.note.name, 'json');
- };
-
- //Clone note
- $scope.cloneNote = function(noteId) {
+ $scope.removeNote = function (noteId) {
+ noteActionSrv.removeNote(noteId, true)
+ }
+
+ $scope.isTrash = function (note) {
+ return note ? note.name.split('/')[0] === TRASH_FOLDER_ID : false
+ }
+
+ // Export notebook
+ $scope.exportNote = function () {
+ let jsonContent = JSON.stringify($scope.note)
+ saveAsService.saveAs(jsonContent, $scope.note.name, 'json')
+ }
+
+ // Clone note
+ $scope.cloneNote = function (noteId) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Do you want to clone this note?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.cloneNote(noteId);
- $location.path('/');
+ websocketMsgSrv.cloneNote(noteId)
+ $location.path('/')
}
}
- });
- };
+ })
+ }
// checkpoint/commit notebook
- $scope.checkpointNote = function(commitMessage) {
+ $scope.checkpointNote = function (commitMessage) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Commit note to current repository?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.checkpointNote($routeParams.noteId, commitMessage);
+ websocketMsgSrv.checkpointNote($routeParams.noteId, commitMessage)
}
}
- });
- document.getElementById('note.checkpoint.message').value = '';
- };
+ })
+ document.getElementById('note.checkpoint.message').value = ''
+ }
// set notebook head to given revision
- $scope.setNoteRevision = function() {
+ $scope.setNoteRevision = function () {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Set notebook head to current revision?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- websocketMsgSrv.setNoteRevision($routeParams.noteId, $routeParams.revisionId);
+ websocketMsgSrv.setNoteRevision($routeParams.noteId, $routeParams.revisionId)
}
}
- });
- };
+ })
+ }
- $scope.$on('listRevisionHistory', function(event, data) {
- console.log('received list of revisions %o', data);
- $scope.noteRevisions = data.revisionList;
+ $scope.$on('listRevisionHistory', function (event, data) {
+ console.log('received list of revisions %o', data)
+ $scope.noteRevisions = data.revisionList
$scope.noteRevisions.splice(0, 0, {
id: 'Head',
message: 'Head'
- });
+ })
if ($routeParams.revisionId) {
- var index = _.findIndex($scope.noteRevisions, {'id': $routeParams.revisionId});
+ let index = _.findIndex($scope.noteRevisions, {'id': $routeParams.revisionId})
if (index > -1) {
- $scope.currentRevision = $scope.noteRevisions[index].message;
+ $scope.currentRevision = $scope.noteRevisions[index].message
}
}
- });
+ })
- $scope.$on('noteRevision', function(event, data) {
- console.log('received note revision %o', data);
+ $scope.$on('noteRevision', function (event, data) {
+ console.log('received note revision %o', data)
if (data.note) {
- $scope.note = data.note;
- initializeLookAndFeel();
+ $scope.note = data.note
+ initializeLookAndFeel()
} else {
- $location.path('/');
+ $location.path('/')
}
- });
+ })
- $scope.$on('setNoteRevisionResult', function(event, data) {
- console.log('received set note revision result %o', data);
+ $scope.$on('setNoteRevisionResult', function (event, data) {
+ console.log('received set note revision result %o', data)
if (data.status) {
- $location.path('/notebook/' + $routeParams.noteId);
+ $location.path('/notebook/' + $routeParams.noteId)
}
- });
+ })
- $scope.visitRevision = function(revision) {
+ $scope.visitRevision = function (revision) {
if (revision.id) {
if (revision.id === 'Head') {
- $location.path('/notebook/' + $routeParams.noteId);
+ $location.path('/notebook/' + $routeParams.noteId)
} else {
- $location.path('/notebook/' + $routeParams.noteId + '/revision/' + revision.id);
+ $location.path('/notebook/' + $routeParams.noteId + '/revision/' + revision.id)
}
} else {
ngToast.danger({content: 'There is a problem with this Revision',
- verticalPosition: 'top', dismissOnTimeout: false});
+ verticalPosition: 'top',
+ dismissOnTimeout: false
+ })
}
- };
+ }
- $scope.runAllParagraphs = function(noteId) {
+ $scope.runAllParagraphs = function (noteId) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Run all paragraphs?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
const paragraphs = $scope.note.paragraphs.map(p => {
return {
@@ -281,439 +283,439 @@ function NotebookCtrl($scope, $route, $routeParams, $location, $rootScope,
paragraph: p.text,
config: p.config,
params: p.settings.params
- };
- });
- websocketMsgSrv.runAllParagraphs(noteId, paragraphs);
+ }
+ })
+ websocketMsgSrv.runAllParagraphs(noteId, paragraphs)
}
}
- });
- };
+ })
+ }
- $scope.saveNote = function() {
+ $scope.saveNote = function () {
if ($scope.note && $scope.note.paragraphs) {
- _.forEach($scope.note.paragraphs, function(par) {
+ _.forEach($scope.note.paragraphs, function (par) {
angular
.element('#' + par.id + '_paragraphColumn_main')
.scope()
- .saveParagraph(par);
- });
- $scope.isNoteDirty = null;
+ .saveParagraph(par)
+ })
+ $scope.isNoteDirty = null
}
- };
+ }
- $scope.clearAllParagraphOutput = function(noteId) {
- noteActionSrv.clearAllParagraphOutput(noteId);
- };
+ $scope.clearAllParagraphOutput = function (noteId) {
+ noteActionSrv.clearAllParagraphOutput(noteId)
+ }
- $scope.toggleAllEditor = function() {
+ $scope.toggleAllEditor = function () {
if ($scope.editorToggled) {
- $scope.$broadcast('openEditor');
+ $scope.$broadcast('openEditor')
} else {
- $scope.$broadcast('closeEditor');
+ $scope.$broadcast('closeEditor')
}
- $scope.editorToggled = !$scope.editorToggled;
- };
+ $scope.editorToggled = !$scope.editorToggled
+ }
- $scope.showAllEditor = function() {
- $scope.$broadcast('openEditor');
- };
+ $scope.showAllEditor = function () {
+ $scope.$broadcast('openEditor')
+ }
- $scope.hideAllEditor = function() {
- $scope.$broadcast('closeEditor');
- };
+ $scope.hideAllEditor = function () {
+ $scope.$broadcast('closeEditor')
+ }
- $scope.toggleAllTable = function() {
+ $scope.toggleAllTable = function () {
if ($scope.tableToggled) {
- $scope.$broadcast('openTable');
+ $scope.$broadcast('openTable')
} else {
- $scope.$broadcast('closeTable');
+ $scope.$broadcast('closeTable')
}
- $scope.tableToggled = !$scope.tableToggled;
- };
+ $scope.tableToggled = !$scope.tableToggled
+ }
- $scope.showAllTable = function() {
- $scope.$broadcast('openTable');
- };
+ $scope.showAllTable = function () {
+ $scope.$broadcast('openTable')
+ }
- $scope.hideAllTable = function() {
- $scope.$broadcast('closeTable');
- };
+ $scope.hideAllTable = function () {
+ $scope.$broadcast('closeTable')
+ }
/**
* @returns {boolean} true if one more paragraphs are running. otherwise return false.
*/
- $scope.isNoteRunning = function() {
- if (!$scope.note) { return false; }
+ $scope.isNoteRunning = function () {
+ if (!$scope.note) { return false }
for (let i = 0; i < $scope.note.paragraphs.length; i++) {
if (isParagraphRunning($scope.note.paragraphs[i])) {
- return true;
+ return true
}
}
- return false;
- };
+ return false
+ }
- $scope.killSaveTimer = function() {
+ $scope.killSaveTimer = function () {
if ($scope.saveTimer) {
- $timeout.cancel($scope.saveTimer);
- $scope.saveTimer = null;
- }
- };
-
- $scope.startSaveTimer = function() {
- $scope.killSaveTimer();
- $scope.isNoteDirty = true;
- //console.log('startSaveTimer called ' + $scope.note.id);
- $scope.saveTimer = $timeout(function() {
- $scope.saveNote();
- }, 10000);
- };
-
- angular.element(window).on('beforeunload', function(e) {
- $scope.killSaveTimer();
- $scope.saveNote();
- });
-
- $scope.setLookAndFeel = function(looknfeel) {
- $scope.note.config.looknfeel = looknfeel;
+ $timeout.cancel($scope.saveTimer)
+ $scope.saveTimer = null
+ }
+ }
+
+ $scope.startSaveTimer = function () {
+ $scope.killSaveTimer()
+ $scope.isNoteDirty = true
+ // console.log('startSaveTimer called ' + $scope.note.id);
+ $scope.saveTimer = $timeout(function () {
+ $scope.saveNote()
+ }, 10000)
+ }
+
+ angular.element(window).on('beforeunload', function (e) {
+ $scope.killSaveTimer()
+ $scope.saveNote()
+ })
+
+ $scope.setLookAndFeel = function (looknfeel) {
+ $scope.note.config.looknfeel = looknfeel
if ($scope.revisionView === true) {
- $rootScope.$broadcast('setLookAndFeel', $scope.note.config.looknfeel);
+ $rootScope.$broadcast('setLookAndFeel', $scope.note.config.looknfeel)
} else {
- $scope.setConfig();
+ $scope.setConfig()
}
- };
+ }
/** Set cron expression for this note **/
- $scope.setCronScheduler = function(cronExpr) {
+ $scope.setCronScheduler = function (cronExpr) {
if (cronExpr) {
if (!$scope.note.config.cronExecutingUser) {
- $scope.note.config.cronExecutingUser = $rootScope.ticket.principal;
+ $scope.note.config.cronExecutingUser = $rootScope.ticket.principal
}
} else {
- $scope.note.config.cronExecutingUser = '';
+ $scope.note.config.cronExecutingUser = ''
}
- $scope.note.config.cron = cronExpr;
- $scope.setConfig();
- };
+ $scope.note.config.cron = cronExpr
+ $scope.setConfig()
+ }
/** Set the username of the user to be used to execute all notes in notebook **/
- $scope.setCronExecutingUser = function(cronExecutingUser) {
- $scope.note.config.cronExecutingUser = cronExecutingUser;
- $scope.setConfig();
- };
+ $scope.setCronExecutingUser = function (cronExecutingUser) {
+ $scope.note.config.cronExecutingUser = cronExecutingUser
+ $scope.setConfig()
+ }
/** Set release resource for this note **/
- $scope.setReleaseResource = function(value) {
- $scope.note.config.releaseresource = value;
- $scope.setConfig();
- };
+ $scope.setReleaseResource = function (value) {
+ $scope.note.config.releaseresource = value
+ $scope.setConfig()
+ }
/** Update note config **/
- $scope.setConfig = function(config) {
+ $scope.setConfig = function (config) {
if (config) {
- $scope.note.config = config;
+ $scope.note.config = config
}
- websocketMsgSrv.updateNote($scope.note.id, $scope.note.name, $scope.note.config);
- };
+ websocketMsgSrv.updateNote($scope.note.id, $scope.note.name, $scope.note.config)
+ }
/** Update the note name */
- $scope.updateNoteName = function(newName) {
- const trimmedNewName = newName.trim();
+ $scope.updateNoteName = function (newName) {
+ const trimmedNewName = newName.trim()
if (trimmedNewName.length > 0 && $scope.note.name !== trimmedNewName) {
- $scope.note.name = trimmedNewName;
- websocketMsgSrv.renameNote($scope.note.id, $scope.note.name);
+ $scope.note.name = trimmedNewName
+ websocketMsgSrv.renameNote($scope.note.id, $scope.note.name)
}
- };
+ }
- var initializeLookAndFeel = function() {
+ const initializeLookAndFeel = function () {
if (!$scope.note.config.looknfeel) {
- $scope.note.config.looknfeel = 'default';
+ $scope.note.config.looknfeel = 'default'
} else {
- $scope.viewOnly = $scope.note.config.looknfeel === 'report' ? true : false;
+ $scope.viewOnly = $scope.note.config.looknfeel === 'report' ? true : false
}
if ($scope.note.paragraphs && $scope.note.paragraphs[0]) {
- $scope.note.paragraphs[0].focus = true;
- }
- $rootScope.$broadcast('setLookAndFeel', $scope.note.config.looknfeel);
- };
-
- var cleanParagraphExcept = function(paragraphId, note) {
- var noteCopy = {};
- noteCopy.id = note.id;
- noteCopy.name = note.name;
- noteCopy.config = note.config;
- noteCopy.info = note.info;
- noteCopy.paragraphs = [];
- for (var i = 0; i < note.paragraphs.length; i++) {
+ $scope.note.paragraphs[0].focus = true
+ }
+ $rootScope.$broadcast('setLookAndFeel', $scope.note.config.looknfeel)
+ }
+
+ let cleanParagraphExcept = function (paragraphId, note) {
+ let noteCopy = {}
+ noteCopy.id = note.id
+ noteCopy.name = note.name
+ noteCopy.config = note.config
+ noteCopy.info = note.info
+ noteCopy.paragraphs = []
+ for (let i = 0; i < note.paragraphs.length; i++) {
if (note.paragraphs[i].id === paragraphId) {
- noteCopy.paragraphs[0] = note.paragraphs[i];
+ noteCopy.paragraphs[0] = note.paragraphs[i]
if (!noteCopy.paragraphs[0].config) {
- noteCopy.paragraphs[0].config = {};
+ noteCopy.paragraphs[0].config = {}
}
- noteCopy.paragraphs[0].config.editorHide = true;
- noteCopy.paragraphs[0].config.tableHide = false;
- break;
+ noteCopy.paragraphs[0].config.editorHide = true
+ noteCopy.paragraphs[0].config.tableHide = false
+ break
}
}
- return noteCopy;
- };
+ return noteCopy
+ }
- var addPara = function(paragraph, index) {
- $scope.note.paragraphs.splice(index, 0, paragraph);
- _.each($scope.note.paragraphs, function(para) {
+ let addPara = function (paragraph, index) {
+ $scope.note.paragraphs.splice(index, 0, paragraph)
+ _.each($scope.note.paragraphs, function (para) {
if (para.id === paragraph.id) {
- para.focus = true;
- $scope.$broadcast('focusParagraph', para.id, 0, false);
+ para.focus = true
+ $scope.$broadcast('focusParagraph', para.id, 0, false)
}
- });
- };
+ })
+ }
- var removePara = function(paragraphId) {
- var removeIdx;
- _.each($scope.note.paragraphs, function(para, idx) {
+ let removePara = function (paragraphId) {
+ let removeIdx
+ _.each($scope.note.paragraphs, function (para, idx) {
if (para.id === paragraphId) {
- removeIdx = idx;
+ removeIdx = idx
}
- });
- return $scope.note.paragraphs.splice(removeIdx, 1);
- };
+ })
+ return $scope.note.paragraphs.splice(removeIdx, 1)
+ }
- $scope.$on('addParagraph', function(event, paragraph, index) {
+ $scope.$on('addParagraph', function (event, paragraph, index) {
if ($scope.paragraphUrl) {
- return;
+ return
}
- addPara(paragraph, index);
- });
+ addPara(paragraph, index)
+ })
- $scope.$on('removeParagraph', function(event, paragraphId) {
+ $scope.$on('removeParagraph', function (event, paragraphId) {
if ($scope.paragraphUrl) {
- return;
+ return
}
- removePara(paragraphId);
- });
+ removePara(paragraphId)
+ })
- $scope.$on('moveParagraph', function(event, paragraphId, newIdx) {
- var removedPara = removePara(paragraphId);
+ $scope.$on('moveParagraph', function (event, paragraphId, newIdx) {
+ let removedPara = removePara(paragraphId)
if (removedPara && removedPara.length === 1) {
- addPara(removedPara[0], newIdx);
+ addPara(removedPara[0], newIdx)
}
- });
+ })
- $scope.$on('updateNote', function(event, name, config, info) {
+ $scope.$on('updateNote', function (event, name, config, info) {
/** update Note name */
if (name !== $scope.note.name) {
- console.log('change note name to : %o', $scope.note.name);
- $scope.note.name = name;
+ console.log('change note name to : %o', $scope.note.name)
+ $scope.note.name = name
}
- $scope.note.config = config;
- $scope.note.info = info;
- initializeLookAndFeel();
- });
+ $scope.note.config = config
+ $scope.note.info = info
+ initializeLookAndFeel()
+ })
- var getInterpreterBindings = function() {
- websocketMsgSrv.getInterpreterBindings($scope.note.id);
- };
+ let getInterpreterBindings = function () {
+ websocketMsgSrv.getInterpreterBindings($scope.note.id)
+ }
- $scope.$on('interpreterBindings', function(event, data) {
- $scope.interpreterBindings = data.interpreterBindings;
- $scope.interpreterBindingsOrig = angular.copy($scope.interpreterBindings); // to check dirty
+ $scope.$on('interpreterBindings', function (event, data) {
+ $scope.interpreterBindings = data.interpreterBindings
+ $scope.interpreterBindingsOrig = angular.copy($scope.interpreterBindings) // to check dirty
- var selected = false;
- var key;
- var setting;
+ let selected = false
+ let key
+ let setting
for (key in $scope.interpreterBindings) {
- setting = $scope.interpreterBindings[key];
+ setting = $scope.interpreterBindings[key]
if (setting.selected) {
- selected = true;
- break;
+ selected = true
+ break
}
}
if (!selected) {
// make default selection
- var selectedIntp = {};
+ let selectedIntp = {}
for (key in $scope.interpreterBindings) {
- setting = $scope.interpreterBindings[key];
+ setting = $scope.interpreterBindings[key]
if (!selectedIntp[setting.name]) {
- setting.selected = true;
- selectedIntp[setting.name] = true;
+ setting.selected = true
+ selectedIntp[setting.name] = true
}
}
- $scope.showSetting = true;
+ $scope.showSetting = true
}
- });
+ })
$scope.interpreterSelectionListeners = {
- accept: function(sourceItemHandleScope, destSortableScope) {return true;},
- itemMoved: function(event) {},
- orderChanged: function(event) {}
- };
+ accept: function (sourceItemHandleScope, destSortableScope) { return true },
+ itemMoved: function (event) {},
+ orderChanged: function (event) {}
+ }
- $scope.openSetting = function() {
- $scope.showSetting = true;
- getInterpreterBindings();
- };
+ $scope.openSetting = function () {
+ $scope.showSetting = true
+ getInterpreterBindings()
+ }
- $scope.closeSetting = function() {
+ $scope.closeSetting = function () {
if (isSettingDirty()) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Interpreter setting changes will be discarded.',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- $scope.$apply(function() {
- $scope.showSetting = false;
- });
+ $scope.$apply(function () {
+ $scope.showSetting = false
+ })
}
}
- });
+ })
} else {
- $scope.showSetting = false;
+ $scope.showSetting = false
}
- };
+ }
- $scope.saveSetting = function() {
- var selectedSettingIds = [];
- for (var no in $scope.interpreterBindings) {
- var setting = $scope.interpreterBindings[no];
+ $scope.saveSetting = function () {
+ let selectedSettingIds = []
+ for (let no in $scope.interpreterBindings) {
+ let setting = $scope.interpreterBindings[no]
if (setting.selected) {
- selectedSettingIds.push(setting.id);
+ selectedSettingIds.push(setting.id)
}
}
- websocketMsgSrv.saveInterpreterBindings($scope.note.id, selectedSettingIds);
- console.log('Interpreter bindings %o saved', selectedSettingIds);
+ websocketMsgSrv.saveInterpreterBindings($scope.note.id, selectedSettingIds)
+ console.log('Interpreter bindings %o saved', selectedSettingIds)
- _.forEach($scope.note.paragraphs, function(n, key) {
- var regExp = /^\s*%/g;
+ _.forEach($scope.note.paragraphs, function (n, key) {
+ let regExp = /^\s*%/g
if (n.text && !regExp.exec(n.text)) {
- $scope.$broadcast('saveInterpreterBindings', n.id);
+ $scope.$broadcast('saveInterpreterBindings', n.id)
}
- });
+ })
- $scope.showSetting = false;
- };
+ $scope.showSetting = false
+ }
- $scope.toggleSetting = function() {
+ $scope.toggleSetting = function () {
if ($scope.showSetting) {
- $scope.closeSetting();
+ $scope.closeSetting()
} else {
- $scope.openSetting();
- $scope.closePermissions();
- angular.element('html, body').animate({ scrollTop: 0 }, 'slow');
+ $scope.openSetting()
+ $scope.closePermissions()
+ angular.element('html, body').animate({ scrollTop: 0 }, 'slow')
}
- };
+ }
- var getPermissions = function(callback) {
- $http.get(baseUrlSrv.getRestApiBase() + '/notebook/' + $scope.note.id + '/permissions').
- success(function(data, status, headers, config) {
- $scope.permissions = data.body;
- $scope.permissionsOrig = angular.copy($scope.permissions); // to check dirty
+ let getPermissions = function (callback) {
+ $http.get(baseUrlSrv.getRestApiBase() + '/notebook/' + $scope.note.id + '/permissions')
+ .success(function (data, status, headers, config) {
+ $scope.permissions = data.body
+ $scope.permissionsOrig = angular.copy($scope.permissions) // to check dirty
- var selectJson = {
+ let selectJson = {
tokenSeparators: [',', ' '],
ajax: {
- url: function(params) {
+ url: function (params) {
if (!params.term) {
- return false;
+ return false
}
- return baseUrlSrv.getRestApiBase() + '/security/userlist/' + params.term;
+ return baseUrlSrv.getRestApiBase() + '/security/userlist/' + params.term
},
delay: 250,
- processResults: function(data, params) {
- var results = [];
+ processResults: function (data, params) {
+ let results = []
if (data.body.users.length !== 0) {
- var users = [];
- for (var len = 0; len < data.body.users.length; len++) {
+ let users = []
+ for (let len = 0; len < data.body.users.length; len++) {
users.push({
'id': data.body.users[len],
'text': data.body.users[len]
- });
+ })
}
results.push({
'text': 'Users :',
'children': users
- });
+ })
}
if (data.body.roles.length !== 0) {
- var roles = [];
- for (var len = 0; len < data.body.roles.length; len++) {
+ let roles = []
+ for (let len = 0; len < data.body.roles.length; len++) {
roles.push({
'id': data.body.roles[len],
'text': data.body.roles[len]
- });
+ })
}
results.push({
'text': 'Roles :',
'children': roles
- });
+ })
}
return {
results: results,
pagination: {
more: false
}
- };
+ }
},
cache: false
},
width: ' ',
tags: true,
minimumInputLength: 3
- };
+ }
- $scope.setIamOwner();
- angular.element('#selectOwners').select2(selectJson);
- angular.element('#selectReaders').select2(selectJson);
- angular.element('#selectWriters').select2(selectJson);
+ $scope.setIamOwner()
+ angular.element('#selectOwners').select2(selectJson)
+ angular.element('#selectReaders').select2(selectJson)
+ angular.element('#selectWriters').select2(selectJson)
if (callback) {
- callback();
+ callback()
}
- }).
- error(function(data, status, headers, config) {
+ })
+ .error(function (data, status, headers, config) {
if (status !== 0) {
- console.log('Error %o %o', status, data.message);
+ console.log('Error %o %o', status, data.message)
}
- });
- };
+ })
+ }
- $scope.openPermissions = function() {
- $scope.showPermissions = true;
- getPermissions();
- };
+ $scope.openPermissions = function () {
+ $scope.showPermissions = true
+ getPermissions()
+ }
- $scope.closePermissions = function() {
+ $scope.closePermissions = function () {
if (isPermissionsDirty()) {
BootstrapDialog.confirm({
closable: true,
title: '',
message: 'Changes will be discarded.',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- $scope.$apply(function() {
- $scope.showPermissions = false;
- });
+ $scope.$apply(function () {
+ $scope.showPermissions = false
+ })
}
}
- });
+ })
} else {
- $scope.showPermissions = false;
+ $scope.showPermissions = false
}
- };
+ }
- function convertPermissionsToArray() {
- $scope.permissions.owners = angular.element('#selectOwners').val();
- $scope.permissions.readers = angular.element('#selectReaders').val();
- $scope.permissions.writers = angular.element('#selectWriters').val();
- angular.element('.permissionsForm select').find('option:not([is-select2="false"])').remove();
+ function convertPermissionsToArray () {
+ $scope.permissions.owners = angular.element('#selectOwners').val()
+ $scope.permissions.readers = angular.element('#selectReaders').val()
+ $scope.permissions.writers = angular.element('#selectWriters').val()
+ angular.element('.permissionsForm select').find('option:not([is-select2="false"])').remove()
}
$scope.restartInterpreter = function(interpreter) {
- var thisConfirm = BootstrapDialog.confirm({
+ const thisConfirm = BootstrapDialog.confirm({
closable: false,
closeByBackdrop: false,
closeByKeyboard: false,
@@ -721,51 +723,51 @@ function NotebookCtrl($scope, $route, $routeParams, $location, $rootScope,
message: 'Do you want to restart ' + interpreter.name + ' interpreter?',
callback: function(result) {
if (result) {
- var payload = {
+ let payload = {
'noteId': $scope.note.id
- };
+ }
- thisConfirm.$modalFooter.find('button').addClass('disabled');
+ thisConfirm.$modalFooter.find('button').addClass('disabled')
thisConfirm.$modalFooter.find('button:contains("OK")')
- .html('<i class="fa fa-circle-o-notch fa-spin"></i> Saving Setting');
+ .html('<i class="fa fa-circle-o-notch fa-spin"></i> Saving Setting')
$http.put(baseUrlSrv.getRestApiBase() + '/interpreter/setting/restart/' + interpreter.id, payload)
.success(function(data, status, headers, config) {
- var index = _.findIndex($scope.interpreterSettings, {'id': interpreter.id});
- $scope.interpreterSettings[index] = data.body;
- thisConfirm.close();
- }).error(function(data, status, headers, config) {
- thisConfirm.close();
- console.log('Error %o %o', status, data.message);
- BootstrapDialog.show({
- title: 'Error restart interpreter.',
- message: data.message
- });
- });
- return false;
+ let index = _.findIndex($scope.interpreterSettings, {'id': interpreter.id})
+ $scope.interpreterSettings[index] = data.body
+ thisConfirm.close()
+ }).error(function (data, status, headers, config) {
+ thisConfirm.close()
+ console.log('Error %o %o', status, data.message)
+ BootstrapDialog.show({
+ title: 'Error restart interpreter.',
+ message: data.message
+ })
+ })
+ return false
}
}
- });
- };
+ })
+ }
- $scope.savePermissions = function() {
- convertPermissionsToArray();
+ $scope.savePermissions = function () {
+ convertPermissionsToArray()
$http.put(baseUrlSrv.getRestApiBase() + '/notebook/' + $scope.note.id + '/permissions',
- $scope.permissions, {withCredentials: true}).
- success(function(data, status, headers, config) {
- getPermissions(function() {
- console.log('Note permissions %o saved', $scope.permissions);
+ $scope.permissions, {withCredentials: true})
+ .success(function (data, status, headers, config) {
+ getPermissions(function () {
+ console.log('Note permissions %o saved', $scope.permissions)
BootstrapDialog.alert({
closable: true,
title: 'Permissions Saved Successfully!!!',
message: 'Owners : ' + $scope.permissions.owners + '\n\n' + 'Readers : ' +
$scope.permissions.readers + '\n\n' + 'Writers : ' + $scope.permissions.writers
- });
- $scope.showPermissions = false;
- });
- }).
- error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
+ })
+ $scope.showPermissions = false
+ })
+ })
+ .error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
BootstrapDialog.show({
closable: false,
closeByBackdrop: false,
@@ -775,249 +777,249 @@ function NotebookCtrl($scope, $route, $routeParams, $location, $rootScope,
buttons: [
{
label: 'Login',
- action: function(dialog) {
- dialog.close();
+ action: function (dialog) {
+ dialog.close()
angular.element('#loginModal').modal({
show: 'true'
- });
+ })
}
},
{
label: 'Cancel',
- action: function(dialog) {
- dialog.close();
- $location.path('/');
+ action: function (dialog) {
+ dialog.close()
+ $location.path('/')
}
}
]
- });
- });
- };
+ })
+ })
+ }
- $scope.togglePermissions = function() {
- var principal = $rootScope.ticket.principal;
- $scope.isAnonymous = principal === 'anonymous' ? true : false;
+ $scope.togglePermissions = function () {
+ let principal = $rootScope.ticket.principal
+ $scope.isAnonymous = principal === 'anonymous' ? true : false
if (!!principal && $scope.isAnonymous) {
- $scope.blockAnonUsers();
+ $scope.blockAnonUsers()
} else {
if ($scope.showPermissions) {
- $scope.closePermissions();
- angular.element('#selectOwners').select2({});
- angular.element('#selectReaders').select2({});
- angular.element('#selectWriters').select2({});
+ $scope.closePermissions()
+ angular.element('#selectOwners').select2({})
+ angular.element('#selectReaders').select2({})
+ angular.element('#selectWriters').select2({})
} else {
- $scope.openPermissions();
- $scope.closeSetting();
+ $scope.openPermissions()
+ $scope.closeSetting()
}
}
- };
+ }
- $scope.setIamOwner = function() {
+ $scope.setIamOwner = function () {
if ($scope.permissions.owners.length > 0 &&
_.indexOf($scope.permissions.owners, $rootScope.ticket.principal) < 0) {
- $scope.isOwner = false;
- return false;
+ $scope.isOwner = false
+ return false
}
- $scope.isOwner = true;
- return true;
- };
+ $scope.isOwner = true
+ return true
+ }
- $scope.toggleNotePersonalizedMode = function() {
- var personalizedMode = $scope.note.config.personalizedMode;
+ $scope.toggleNotePersonalizedMode = function () {
+ let personalizedMode = $scope.note.config.personalizedMode
if ($scope.isOwner) {
BootstrapDialog.confirm({
closable: true,
title: 'Setting the result display',
- message: function(dialog) {
- var modeText = $scope.note.config.personalizedMode === 'true' ? 'collaborate' : 'personalize';
- return 'Do you want to <span class="text-info">' + modeText + '</span> your analysis?';
+ message: function (dialog) {
+ let modeText = $scope.note.config.personalizedMode === 'true' ? 'collaborate' : 'personalize'
+ return 'Do you want to <span class="text-info">' + modeText + '</span> your analysis?'
},
- callback: function(result) {
+ callback: function (result) {
if (result) {
if ($scope.note.config.personalizedMode === undefined) {
- $scope.note.config.personalizedMode = 'false';
+ $scope.note.config.personalizedMode = 'false'
}
- $scope.note.config.personalizedMode = personalizedMode === 'true' ? 'false' : 'true';
- websocketMsgSrv.updatePersonalizedMode($scope.note.id, $scope.note.config.personalizedMode);
+ $scope.note.config.personalizedMode = personalizedMode === 'true' ? 'false' : 'true'
+ websocketMsgSrv.updatePersonalizedMode($scope.note.id, $scope.note.config.personalizedMode)
}
}
- });
+ })
}
- };
+ }
- var isSettingDirty = function() {
+ const isSettingDirty = function () {
if (angular.equals($scope.interpreterBindings, $scope.interpreterBindingsOrig)) {
- return false;
+ return false
} else {
- return true;
+ return true
}
- };
+ }
- var isPermissionsDirty = function() {
+ const isPermissionsDirty = function () {
if (angular.equals($scope.permissions, $scope.permissionsOrig)) {
- return false;
+ return false
} else {
- return true;
+ return true
}
- };
+ }
- angular.element(document).click(function() {
- angular.element('.ace_autocomplete').hide();
- });
+ angular.element(document).click(function () {
+ angular.element('.ace_autocomplete').hide()
+ })
/*
** $scope.$on functions below
*/
- $scope.$on('setConnectedStatus', function(event, param) {
+ $scope.$on('setConnectedStatus', function (event, param) {
if (connectedOnce && param) {
- initNotebook();
+ initNotebook()
}
- connectedOnce = true;
- });
+ connectedOnce = true
+ })
- $scope.$on('moveParagraphUp', function(event, paragraph) {
- var newIndex = -1;
- for (var i = 0; i < $scope.note.paragraphs.length; i++) {
+ $scope.$on('moveParagraphUp', function (event, paragraph) {
+ let newIndex = -1
+ for (let i = 0; i < $scope.note.paragraphs.length; i++) {
if ($scope.note.paragraphs[i].id === paragraph.id) {
- newIndex = i - 1;
- break;
+ newIndex = i - 1
+ break
}
}
if (newIndex < 0 || newIndex >= $scope.note.paragraphs.length) {
- return;
+ return
}
// save dirtyText of moving paragraphs.
- var prevParagraph = $scope.note.paragraphs[newIndex];
+ let prevParagraph = $scope.note.paragraphs[newIndex]
angular
.element('#' + paragraph.id + '_paragraphColumn_main')
.scope()
- .saveParagraph(paragraph);
+ .saveParagraph(paragraph)
angular
.element('#' + prevParagraph.id + '_paragraphColumn_main')
.scope()
- .saveParagraph(prevParagraph);
- websocketMsgSrv.moveParagraph(paragraph.id, newIndex);
- });
+ .saveParagraph(prevParagraph)
+ websocketMsgSrv.moveParagraph(paragraph.id, newIndex)
+ })
- $scope.$on('moveParagraphDown', function(event, paragraph) {
- var newIndex = -1;
- for (var i = 0; i < $scope.note.paragraphs.length; i++) {
+ $scope.$on('moveParagraphDown', function (event, paragraph) {
+ let newIndex = -1
+ for (let i = 0; i < $scope.note.paragraphs.length; i++) {
if ($scope.note.paragraphs[i].id === paragraph.id) {
- newIndex = i + 1;
- break;
+ newIndex = i + 1
+ break
}
}
if (newIndex < 0 || newIndex >= $scope.note.paragraphs.length) {
- return;
+ return
}
// save dirtyText of moving paragraphs.
- var nextParagraph = $scope.note.paragraphs[newIndex];
+ let nextParagraph = $scope.note.paragraphs[newIndex]
angular
.element('#' + paragraph.id + '_paragraphColumn_main')
.scope()
- .saveParagraph(paragraph);
+ .saveParagraph(paragraph)
angular
.element('#' + nextParagraph.id + '_paragraphColumn_main')
.scope()
- .saveParagraph(nextParagraph);
- websocketMsgSrv.moveParagraph(paragraph.id, newIndex);
- });
+ .saveParagraph(nextParagraph)
+ websocketMsgSrv.moveParagraph(paragraph.id, newIndex)
+ })
- $scope.$on('moveFocusToPreviousParagraph', function(event, currentParagraphId) {
- var focus = false;
- for (var i = $scope.note.paragraphs.length - 1; i >= 0; i--) {
+ $scope.$on('moveFocusToPreviousParagraph', function (event, currentParagraphId) {
+ let focus = false
+ for (let i = $scope.note.paragraphs.length - 1; i >= 0; i--) {
if (focus === false) {
if ($scope.note.paragraphs[i].id === currentParagraphId) {
- focus = true;
- continue;
+ focus = true
+ continue
}
} else {
- $scope.$broadcast('focusParagraph', $scope.note.paragraphs[i].id, -1);
- break;
+ $scope.$broadcast('focusParagraph', $scope.note.paragraphs[i].id, -1)
+ break
}
}
- });
+ })
- $scope.$on('moveFocusToNextParagraph', function(event, currentParagraphId) {
- var focus = false;
- for (var i = 0; i < $scope.note.paragraphs.length; i++) {
+ $scope.$on('moveFocusToNextParagraph', function (event, currentParagraphId) {
+ let focus = false
+ for (let i = 0; i < $scope.note.paragraphs.length; i++) {
if (focus === false) {
if ($scope.note.paragraphs[i].id === currentParagraphId) {
- focus = true;
- continue;
+ focus = true
+ continue
}
} else {
- $scope.$broadcast('focusParagraph', $scope.note.paragraphs[i].id, 0);
- break;
+ $scope.$broadcast('focusParagraph', $scope.note.paragraphs[i].id, 0)
+ break
}
}
- });
+ })
- $scope.$on('insertParagraph', function(event, paragraphId, position) {
- var newIndex = -1;
- for (var i = 0; i < $scope.note.paragraphs.length; i++) {
+ $scope.$on('insertParagraph', function (event, paragraphId, position) {
+ let newIndex = -1
+ for (let i = 0; i < $scope.note.paragraphs.length; i++) {
if ($scope.note.paragraphs[i].id === paragraphId) {
- //determine position of where to add new paragraph; default is below
+ // determine position of where to add new paragraph; default is below
if (position === 'above') {
- newIndex = i;
+ newIndex = i
} else {
- newIndex = i + 1;
+ newIndex = i + 1
}
- break;
+ break
}
}
if (newIndex < 0 || newIndex > $scope.note.paragraphs.length) {
- return;
+ return
}
- websocketMsgSrv.insertParagraph(newIndex);
- });
+ websocketMsgSrv.insertParagraph(newIndex)
+ })
- $scope.$on('setNoteContent', function(event, note) {
+ $scope.$on('setNoteContent', function (event, note) {
if (note === undefined) {
- $location.path('/');
+ $location.path('/')
}
- $scope.note = note;
+ $scope.note = note
- $scope.paragraphUrl = $routeParams.paragraphId;
- $scope.asIframe = $routeParams.asIframe;
+ $scope.paragraphUrl = $routeParams.paragraphId
+ $scope.asIframe = $routeParams.asIframe
if ($scope.paragraphUrl) {
- $scope.note = cleanParagraphExcept($scope.paragraphUrl, $scope.note);
- $scope.$broadcast('$unBindKeyEvent', $scope.$unBindKeyEvent);
- $rootScope.$broadcast('setIframe', $scope.asIframe);
- initializeLookAndFeel();
- return;
- }
-
- initializeLookAndFeel();
-
- //open interpreter binding setting when there're none selected
- getInterpreterBindings();
- getPermissions();
- var isPersonalized = $scope.note.config.personalizedMode;
- isPersonalized = isPersonalized === undefined ? 'false' : isPersonalized;
- $scope.note.config.personalizedMode = isPersonalized;
- });
-
- $scope.$on('$destroy', function() {
- angular.element(window).off('beforeunload');
- $scope.killSaveTimer();
- $scope.saveNote();
-
- document.removeEventListener('click', $scope.focusParagraphOnClick);
- document.removeEventListener('keydown', $scope.keyboardShortcut);
- });
-
- $scope.$on('$unBindKeyEvent', function() {
- document.removeEventListener('click', $scope.focusParagraphOnClick);
- document.removeEventListener('keydown', $scope.keyboardShortcut);
- });
-
- angular.element(window).bind('resize', function() {
- const actionbarHeight = document.getElementById('actionbar').lastElementChild.clientHeight;
- angular.element(document.getElementById('content')).css('padding-top', actionbarHeight - 20);
- });
+ $scope.note = cleanParagraphExcept($scope.paragraphUrl, $scope.note)
+ $scope.$broadcast('$unBindKeyEvent', $scope.$unBindKeyEvent)
+ $rootScope.$broadcast('setIframe', $scope.asIframe)
+ initializeLookAndFeel()
+ return
+ }
+
+ initializeLookAndFeel()
+
+ // open interpreter binding setting when there're none selected
+ getInterpreterBindings()
+ getPermissions()
+ let isPersonalized = $scope.note.config.personalizedMode
+ isPersonalized = isPersonalized === undefined ? 'false' : isPersonalized
+ $scope.note.config.personalizedMode = isPersonalized
+ })
+
+ $scope.$on('$destroy', function () {
+ angular.element(window).off('beforeunload')
+ $scope.killSaveTimer()
+ $scope.saveNote()
+
+ document.removeEventListener('click', $scope.focusParagraphOnClick)
+ document.removeEventListener('keydown', $scope.keyboardShortcut)
+ })
+
+ $scope.$on('$unBindKeyEvent', function () {
+ document.removeEventListener('click', $scope.focusParagraphOnClick)
+ document.removeEventListener('keydown', $scope.keyboardShortcut)
+ })
+
+ angular.element(window).bind('resize', function () {
+ const actionbarHeight = document.getElementById('actionbar').lastElementChild.clientHeight
+ angular.element(document.getElementById('content')).css('padding-top', actionbarHeight - 20)
+ })
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/notebook/notebook.controller.test.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/notebook/notebook.controller.test.js b/zeppelin-web/src/app/notebook/notebook.controller.test.js
index 6df6893..f393d2c 100644
--- a/zeppelin-web/src/app/notebook/notebook.controller.test.js
+++ b/zeppelin-web/src/app/notebook/notebook.controller.test.js
@@ -1,139 +1,139 @@
-describe('Controller: NotebookCtrl', function() {
- beforeEach(angular.mock.module('zeppelinWebApp'));
-
- var scope;
-
- var websocketMsgSrvMock = {
- getNote: function() {},
- listRevisionHistory: function() {},
- getInterpreterBindings: function() {},
- updateNote: function() {},
- renameNote: function() {}
- };
-
- var baseUrlSrvMock = {
- getRestApiBase: function() {
- return 'http://localhost:8080';
+describe('Controller: NotebookCtrl', function () {
+ beforeEach(angular.mock.module('zeppelinWebApp'))
+
+ let scope
+
+ let websocketMsgSrvMock = {
+ getNote: function () {},
+ listRevisionHistory: function () {},
+ getInterpreterBindings: function () {},
+ updateNote: function () {},
+ renameNote: function () {}
+ }
+
+ let baseUrlSrvMock = {
+ getRestApiBase: function () {
+ return 'http://localhost:8080'
}
- };
+ }
- var noteMock = {
+ let noteMock = {
id: 1,
name: 'my note',
config: {},
- };
+ }
- beforeEach(inject(function($controller, $rootScope) {
- scope = $rootScope.$new();
+ beforeEach(inject(function ($controller, $rootScope) {
+ scope = $rootScope.$new()
$controller('NotebookCtrl', {
$scope: scope,
websocketMsgSrv: websocketMsgSrvMock,
baseUrlSrv: baseUrlSrvMock
- });
- }));
+ })
+ }))
- beforeEach(function() {
- scope.note = noteMock;
- });
+ beforeEach(function () {
+ scope.note = noteMock
+ })
- var functions = ['getCronOptionNameFromValue', 'removeNote', 'runAllParagraphs', 'saveNote', 'toggleAllEditor',
+ let functions = ['getCronOptionNameFromValue', 'removeNote', 'runAllParagraphs', 'saveNote', 'toggleAllEditor',
'showAllEditor', 'hideAllEditor', 'toggleAllTable', 'hideAllTable', 'showAllTable', 'isNoteRunning',
'killSaveTimer', 'startSaveTimer', 'setLookAndFeel', 'setCronScheduler', 'setConfig', 'updateNoteName',
- 'openSetting', 'closeSetting', 'saveSetting', 'toggleSetting'];
-
- functions.forEach(function(fn) {
- it('check for scope functions to be defined : ' + fn, function() {
- expect(scope[fn]).toBeDefined();
- });
- });
-
- it('should set default value of "editorToggled" to false', function() {
- expect(scope.editorToggled).toEqual(false);
- });
-
- it('should set "showSetting" to true when openSetting() is called', function() {
- scope.openSetting();
- expect(scope.showSetting).toEqual(true);
- });
-
- it('should set "showSetting" to false when closeSetting() is called', function() {
- scope.closeSetting();
- expect(scope.showSetting).toEqual(false);
- });
-
- it('should return the correct value for getCronOptionNameFromValue()', function() {
- var none = scope.getCronOptionNameFromValue();
- var oneMin = scope.getCronOptionNameFromValue('0 0/1 * * * ?');
- var fiveMin = scope.getCronOptionNameFromValue('0 0/5 * * * ?');
- var oneHour = scope.getCronOptionNameFromValue('0 0 0/1 * * ?');
- var threeHours = scope.getCronOptionNameFromValue('0 0 0/3 * * ?');
- var sixHours = scope.getCronOptionNameFromValue('0 0 0/6 * * ?');
- var twelveHours = scope.getCronOptionNameFromValue('0 0 0/12 * * ?');
- var oneDay = scope.getCronOptionNameFromValue('0 0 0 * * ?');
-
- expect(none).toEqual('');
- expect(oneMin).toEqual('1m');
- expect(fiveMin).toEqual('5m');
- expect(oneHour).toEqual('1h');
- expect(threeHours).toEqual('3h');
- expect(sixHours).toEqual('6h');
- expect(twelveHours).toEqual('12h');
- expect(oneDay).toEqual('1d');
- });
-
- it('should have "isNoteDirty" as null by default', function() {
- expect(scope.isNoteDirty).toEqual(null);
- });
-
- it('should first call killSaveTimer() when calling startSaveTimer()', function() {
- expect(scope.saveTimer).toEqual(null);
- spyOn(scope, 'killSaveTimer');
- scope.startSaveTimer();
- expect(scope.killSaveTimer).toHaveBeenCalled();
- });
-
- it('should set "saveTimer" when saveTimer() and killSaveTimer() are called', function() {
- expect(scope.saveTimer).toEqual(null);
- scope.startSaveTimer();
- expect(scope.saveTimer).toBeTruthy();
- scope.killSaveTimer();
- expect(scope.saveTimer).toEqual(null);
- });
-
- it('should NOT update note name when updateNoteName() is called with an invalid name', function() {
- spyOn(websocketMsgSrvMock, 'renameNote');
- scope.updateNoteName('');
- expect(scope.note.name).toEqual(noteMock.name);
- expect(websocketMsgSrvMock.renameNote).not.toHaveBeenCalled();
- scope.updateNoteName(' ');
- expect(scope.note.name).toEqual(noteMock.name);
- expect(websocketMsgSrvMock.renameNote).not.toHaveBeenCalled();
- scope.updateNoteName(scope.note.name);
- expect(scope.note.name).toEqual(noteMock.name);
- expect(websocketMsgSrvMock.renameNote).not.toHaveBeenCalled();
- });
-
- it('should update note name when updateNoteName() is called with a valid name', function() {
- spyOn(websocketMsgSrvMock, 'renameNote');
- var newName = 'Your Note';
- scope.updateNoteName(newName);
- expect(scope.note.name).toEqual(newName);
- expect(websocketMsgSrvMock.renameNote).toHaveBeenCalled();
- });
-
- it('should reload note info once per one "setNoteMenu" event', function() {
- spyOn(websocketMsgSrvMock, 'getNote');
- spyOn(websocketMsgSrvMock, 'listRevisionHistory');
-
- scope.$broadcast('setNoteMenu');
- expect(websocketMsgSrvMock.getNote.calls.count()).toEqual(0);
- expect(websocketMsgSrvMock.listRevisionHistory.calls.count()).toEqual(0);
-
- websocketMsgSrvMock.getNote.calls.reset();
- websocketMsgSrvMock.listRevisionHistory.calls.reset();
-
- scope.$broadcast('setNoteMenu');
- expect(websocketMsgSrvMock.getNote.calls.count()).toEqual(0);
- expect(websocketMsgSrvMock.listRevisionHistory.calls.count()).toEqual(0);
- });
-});
+ 'openSetting', 'closeSetting', 'saveSetting', 'toggleSetting']
+
+ functions.forEach(function (fn) {
+ it('check for scope functions to be defined : ' + fn, function () {
+ expect(scope[fn]).toBeDefined()
+ })
+ })
+
+ it('should set default value of "editorToggled" to false', function () {
+ expect(scope.editorToggled).toEqual(false)
+ })
+
+ it('should set "showSetting" to true when openSetting() is called', function () {
+ scope.openSetting()
+ expect(scope.showSetting).toEqual(true)
+ })
+
+ it('should set "showSetting" to false when closeSetting() is called', function () {
+ scope.closeSetting()
+ expect(scope.showSetting).toEqual(false)
+ })
+
+ it('should return the correct value for getCronOptionNameFromValue()', function () {
+ let none = scope.getCronOptionNameFromValue()
+ let oneMin = scope.getCronOptionNameFromValue('0 0/1 * * * ?')
+ let fiveMin = scope.getCronOptionNameFromValue('0 0/5 * * * ?')
+ let oneHour = scope.getCronOptionNameFromValue('0 0 0/1 * * ?')
+ let threeHours = scope.getCronOptionNameFromValue('0 0 0/3 * * ?')
+ let sixHours = scope.getCronOptionNameFromValue('0 0 0/6 * * ?')
+ let twelveHours = scope.getCronOptionNameFromValue('0 0 0/12 * * ?')
+ let oneDay = scope.getCronOptionNameFromValue('0 0 0 * * ?')
+
+ expect(none).toEqual('')
+ expect(oneMin).toEqual('1m')
+ expect(fiveMin).toEqual('5m')
+ expect(oneHour).toEqual('1h')
+ expect(threeHours).toEqual('3h')
+ expect(sixHours).toEqual('6h')
+ expect(twelveHours).toEqual('12h')
+ expect(oneDay).toEqual('1d')
+ })
+
+ it('should have "isNoteDirty" as null by default', function () {
+ expect(scope.isNoteDirty).toEqual(null)
+ })
+
+ it('should first call killSaveTimer() when calling startSaveTimer()', function () {
+ expect(scope.saveTimer).toEqual(null)
+ spyOn(scope, 'killSaveTimer')
+ scope.startSaveTimer()
+ expect(scope.killSaveTimer).toHaveBeenCalled()
+ })
+
+ it('should set "saveTimer" when saveTimer() and killSaveTimer() are called', function () {
+ expect(scope.saveTimer).toEqual(null)
+ scope.startSaveTimer()
+ expect(scope.saveTimer).toBeTruthy()
+ scope.killSaveTimer()
+ expect(scope.saveTimer).toEqual(null)
+ })
+
+ it('should NOT update note name when updateNoteName() is called with an invalid name', function () {
+ spyOn(websocketMsgSrvMock, 'renameNote')
+ scope.updateNoteName('')
+ expect(scope.note.name).toEqual(noteMock.name)
+ expect(websocketMsgSrvMock.renameNote).not.toHaveBeenCalled()
+ scope.updateNoteName(' ')
+ expect(scope.note.name).toEqual(noteMock.name)
+ expect(websocketMsgSrvMock.renameNote).not.toHaveBeenCalled()
+ scope.updateNoteName(scope.note.name)
+ expect(scope.note.name).toEqual(noteMock.name)
+ expect(websocketMsgSrvMock.renameNote).not.toHaveBeenCalled()
+ })
+
+ it('should update note name when updateNoteName() is called with a valid name', function () {
+ spyOn(websocketMsgSrvMock, 'renameNote')
+ let newName = 'Your Note'
+ scope.updateNoteName(newName)
+ expect(scope.note.name).toEqual(newName)
+ expect(websocketMsgSrvMock.renameNote).toHaveBeenCalled()
+ })
+
+ it('should reload note info once per one "setNoteMenu" event', function () {
+ spyOn(websocketMsgSrvMock, 'getNote')
+ spyOn(websocketMsgSrvMock, 'listRevisionHistory')
+
+ scope.$broadcast('setNoteMenu')
+ expect(websocketMsgSrvMock.getNote.calls.count()).toEqual(0)
+ expect(websocketMsgSrvMock.listRevisionHistory.calls.count()).toEqual(0)
+
+ websocketMsgSrvMock.getNote.calls.reset()
+ websocketMsgSrvMock.listRevisionHistory.calls.reset()
+
+ scope.$broadcast('setNoteMenu')
+ expect(websocketMsgSrvMock.getNote.calls.count()).toEqual(0)
+ expect(websocketMsgSrvMock.listRevisionHistory.calls.count()).toEqual(0)
+ })
+})
[8/8] zeppelin git commit: [ZEPPELIN-1940] lint rule set is NOT
applied at all.
Posted by ah...@apache.org.
[ZEPPELIN-1940] lint rule set is NOT applied at all.
### What is this PR for?
eslint ruleset is NOT applied at all due to invalid `.eslintrc`.
This PR includes
- fixes which are automatically done by eslint (`eslint --fix src`)
- modification in `.eslintrc`, `package.json`
- while removing eslint conf in `gruntfile.js`
As a result of this PR, we can have more strict and modernized rulesets which can help us to prevent bugs.
### What type of PR is it?
[Improvement]
### Todos
* [x] - Setup rules
* [x] - Remove grunt eslint config
* [x] - Ignore useless rules
* [x] - Fix code for applied rules
### What is the Jira issue?
[ZEPPELIN-1940](https://issues.apache.org/jira/browse/ZEPPELIN-1940)
### How should this be tested?
- `cd zeppelin-web`
- `npm install` (or `yarn install` if you have yarn)
- `npm run lint:once`
### Screenshots (if appropriate)
### Questions:
* Does the licenses files need update? - NO
* Is there breaking changes for older versions? - NO
* Does this needs documentation? - NO
Author: 1ambda <1a...@gmail.com>
Closes #2252 from 1ambda/ZEPPELIN-1940/apply-lint-rule-set and squashes the following commits:
d3e6c0a [1ambda] fix: eslint errors for #2245
013d7ca [1ambda] fix: eslint errors for #2244
6feb158 [1ambda] fix: eslint errors for #2133
02545c7 [1ambda] fix: eslint for #2203, #2248
4ab8a39 [1ambda] fix: eslint errors for #2228
cc874d2 [1ambda] fix: semi
d4a8082 [1ambda] fix: lint for src/app/tabledata/advanced-
4d991a2 [1ambda] fix: ignore array-bracket-spacing
d69113a [1ambda] fix: ignore space-before-function-paren
526dbeb [1ambda] fix: no-var
3fd91fe [1ambda] fix: no-redeclare
a5947da [1ambda] fix: prefer-spread
a20d20e [1ambda] fix: prefer-rest-params
e3f9641 [1ambda] fix: no-unused-expressions
bd981d7 [1ambda] fix: ignore no-unneeded-ternary
c52b095 [1ambda] fix: no-useless-constructor
83d6789 [1ambda] fix: no-eval
7a740b5 [1ambda] fix: ignore comma-dangle
7d3b393 [1ambda] fix: ignore standard/object-curly-even-spacing
a3f1264 [1ambda] fix: padded-blocks
5d19c6f [1ambda] fix: space-infix-ops
eac6b43 [1ambda] fix: no-extra-semi
bfd7984 [1ambda] fix: ignore arrow-parens
3c91566 [1ambda] fix: ignore object-curly-spacing
6e44e96 [1ambda] fix: space-before-function-paren
59c3996 [1ambda] fix: indent
40125e9 [1ambda] fix: no-multiple-empty-lines
3a6626f [1ambda] fix: no-trailing-spaces
ca94341 [1ambda] fix: spaced-comment
d65c47b [1ambda] fix: comma-spacing
9150539 [1ambda] fix: operator-linebreak
925dc7b [1ambda] fix: block-spacing
021f9e7 [1ambda] fix: space-before-blocks
a896442 [1ambda] fix: keyword-spacing
5948d97 [1ambda] fix: space-in-parens
b094fff [1ambda] fix: no-empty
131c901 [1ambda] fix: no-multi-spaces
1de9a8d [1ambda] fix: one-var
7aa4b1a [1ambda] fix: brace-style
cde8a2d [1ambda] fix: dot-location
d62af8d [1ambda] fix: object-property-newline
70cb63b [1ambda] fix: no-extra-boolean-cast
a5c7842 [1ambda] fix: semi-spacing
3abfc7c [1ambda] fix: no-mixed-spaces-and-tabs
8d5a3d9 [1ambda] fix: yoda
4b36afb [1ambda] fix: ignore all rules
7840ca5 [1ambda] fix: Set ignored, warn lint rules
5566911 [1ambda] fix: Remove invalid visdev
4baadbb [1ambda] fix: Use eslint instead of grunt-eslint
Project: http://git-wip-us.apache.org/repos/asf/zeppelin/repo
Commit: http://git-wip-us.apache.org/repos/asf/zeppelin/commit/19b0f30f
Tree: http://git-wip-us.apache.org/repos/asf/zeppelin/tree/19b0f30f
Diff: http://git-wip-us.apache.org/repos/asf/zeppelin/diff/19b0f30f
Branch: refs/heads/master
Commit: 19b0f30f8df5e65e11d1384d588ee62538930b23
Parents: 13aabe3
Author: 1ambda <1a...@gmail.com>
Authored: Thu Apr 20 12:03:56 2017 +0900
Committer: ahyoungryu <ah...@apache.org>
Committed: Thu Apr 20 13:52:34 2017 +0900
----------------------------------------------------------------------
zeppelin-web/.eslintrc | 16 +-
zeppelin-web/Gruntfile.js | 27 -
zeppelin-web/package.json | 19 +-
zeppelin-web/src/app/app.controller.js | 53 +-
zeppelin-web/src/app/app.controller.test.js | 43 +-
zeppelin-web/src/app/app.js | 89 +-
.../configuration/configuration.controller.js | 46 +-
.../src/app/credential/credential.controller.js | 219 ++-
.../src/app/handsontable/handsonHelper.js | 192 +--
zeppelin-web/src/app/helium/helium.config.js | 79 +-
.../src/app/helium/helium.controller.js | 354 ++--
zeppelin-web/src/app/helium/index.js | 5 +-
zeppelin-web/src/app/home/home.controller.js | 168 +-
.../app/interpreter/interpreter.controller.js | 770 ++++-----
.../src/app/interpreter/interpreter.filter.js | 12 +-
.../src/app/jobmanager/jobmanager.controller.js | 219 ++-
.../src/app/jobmanager/jobmanager.filter.js | 43 +-
.../src/app/jobmanager/jobs/job.controller.js | 87 +-
.../src/app/notebook/notebook.controller.js | 1100 ++++++-------
.../app/notebook/notebook.controller.test.js | 250 +--
.../notebook/paragraph/paragraph.controller.js | 1534 +++++++++---------
.../paragraph/paragraph.controller.test.js | 63 +-
.../app/notebook/paragraph/paragraph.status.js | 12 +-
.../paragraph/result/result.controller.js | 937 ++++++-----
.../notebookRepos/notebookRepos.controller.js | 89 +-
.../src/app/search/result-list.controller.js | 135 +-
zeppelin-web/src/app/spell/index.js | 4 +-
zeppelin-web/src/app/spell/spell-base.js | 18 +-
zeppelin-web/src/app/spell/spell-result.js | 167 +-
.../tabledata/advanced-transformation-util.js | 286 ++--
.../advanced-transformation-util.test.js | 75 +-
.../app/tabledata/advanced-transformation.js | 35 +-
.../src/app/tabledata/columnselector.js | 62 +-
zeppelin-web/src/app/tabledata/passthrough.js | 15 +-
zeppelin-web/src/app/tabledata/pivot.js | 243 +--
zeppelin-web/src/app/tabledata/tabledata.js | 68 +-
.../src/app/tabledata/tabledata.test.js | 38 +-
.../src/app/tabledata/transformation.js | 84 +-
.../builtins/visualization-areachart.js | 73 +-
.../builtins/visualization-barchart.js | 122 +-
.../builtins/visualization-linechart.js | 94 +-
.../builtins/visualization-nvd3chart.js | 243 ++-
.../builtins/visualization-piechart.js | 68 +-
.../builtins/visualization-scatterchart.js | 390 +++--
.../builtins/visualization-table.js | 67 +-
.../src/app/visualization/visualization.js | 130 +-
.../arrayOrderingSrv/arrayOrdering.service.js | 25 +-
.../src/components/baseUrl/baseUrl.service.js | 41 +-
.../browser-detect/browserDetect.service.js | 27 +-
.../clipboard/clipboard.controller.js | 36 +-
.../dropdowninput/dropdowninput.directive.js | 15 +-
.../components/editor/codeEditor.directive.js | 23 +-
.../elasticInputCtrl/elasticInput.controller.js | 11 +-
.../expandCollapse/expandCollapse.directive.js | 25 +-
.../src/components/helium/helium-conf.js | 75 +-
.../src/components/helium/helium-package.js | 24 +-
.../src/components/helium/helium.service.js | 245 ++-
.../interpreter/interpreter.directive.js | 19 +-
.../src/components/login/login.controller.js | 88 +-
.../src/components/navbar/navbar.controller.js | 178 +-
.../components/navbar/navbar.controller.test.js | 26 +-
.../src/components/ngenter/ngenter.directive.js | 21 +-
.../ngenter/ngenter.directive.test.js | 31 +-
.../components/ngescape/ngescape.directive.js | 21 +-
.../components/noteAction/noteAction.service.js | 126 +-
.../noteListDataFactory/noteList.datafactory.js | 63 +-
.../noteList.datafactory.test.js | 124 +-
.../noteName-create/notename.controller.js | 127 +-
.../noteName-create/notename.controller.test.js | 53 +-
.../noteName-create/visible.directive.js | 37 +-
.../notenameImport.controller.js | 174 +-
.../notevarshareService/notevarshare.service.js | 36 +-
.../popover-html-unsafe-popup.directive.js | 7 +-
.../popover-html-unsafe.directive.js | 9 +-
.../src/components/rename/rename.controller.js | 45 +-
.../src/components/rename/rename.service.js | 14 +-
.../components/resizable/resizable.directive.js | 63 +-
.../src/components/saveAs/saveAs.service.js | 57 +-
.../components/searchService/search.service.js | 25 +-
.../websocketEvents/websocketEvents.factory.js | 188 ++-
.../websocketEvents/websocketMsg.service.js | 201 ++-
zeppelin-web/src/index.js | 120 +-
82 files changed, 5591 insertions(+), 5652 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/.eslintrc
----------------------------------------------------------------------
diff --git a/zeppelin-web/.eslintrc b/zeppelin-web/.eslintrc
index 3981770..1fe3fa5 100644
--- a/zeppelin-web/.eslintrc
+++ b/zeppelin-web/.eslintrc
@@ -1,5 +1,5 @@
{
- "preset": "google",
+ "extends": ["eslint:recommended", "google", "standard"],
"env": {
"browser": true,
"jasmine": true,
@@ -31,6 +31,20 @@
"process": false
},
"rules": {
+ "array-bracket-spacing": 0,
+ "space-before-function-paren": 0,
+ "no-unneeded-ternary": 0,
+ "comma-dangle": 0,
+ "object-curly-spacing": 0,
+ "standard/object-curly-even-spacing": 0,
+ "arrow-parens": 0,
+ "require-jsdoc": 0,
+ "valid-jsdoc": 0,
+ "no-invalid-this": 0,
+ "no-console": 0,
+ "guard-for-in": 0,
+ "no-mixed-operators": 1,
+ "no-useless-escape": 1,
"no-bitwise": 2,
"camelcase": 2,
"curly": 2,
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/Gruntfile.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/Gruntfile.js b/zeppelin-web/Gruntfile.js
index b6c1859..764bbc2 100644
--- a/zeppelin-web/Gruntfile.js
+++ b/zeppelin-web/Gruntfile.js
@@ -104,13 +104,6 @@ module.exports = function(grunt) {
files: ['bower.json'],
tasks: ['wiredep']
},
- js: {
- files: [
- '<%= yeoman.app %>/app/**/*.js',
- '<%= yeoman.app %>/components/**/*.js'
- ],
- tasks: ['newer:eslint:all'],
- },
html: {
files: [
'<%= yeoman.app %>/**/*.html'
@@ -120,7 +113,6 @@ module.exports = function(grunt) {
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: [
- 'newer:eslint:test',
'karma'
]
},
@@ -148,24 +140,6 @@ module.exports = function(grunt) {
}
},
- eslint: {
- all: {
- src: [
- 'Gruntfile.js',
- '<%= yeoman.app %>/app/**/*.js',
- '<%= yeoman.app %>/components/**/*.js'
- ]
- },
- test: {
- options: {
- rules: {
- 'no-undef': 0
- }
- },
- src: ['test/spec/{,*/}*.js']
- }
- },
-
// Add vendor prefixed styles
postcss: {
options: {
@@ -430,7 +404,6 @@ module.exports = function(grunt) {
]);
grunt.registerTask('pre-webpack-dist', [
- 'eslint',
'htmlhint',
'wiredep',
]);
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/package.json
----------------------------------------------------------------------
diff --git a/zeppelin-web/package.json b/zeppelin-web/package.json
index 99dc058..17bcb8d 100644
--- a/zeppelin-web/package.json
+++ b/zeppelin-web/package.json
@@ -8,14 +8,15 @@
"scripts": {
"clean": "rimraf dist && rimraf .tmp",
"postinstall": "bower install --silent",
- "prebuild": "npm-run-all clean",
+ "prebuild": "npm-run-all clean lint:once",
"build": "grunt pre-webpack-dist && webpack && grunt post-webpack-dist",
+ "lint:watch": "esw --watch src",
+ "lint:once": "eslint src",
"predev": "grunt pre-webpack-dev",
"dev:server": "webpack-dev-server --hot",
"dev:helium": "HELIUM_BUNDLE_DEV=true webpack-dev-server --hot",
"dev:watch": "grunt watch-webpack-dev",
- "dev": "npm-run-all --parallel dev:server dev:watch",
- "visdev": "npm-run-all --parallel visdev:server dev:watch",
+ "dev": "npm-run-all --parallel dev:server lint:watch dev:watch",
"pretest": "npm install karma-phantomjs-launcher babel-polyfill",
"test": "karma start karma.conf.js"
},
@@ -33,7 +34,14 @@
"bower": "^1.8.0",
"copy-webpack-plugin": "^4.0.1",
"css-loader": "^0.26.1",
+ "eslint": "^3.19.0",
"eslint-config-google": "^0.7.1",
+ "eslint-config-standard": "^10.2.0",
+ "eslint-plugin-import": "^2.2.0",
+ "eslint-plugin-node": "^4.2.2",
+ "eslint-plugin-promise": "^3.5.0",
+ "eslint-plugin-standard": "^3.0.1",
+ "eslint-watch": "^3.1.0",
"express": "^4.14.0",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.9.0",
@@ -47,7 +55,6 @@
"grunt-contrib-htmlmin": "^0.3.0",
"grunt-contrib-uglify": "^0.4.0",
"grunt-contrib-watch": "^0.6.1",
- "grunt-eslint": "^19.0.0",
"grunt-filerev": "^0.2.1",
"grunt-htmlhint": "^0.9.13",
"grunt-newer": "^0.7.0",
@@ -70,11 +77,11 @@
"postcss-loader": "^1.2.1",
"raw-loader": "^0.5.1",
"rimraf": "^2.5.4",
+ "string-replace-webpack-plugin": "^0.1.3",
"style-loader": "^0.13.1",
"time-grunt": "^0.3.1",
"webpack": "^1.14.0",
- "webpack-dev-server": "^1.16.2",
- "string-replace-webpack-plugin": "^0.1.3"
+ "webpack-dev-server": "^1.16.2"
},
"repository": {
"type": "git",
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/app.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/app.controller.js b/zeppelin-web/src/app/app.controller.js
index 30c96a1..6c64a33 100644
--- a/zeppelin-web/src/app/app.controller.js
+++ b/zeppelin-web/src/app/app.controller.js
@@ -12,49 +12,48 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('MainCtrl', MainCtrl);
+angular.module('zeppelinWebApp').controller('MainCtrl', MainCtrl)
-function MainCtrl($scope, $rootScope, $window, arrayOrderingSrv) {
- 'ngInject';
+function MainCtrl ($scope, $rootScope, $window, arrayOrderingSrv) {
+ 'ngInject'
- $scope.looknfeel = 'default';
+ $scope.looknfeel = 'default'
- var init = function() {
- $scope.asIframe = (($window.location.href.indexOf('asIframe') > -1) ? true : false);
- };
+ let init = function () {
+ $scope.asIframe = (($window.location.href.indexOf('asIframe') > -1) ? true : false)
+ }
- init();
+ init()
- $rootScope.$on('setIframe', function(event, data) {
+ $rootScope.$on('setIframe', function (event, data) {
if (!event.defaultPrevented) {
- $scope.asIframe = data;
- event.preventDefault();
+ $scope.asIframe = data
+ event.preventDefault()
}
- });
+ })
- $rootScope.$on('setLookAndFeel', function(event, data) {
+ $rootScope.$on('setLookAndFeel', function (event, data) {
if (!event.defaultPrevented && data && data !== '' && data !== $scope.looknfeel) {
- $scope.looknfeel = data;
- event.preventDefault();
+ $scope.looknfeel = data
+ event.preventDefault()
}
- });
+ })
// Set The lookAndFeel to default on every page
- $rootScope.$on('$routeChangeStart', function(event, next, current) {
- $rootScope.$broadcast('setLookAndFeel', 'default');
- });
+ $rootScope.$on('$routeChangeStart', function (event, next, current) {
+ $rootScope.$broadcast('setLookAndFeel', 'default')
+ })
- $rootScope.noteName = function(note) {
+ $rootScope.noteName = function (note) {
if (!_.isEmpty(note)) {
- return arrayOrderingSrv.getNoteName(note);
+ return arrayOrderingSrv.getNoteName(note)
}
- };
+ }
- BootstrapDialog.defaultOptions.onshown = function() {
- angular.element('#' + this.id).find('.btn:last').focus();
- };
+ BootstrapDialog.defaultOptions.onshown = function () {
+ angular.element('#' + this.id).find('.btn:last').focus()
+ }
// Remove BootstrapDialog animation
- BootstrapDialog.configDefaultOptions({animate: false});
+ BootstrapDialog.configDefaultOptions({animate: false})
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/app.controller.test.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/app.controller.test.js b/zeppelin-web/src/app/app.controller.test.js
index 329fb21..67d5034 100644
--- a/zeppelin-web/src/app/app.controller.test.js
+++ b/zeppelin-web/src/app/app.controller.test.js
@@ -1,29 +1,28 @@
-describe('Controller: MainCtrl', function() {
- beforeEach(angular.mock.module('zeppelinWebApp'));
+describe('Controller: MainCtrl', function () {
+ beforeEach(angular.mock.module('zeppelinWebApp'))
- var scope;
- var rootScope;
+ let scope
+ let rootScope
- beforeEach(inject(function($controller, $rootScope) {
- rootScope = $rootScope;
- scope = $rootScope.$new();
+ beforeEach(inject(function ($controller, $rootScope) {
+ rootScope = $rootScope
+ scope = $rootScope.$new()
$controller('MainCtrl', {
$scope: scope
- });
- }));
+ })
+ }))
- it('should attach "asIframe" to the scope and the default value should be false', function() {
- expect(scope.asIframe).toBeDefined();
- expect(scope.asIframe).toEqual(false);
- });
+ it('should attach "asIframe" to the scope and the default value should be false', function () {
+ expect(scope.asIframe).toBeDefined()
+ expect(scope.asIframe).toEqual(false)
+ })
- it('should set the default value of "looknfeel to "default"', function() {
- expect(scope.looknfeel).toEqual('default');
- });
+ it('should set the default value of "looknfeel to "default"', function () {
+ expect(scope.looknfeel).toEqual('default')
+ })
- it('should set "asIframe" flag to true when a controller broadcasts setIframe event', function() {
- rootScope.$broadcast('setIframe', true);
- expect(scope.asIframe).toEqual(true);
- });
-
-});
+ it('should set "asIframe" flag to true when a controller broadcasts setIframe event', function () {
+ rootScope.$broadcast('setIframe', true)
+ expect(scope.asIframe).toEqual(true)
+ })
+})
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/app.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/app.js b/zeppelin-web/src/app/app.js
index 40b19c1..0775d38 100644
--- a/zeppelin-web/src/app/app.js
+++ b/zeppelin-web/src/app/app.js
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-var zeppelinWebApp = angular.module('zeppelinWebApp', [
+let zeppelinWebApp = angular.module('zeppelinWebApp', [
'ngCookies',
'ngAnimate',
'ngRoute',
@@ -35,22 +35,23 @@ var zeppelinWebApp = angular.module('zeppelinWebApp', [
'ngResource',
'ngclipboard'
])
- .filter('breakFilter', function() {
- return function(text) {
+ .filter('breakFilter', function () {
+ return function (text) {
+ // eslint-disable-next-line no-extra-boolean-cast
if (!!text) {
- return text.replace(/\n/g, '<br />');
+ return text.replace(/\n/g, '<br />')
}
- };
+ }
})
- .config(function($httpProvider, $routeProvider, ngToastProvider) {
+ .config(function ($httpProvider, $routeProvider, ngToastProvider) {
// withCredentials when running locally via grunt
- $httpProvider.defaults.withCredentials = true;
+ $httpProvider.defaults.withCredentials = true
- var visBundleLoad = {
- load: ['heliumService', function(heliumService) {
- return heliumService.load;
+ let visBundleLoad = {
+ load: ['heliumService', function (heliumService) {
+ return heliumService.load
}]
- };
+ }
$routeProvider
.when('/', {
@@ -107,67 +108,67 @@ var zeppelinWebApp = angular.module('zeppelinWebApp', [
})
.otherwise({
redirectTo: '/'
- });
+ })
ngToastProvider.configure({
dismissButton: true,
dismissOnClick: false,
combineDuplications: true,
timeout: 6000
- });
+ })
})
- //handel logout on API failure
+ // handel logout on API failure
.config(function ($httpProvider, $provide) {
$provide.factory('httpInterceptor', function ($q, $rootScope) {
return {
'responseError': function (rejection) {
if (rejection.status === 405) {
- var data = {};
- data.info = '';
- $rootScope.$broadcast('session_logout', data);
+ let data = {}
+ data.info = ''
+ $rootScope.$broadcast('session_logout', data)
}
- $rootScope.$broadcast('httpResponseError', rejection);
- return $q.reject(rejection);
+ $rootScope.$broadcast('httpResponseError', rejection)
+ return $q.reject(rejection)
}
- };
- });
- $httpProvider.interceptors.push('httpInterceptor');
+ }
+ })
+ $httpProvider.interceptors.push('httpInterceptor')
})
- .constant('TRASH_FOLDER_ID', '~Trash');
+ .constant('TRASH_FOLDER_ID', '~Trash')
-function auth() {
- var $http = angular.injector(['ng']).get('$http');
- var baseUrlSrv = angular.injector(['zeppelinWebApp']).get('baseUrlSrv');
+function auth () {
+ let $http = angular.injector(['ng']).get('$http')
+ let baseUrlSrv = angular.injector(['zeppelinWebApp']).get('baseUrlSrv')
// withCredentials when running locally via grunt
- $http.defaults.withCredentials = true;
+ $http.defaults.withCredentials = true
jQuery.ajaxSetup({
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true
- });
- return $http.get(baseUrlSrv.getRestApiBase() + '/security/ticket').then(function(response) {
- zeppelinWebApp.run(function($rootScope) {
- $rootScope.ticket = angular.fromJson(response.data).body;
- });
- }, function(errorResponse) {
+ })
+ return $http.get(baseUrlSrv.getRestApiBase() + '/security/ticket').then(function (response) {
+ zeppelinWebApp.run(function ($rootScope) {
+ $rootScope.ticket = angular.fromJson(response.data).body
+ })
+ }, function (errorResponse) {
// Handle error case
- });
+ })
}
-function bootstrapApplication() {
- zeppelinWebApp.run(function($rootScope, $location) {
- $rootScope.$on('$routeChangeStart', function(event, next, current) {
+function bootstrapApplication () {
+ zeppelinWebApp.run(function ($rootScope, $location) {
+ $rootScope.$on('$routeChangeStart', function (event, next, current) {
if (!$rootScope.ticket && next.$$route && !next.$$route.publicAccess) {
- $location.path('/');
+ $location.path('/')
}
- });
- });
- angular.bootstrap(document, ['zeppelinWebApp']);
+ })
+ })
+ angular.bootstrap(document, ['zeppelinWebApp'])
}
-angular.element(document).ready(function() {
- auth().then(bootstrapApplication);
-});
+angular.element(document).ready(function () {
+ auth().then(bootstrapApplication)
+})
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/configuration/configuration.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/configuration/configuration.controller.js b/zeppelin-web/src/app/configuration/configuration.controller.js
index 70c9fe0..e4f4e5d 100644
--- a/zeppelin-web/src/app/configuration/configuration.controller.js
+++ b/zeppelin-web/src/app/configuration/configuration.controller.js
@@ -12,38 +12,38 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('ConfigurationCtrl', ConfigurationCtrl);
+angular.module('zeppelinWebApp').controller('ConfigurationCtrl', ConfigurationCtrl)
-function ConfigurationCtrl($scope, $rootScope, $http, baseUrlSrv, ngToast) {
- 'ngInject';
+function ConfigurationCtrl ($scope, $rootScope, $http, baseUrlSrv, ngToast) {
+ 'ngInject'
- $scope.configrations = [];
- $scope._ = _;
- ngToast.dismiss();
+ $scope.configrations = []
+ $scope._ = _
+ ngToast.dismiss()
- var getConfigurations = function() {
- $http.get(baseUrlSrv.getRestApiBase() + '/configurations/all').
- success(function(data, status, headers, config) {
- $scope.configurations = data.body;
- }).
- error(function(data, status, headers, config) {
+ let getConfigurations = function () {
+ $http.get(baseUrlSrv.getRestApiBase() + '/configurations/all')
+ .success(function (data, status, headers, config) {
+ $scope.configurations = data.body
+ })
+ .error(function (data, status, headers, config) {
if (status === 401) {
ngToast.danger({
content: 'You don\'t have permission on this page',
verticalPosition: 'bottom',
timeout: '3000'
- });
- setTimeout(function() {
- window.location.replace('/');
- }, 3000);
+ })
+ setTimeout(function () {
+ window.location.replace('/')
+ }, 3000)
}
- console.log('Error %o %o', status, data.message);
- });
- };
+ console.log('Error %o %o', status, data.message)
+ })
+ }
- var init = function() {
- getConfigurations();
- };
+ let init = function () {
+ getConfigurations()
+ }
- init();
+ init()
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/credential/credential.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/credential/credential.controller.js b/zeppelin-web/src/app/credential/credential.controller.js
index 30edfe9..eb649c8 100644
--- a/zeppelin-web/src/app/credential/credential.controller.js
+++ b/zeppelin-web/src/app/credential/credential.controller.js
@@ -12,179 +12,178 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('CredentialCtrl', CredentialCtrl);
-
-function CredentialCtrl($scope, $rootScope, $http, baseUrlSrv, ngToast) {
- 'ngInject';
-
- $scope._ = _;
- ngToast.dismiss();
-
- $scope.credentialInfo = [];
- $scope.showAddNewCredentialInfo = false;
- $scope.availableInterpreters = [];
-
- var getCredentialInfo = function() {
- $http.get(baseUrlSrv.getRestApiBase() + '/credential').
- success(function(data, status, headers, config) {
- $scope.credentialInfo = _.map(data.body.userCredentials, function(value, prop) {
- return {entity: prop, password: value.password, username: value.username};
- });
- console.log('Success %o %o', status, $scope.credentialInfo);
- }).
- error(function(data, status, headers, config) {
+angular.module('zeppelinWebApp').controller('CredentialCtrl', CredentialCtrl)
+
+function CredentialCtrl ($scope, $rootScope, $http, baseUrlSrv, ngToast) {
+ 'ngInject'
+
+ $scope._ = _
+ ngToast.dismiss()
+
+ $scope.credentialInfo = []
+ $scope.showAddNewCredentialInfo = false
+ $scope.availableInterpreters = []
+
+ let getCredentialInfo = function () {
+ $http.get(baseUrlSrv.getRestApiBase() + '/credential')
+ .success(function (data, status, headers, config) {
+ $scope.credentialInfo = _.map(data.body.userCredentials, function (value, prop) {
+ return {entity: prop, password: value.password, username: value.username}
+ })
+ console.log('Success %o %o', status, $scope.credentialInfo)
+ })
+ .error(function (data, status, headers, config) {
if (status === 401) {
ngToast.danger({
content: 'You don\'t have permission on this page',
verticalPosition: 'bottom',
timeout: '3000'
- });
- setTimeout(function() {
- window.location.replace('/');
- }, 3000);
+ })
+ setTimeout(function () {
+ window.location.replace('/')
+ }, 3000)
}
- console.log('Error %o %o', status, data.message);
- });
- };
+ console.log('Error %o %o', status, data.message)
+ })
+ }
- $scope.addNewCredentialInfo = function() {
+ $scope.addNewCredentialInfo = function () {
if ($scope.entity && _.isEmpty($scope.entity.trim()) &&
$scope.username && _.isEmpty($scope.username.trim())) {
ngToast.danger({
content: 'Username \\ Entity can not be empty.',
verticalPosition: 'bottom',
timeout: '3000'
- });
- return;
+ })
+ return
}
- var newCredential = {
+ let newCredential = {
'entity': $scope.entity,
'username': $scope.username,
'password': $scope.password
- };
+ }
- $http.put(baseUrlSrv.getRestApiBase() + '/credential', newCredential).
- success(function(data, status, headers, config) {
+ $http.put(baseUrlSrv.getRestApiBase() + '/credential', newCredential)
+ .success(function (data, status, headers, config) {
ngToast.success({
content: 'Successfully saved credentials.',
verticalPosition: 'bottom',
timeout: '3000'
- });
- $scope.credentialInfo.push(newCredential);
- resetCredentialInfo();
- $scope.showAddNewCredentialInfo = false;
- console.log('Success %o %o', status, data.message);
- }).
- error(function(data, status, headers, config) {
+ })
+ $scope.credentialInfo.push(newCredential)
+ resetCredentialInfo()
+ $scope.showAddNewCredentialInfo = false
+ console.log('Success %o %o', status, data.message)
+ })
+ .error(function (data, status, headers, config) {
ngToast.danger({
content: 'Error saving credentials',
verticalPosition: 'bottom',
timeout: '3000'
- });
- console.log('Error %o %o', status, data.message);
- });
- };
+ })
+ console.log('Error %o %o', status, data.message)
+ })
+ }
- var getAvailableInterpreters = function() {
+ let getAvailableInterpreters = function () {
$http.get(baseUrlSrv.getRestApiBase() + '/interpreter/setting')
- .success(function(data, status, headers, config) {
- for (var setting = 0; setting < data.body.length; setting++) {
+ .success(function (data, status, headers, config) {
+ for (let setting = 0; setting < data.body.length; setting++) {
$scope.availableInterpreters.push(
- data.body[setting].group + '.' + data.body[setting].name);
+ data.body[setting].group + '.' + data.body[setting].name)
}
angular.element('#entityname').autocomplete({
source: $scope.availableInterpreters,
- select: function(event, selected) {
- $scope.entity = selected.item.value;
- return false;
+ select: function (event, selected) {
+ $scope.entity = selected.item.value
+ return false
}
- });
- }).error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- });
- };
+ })
+ }).error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ })
+ }
- $scope.toggleAddNewCredentialInfo = function() {
+ $scope.toggleAddNewCredentialInfo = function () {
if ($scope.showAddNewCredentialInfo) {
- $scope.showAddNewCredentialInfo = false;
+ $scope.showAddNewCredentialInfo = false
} else {
- $scope.showAddNewCredentialInfo = true;
+ $scope.showAddNewCredentialInfo = true
}
- };
+ }
- $scope.cancelCredentialInfo = function() {
- $scope.showAddNewCredentialInfo = false;
- resetCredentialInfo();
- };
+ $scope.cancelCredentialInfo = function () {
+ $scope.showAddNewCredentialInfo = false
+ resetCredentialInfo()
+ }
- var resetCredentialInfo = function() {
- $scope.entity = '';
- $scope.username = '';
- $scope.password = '';
- };
+ const resetCredentialInfo = function () {
+ $scope.entity = ''
+ $scope.username = ''
+ $scope.password = ''
+ }
- $scope.copyOriginCredentialsInfo = function() {
+ $scope.copyOriginCredentialsInfo = function () {
ngToast.info({
content: 'Since entity is a unique key, you can edit only username & password',
verticalPosition: 'bottom',
timeout: '3000'
- });
- };
+ })
+ }
- $scope.updateCredentialInfo = function(form, data, entity) {
- var request = {
+ $scope.updateCredentialInfo = function (form, data, entity) {
+ let request = {
entity: entity,
username: data.username,
password: data.password
- };
-
- $http.put(baseUrlSrv.getRestApiBase() + '/credential/', request).
- success(function(data, status, headers, config) {
- var index = _.findIndex($scope.credentialInfo, {'entity': entity});
- $scope.credentialInfo[index] = request;
- return true;
- }).
- error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
+ }
+
+ $http.put(baseUrlSrv.getRestApiBase() + '/credential/', request)
+ .success(function (data, status, headers, config) {
+ let index = _.findIndex($scope.credentialInfo, {'entity': entity})
+ $scope.credentialInfo[index] = request
+ return true
+ })
+ .error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
ngToast.danger({
content: 'We couldn\'t save the credential',
verticalPosition: 'bottom',
timeout: '3000'
- });
- form.$show();
- });
- return false;
- };
+ })
+ form.$show()
+ })
+ return false
+ }
- $scope.removeCredentialInfo = function(entity) {
+ $scope.removeCredentialInfo = function (entity) {
BootstrapDialog.confirm({
closable: false,
closeByBackdrop: false,
closeByKeyboard: false,
title: '',
message: 'Do you want to delete this credential information?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- $http.delete(baseUrlSrv.getRestApiBase() + '/credential/' + entity).
- success(function(data, status, headers, config) {
- var index = _.findIndex($scope.credentialInfo, {'entity': entity});
- $scope.credentialInfo.splice(index, 1);
- console.log('Success %o %o', status, data.message);
- }).
- error(function(data, status, headers, config) {
- console.log('Error %o %o', status, data.message);
- });
+ $http.delete(baseUrlSrv.getRestApiBase() + '/credential/' + entity)
+ .success(function (data, status, headers, config) {
+ let index = _.findIndex($scope.credentialInfo, {'entity': entity})
+ $scope.credentialInfo.splice(index, 1)
+ console.log('Success %o %o', status, data.message)
+ })
+ .error(function (data, status, headers, config) {
+ console.log('Error %o %o', status, data.message)
+ })
}
}
- });
- };
+ })
+ }
- var init = function() {
- getAvailableInterpreters();
- getCredentialInfo();
- };
+ let init = function () {
+ getAvailableInterpreters()
+ getCredentialInfo()
+ }
- init();
+ init()
}
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/handsontable/handsonHelper.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/handsontable/handsonHelper.js b/zeppelin-web/src/app/handsontable/handsonHelper.js
index ccfa87a..8d724c0 100644
--- a/zeppelin-web/src/app/handsontable/handsonHelper.js
+++ b/zeppelin-web/src/app/handsontable/handsonHelper.js
@@ -16,15 +16,15 @@
* HandsonHelper class
*/
export default class HandsonHelper {
- constructor(columns, rows, comment) {
- this.columns = columns || [];
- this.rows = rows || [];
- this.comment = comment || '';
- this._numericValidator = this._numericValidator.bind(this);
- };
-
- getHandsonTableConfig(columns, columnNames, resultRows) {
- var self = this;
+ constructor (columns, rows, comment) {
+ this.columns = columns || []
+ this.rows = rows || []
+ this.comment = comment || ''
+ this._numericValidator = this._numericValidator.bind(this)
+ }
+
+ getHandsonTableConfig (columns, columnNames, resultRows) {
+ let self = this
return {
colHeaders: columnNames,
data: resultRows,
@@ -41,159 +41,161 @@ export default class HandsonHelper {
fillHandle: false,
fragmentSelection: true,
disableVisualSelection: true,
- cells: function(ro, co, pro) {
- var cellProperties = {};
- var colType = columns[co].type;
- cellProperties.renderer = function(instance, td, row, col, prop, value, cellProperties) {
- self._cellRenderer(instance, td, row, col, prop, value, cellProperties, colType);
- };
- return cellProperties;
+ cells: function (ro, co, pro) {
+ let cellProperties = {}
+ let colType = columns[co].type
+ cellProperties.renderer = function (instance, td, row, col, prop, value, cellProperties) {
+ self._cellRenderer(instance, td, row, col, prop, value, cellProperties, colType)
+ }
+ return cellProperties
},
- afterGetColHeader: function(col, TH) {
- var instance = this;
- var menu = self._buildDropDownMenu(columns[col].type);
- var button = self._buildTypeSwitchButton();
+ afterGetColHeader: function (col, TH) {
+ let instance = this
+ let menu = self._buildDropDownMenu(columns[col].type)
+ let button = self._buildTypeSwitchButton()
- self._addButtonMenuEvent(button, menu);
+ self._addButtonMenuEvent(button, menu)
- Handsontable.Dom.addEvent(menu, 'click', function(event) {
+ Handsontable.Dom.addEvent(menu, 'click', function (event) {
if (event.target.nodeName === 'LI') {
- self._setColumnType(columns, event.target.data.colType, instance, col);
+ self._setColumnType(columns, event.target.data.colType, instance, col)
}
- });
+ })
if (TH.firstChild.lastChild.nodeName === 'BUTTON') {
- TH.firstChild.removeChild(TH.firstChild.lastChild);
+ TH.firstChild.removeChild(TH.firstChild.lastChild)
}
- TH.firstChild.appendChild(button);
- TH.style['white-space'] = 'normal';
+ TH.firstChild.appendChild(button)
+ TH.style['white-space'] = 'normal'
}
- };
- };
+ }
+ }
/*
** Private Service Functions
*/
- _addButtonMenuEvent(button, menu) {
- Handsontable.Dom.addEvent(button, 'click', function(event) {
- var changeTypeMenu;
- var position;
- var removeMenu;
+ _addButtonMenuEvent (button, menu) {
+ Handsontable.Dom.addEvent(button, 'click', function (event) {
+ let changeTypeMenu
+ let position
+ let removeMenu
- document.body.appendChild(menu);
+ document.body.appendChild(menu)
- event.preventDefault();
- event.stopImmediatePropagation();
+ event.preventDefault()
+ event.stopImmediatePropagation()
- changeTypeMenu = document.querySelectorAll('.changeTypeMenu');
+ changeTypeMenu = document.querySelectorAll('.changeTypeMenu')
- for (var i = 0, len = changeTypeMenu.length; i < len; i++) {
- changeTypeMenu[i].style.display = 'none';
+ for (let i = 0, len = changeTypeMenu.length; i < len; i++) {
+ changeTypeMenu[i].style.display = 'none'
}
- menu.style.display = 'block';
- position = button.getBoundingClientRect();
+ menu.style.display = 'block'
+ position = button.getBoundingClientRect()
- menu.style.top = (position.top + (window.scrollY || window.pageYOffset)) + 2 + 'px';
- menu.style.left = (position.left) + 'px';
+ menu.style.top = (position.top + (window.scrollY || window.pageYOffset)) + 2 + 'px'
+ menu.style.left = (position.left) + 'px'
- removeMenu = function(event) {
+ removeMenu = function (event) {
if (menu.parentNode) {
- menu.parentNode.removeChild(menu);
+ menu.parentNode.removeChild(menu)
}
- };
- Handsontable.Dom.removeEvent(document, 'click', removeMenu);
- Handsontable.Dom.addEvent(document, 'click', removeMenu);
- });
+ }
+ Handsontable.Dom.removeEvent(document, 'click', removeMenu)
+ Handsontable.Dom.addEvent(document, 'click', removeMenu)
+ })
}
- _buildDropDownMenu(activeCellType) {
- var menu = document.createElement('UL');
- var types = ['text', 'numeric', 'date'];
- var item;
+ _buildDropDownMenu (activeCellType) {
+ let menu = document.createElement('UL')
+ let types = ['text', 'numeric', 'date']
+ let item
- menu.className = 'changeTypeMenu';
+ menu.className = 'changeTypeMenu'
- for (var i = 0, len = types.length; i < len; i++) {
- item = document.createElement('LI');
+ for (let i = 0, len = types.length; i < len; i++) {
+ item = document.createElement('LI')
if ('innerText' in item) {
- item.innerText = types[i];
+ item.innerText = types[i]
} else {
- item.textContent = types[i];
+ item.textContent = types[i]
}
- item.data = {'colType': types[i]};
+ item.data = {'colType': types[i]}
if (activeCellType === types[i]) {
- item.className = 'active';
+ item.className = 'active'
}
- menu.appendChild(item);
+ menu.appendChild(item)
}
- return menu;
+ return menu
}
- _buildTypeSwitchButton() {
- var button = document.createElement('BUTTON');
+ _buildTypeSwitchButton () {
+ let button = document.createElement('BUTTON')
- button.innerHTML = '\u25BC';
- button.className = 'changeType';
+ button.innerHTML = '\u25BC'
+ button.className = 'changeType'
- return button;
+ return button
}
- _isNumeric(value) {
+ _isNumeric (value) {
if (!isNaN(value)) {
if (value.length !== 0) {
if (Number(value) <= Number.MAX_SAFE_INTEGER && Number(value) >= Number.MIN_SAFE_INTEGER) {
- return true;
+ return true
}
}
}
- return false;
+ return false
}
- _cellRenderer(instance, td, row, col, prop, value, cellProperties, colType) {
+ _cellRenderer (instance, td, row, col, prop, value, cellProperties, colType) {
if (colType === 'numeric' && this._isNumeric(value)) {
- cellProperties.format = '0,0.[00000]';
- td.style.textAlign = 'left';
- Handsontable.renderers.NumericRenderer.apply(this, arguments);
- } else if (value.length > '%html'.length && '%html ' === value.substring(0, '%html '.length)) {
- td.innerHTML = value.substring('%html'.length);
+ cellProperties.format = '0,0.[00000]'
+ td.style.textAlign = 'left'
+ // eslint-disable-next-line prefer-rest-params
+ Handsontable.renderers.NumericRenderer.apply(this, arguments)
+ } else if (value.length > '%html'.length && value.substring(0, '%html '.length) === '%html ') {
+ td.innerHTML = value.substring('%html'.length)
} else {
- Handsontable.renderers.TextRenderer.apply(this, arguments);
+ // eslint-disable-next-line prefer-rest-params
+ Handsontable.renderers.TextRenderer.apply(this, arguments)
}
}
- _dateValidator(value, callback) {
- var d = moment(value);
- return callback(d.isValid());
+ _dateValidator (value, callback) {
+ let d = moment(value)
+ return callback(d.isValid())
}
- _numericValidator(value, callback) {
- return callback(this._isNumeric(value));
+ _numericValidator (value, callback) {
+ return callback(this._isNumeric(value))
}
- _setColumnType(columns, type, instance, col) {
- columns[col].type = type;
- this._setColumnValidator(columns, col);
- instance.updateSettings({columns: columns});
- instance.validateCells(null);
+ _setColumnType (columns, type, instance, col) {
+ columns[col].type = type
+ this._setColumnValidator(columns, col)
+ instance.updateSettings({columns: columns})
+ instance.validateCells(null)
if (this._isColumnSorted(instance, col)) {
- instance.sort(col, instance.sortOrder);
+ instance.sort(col, instance.sortOrder)
}
}
- _isColumnSorted(instance, col) {
- return instance.sortingEnabled && instance.sortColumn === col;
+ _isColumnSorted (instance, col) {
+ return instance.sortingEnabled && instance.sortColumn === col
}
- _setColumnValidator(columns, col) {
+ _setColumnValidator (columns, col) {
if (columns[col].type === 'numeric') {
- columns[col].validator = this._numericValidator;
+ columns[col].validator = this._numericValidator
} else if (columns[col].type === 'date') {
- columns[col].validator = this._dateValidator;
+ columns[col].validator = this._dateValidator
} else {
- columns[col].validator = null;
+ columns[col].validator = null
}
}
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/helium/helium.config.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/helium/helium.config.js b/zeppelin-web/src/app/helium/helium.config.js
index e21fe19..ace7136 100644
--- a/zeppelin-web/src/app/helium/helium.config.js
+++ b/zeppelin-web/src/app/helium/helium.config.js
@@ -16,85 +16,86 @@ export const HeliumConfFieldType = {
NUMBER: 'number',
JSON: 'json',
STRING: 'string',
-};
+}
/**
* @param persisted <Object> including `type`, `description`, `defaultValue` for each conf key
* @param spec <Object> including `value` for each conf key
*/
-export function mergePersistedConfWithSpec(persisted, spec) {
- const confs = [];
+export function mergePersistedConfWithSpec (persisted, spec) {
+ const confs = []
- for(let name in spec) {
- const specField = spec[name];
- const persistedValue = persisted[name];
+ for (let name in spec) {
+ const specField = spec[name]
+ const persistedValue = persisted[name]
- const value = (persistedValue) ? persistedValue : specField.defaultValue;
+ const value = (persistedValue) ? persistedValue : specField.defaultValue
const merged = {
- name: name, type: specField.type, description: specField.description,
- value: value, defaultValue: specField.defaultValue,
- };
+ name: name,
+ type: specField.type,
+ description: specField.description,
+ value: value,
+ defaultValue: specField.defaultValue,
+ }
- confs.push(merged);
+ confs.push(merged)
}
- return confs;
+ return confs
}
-export function createPackageConf(defaultPackages, persistedPackacgeConfs) {
- let packageConfs = {};
+export function createPackageConf (defaultPackages, persistedPackacgeConfs) {
+ let packageConfs = {}
for (let name in defaultPackages) {
- const pkgInfo = defaultPackages[name];
+ const pkgInfo = defaultPackages[name]
- const configSpec = pkgInfo.pkg.config;
- if (!configSpec) { continue; }
+ const configSpec = pkgInfo.pkg.config
+ if (!configSpec) { continue }
- const version = pkgInfo.pkg.version;
- if (!version) { continue; }
+ const version = pkgInfo.pkg.version
+ if (!version) { continue }
- let config = {};
+ let config = {}
if (persistedPackacgeConfs[name] && persistedPackacgeConfs[name][version]) {
- config = persistedPackacgeConfs[name][version];
+ config = persistedPackacgeConfs[name][version]
}
- const confs = mergePersistedConfWithSpec(config, configSpec);
- packageConfs[name] = confs;
+ const confs = mergePersistedConfWithSpec(config, configSpec)
+ packageConfs[name] = confs
}
- return packageConfs;
+ return packageConfs
}
-export function parseConfigValue(type, stringified) {
- let value = stringified;
+export function parseConfigValue (type, stringified) {
+ let value = stringified
try {
if (HeliumConfFieldType.NUMBER === type) {
- value = parseFloat(stringified);
+ value = parseFloat(stringified)
} else if (HeliumConfFieldType.JSON === type) {
- value = JSON.parse(stringified);
+ value = JSON.parse(stringified)
}
- } catch(error) {
+ } catch (error) {
// return just the stringified one
- console.error(`Failed to parse conf type ${type}, value ${value}`);
+ console.error(`Failed to parse conf type ${type}, value ${value}`)
}
- return value;
+ return value
}
/**
* create persistable config object
*/
-export function createPersistableConfig(currentConf) {
+export function createPersistableConfig (currentConf) {
// persist key-value only
// since other info (e.g type, desc) can be provided by default config
const filtered = currentConf.reduce((acc, c) => {
- let value = parseConfigValue(c.type, c.value);
- acc[c.name] = value;
- return acc;
- }, {});
+ let value = parseConfigValue(c.type, c.value)
+ acc[c.name] = value
+ return acc
+ }, {})
- return filtered;
+ return filtered
}
-
-
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/helium/helium.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/helium/helium.controller.js b/zeppelin-web/src/app/helium/helium.controller.js
index 615f811..7a112e2 100644
--- a/zeppelin-web/src/app/helium/helium.controller.js
+++ b/zeppelin-web/src/app/helium/helium.controller.js
@@ -12,17 +12,17 @@
* limitations under the License.
*/
-import { HeliumType, } from '../../components/helium/helium-type';
+import { HeliumType, } from '../../components/helium/helium-type'
-export default function HeliumCtrl($scope, $rootScope, $sce,
+export default function HeliumCtrl ($scope, $rootScope, $sce,
baseUrlSrv, ngToast, heliumService) {
- 'ngInject';
+ 'ngInject'
- $scope.pkgSearchResults = {};
- $scope.defaultPackages = {};
- $scope.showVersions = {};
- $scope.bundleOrder = [];
- $scope.bundleOrderChanged = false;
+ $scope.pkgSearchResults = {}
+ $scope.defaultPackages = {}
+ $scope.showVersions = {}
+ $scope.bundleOrder = []
+ $scope.bundleOrderChanged = false
$scope.vizTypePkg = {}
$scope.spellTypePkg = {}
$scope.intpTypePkg = {}
@@ -30,168 +30,168 @@ export default function HeliumCtrl($scope, $rootScope, $sce,
$scope.numberOfEachPackageByType = {}
$scope.allPackageTypes = [HeliumType][0]
$scope.pkgListByType = 'VISUALIZATION'
- $scope.defaultPackageConfigs = {}; // { pkgName, [{name, type, desc, value, defaultValue}] }
- $scope.intpDefaultIcon = $sce.trustAsHtml('<img src="../assets/images/maven_default_icon.png" style="width: 12px"/>');
+ $scope.defaultPackageConfigs = {} // { pkgName, [{name, type, desc, value, defaultValue}] }
+ $scope.intpDefaultIcon = $sce.trustAsHtml('<img src="../assets/images/maven_default_icon.png" style="width: 12px"/>')
- function init() {
+ function init () {
// get all package info and set config
heliumService.getAllPackageInfoAndDefaultPackages()
.then(({ pkgSearchResults, defaultPackages }) => {
// pagination
- $scope.itemsPerPage = 10;
- $scope.currentPage = 1;
- $scope.maxSize = 5;
-
- $scope.pkgSearchResults = pkgSearchResults;
- $scope.defaultPackages = defaultPackages;
- classifyPkgType($scope.defaultPackages);
-
+ $scope.itemsPerPage = 10
+ $scope.currentPage = 1
+ $scope.maxSize = 5
+
+ $scope.pkgSearchResults = pkgSearchResults
+ $scope.defaultPackages = defaultPackages
+ classifyPkgType($scope.defaultPackages)
+
return heliumService.getAllPackageConfigs()
})
.then(defaultPackageConfigs => {
- $scope.defaultPackageConfigs = defaultPackageConfigs;
- });
+ $scope.defaultPackageConfigs = defaultPackageConfigs
+ })
// 2. get vis package order
heliumService.getVisualizationPackageOrder()
.then(visPackageOrder => {
- $scope.bundleOrder = visPackageOrder;
- $scope.bundleOrderChanged = false;
- });
- };
+ $scope.bundleOrder = visPackageOrder
+ $scope.bundleOrderChanged = false
+ })
+ }
- var orderPackageByPubDate = function(a, b) {
+ let orderPackageByPubDate = function (a, b) {
if (!a.pkg.published) {
// Because local registry pkgs don't have 'published' field, put current time instead to show them first
a.pkg.published = new Date().getTime()
}
- return new Date(a.pkg.published).getTime() - new Date(b.pkg.published).getTime();
- };
+ return new Date(a.pkg.published).getTime() - new Date(b.pkg.published).getTime()
+ }
- var classifyPkgType = function(packageInfo) {
- var allTypesOfPkg = {};
- var vizTypePkg = [];
- var spellTypePkg = [];
- var intpTypePkg = [];
- var appTypePkg = [];
+ const classifyPkgType = function (packageInfo) {
+ let allTypesOfPkg = {}
+ let vizTypePkg = []
+ let spellTypePkg = []
+ let intpTypePkg = []
+ let appTypePkg = []
- var packageInfoArr = Object.keys(packageInfo).map(key => packageInfo[key])
- packageInfoArr = packageInfoArr.sort(orderPackageByPubDate).reverse();
+ let packageInfoArr = Object.keys(packageInfo).map(key => packageInfo[key])
+ packageInfoArr = packageInfoArr.sort(orderPackageByPubDate).reverse()
- for (var name in packageInfoArr) {
- var pkgs = packageInfoArr[name];
- var pkgType = pkgs.pkg.type;
+ for (let name in packageInfoArr) {
+ let pkgs = packageInfoArr[name]
+ let pkgType = pkgs.pkg.type
switch (pkgType) {
case HeliumType.VISUALIZATION:
- vizTypePkg.push(pkgs);
- break;
+ vizTypePkg.push(pkgs)
+ break
case HeliumType.SPELL:
- spellTypePkg.push(pkgs);
- break;
+ spellTypePkg.push(pkgs)
+ break
case HeliumType.INTERPRETER:
- intpTypePkg.push(pkgs);
- break;
+ intpTypePkg.push(pkgs)
+ break
case HeliumType.APPLICATION:
- appTypePkg.push(pkgs);
- break;
+ appTypePkg.push(pkgs)
+ break
}
}
- var pkgsArr = [
+ let pkgsArr = [
vizTypePkg,
spellTypePkg,
intpTypePkg,
appTypePkg
]
- for (var idx in _.keys(HeliumType)) {
- allTypesOfPkg[_.keys(HeliumType)[idx]] = pkgsArr[idx];
+ for (let idx in _.keys(HeliumType)) {
+ allTypesOfPkg[_.keys(HeliumType)[idx]] = pkgsArr[idx]
}
-
- $scope.allTypesOfPkg = allTypesOfPkg;
- };
+
+ $scope.allTypesOfPkg = allTypesOfPkg
+ }
$scope.bundleOrderListeners = {
- accept: function(sourceItemHandleScope, destSortableScope) {return true;},
- itemMoved: function(event) {},
- orderChanged: function(event) {
- $scope.bundleOrderChanged = true;
+ accept: function (sourceItemHandleScope, destSortableScope) { return true },
+ itemMoved: function (event) {},
+ orderChanged: function (event) {
+ $scope.bundleOrderChanged = true
}
- };
+ }
- $scope.saveBundleOrder = function() {
- var confirm = BootstrapDialog.confirm({
+ $scope.saveBundleOrder = function () {
+ const confirm = BootstrapDialog.confirm({
closable: false,
closeByBackdrop: false,
closeByKeyboard: false,
title: '',
message: 'Save changes?',
- callback: function(result) {
+ callback: function (result) {
if (result) {
- confirm.$modalFooter.find('button').addClass('disabled');
+ confirm.$modalFooter.find('button').addClass('disabled')
confirm.$modalFooter.find('button:contains("OK")')
- .html('<i class="fa fa-circle-o-notch fa-spin"></i> Enabling');
- heliumService.setVisualizationPackageOrder($scope.bundleOrder).
- success(function(data, status) {
- init();
- confirm.close();
- }).
- error(function(data, status) {
- confirm.close();
- console.log('Failed to save order');
+ .html('<i class="fa fa-circle-o-notch fa-spin"></i> Enabling')
+ heliumService.setVisualizationPackageOrder($scope.bundleOrder)
+ .success(function (data, status) {
+ init()
+ confirm.close()
+ })
+ .error(function (data, status) {
+ confirm.close()
+ console.log('Failed to save order')
BootstrapDialog.show({
title: 'Error on saving order ',
message: data.message
- });
- });
- return false;
+ })
+ })
+ return false
}
}
- });
- };
+ })
+ }
- var getLicense = function(name, artifact) {
- var filteredPkgSearchResults = _.filter($scope.defaultPackages[name], function(p) {
- return p.artifact === artifact;
- });
+ let getLicense = function (name, artifact) {
+ let filteredPkgSearchResults = _.filter($scope.defaultPackages[name], function (p) {
+ return p.artifact === artifact
+ })
- var license;
+ let license
if (filteredPkgSearchResults.length === 0) {
- filteredPkgSearchResults = _.filter($scope.pkgSearchResults[name], function(p) {
- return p.pkg.artifact === artifact;
- });
+ filteredPkgSearchResults = _.filter($scope.pkgSearchResults[name], function (p) {
+ return p.pkg.artifact === artifact
+ })
if (filteredPkgSearchResults.length > 0) {
- license = filteredPkgSearchResults[0].pkg.license;
+ license = filteredPkgSearchResults[0].pkg.license
}
} else {
- license = filteredPkgSearchResults[0].license;
+ license = filteredPkgSearchResults[0].license
}
if (!license) {
- license = 'Unknown';
+ license = 'Unknown'
}
- return license;
+ return license
}
- const getHeliumTypeText = function(type) {
+ const getHeliumTypeText = function (type) {
if (type === HeliumType.VISUALIZATION) {
- return `<a target="_blank" href="https://zeppelin.apache.org/docs/${$rootScope.zeppelinVersion}/development/writingzeppelinvisualization.html">${type}</a>`; // eslint-disable-line max-len
+ return `<a target="_blank" href="https://zeppelin.apache.org/docs/${$rootScope.zeppelinVersion}/development/writingzeppelinvisualization.html">${type}</a>` // eslint-disable-line max-len
} else if (type === HeliumType.SPELL) {
- return `<a target="_blank" href="https://zeppelin.apache.org/docs/${$rootScope.zeppelinVersion}/development/writingzeppelinspell.html">${type}</a>`; // eslint-disable-line max-len
+ return `<a target="_blank" href="https://zeppelin.apache.org/docs/${$rootScope.zeppelinVersion}/development/writingzeppelinspell.html">${type}</a>` // eslint-disable-line max-len
} else {
- return type;
+ return type
}
}
- $scope.enable = function(name, artifact, type, groupId, description) {
- var license = getLicense(name, artifact);
- var mavenArtifactInfoToHTML = groupId +':'+ artifact.split('@')[0] + ':' + artifact.split('@')[1];
- var zeppelinVersion = $rootScope.zeppelinVersion;
- var url = 'https://zeppelin.apache.org/docs/' + zeppelinVersion + '/manual/interpreterinstallation.html';
+ $scope.enable = function (name, artifact, type, groupId, description) {
+ let license = getLicense(name, artifact)
+ let mavenArtifactInfoToHTML = groupId + ':' + artifact.split('@')[0] + ':' + artifact.split('@')[1]
+ let zeppelinVersion = $rootScope.zeppelinVersion
+ let url = 'https://zeppelin.apache.org/docs/' + zeppelinVersion + '/manual/interpreterinstallation.html'
- var confirm = ''
+ let confirm = ''
if (type === HeliumType.INTERPRETER) {
confirm = BootstrapDialog.show({
title: '',
@@ -201,11 +201,11 @@ export default function HeliumCtrl($scope, $rootScope, $sce,
' and all of its transitive dependencies into interpreter/interpreter-name directory.<p>' +
'<div class="highlight"><pre><code class="text language-text" data-lang="text" style="font-size: 11.5px">' +
'./bin/install-interpreter.sh --name "interpreter-name" --artifact ' +
- mavenArtifactInfoToHTML +' </code></pre>' +
+ mavenArtifactInfoToHTML + ' </code></pre>' +
'<p>After restart Zeppelin, create interpreter setting and bind it with your note. ' +
'For more detailed information, see <a target="_blank" href=' +
url + '>Interpreter Installation.</a></p>'
- });
+ })
} else {
confirm = BootstrapDialog.confirm({
closable: false,
@@ -226,136 +226,136 @@ export default function HeliumCtrl($scope, $rootScope, $sce,
`<div style="color:gray">${license}</div>`,
callback: function (result) {
if (result) {
- confirm.$modalFooter.find('button').addClass('disabled');
+ confirm.$modalFooter.find('button').addClass('disabled')
confirm.$modalFooter.find('button:contains("OK")')
- .html('<i class="fa fa-circle-o-notch fa-spin"></i> Enabling');
+ .html('<i class="fa fa-circle-o-notch fa-spin"></i> Enabling')
heliumService.enable(name, artifact, type).success(function (data, status) {
- init();
- confirm.close();
+ init()
+ confirm.close()
}).error(function (data, status) {
- confirm.close();
- console.log('Failed to enable package %o %o. %o', name, artifact, data);
+ confirm.close()
+ console.log('Failed to enable package %o %o. %o', name, artifact, data)
BootstrapDialog.show({
title: 'Error on enabling ' + name,
message: data.message
- });
- });
- return false;
+ })
+ })
+ return false
}
}
- });
+ })
}
- };
+ }
- $scope.disable = function(name, artifact) {
- var confirm = BootstrapDialog.confirm({
+ $scope.disable = function (name, artifact) {
+ const confirm = BootstrapDialog.confirm({
closable: false,
closeByBackdrop: false,
closeByKeyboard: false,
title: '<div style="font-weight: 300;">Do you want to disable Helium Package?</div>',
message: artifact,
- callback: function(result) {
+ callback: function (result) {
if (result) {
- confirm.$modalFooter.find('button').addClass('disabled');
+ confirm.$modalFooter.find('button').addClass('disabled')
confirm.$modalFooter.find('button:contains("OK")')
- .html('<i class="fa fa-circle-o-notch fa-spin"></i> Disabling');
- heliumService.disable(name).
- success(function(data, status) {
- init();
- confirm.close();
- }).
- error(function(data, status) {
- confirm.close();
- console.log('Failed to disable package %o. %o', name, data);
+ .html('<i class="fa fa-circle-o-notch fa-spin"></i> Disabling')
+ heliumService.disable(name)
+ .success(function (data, status) {
+ init()
+ confirm.close()
+ })
+ .error(function (data, status) {
+ confirm.close()
+ console.log('Failed to disable package %o. %o', name, data)
BootstrapDialog.show({
title: 'Error on disabling ' + name,
message: data.message
- });
- });
- return false;
+ })
+ })
+ return false
}
}
- });
- };
+ })
+ }
- $scope.toggleVersions = function(pkgName) {
+ $scope.toggleVersions = function (pkgName) {
if ($scope.showVersions[pkgName]) {
- $scope.showVersions[pkgName] = false;
+ $scope.showVersions[pkgName] = false
} else {
- $scope.showVersions[pkgName] = true;
+ $scope.showVersions[pkgName] = true
}
- };
+ }
- $scope.isLocalPackage = function(pkgSearchResult) {
- const pkg = pkgSearchResult.pkg;
- return pkg.artifact && !pkg.artifact.includes('@');
- };
+ $scope.isLocalPackage = function (pkgSearchResult) {
+ const pkg = pkgSearchResult.pkg
+ return pkg.artifact && !pkg.artifact.includes('@')
+ }
- $scope.hasNpmLink = function(pkgSearchResult) {
- const pkg = pkgSearchResult.pkg;
+ $scope.hasNpmLink = function (pkgSearchResult) {
+ const pkg = pkgSearchResult.pkg
return (pkg.type === HeliumType.SPELL || pkg.type === HeliumType.VISUALIZATION) &&
- !$scope.isLocalPackage(pkgSearchResult);
- };
+ !$scope.isLocalPackage(pkgSearchResult)
+ }
- $scope.hasMavenLink = function(pkgSearchResult) {
- const pkg = pkgSearchResult.pkg;
+ $scope.hasMavenLink = function (pkgSearchResult) {
+ const pkg = pkgSearchResult.pkg
return (pkg.type === HeliumType.APPLICATION || pkg.type === HeliumType.INTERPRETER) &&
- !$scope.isLocalPackage(pkgSearchResult);
- };
+ !$scope.isLocalPackage(pkgSearchResult)
+ }
- $scope.getPackageSize = function(pkgSearchResult, targetPkgType) {
- var result = []
+ $scope.getPackageSize = function (pkgSearchResult, targetPkgType) {
+ let result = []
_.map(pkgSearchResult, function (pkg) {
result.push(_.find(pkg, {type: targetPkgType}))
})
return _.compact(result).length
}
- $scope.configExists = function(pkgSearchResult) {
+ $scope.configExists = function (pkgSearchResult) {
// helium package config is persisted per version
- return pkgSearchResult.pkg.config && pkgSearchResult.pkg.artifact;
- };
+ return pkgSearchResult.pkg.config && pkgSearchResult.pkg.artifact
+ }
- $scope.configOpened = function(pkgSearchResult) {
- return pkgSearchResult.configOpened && !pkgSearchResult.configFetching;
- };
+ $scope.configOpened = function (pkgSearchResult) {
+ return pkgSearchResult.configOpened && !pkgSearchResult.configFetching
+ }
- $scope.getConfigButtonClass = function(pkgSearchResult) {
- return (pkgSearchResult.configOpened && pkgSearchResult.configFetching) ?
- 'disabled' : '';
+ $scope.getConfigButtonClass = function (pkgSearchResult) {
+ return (pkgSearchResult.configOpened && pkgSearchResult.configFetching)
+ ? 'disabled' : ''
}
- $scope.toggleConfigButton = function(pkgSearchResult) {
+ $scope.toggleConfigButton = function (pkgSearchResult) {
if (pkgSearchResult.configOpened) {
- pkgSearchResult.configOpened = false;
- return;
+ pkgSearchResult.configOpened = false
+ return
}
- const pkg = pkgSearchResult.pkg;
- const pkgName = pkg.name;
- pkgSearchResult.configFetching = true;
- pkgSearchResult.configOpened = true;
+ const pkg = pkgSearchResult.pkg
+ const pkgName = pkg.name
+ pkgSearchResult.configFetching = true
+ pkgSearchResult.configOpened = true
heliumService.getSinglePackageConfigs(pkg)
.then(confs => {
- $scope.defaultPackageConfigs[pkgName] = confs;
- pkgSearchResult.configFetching = false;
- });
- };
+ $scope.defaultPackageConfigs[pkgName] = confs
+ pkgSearchResult.configFetching = false
+ })
+ }
- $scope.saveConfig = function(pkgSearchResult) {
- const pkgName = pkgSearchResult.pkg.name;
- const currentConf = $scope.defaultPackageConfigs[pkgName];
+ $scope.saveConfig = function (pkgSearchResult) {
+ const pkgName = pkgSearchResult.pkg.name
+ const currentConf = $scope.defaultPackageConfigs[pkgName]
heliumService.saveConfig(pkgSearchResult.pkg, currentConf, () => {
// close after config is saved
- pkgSearchResult.configOpened = false;
- });
- };
+ pkgSearchResult.configOpened = false
+ })
+ }
- $scope.getDescriptionText = function(pkgSearchResult) {
- return $sce.trustAsHtml(pkgSearchResult.pkg.description);
- };
+ $scope.getDescriptionText = function (pkgSearchResult) {
+ return $sce.trustAsHtml(pkgSearchResult.pkg.description)
+ }
- init();
+ init()
}
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/helium/index.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/helium/index.js b/zeppelin-web/src/app/helium/index.js
index 632969e..2b27d60 100644
--- a/zeppelin-web/src/app/helium/index.js
+++ b/zeppelin-web/src/app/helium/index.js
@@ -12,8 +12,7 @@
* limitations under the License.
*/
-import HeliumController from './helium.controller';
+import HeliumController from './helium.controller'
angular.module('zeppelinWebApp')
- .controller('HeliumCtrl', HeliumController);
-
+ .controller('HeliumCtrl', HeliumController)
http://git-wip-us.apache.org/repos/asf/zeppelin/blob/19b0f30f/zeppelin-web/src/app/home/home.controller.js
----------------------------------------------------------------------
diff --git a/zeppelin-web/src/app/home/home.controller.js b/zeppelin-web/src/app/home/home.controller.js
index 65332ce..e8fccb9 100644
--- a/zeppelin-web/src/app/home/home.controller.js
+++ b/zeppelin-web/src/app/home/home.controller.js
@@ -12,135 +12,135 @@
* limitations under the License.
*/
-angular.module('zeppelinWebApp').controller('HomeCtrl', HomeCtrl);
+angular.module('zeppelinWebApp').controller('HomeCtrl', HomeCtrl)
-function HomeCtrl($scope, noteListDataFactory, websocketMsgSrv, $rootScope, arrayOrderingSrv,
+function HomeCtrl ($scope, noteListDataFactory, websocketMsgSrv, $rootScope, arrayOrderingSrv,
ngToast, noteActionSrv, TRASH_FOLDER_ID) {
- 'ngInject';
+ 'ngInject'
- ngToast.dismiss();
- var vm = this;
- vm.notes = noteListDataFactory;
- vm.websocketMsgSrv = websocketMsgSrv;
- vm.arrayOrderingSrv = arrayOrderingSrv;
+ ngToast.dismiss()
+ let vm = this
+ vm.notes = noteListDataFactory
+ vm.websocketMsgSrv = websocketMsgSrv
+ vm.arrayOrderingSrv = arrayOrderingSrv
- vm.notebookHome = false;
- vm.noteCustomHome = true;
+ vm.notebookHome = false
+ vm.noteCustomHome = true
if ($rootScope.ticket !== undefined) {
- vm.staticHome = false;
+ vm.staticHome = false
} else {
- vm.staticHome = true;
+ vm.staticHome = true
}
- $scope.isReloading = false;
- $scope.TRASH_FOLDER_ID = TRASH_FOLDER_ID;
- $scope.query = {q: ''};
+ $scope.isReloading = false
+ $scope.TRASH_FOLDER_ID = TRASH_FOLDER_ID
+ $scope.query = {q: ''}
- $scope.initHome = function() {
- websocketMsgSrv.getHomeNote();
- vm.noteCustomHome = false;
- };
+ $scope.initHome = function () {
+ websocketMsgSrv.getHomeNote()
+ vm.noteCustomHome = false
+ }
- $scope.reloadNoteList = function() {
- websocketMsgSrv.reloadAllNotesFromRepo();
- $scope.isReloadingNotes = true;
- };
+ $scope.reloadNoteList = function () {
+ websocketMsgSrv.reloadAllNotesFromRepo()
+ $scope.isReloadingNotes = true
+ }
- $scope.toggleFolderNode = function(node) {
- node.hidden = !node.hidden;
- };
+ $scope.toggleFolderNode = function (node) {
+ node.hidden = !node.hidden
+ }
- angular.element('#loginModal').on('hidden.bs.modal', function(e) {
- $rootScope.$broadcast('initLoginValues');
- });
+ angular.element('#loginModal').on('hidden.bs.modal', function (e) {
+ $rootScope.$broadcast('initLoginValues')
+ })
/*
** $scope.$on functions below
*/
- $scope.$on('setNoteMenu', function(event, notes) {
- $scope.isReloadingNotes = false;
- });
+ $scope.$on('setNoteMenu', function (event, notes) {
+ $scope.isReloadingNotes = false
+ })
- $scope.$on('setNoteContent', function(event, note) {
+ $scope.$on('setNoteContent', function (event, note) {
if (vm.noteCustomHome) {
- return;
+ return
}
if (note) {
- vm.note = note;
+ vm.note = note
// initialize look And Feel
- $rootScope.$broadcast('setLookAndFeel', 'home');
+ $rootScope.$broadcast('setLookAndFeel', 'home')
// make it read only
- vm.viewOnly = true;
+ vm.viewOnly = true
- vm.notebookHome = true;
- vm.staticHome = false;
+ vm.notebookHome = true
+ vm.staticHome = false
} else {
- vm.staticHome = true;
- vm.notebookHome = false;
+ vm.staticHome = true
+ vm.notebookHome = false
}
- });
+ })
- $scope.renameNote = function(nodeId, nodePath) {
- noteActionSrv.renameNote(nodeId, nodePath);
- };
+ $scope.renameNote = function (nodeId, nodePath) {
+ noteActionSrv.renameNote(nodeId, nodePath)
+ }
- $scope.moveNoteToTrash = function(noteId) {
- noteActionSrv.moveNoteToTrash(noteId, false);
- };
+ $scope.moveNoteToTrash = function (noteId) {
+ noteActionSrv.moveNoteToTrash(noteId, false)
+ }
- $scope.moveFolderToTrash = function(folderId) {
- noteActionSrv.moveFolderToTrash(folderId);
- };
+ $scope.moveFolderToTrash = function (folderId) {
+ noteActionSrv.moveFolderToTrash(folderId)
+ }
- $scope.restoreNote = function(noteId) {
- websocketMsgSrv.restoreNote(noteId);
- };
+ $scope.restoreNote = function (noteId) {
+ websocketMsgSrv.restoreNote(noteId)
+ }
- $scope.restoreFolder = function(folderId) {
- websocketMsgSrv.restoreFolder(folderId);
- };
+ $scope.restoreFolder = function (folderId) {
+ websocketMsgSrv.restoreFolder(folderId)
+ }
- $scope.restoreAll = function() {
- noteActionSrv.restoreAll();
- };
+ $scope.restoreAll = function () {
+ noteActionSrv.restoreAll()
+ }
- $scope.renameFolder = function(node) {
- noteActionSrv.renameFolder(node.id);
- };
+ $scope.renameFolder = function (node) {
+ noteActionSrv.renameFolder(node.id)
+ }
- $scope.removeNote = function(noteId) {
- noteActionSrv.removeNote(noteId, false);
- };
+ $scope.removeNote = function (noteId) {
+ noteActionSrv.removeNote(noteId, false)
+ }
- $scope.removeFolder = function(folderId) {
- noteActionSrv.removeFolder(folderId);
- };
+ $scope.removeFolder = function (folderId) {
+ noteActionSrv.removeFolder(folderId)
+ }
- $scope.emptyTrash = function() {
- noteActionSrv.emptyTrash();
- };
+ $scope.emptyTrash = function () {
+ noteActionSrv.emptyTrash()
+ }
- $scope.clearAllParagraphOutput = function(noteId) {
- noteActionSrv.clearAllParagraphOutput(noteId);
- };
+ $scope.clearAllParagraphOutput = function (noteId) {
+ noteActionSrv.clearAllParagraphOutput(noteId)
+ }
- $scope.isFilterNote = function(note) {
+ $scope.isFilterNote = function (note) {
if (!$scope.query.q) {
- return true;
+ return true
}
- var noteName = note.name;
+ let noteName = note.name
if (noteName.toLowerCase().indexOf($scope.query.q.toLowerCase()) > -1) {
- return true;
+ return true
}
- return false;
- };
+ return false
+ }
- $scope.getNoteName = function(note) {
- return arrayOrderingSrv.getNoteName(note);
- };
+ $scope.getNoteName = function (note) {
+ return arrayOrderingSrv.getNoteName(note)
+ }
}