Fixed the warnings/errors reported by eslint for all the static

javascripts.
This commit is contained in:
Ashesh Vashi
2018-01-12 12:59:51 +05:30
parent b78b97d89b
commit c32eb6bd37
102 changed files with 25830 additions and 24548 deletions

View File

@@ -1,7 +1,6 @@
define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
'backgrid', 'alertify', 'pgadmin.browser.node', 'pgadmin.browser.node.ui'
],
function(gettext, _, $, Backbone, Backform, Backgrid, Alertify, pgNode) {
'backgrid', 'alertify', 'pgadmin.browser.node', 'pgadmin.browser.node.ui',
], function(gettext, _, $, Backbone, Backform, Backgrid, Alertify, pgNode) {
/**
* Each Privilege, supporeted by an database object, will be represented
* using this Model.
@@ -17,11 +16,11 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
defaults: {
privilege_type: undefined,
privilege: false,
with_grant: false
with_grant: false,
},
validate: function() {
return null;
}
},
});
/**
@@ -39,7 +38,7 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
defaults: {
grantee: undefined,
grantor: undefined,
privileges: undefined
privileges: undefined,
},
keys: ['grantee', 'grantor'],
/*
@@ -58,28 +57,28 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
}
return !(
m.top && m.top.node_info &&
m.top.node_info.server.user.name == m.get('grantor')
m.top.node_info.server.user.name == m.get('grantor')
);
},
transform: function(data) {
transform: function() {
var res =
Backgrid.Extension.NodeListByNameCell.prototype.defaults.transform.apply(
this, arguments
);
);
res.unshift({label: 'PUBLIC', value: 'PUBLIC'});
return res;
},
cell: Backgrid.Extension.NodeListByNameCell.extend({
initialize: function(opts) {
var self = this,
override_opts = true;
override_opts = true;
// We would like to override the original options, because - we
// should omit the existing role/user from the privilege cell.
// Because - the column is shared among all the cell, we can only
// override only once.
if (opts && opts.column &&
opts.column instanceof Backbone.Model &&
opts.column instanceof Backbone.Model &&
opts.column.get('options_cached')) {
override_opts = false;
}
@@ -89,8 +88,10 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
// Let's override the options
if (override_opts) {
var opts = self.column.get('options');
self.column.set('options', self.omit_selected_roles.bind(self, opts));
opts = self.column.get('options');
self.column.set(
'options', self.omit_selected_roles.bind(self, opts)
);
}
var rerender = function (m) {
@@ -108,32 +109,30 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
// collection, because - we need to omit the newly selected roles
// form the list. Also, the render will be automatically called for
// the model represented by this cell, we will not do that again.
this.listenTo(self.model.collection, "change", rerender, this);
this.listenTo(self.model.collection, "remove", rerender, this);
this.listenTo(self.model.collection, 'change', rerender, this);
this.listenTo(self.model.collection, 'remove', rerender, this);
},
// Remove all the selected roles (though- not mine).
omit_selected_roles: function(opts, cell) {
var res = opts(cell),
selected = {},
model = cell.model,
cid = model.cid,
// We need to check node_info values in parent when object is nested.
// eg: column level privileges in table dialog
// In this case node_info will not be avilable to column node as
// it is not loaded yet
node_info = (_.has(model.top, 'node_info')
&& !_.isUndefined(model.top.node_info)) ?
model.top.node_info :
model.handler.top.node_info,
curr_user = node_info.server.user.name;
var idx = 0;
selected = {},
model = cell.model,
cid = model.cid,
// We need to check node_info values in parent when object is nested.
// eg: column level privileges in table dialog
// In this case node_info will not be avilable to column node as
// it is not loaded yet
node_info = (_.has(model.top, 'node_info')
&& !_.isUndefined(model.top.node_info)) ?
model.top.node_info :
model.handler.top.node_info,
curr_user = node_info.server.user.name;
model.collection.each(function(m) {
var grantee = m.get('grantee');
if (m.cid != cid && !_.isUndefined(grantee) &&
curr_user == m.get('grantor')) {
curr_user == m.get('grantor')) {
selected[grantee] = m.cid;
}
});
@@ -143,23 +142,26 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
});
return res;
}
},
}),
},{
id: 'privileges', label: gettext('Privileges'),
type: 'collection', model: PrivilegeModel, group: null,
cell: 'privilege', control: 'text', cellHeaderClasses: 'width_percent_40',
disabled : function(column, collection) {
disabled : function(column) {
if (column instanceof Backbone.Collection) {
// This has been called during generating the header cell
return false;
}
return !(this.node_info && this.node_info.server.user.name == column.get('grantor') ||
this.attributes.node_info.server.user.name == column.get('grantor'));
}
return !(
this.node_info &&
this.node_info.server.user.name == column.get('grantor') ||
this.attributes.node_info.server.user.name == column.get('grantor')
);
},
},{
id: 'grantor', label: gettext('Grantor'), type: 'text', disabled: true,
cell: 'node-list-by-name', node: 'role'
cell: 'node-list-by-name', node: 'role',
}],
/*
@@ -172,36 +174,36 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
if (_.isNull(attrs)) {
this.set(
'grantor',
opts && opts.top && opts.top.node_info && opts.top.node_info.server.user.name,
{silent: true}
);
'grantor',
opts && opts.top && opts.top.node_info && opts.top.node_info.server.user.name,
{silent: true}
);
}
/*
* Define the collection of the privilege supported by this model
*/
var self = this,
models = self.get('privileges'),
privileges = this.get('privileges') || {};
models = self.get('privileges'),
privileges = this.get('privileges') || {};
if (_.isArray(privileges)) {
privileges = new (pgNode.Collection)(
models, {
model: PrivilegeModel,
top: this.top || this,
handler: this,
silent: true,
parse: false
});
models, {
model: PrivilegeModel,
top: this.top || this,
handler: this,
silent: true,
parse: false,
});
this.set('privileges', privileges, {silent: true});
}
var privs = {};
_.each(self.privileges, function(p) {
privs[p] = {
'privilege_type': p, 'privilege': false, 'with_grant': false
}
'privilege_type': p, 'privilege': false, 'with_grant': false,
};
});
privileges.each(function(m) {
@@ -212,7 +214,7 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
privileges.add(p, {silent: true});
});
self.on("change:grantee", self.granteeChanged);
self.on('change:grantee', self.granteeChanged);
privileges.on('change', function() {
self.trigger('change:privileges', self);
});
@@ -222,22 +224,22 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
granteeChanged: function() {
var privileges = this.get('privileges'),
grantee = this.get('grantee');
grantee = this.get('grantee');
// Reset all with grant options if grantee is public.
if (grantee == 'PUBLIC') {
privileges.each(function(m) {
m.set("with_grant", false, {silent: true});
m.set('with_grant', false, {silent: true});
});
}
},
toJSON: function(session) {
toJSON: function() {
var privileges = [];
if (this.attributes &&
!this.attributes['privileges']) {
!this.attributes['privileges']) {
return null;
}
@@ -251,71 +253,68 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
return {
'grantee': this.get('grantee'),
'grantor': this.get('grantor'),
'privileges': privileges
};
'privileges': privileges,
};
},
validate: function() {
var err = {},
errmsg = null,
changedAttrs = this.sessAttrs,
msg = undefined;
var errmsg = null,
msg;
if (_.isUndefined(this.get('grantee'))) {
msg = gettext('A grantee must be selected.');
this.errorModel.set('grantee', msg);
errmsg = msg;
} else {
this.errorModel.unset('grantee');
this.errorModel.unset('grantee');
}
if (this.attributes &&
this.attributes['privileges']) {
var anyPrivSelected = false;
this.attributes['privileges'].each(
this.attributes['privileges']) {
var anyPrivSelected = false;
this.attributes['privileges'].each(
function(p) {
if (p.get('privilege')) {
anyPrivSelected = true;
}
});
if (!anyPrivSelected) {
msg = gettext('At least one privilege should be selected.');
this.errorModel.set('privileges', msg);
errmsg = errmsg || msg;
} else {
this.errorModel.unset('privileges');
}
if (!anyPrivSelected) {
msg = gettext('At least one privilege should be selected.');
this.errorModel.set('privileges', msg);
errmsg = errmsg || msg;
} else {
this.errorModel.unset('privileges');
}
}
return errmsg;
}
},
});
/**
Custom cell editor for editing privileges.
Custom cell editor for editing privileges.
*/
var PrivilegeCellEditor = Backgrid.Extension.PrivilegeCellEditor =
Backgrid.CellEditor.extend({
tagName: "div",
tagName: 'div',
// All available privileges in the PostgreSQL database server for
// generating the label for the specific Control
Labels: {
"C": "CREATE",
"T": "TEMPORARY",
"c": "CONNECT",
"a": "INSERT",
"r": "SELECT",
"w": "UPDATE",
"d": "DELETE",
"D": "TRUNCATE",
"x": "REFERENCES",
"t": "TRIGGER",
"U": "USAGE",
"X": "EXECUTE"
},
'C': 'CREATE',
'T': 'TEMPORARY',
'c': 'CONNECT',
'a': 'INSERT',
'r': 'SELECT',
'w': 'UPDATE',
'd': 'DELETE',
'D': 'TRUNCATE',
'x': 'REFERENCES',
't': 'TRIGGER',
'U': 'USAGE',
'X': 'EXECUTE',
},
template: _.template([
'<tr class="<%= header ? "header" : "" %>">',
@@ -331,11 +330,11 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
' WITH GRANT OPTION',
' </label>',
' </td>',
'</tr>'].join(" "), null, {variable: null}),
'</tr>'].join(' '), null, {variable: null}),
events: {
'change': 'privilegeChanged',
'blur': 'lostFocus'
'blur': 'lostFocus',
},
render: function () {
@@ -343,10 +342,10 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
this.$el.attr('tabindex', '1');
this.$el.attr('target', this.elId);
var collection = this.model.get(this.column.get("name")),
tbl = $("<table></table>").appendTo(this.$el),
self = this,
privilege = true, with_grant = true;
var collection = this.model.get(this.column.get('name')),
tbl = $('<table></table>').appendTo(this.$el),
self = this,
privilege = true, with_grant = true;
// For each privilege generate html template.
// List down all the Privilege model.
@@ -362,8 +361,8 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
'header': false,
'privilege_label': self.Labels[d.privilege_type],
'with_grant': (self.model.get('grantee') != 'PUBLIC' && d.with_grant),
'enable_with_grant': (self.model.get('grantee') != 'PUBLIC' && d.privilege)
});
'enable_with_grant': (self.model.get('grantee') != 'PUBLIC' && d.privilege),
});
privilege = (privilege && d.privilege);
with_grant = (with_grant && privilege && d.with_grant);
tbl.append(self.template(d));
@@ -372,15 +371,15 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
if (collection.length > 1) {
// Preprend the ALL controls on that table
tbl.prepend(
self.template({
'target': self.cid,
'privilege_label': 'ALL',
'privilege_type': 'ALL',
'privilege': privilege,
'with_grant': (self.model.get('grantee') != 'PUBLIC' && with_grant),
'enable_with_grant': (self.model.get('grantee') != 'PUBLIC' && privilege),
'header': true
}));
self.template({
'target': self.cid,
'privilege_label': 'ALL',
'privilege_type': 'ALL',
'privilege': privilege,
'with_grant': (self.model.get('grantee') != 'PUBLIC' && with_grant),
'enable_with_grant': (self.model.get('grantee') != 'PUBLIC' && privilege),
'header': true,
}));
}
self.$el.find('input[type=checkbox]').first().focus();
// Since blur event does not bubble we need to explicitly call parent's blur event.
@@ -406,13 +405,14 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
* We're looking for checkboxes only.
*/
var $el = $(ev.target),
privilege_type = $el.attr('privilege'),
type = $el.attr('name'),
checked = $el.prop('checked'),
$tr = $el.closest('tr'),
$tbl = $tr.closest('table'),
collection = this.model.get('privileges'),
grantee = this.model.get('grantee');
privilege_type = $el.attr('privilege'),
type = $el.attr('name'),
checked = $el.prop('checked'),
$tr = $el.closest('tr'),
$tbl = $tr.closest('table'),
collection = this.model.get('privileges'),
grantee = this.model.get('grantee'), $allGrants,
$allPrivileges, $elGrant;
this.undelegateEvents();
/*
@@ -420,14 +420,15 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
* the checkbox for each privilege.
*/
if (privilege_type == 'ALL') {
var $elGrant = $tr.find('input[name=with_grant]'),
$allPrivileges = $tbl.find(
'input[name=privilege][privilege!=\'ALL\']'
),
$allGrants = $tbl.find(
'input[name=with_grant][privilege!=\'ALL\']'
),
allPrivilege, allWithGrant;
var allPrivilege, allWithGrant;
$elGrant = $tr.find('input[name=with_grant]');
$allPrivileges = $tbl.find(
'input[name=privilege][privilege!=\'ALL\']'
);
$allGrants = $tbl.find(
'input[name=with_grant][privilege!=\'ALL\']'
);
if (type == 'privilege') {
/*
@@ -439,6 +440,7 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
if (checked) {
$allPrivileges.prop('checked', true);
/*
* We have clicked the ALL checkbox, we should be able to select
* the grant options too.
@@ -461,7 +463,7 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
*/
$allPrivileges.prop('checked', false);
$elGrant.prop('checked', false),
$allGrants.prop('checked', false);
$allGrants.prop('checked', false);
$elGrant.prop('disabled', true);
$allGrants.prop('disabled', true);
}
@@ -479,146 +481,149 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
$allGrants.prop('checked', checked);
}
/*
* Set the values for each Privilege Model.
*/
collection.each(function(m) {
m.set(
{'privilege': allPrivilege, 'with_grant': allWithGrant},
{silent: true}
/*
* Set the values for each Privilege Model.
*/
collection.each(function(m) {
m.set(
{'privilege': allPrivilege, 'with_grant': allWithGrant},
{silent: true}
);
});
} else {
/*
* Particular privilege has been selected/deselected, which can be
* identified using the privilege="X" attribute.
*/
var attrs = {};
$tbl = $tr.closest('table');
$allPrivileges = $tbl.find(
'input[name=privilege][privilege=\'ALL\']'
);
$allGrants = $tbl.find(
'input[name=with_grant][privilege=\'ALL\']'
);
});
} else {
/*
* Particular privilege has been selected/deselected, which can be
* identified using the privilege="X" attribute.
*/
var attrs = {},
$tbl = $tr.closest('table'),
$allPrivilege = $tbl.find(
'input[name=privilege][privilege=\'ALL\']'
),
$allGrant = $tbl.find(
'input[name=with_grant][privilege=\'ALL\']'
);
attrs[type] = checked;
attrs[type] = checked;
if (type == 'privilege') {
var $elGrant = ($el.closest('tr')).find('input[name=with_grant]');
if (!checked) {
attrs['with_grant'] = false;
if (type == 'privilege') {
$elGrant = ($el.closest('tr')).find('input[name=with_grant]');
if (!checked) {
attrs['with_grant'] = false;
$elGrant.prop('checked', false).prop('disabled', true);
$allPrivilege.prop('checked', false);
$allGrant.prop('disabled', true);
$allGrant.prop('checked', false);
} else if (grantee != "PUBLIC") {
$elGrant.prop('disabled', false);
$elGrant.prop('checked', false).prop('disabled', true);
$allPrivileges.prop('checked', false);
$allGrants.prop('disabled', true);
$allGrants.prop('checked', false);
} else if (grantee != 'PUBLIC') {
$elGrant.prop('disabled', false);
}
} else if (!checked) {
$allGrants.prop('checked', false);
}
} else if (!checked) {
$allGrant.prop('checked', false);
}
collection.get(privilege_type).set(attrs, {silent: true});
collection.get(privilege_type).set(attrs, {silent: true});
if (checked) {
var $allPrivileges = $tbl.find(
'input[name=privilege][privilege!=\'ALL\']:checked'
);
if (checked) {
$allPrivileges = $tbl.find(
'input[name=privilege][privilege!=\'ALL\']:checked'
);
if ($allPrivileges.length > 1 &&
$allPrivileges.length == collection.models.length) {
if ($allPrivileges.length > 1 &&
$allPrivileges.length == collection.models.length) {
$allPrivilege.prop('checked', true);
$allPrivileges.prop('checked', true);
if (type == 'with_grant') {
var $allGrants = $tbl.find(
'input[name=with_grant][privilege!=\'ALL\']:checked'
if (type == 'with_grant') {
$allGrants = $tbl.find(
'input[name=with_grant][privilege!=\'ALL\']:checked'
);
if ($allGrants.length == collection.models.length) {
$allGrant.prop('disabled', false);
$allGrant.prop('checked', true);
if ($allGrants.length == collection.models.length) {
$allGrants.prop('disabled', false);
$allGrants.prop('checked', true);
}
} else if (grantee != 'PUBLIC') {
$allGrants.prop('disabled', false);
}
} else if (grantee != "PUBLIC") {
$allGrant.prop('disabled', false);
}
}
}
}
this.model.trigger('change', this.model);
this.model.trigger('change', this.model);
var anySelected = false,
var anySelected = false,
msg = null;
collection.each(function(m) {
anySelected = anySelected || m.get('privilege');
});
collection.each(function(m) {
anySelected = anySelected || m.get('privilege');
});
if (anySelected) {
this.model.errorModel.unset('privileges');
if (this.model.errorModel.has('grantee')) {
msg = this.model.errorModel.get('grantee');
if (anySelected) {
this.model.errorModel.unset('privileges');
if (this.model.errorModel.has('grantee')) {
msg = this.model.errorModel.get('grantee');
}
} else {
this.model.errorModel.set(
'privileges', gettext('At least one privilege should be selected.')
);
msg = gettext('At least one privilege should be selected.');
}
} else {
this.model.errorModel.set(
'privileges', gettext('At least one privilege should be selected.')
if (msg) {
this.model.collection.trigger(
'pgadmin-session:model:invalid', msg, this.model
);
msg = gettext('At least one privilege should be selected.');
} else {
this.model.collection.trigger(
'pgadmin-session:model:valid', this.model
);
}
}
if (msg) {
this.model.collection.trigger(
'pgadmin-session:model:invalid', msg, this.model
);
} else {
this.model.collection.trigger(
'pgadmin-session:model:valid', this.model
);
}
}
this.delegateEvents();
},
this.delegateEvents();
},
lostFocus: function(ev) {
/*
* We lost the focus, it's time for us to exit the editor.
*/
var self = this,
/*
* Function to determine whether one dom element is descendant of another
* dom element.
*/
isDescendant = function (parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
/*
* Between leaving the old element focus and entering the new element focus the
* active element is the document/body itself so add timeout to get the proper
* focused active element.
*/
setTimeout(function() {
lostFocus: function(ev) {
/*
Do not close the control if user clicks outside dialog window,
only close the row if user clicks on add button or on another row, if user
clicks somewhere else then we will get tagName as 'BODY' or 'WINDOW'
*/
var is_active_element = document.activeElement.tagName == 'DIV' ||
document.activeElement.tagName == 'BUTTON';
* We lost the focus, it's time for us to exit the editor.
*/
var self = this,
/*
* Function to determine whether one dom element is descendant of another
* dom element.
*/
isDescendant = function (parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
};
if (is_active_element && self.$el[0] != document.activeElement &&
!isDescendant(self.$el[0], document.activeElement)) {
var m = self.model;
m.trigger('backgrid:edited', m, self.column, new Backgrid.Command(ev));
}},10);
return;
}
});
/*
* Between leaving the old element focus and entering the new element focus the
* active element is the document/body itself so add timeout to get the proper
* focused active element.
*/
setTimeout(function() {
/*
* Do not close the control if user clicks outside dialog window,
* only close the row if user clicks on add button or on another row,
* if user clicks somewhere else then we will get tagName as 'BODY'
* or 'WINDOW'
*/
var is_active_element = document.activeElement.tagName == 'DIV' ||
document.activeElement.tagName == 'BUTTON';
if (is_active_element && self.$el[0] != document.activeElement &&
!isDescendant(self.$el[0], document.activeElement)) {
var m = self.model;
m.trigger('backgrid:edited', m, self.column, new Backgrid.Command(ev));
}},10);
return;
},
});
/*
* This will help us transform the privileges value in proper format to be
@@ -628,26 +633,25 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
function () {};
_.extend(PrivilegeCellFormatter.prototype, {
notation: {
"CREATE" : "C",
"TEMPORARY" : "T",
"CONNECT" : "c",
"INSERT" : "a",
"SELECT" : "r",
"UPDATE" : "w",
"DELETE" : "d",
"TRUNCATE" : "D",
"REFERENCES" : "x",
"TRIGGER" : "t",
"USAGE" : "U",
"EXECUTE" : "X"
'CREATE' : 'C',
'TEMPORARY' : 'T',
'CONNECT' : 'c',
'INSERT' : 'a',
'SELECT' : 'r',
'UPDATE' : 'w',
'DELETE' : 'd',
'TRUNCATE' : 'D',
'REFERENCES' : 'x',
'TRIGGER' : 't',
'USAGE' : 'U',
'EXECUTE' : 'X',
},
/**
* Takes a raw value from a model and returns an optionally formatted
* string for display.
*/
fromRaw: function (rawData, model) {
var res = '',
self = this;
fromRaw: function (rawData) {
var res = '';
if (rawData instanceof Backbone.Collection) {
rawData.each(function(m) {
@@ -660,23 +664,23 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
});
}
return res;
}
},
});
/*
* PrivilegeCell for rendering and taking input for the privileges.
*/
var PrivilegeCell = Backgrid.Extension.PrivilegeCell = Backgrid.Cell.extend({
className: "edit-cell",
Backgrid.Extension.PrivilegeCell = Backgrid.Cell.extend({
className: 'edit-cell',
formatter: PrivilegeCellFormatter,
editor: PrivilegeCellEditor,
initialize: function (options) {
initialize: function () {
var self = this;
Backgrid.Cell.prototype.initialize.apply(this, arguments);
self.model.on("change:grantee", function() {
if (!self.$el.hasClass("editor")) {
self.model.on('change:grantee', function() {
if (!self.$el.hasClass('editor')) {
/*
* Add time out before render; As we might want to wait till model
* is updated by PrivilegeRoleModel:granteeChanged.
@@ -686,7 +690,7 @@ define(['sources/gettext', 'underscore', 'jquery', 'backbone', 'backform',
},10);
}
});
}
},
});
return PrivilegeRoleModel;

File diff suppressed because it is too large Load Diff

View File

@@ -1,495 +1,480 @@
define([
'sources/gettext', 'underscore', 'jquery', 'backbone', 'backform', 'backgrid', 'alertify',
'sources/pgadmin', 'pgadmin.browser.node', 'pgadmin.browser.node.ui'
],
function(gettext, _, $, Backbone, Backform, Backgrid, Alertify, pgAdmin, pgNode) {
'sources/pgadmin', 'pgadmin.browser.node', 'pgadmin.browser.node.ui',
],
function(gettext, _, $, Backbone, Backform, Backgrid, Alertify, pgAdmin, pgNode) {
/*
* cellFunction for variable control.
* This function returns cell class depending on vartype.
*/
var cellFunction = function(model) {
var self = this,
name = model.get("name"),
availVariables = {};
/*
* cellFunction for variable control.
* This function returns cell class depending on vartype.
*/
var cellFunction = function(model) {
var self = this,
name = model.get('name'),
availVariables = {};
self.collection.each(function(col) {
if (col.get("name") == "name") {
availVariables = col.get('availVariables');
}
});
self.collection.each(function(col) {
if (col.get('name') == 'name') {
availVariables = col.get('availVariables');
}
});
var variable = name ? availVariables[name]: undefined,
value = model.get('value');
var variable = name ? availVariables[name]: undefined,
value = model.get("value");
switch(variable && variable.vartype) {
case 'bool':
/*
* bool cell and variable cannot be stateless (i.e undefined).
* It should be either true or false.
*/
switch(variable && variable.vartype) {
case "bool":
/*
* bool cell and variable cannot be stateless (i.e undefined).
* It should be either true or false.
*/
model.set("value", !!model.get("value"), {silent: true});
model.set('value', !!model.get('value'), {silent: true});
return Backgrid.Extension.SwitchCell;
break;
case "enum":
case 'enum':
model.set({'value': value}, {silent:true});
var options = [],
enumVals = variable.enumvals;
enumVals = variable.enumvals;
_.each(enumVals, function(enumVal) {
options.push([enumVal, enumVal]);
});
return Backgrid.Extension.Select2Cell.extend({optionValues: options});
break;
case "integer":
case 'integer':
if (!_.isNaN(parseInt(value))) {
model.set({'value': parseInt(value)}, {silent:true});
} else {
model.set({'value': undefined}, {silent:true});
}
return Backgrid.IntegerCell;
break;
case "real":
case 'real':
if (!_.isNaN(parseFloat(value))) {
model.set({'value': parseFloat(value)}, {silent:true});
} else {
model.set({'value': undefined}, {silent:true});
}
return Backgrid.NumberCell.extend({decimals: 0});
break;
case "string":
case 'string':
return Backgrid.StringCell;
break;
default:
model.set({'value': undefined}, {silent:true});
return Backgrid.Cell;
break;
}
model.set({'value': undefined}, {silent:true});
return Backgrid.Cell;
}
}
};
/*
* This row will define behaviour or value column cell depending upon
* variable name.
*/
var VariableRow = Backgrid.Row.extend({
modelDuplicateColor: "lightYellow",
/*
* This row will define behaviour or value column cell depending upon
* variable name.
*/
var VariableRow = Backgrid.Row.extend({
modelDuplicateColor: 'lightYellow',
modelUniqueColor: "#fff",
modelUniqueColor: '#fff',
initialize: function () {
Backgrid.Row.prototype.initialize.apply(this, arguments);
var self = this;
self.model.on("change:name", function() {
setTimeout(function() {
self.columns.each(function(col) {
if (col.get('name') == 'value') {
initialize: function () {
Backgrid.Row.prototype.initialize.apply(this, arguments);
var self = this;
self.model.on('change:name', function() {
setTimeout(function() {
self.columns.each(function(col) {
if (col.get('name') == 'value') {
var idx = self.columns.indexOf(col),
cf = col.get("cellFunction"),
cell = new (cf.apply(col, [self.model]))({
column: col,
model: self.model
}),
var idx = self.columns.indexOf(col),
cf = col.get('cellFunction'),
cell = new (cf.apply(col, [self.model]))({
column: col,
model: self.model,
}),
oldCell = self.cells[idx];
oldCell.remove();
self.cells[idx] = cell;
self.render();
}
}
});
}, 10);
});
self.listenTo(self.model, 'pgadmin-session:model:duplicate', self.modelDuplicate);
self.listenTo(self.model, 'pgadmin-session:model:unique', self.modelUnique);
},
modelDuplicate: function() {
$(this.el).removeClass("new");
this.el.style.backgroundColor = this.modelDuplicateColor;
},
modelUnique: function() {
this.el.style.backgroundColor = this.modelUniqueColor;
}
});
}, 10);
});
self.listenTo(self.model, 'pgadmin-session:model:duplicate', self.modelDuplicate);
self.listenTo(self.model, 'pgadmin-session:model:unique', self.modelUnique);
},
modelDuplicate: function() {
$(this.el).removeClass('new');
this.el.style.backgroundColor = this.modelDuplicateColor;
},
modelUnique: function() {
this.el.style.backgroundColor = this.modelUniqueColor;
},
})
/**
* VariableModel used to represent configuration parameters (variables tab)
* for database objects.
**/
var VariableModel = pgNode.VariableModel = pgNode.Model.extend({
keys: ['name'],
defaults: {
name: undefined,
value: undefined,
role: null,
database: null,
},
schema: [
{
id: 'name', label: gettext('Name'), type:'text', cellHeaderClasses: 'width_percent_30',
editable: function(m) {
return (m instanceof Backbone.Collection) ? true : m.isNew();
},
cell: Backgrid.Extension.NodeAjaxOptionsCell.extend({
initialize: function() {
Backgrid.Extension.NodeAjaxOptionsCell.prototype.initialize.apply(this, arguments);
});
/**
* VariableModel used to represent configuration parameters (variables tab)
* for database objects.
**/
var VariableModel = pgNode.VariableModel = pgNode.Model.extend({
keys: ['name'],
defaults: {
name: undefined,
value: undefined,
role: null,
database: null,
},
schema: [
{
id: 'name', label: gettext('Name'), type:'text', cellHeaderClasses: 'width_percent_30',
editable: function(m) {
return (m instanceof Backbone.Collection) ? true : m.isNew();
},
cell: Backgrid.Extension.NodeAjaxOptionsCell.extend({
initialize: function() {
Backgrid.Extension.NodeAjaxOptionsCell.prototype.initialize.apply(this, arguments);
// Immediately process options as we need them before render.
// Immediately process options as we need them before render.
var opVals = _.clone(this.optionValues ||
var opVals = _.clone(this.optionValues ||
(_.isFunction(this.column.get('options')) ?
(this.column.get('options'))(this) :
(this.column.get('options'))(this) :
this.column.get('options')));
this.column.set('options', opVals);
}
}),
url: 'vopts',
select2: { allowClear: false },
transform: function(vars, cell) {
var self = this,
res = [],
this.column.set('options', opVals);
},
}),
url: 'vopts',
select2: { allowClear: false },
transform: function(vars, cell) {
var res = [],
availVariables = {};
_.each(vars, function(v) {
res.push({
'value': v.name,
'image': undefined,
'label': v.name
_.each(vars, function(v) {
res.push({
'value': v.name,
'image': undefined,
'label': v.name,
});
availVariables[v.name] = v;
});
availVariables[v.name] = v;
});
cell.column.set("availVariables", availVariables);
return res;
cell.column.set('availVariables', availVariables);
return res;
},
},
{
id: 'value', label: gettext('Value'), type: 'text', editable: true,
cellFunction: cellFunction, cellHeaderClasses: 'width_percent_40',
},
{id: 'database', label: gettext('Database'), type: 'text', editable: true,
node: 'database', cell: Backgrid.Extension.NodeListByNameCell,
},
{id: 'role', label: gettext('Role'), type: 'text', editable: true,
node: 'role', cell: Backgrid.Extension.NodeListByNameCell},
],
toJSON: function() {
var d = Backbone.Model.prototype.toJSON.apply(this);
// Remove not defined values from model values.
// i.e.
// role, database
if (_.isUndefined(d.database) || _.isNull(d.database)) {
delete d.database;
}
},
{
id: 'value', label: gettext('Value'), type: 'text', editable: true,
cellFunction: cellFunction, cellHeaderClasses: 'width_percent_40'
},
{id: 'database', label: gettext('Database'), type: 'text', editable: true,
node: 'database', cell: Backgrid.Extension.NodeListByNameCell
},
{id: 'role', label: gettext('Role'), type: 'text', editable: true,
node: 'role', cell: Backgrid.Extension.NodeListByNameCell}
],
toJSON: function() {
var d = Backbone.Model.prototype.toJSON.apply(this);
// Remove not defined values from model values.
// i.e.
// role, database
if (_.isUndefined(d.database) || _.isNull(d.database)) {
delete d.database;
}
if (_.isUndefined(d.role) || _.isNull(d.role)) {
delete d.role;
}
if (_.isUndefined(d.role) || _.isNull(d.role)) {
delete d.role;
}
return d;
},
validate: function() {
if (_.isUndefined(this.get('name')) ||
return d;
},
validate: function() {
var msg = null;
if (_.isUndefined(this.get('name')) ||
_.isNull(this.get('name')) ||
String(this.get('name')).replace(/^\s+|\s+$/g, '') == '') {
var msg = 'Please select a parameter name.';
this.errorModel.set('name', msg);
return msg;
} else if (_.isUndefined(this.get('value')) ||
_.isNull(this.get('value')) ||
String(this.get('value')).replace(/^\s+|\s+$/g, '') == '') {
var msg = 'Please enter a value for the parameter.';
this.errorModel.set('value', msg);
return msg;
} else {
this.errorModel.unset('name');
this.errorModel.unset('value');
}
return null;
}
});
/**
* Variable Tab Control to set/update configuration values for database object.
*
**/
var VariableCollectionControl = Backform.VariableCollectionControl =
Backform.UniqueColCollectionControl.extend({
hasDatabase: false,
hasRole: false,
initialize: function(opts) {
var self = this,
keys = ['name'];
/*
* Read from field schema whether user wants to use database and role
* fields in Variable control.
*/
self.hasDatabase = opts.field.get('hasDatabase');
self.hasRole = opts.field.get('hasRole');
// Update unique coll field based on above flag status.
if (self.hasDatabase) {
keys.push('database');
} else if (self.hasRole) {
keys.push('role');
}
// Overriding the uniqueCol in the field
if (opts && opts.field) {
if (opts.field instanceof Backform.Field) {
opts.field.set({
model: pgNode.VariableModel.extend({keys:keys})
},
{
silent: true
});
String(this.get('name')).replace(/^\s+|\s+$/g, '') == '') {
msg = gettext('Please select a parameter name.');
this.errorModel.set('name', msg);
} else if (_.isUndefined(this.get('value')) ||
_.isNull(this.get('value')) ||
String(this.get('value')).replace(/^\s+|\s+$/g, '') == '') {
msg = ('Please enter a value for the parameter.');
this.errorModel.set('value', msg);
this.errorModel.unset('name');
} else {
opts.field.extend({
model: pgNode.VariableModel.extend({keys:keys})
});
this.errorModel.unset('name');
this.errorModel.unset('value');
}
}
Backform.UniqueColCollectionControl.prototype.initialize.apply(
self, arguments
);
return msg;
},
});
self.availVariables = {};
/**
* Variable Tab Control to set/update configuration values for database object.
*
**/
Backform.VariableCollectionControl =
Backform.UniqueColCollectionControl.extend({
var node = self.field.get('node').type,
gridCols = ['name', 'value'];
hasDatabase: false,
hasRole: false,
if (self.hasDatabase) {
gridCols.push('database');
}
initialize: function(opts) {
var self = this,
keys = ['name'];
if (self.hasRole) {
gridCols.push('role');
}
/*
* Read from field schema whether user wants to use database and role
* fields in Variable control.
*/
self.hasDatabase = opts.field.get('hasDatabase');
self.hasRole = opts.field.get('hasRole');
self.gridSchema = Backform.generateGridColumnsFromModel(
self.field.get('node_info'), VariableModel.extend({keys:keys}), 'edit', gridCols, self.field.get('schema_node')
);
// Make sure - we do have the data for variables
self.getVariables();
},
/*
* Get the variable data for this node.
*/
getVariables: function() {
var self = this,
url = this.field.get('url'),
m = self.model;
if (!this.field.get('version_compatible'))
return;
if (url && !m.isNew()) {
var node = self.field.get('node'),
node_data = self.field.get('node_data'),
node_info = self.field.get('node_info'),
full_url = node.generate_url.apply(
node, [
null, url, node_data, true, node_info
]),
data,
isTracking = self.collection.trackChanges;
if (isTracking) {
self.collection.stopSession();
}
m.trigger('pgadmin-view:fetching', m, self.field);
$.ajax({
async: false,
url: full_url,
success: function (res) {
data = res.data;
},
error: function() {
m.trigger('pgadmin-view:fetch:error', m, self.field);
// Update unique coll field based on above flag status.
if (self.hasDatabase) {
keys.push('database');
} else if (self.hasRole) {
keys.push('role');
}
// Overriding the uniqueCol in the field
if (opts && opts.field) {
if (opts.field instanceof Backform.Field) {
opts.field.set({
model: pgNode.VariableModel.extend({keys:keys}),
},
{
silent: true,
});
} else {
opts.field.extend({
model: pgNode.VariableModel.extend({keys:keys}),
});
}
}
});
m.trigger('pgadmin-view:fetched', m, self.field);
if (data && _.isArray(data)) {
self.collection.reset(data, {silent: true});
}
Backform.UniqueColCollectionControl.prototype.initialize.apply(
self, arguments
);
self.availVariables = {};
var gridCols = ['name', 'value'];
if (self.hasDatabase) {
gridCols.push('database');
}
if (self.hasRole) {
gridCols.push('role');
}
self.gridSchema = Backform.generateGridColumnsFromModel(
self.field.get('node_info'), VariableModel.extend({keys:keys}), 'edit', gridCols, self.field.get('schema_node')
);
// Make sure - we do have the data for variables
self.getVariables();
},
/*
* Make sure - new data will be taken care by the session management
* Get the variable data for this node.
*/
if (isTracking) {
self.collection.startNewSession();
}
}
},
getVariables: function() {
var self = this,
url = this.field.get('url'),
m = self.model;
showGridControl: function(data) {
if (!this.field.get('version_compatible'))
return;
var self = this,
titleTmpl = _.template([
"<div class='subnode-header'>",
"<label class='control-label'><%-label%></label>",
"<button class='btn-sm btn-default add fa fa-plus' <%=canAdd ? '' : 'disabled=\"disabled\"'%>></button>",
"</div>"].join("\n")),
$gridBody =
$("<div class='pgadmin-control-group backgrid form-group col-xs-12 object subnode'></div>").append(
if (url && !m.isNew()) {
var node = self.field.get('node'),
node_data = self.field.get('node_data'),
node_info = self.field.get('node_info'),
full_url = node.generate_url.apply(
node, [
null, url, node_data, true, node_info,
]),
data,
isTracking = self.collection.trackChanges;
if (isTracking) {
self.collection.stopSession();
}
m.trigger('pgadmin-view:fetching', m, self.field);
$.ajax({
async: false,
url: full_url,
success: function (res) {
data = res.data;
},
error: function() {
m.trigger('pgadmin-view:fetch:error', m, self.field);
},
});
m.trigger('pgadmin-view:fetched', m, self.field);
if (data && _.isArray(data)) {
self.collection.reset(data, {silent: true});
}
/*
* Make sure - new data will be taken care by the session management
*/
if (isTracking) {
self.collection.startNewSession();
}
}
},
showGridControl: function(data) {
var self = this,
titleTmpl = _.template([
'<div class=\'subnode-header\'>',
'<label class=\'control-label\'><%-label%></label>',
'<button class=\'btn-sm btn-default add fa fa-plus\' <%=canAdd ? \'\' : \'disabled="disabled"\'%>></button>',
'</div>'].join('\n')),
$gridBody =
$('<div class=\'pgadmin-control-group backgrid form-group col-xs-12 object subnode\'></div>').append(
titleTmpl(data)
);
// Clean up existing grid if any (in case of re-render)
if (self.grid) {
self.grid.remove();
}
var gridSchema = _.clone(this.gridSchema);
_.each(gridSchema.columns, function(col) {
if (col.name == 'value') {
col.availVariables = self.availVariables;
}
});
// Insert Delete Cell into Grid
if (data.disabled == false && data.canDelete) {
gridSchema.columns.unshift({
name: "pg-backform-delete", label: "",
cell: Backgrid.Extension.DeleteCell,
editable: false, cell_priority: -1
});
}
// Change format of each of the data
// Because - data coming from the server is in string format
self.collection.each(function(model) {
var name = model.get("name");
if (name in self.availVariables) {
switch(self.availVariables[name].vartype) {
case 'real':
var v = parseFloat(model.get('value'));
model.set('value', (isNaN(v) ? undefined : v), {silent: true});
break;
case 'integer':
var v = parseInt(model.get('value'));
model.set('value', (isNaN(v) ? undefined : v), {silent: true});
break;
default:
break;
// Clean up existing grid if any (in case of re-render)
if (self.grid) {
self.grid.remove();
}
}
});
// Initialize a new Grid instance
var grid = self.grid = new Backgrid.Grid({
columns: gridSchema.columns,
collection: self.collection,
row: VariableRow,
className: "backgrid table-bordered"
});
self.$grid = grid.render().$el;
var gridSchema = _.clone(this.gridSchema);
$gridBody.append(self.$grid);
_.each(gridSchema.columns, function(col) {
if (col.name == 'value') {
col.availVariables = self.availVariables;
}
});
// Add button callback
if (!(data.disabled || data.canAdd == false)) {
$gridBody.find('button.add').first().click(function(e) {
e.preventDefault();
var canAddRow = _.isFunction(data.canAddRow) ?
data.canAddRow.apply(self, [self.model]) : true;
if (canAddRow) {
// Insert Delete Cell into Grid
if (data.disabled == false && data.canDelete) {
gridSchema.columns.unshift({
name: 'pg-backform-delete', label: '',
cell: Backgrid.Extension.DeleteCell,
editable: false, cell_priority: -1,
});
}
var allowMultipleEmptyRows = !!self.field.get('allowMultipleEmptyRows');
// Change format of each of the data
// Because - data coming from the server is in string format
self.collection.each(function(model) {
var name = model.get('name'), val;
// If allowMultipleEmptyRows is not set or is false then don't allow second new empty row.
// There should be only one empty row.
if (!allowMultipleEmptyRows && self.collection) {
var isEmpty = false;
self.collection.each(function(model) {
var modelValues = [];
_.each(model.attributes, function(val, key) {
modelValues.push(val);
})
if(!_.some(modelValues, _.identity)) {
isEmpty = true;
}
});
if(isEmpty) {
return false;
}
if (name in self.availVariables) {
switch(self.availVariables[name].vartype) {
case 'real':
val = parseFloat(model.get('value'));
model.set('value', (isNaN(val) ? undefined : val), {silent: true});
break;
case 'integer':
val = parseInt(model.get('value'));
model.set('value', (isNaN(val) ? undefined : val), {silent: true});
break;
default:
break;
}
}
});
$(grid.body.$el.find($("tr.new"))).removeClass("new")
var m = new (data.model) (null, {
silent: true,
handler: self.collection,
top: self.model.top || self.model,
collection: self.collection,
node_info: self.model.node_info
});
self.collection.add(m);
// Initialize a new Grid instance
var grid = self.grid = new Backgrid.Grid({
columns: gridSchema.columns,
collection: self.collection,
row: VariableRow,
className: 'backgrid table-bordered',
});
self.$grid = grid.render().$el;
var idx = self.collection.indexOf(m),
$gridBody.append(self.$grid);
// Add button callback
if (!(data.disabled || data.canAdd == false)) {
$gridBody.find('button.add').first().click(function(e) {
e.preventDefault();
var canAddRow = _.isFunction(data.canAddRow) ?
data.canAddRow.apply(self, [self.model]) : true;
if (canAddRow) {
var allowMultipleEmptyRows = !!self.field.get('allowMultipleEmptyRows');
// If allowMultipleEmptyRows is not set or is false then don't allow second new empty row.
// There should be only one empty row.
if (!allowMultipleEmptyRows && self.collection) {
var isEmpty = false;
self.collection.each(function(model) {
var modelValues = [];
_.each(model.attributes, function(val) {
modelValues.push(val);
});
if(!_.some(modelValues, _.identity)) {
isEmpty = true;
}
});
if(isEmpty) {
return false;
}
}
$(grid.body.$el.find($('tr.new'))).removeClass('new');
var m = new (data.model) (null, {
silent: true,
handler: self.collection,
top: self.model.top || self.model,
collection: self.collection,
node_info: self.model.node_info,
});
self.collection.add(m);
var idx = self.collection.indexOf(m),
newRow = grid.body.rows[idx].$el;
newRow.addClass("new");
$(newRow).pgMakeVisible('backform-tab');
newRow.addClass('new');
$(newRow).pgMakeVisible('backform-tab');
return false;
return false;
}
});
}
});
}
// Render node grid
return $gridBody;
},
// Render node grid
return $gridBody;
},
addVariable: function(ev) {
ev.preventDefault();
addVariable: function(ev) {
ev.preventDefault();
var self = this,
m = new (self.field.get('model'))(
self.headerData.toJSON(), {
silent: true, top: self.collection.top,
handler: self.collection
}),
coll = self.model.get(self.field.get('name'));
var self = this,
m = new (self.field.get('model'))(
self.headerData.toJSON(), {
silent: true, top: self.collection.top,
handler: self.collection,
}),
coll = self.model.get(self.field.get('name'));
coll.add(m);
coll.add(m);
var idx = coll.indexOf(m);
var idx = coll.indexOf(m);
// idx may not be always > -1 because our UniqueColCollection may
// remove 'm' if duplicate value found.
if (idx > -1) {
self.$grid.find('.new').removeClass('new');
// idx may not be always > -1 because our UniqueColCollection may
// remove 'm' if duplicate value found.
if (idx > -1) {
self.$grid.find('.new').removeClass('new');
var newRow = self.grid.body.rows[idx].$el;
var newRow = self.grid.body.rows[idx].$el;
newRow.addClass("new");
$(newRow).pgMakeVisible('backform-tab');
}
newRow.addClass('new');
$(newRow).pgMakeVisible('backform-tab');
}
return false;
}
return false;
},
});
return VariableModel;
});
return VariableModel;
});