diff --git a/web/pgadmin/browser/static/js/browser.js b/web/pgadmin/browser/static/js/browser.js index 4aa5b8ba..3dac0cb6 100644 --- a/web/pgadmin/browser/static/js/browser.js +++ b/web/pgadmin/browser/static/js/browser.js @@ -1,17 +1,16 @@ -define( - 'pgadmin.browser', [ - 'sources/gettext', 'sources/url_for', 'require', 'jquery', 'underscore', 'underscore.string', - 'bootstrap', 'sources/pgadmin', 'pgadmin.alertifyjs', 'bundled_codemirror', - 'sources/check_node_visibility', 'pgadmin.browser.utils', 'wcdocker', - 'jquery.contextmenu', 'jquery.aciplugin', 'jquery.acitree', - 'pgadmin.browser.messages', - 'pgadmin.browser.menu', 'pgadmin.browser.panel', - 'pgadmin.browser.error', 'pgadmin.browser.frame', - 'pgadmin.browser.node', 'pgadmin.browser.collection', - 'sources/codemirror/addon/fold/pgadmin-sqlfoldcode' - ], function( - gettext, url_for, require, $, _, S, Bootstrap, pgAdmin, Alertify, - codemirror, checkNodeVisibility +define('pgadmin.browser', [ + 'sources/gettext', 'sources/url_for', 'require', 'jquery', 'underscore', 'underscore.string', + 'bootstrap', 'sources/pgadmin', 'pgadmin.alertifyjs', 'bundled_codemirror', + 'sources/check_node_visibility', 'pgadmin.browser.utils', 'wcdocker', + 'jquery.contextmenu', 'jquery.aciplugin', 'jquery.acitree', + 'pgadmin.browser.messages', + 'pgadmin.browser.menu', 'pgadmin.browser.panel', + 'pgadmin.browser.error', 'pgadmin.browser.frame', + 'pgadmin.browser.node', 'pgadmin.browser.collection', + 'sources/codemirror/addon/fold/pgadmin-sqlfoldcode', +], function( + gettext, url_for, require, $, _, S, Bootstrap, pgAdmin, Alertify, + codemirror, checkNodeVisibility ) { window.jQuery = window.$ = $; // Some scripts do export their object in the window only. @@ -28,11 +27,11 @@ define( panelEvents[wcDocker.EVENT.VISIBILITY_CHANGED] = function() { if (this.isVisible()) { var obj = pgAdmin.Browser, - i = obj.tree ? obj.tree.selected() : undefined, - d = i && i.length == 1 ? obj.tree.itemData(i) : undefined; + i = obj.tree ? obj.tree.selected() : undefined, + d = i && i.length == 1 ? obj.tree.itemData(i) : undefined; if (d && obj.Nodes[d._type].callbacks['selected'] && - _.isFunction(obj.Nodes[d._type].callbacks['selected'])) { + _.isFunction(obj.Nodes[d._type].callbacks['selected'])) { return obj.Nodes[d._type].callbacks['selected'].apply( obj.Nodes[d._type], [i, d, obj]); } @@ -42,15 +41,15 @@ define( var processTreeData = function(payload) { var data = JSON.parse(payload).data; if (data.length && data[0]._type !== 'column' && - data[0]._type !== 'catalog_object_column') { + data[0]._type !== 'catalog_object_column') { data = data.sort(function(a, b) { - return pgAdmin.natural_sort(a.label, b.label); + return pgAdmin.natural_sort(a.label, b.label); }); } _.each(data, function(d){ d._label = d.label; d.label = _.escape(d.label); - }) + }); return data; }; @@ -61,7 +60,7 @@ define( url: url_for('browser.nodes'), converters: { 'text json': processTreeData, - } + }, }, ajaxHook: function(item, settings) { if (item != null) { @@ -73,14 +72,14 @@ define( }, loaderDelay: 100, show: { - duration: 75 + duration: 75, }, hide: { - duration: 75 + duration: 75, }, view: { - duration: 75 - } + duration: 75, + }, }); b.tree = $('#tree').aciTree('api'); @@ -112,7 +111,7 @@ define( isCloseable: false, isPrivate: true, icon: 'fa fa-binoculars', - content: '
' + content: '
', }), // Properties of the object node 'properties': new pgAdmin.Browser.Panel({ @@ -127,7 +126,7 @@ define( events: panelEvents, onCreate: function(myPanel, $container) { $container.addClass('pg-no-overflow'); - } + }, }), // Statistics of the object 'statistics': new pgAdmin.Browser.Panel({ @@ -138,7 +137,7 @@ define( isCloseable: false, isPrivate: true, content: '
' + select_object_msg + '
', - events: panelEvents + events: panelEvents, }), // Reversed engineered SQL for the object 'sql': new pgAdmin.Browser.Panel({ @@ -148,7 +147,7 @@ define( width: 500, isCloseable: false, isPrivate: true, - content: '
' + content: '
', }), // Dependencies of the object 'dependencies': new pgAdmin.Browser.Panel({ @@ -159,7 +158,7 @@ define( isCloseable: false, isPrivate: true, content: '
' + select_object_msg + '
', - events: panelEvents + events: panelEvents, }), // Dependents of the object 'dependents': new pgAdmin.Browser.Panel({ @@ -170,14 +169,14 @@ define( isCloseable: false, isPrivate: true, content: '
' + select_object_msg + '
', - events: panelEvents - }) + events: panelEvents, + }), }, // We also support showing dashboards, HTML file, external URL frames: {}, - /* Menus */ - // pgAdmin.Browser.MenuItem.add_menus(...) will register all the menus - // in this container + /* Menus */ + // pgAdmin.Browser.MenuItem.add_menus(...) will register all the menus + // in this container menus: { // All context menu goes here under certain menu types. // i.e. context: {'server': [...], 'server-group': [...]} @@ -193,7 +192,7 @@ define( // Tools menus tools: {}, // Help menus - help: {} + help: {}, }, add_panels: function() { /* Add hooked-in panels by extensions */ @@ -209,8 +208,8 @@ define( showTitle: panel.showTitle, isCloseable: panel.isCloseable, isPrivate: panel.isPrivate, - url: panel.content - }) + url: panel.content, + }); } else { pgBrowser.panels[panel.name] = new pgBrowser.Panel({ name: panel.name, @@ -223,8 +222,8 @@ define( isPrivate: panel.isPrivate, content: (panel.content) ? panel.content : '', events: (panel.events) ? panel.events : '', - canHide: (panel.canHide) ? panel.canHide : '' - }) + canHide: (panel.canHide) ? panel.canHide : '', + }); } }); @@ -238,8 +237,8 @@ define( above: false, below: true, /* icon: 'fa fa-magic', */ - single: true - } + single: true, + }, }, // A callback to load/fetch a script when a certain node is loaded register_script: function(n, m, p) { @@ -251,37 +250,37 @@ define( buildDefaultLayout: function() { var browserPanel = this.docker.addPanel('browser', wcDocker.DOCK.LEFT); var dashboardPanel = this.docker.addPanel( - 'dashboard', wcDocker.DOCK.RIGHT, browserPanel); + 'dashboard', wcDocker.DOCK.RIGHT, browserPanel); this.docker.addPanel('properties', wcDocker.DOCK.STACKED, dashboardPanel, { - tabOrientation: wcDocker.TAB.TOP + tabOrientation: wcDocker.TAB.TOP, }); this.docker.addPanel('sql', wcDocker.DOCK.STACKED, dashboardPanel); this.docker.addPanel( - 'statistics', wcDocker.DOCK.STACKED, dashboardPanel); + 'statistics', wcDocker.DOCK.STACKED, dashboardPanel); this.docker.addPanel( - 'dependencies', wcDocker.DOCK.STACKED, dashboardPanel); + 'dependencies', wcDocker.DOCK.STACKED, dashboardPanel); this.docker.addPanel( - 'dependents', wcDocker.DOCK.STACKED, dashboardPanel); + 'dependents', wcDocker.DOCK.STACKED, dashboardPanel); }, // Enable/disable menu options enable_disable_menus: function(item) { // Mechanism to enable/disable menus depending on the condition. - var obj = this, j, e, - // menu navigation bar - navbar = $('#navbar-menu > ul').first(), - // Drop down menu for objects - $obj_mnu = navbar.find('li#mnu_obj > ul.dropdown-menu').first(), - // data for current selected object - d = obj.tree.itemData(item), - update_menuitem = function(m) { - if (m instanceof pgAdmin.Browser.MenuItem) { - m.update(d, item); - } else { - for (var key in m) { - update_menuitem(m[key]); - } + var obj = this, + // menu navigation bar + navbar = $('#navbar-menu > ul').first(), + // Drop down menu for objects + $obj_mnu = navbar.find('li#mnu_obj > ul.dropdown-menu').first(), + // data for current selected object + d = obj.tree.itemData(item), + update_menuitem = function(m) { + if (m instanceof pgAdmin.Browser.MenuItem) { + m.update(d, item); + } else { + for (var key in m) { + update_menuitem(m[key]); } - }; + } + }; // All menus from the object menus (except the create drop-down // menu) needs to be removed. @@ -296,26 +295,22 @@ define( {m: 'management', id: '#mnu_management'}, {m: 'tools', id: '#mnu_tools'}, {m: 'help', id:'#mnu_help'}], function(o) { - _.each( - obj.menus[o.m], - function(m, k) { - update_menuitem(m); - }); - }); + _.each( obj.menus[o.m], function(m) { update_menuitem(m); }); + }); // Create the object menu dynamically if (item && obj.menus['object'] && obj.menus['object'][d._type]) { pgAdmin.Browser.MenuCreator( $obj_mnu, obj.menus['object'][d._type], obj.menu_categories, d, item - ) + ); } else { // Create a dummy 'no object seleted' menu var create_submenu = pgAdmin.Browser.MenuGroup( obj.menu_categories['create'], [{ - $el: $(''), + $el: $(''), priority: 1, category: 'create', - update: function() {} + update: function() {}, }], false); $obj_mnu.append(create_submenu.$el); } @@ -323,11 +318,11 @@ define( save_current_layout: function(obj) { if(obj.docker) { var state = obj.docker.save(); - var settings = { setting: "Browser/Layout", value: state }; + var settings = { setting: 'Browser/Layout', value: state }; $.ajax({ type: 'POST', url: url_for('settings.store_bulk'), - data: settings + data: settings, }); } }, @@ -344,11 +339,11 @@ define( // Initialize the Docker obj.docker = new wcDocker( '#dockerContainer', { - allowContextMenu: true, - allowCollapse: false, - themePath: '../static/css/', - theme: 'webcabin.overrides.css' - }); + allowContextMenu: true, + allowCollapse: false, + themePath: '../static/css/', + theme: 'webcabin.overrides.css', + }); if (obj.docker) { // Initialize all the panels _.each(obj.panels, function(panel, name) { @@ -365,18 +360,18 @@ define( // Try to restore the layout if there is one if (layout != '') { try { - obj.docker.restore(layout) + obj.docker.restore(layout); } catch(err) { obj.docker.clear(); - obj.buildDefaultLayout() + obj.buildDefaultLayout(); } } else { - obj.buildDefaultLayout() + obj.buildDefaultLayout(); } // Listen to panel attach/detach event so that last layout will be remembered - _.each(obj.panels, function(panel, name) { + _.each(obj.panels, function(panel) { if (panel.panel) { panel.panel.on(wcDocker.EVENT.ATTACHED, function() { obj.save_current_layout(obj); @@ -393,16 +388,16 @@ define( // Syntax highlight the SQL Pane obj.editor = CodeMirror.fromTextArea( - document.getElementById("sql-textarea"), { - lineNumbers: true, - mode: "text/x-pgsql", - readOnly: true, - extraKeys: pgAdmin.Browser.editor_shortcut_keys, - tabSize: pgAdmin.Browser.editor_options.tabSize, - lineWrapping: pgAdmin.Browser.editor_options.wrapCode, - autoCloseBrackets: pgAdmin.Browser.editor_options.insert_pair_brackets, - matchBrackets: pgAdmin.Browser.editor_options.brace_matching - }); + document.getElementById('sql-textarea'), { + lineNumbers: true, + mode: 'text/x-pgsql', + readOnly: true, + extraKeys: pgAdmin.Browser.editor_shortcut_keys, + tabSize: pgAdmin.Browser.editor_options.tabSize, + lineWrapping: pgAdmin.Browser.editor_options.wrapCode, + autoCloseBrackets: pgAdmin.Browser.editor_options.insert_pair_brackets, + matchBrackets: pgAdmin.Browser.editor_options.brace_matching, + }); setTimeout(function() { obj.editor.refresh(); @@ -417,10 +412,10 @@ define( autoHide: false, build: function(element) { var item = obj.tree.itemFrom(element), - d = obj.tree.itemData(item), - menus = obj.menus['context'][d._type], - $div = $('
'), - context_menu = {}; + d = obj.tree.itemData(item), + menus = obj.menus['context'][d._type], + $div = $('
'), + context_menu = {}; pgAdmin.Browser.MenuCreator( $div, menus, obj.menu_categories, d, item, context_menu @@ -428,72 +423,48 @@ define( return { autoHide: false, - items: context_menu + items: context_menu, }; - } + }, }); // Treeview event handler $('#tree').on('acitree', function(event, api, item, eventName, options) { var d = item ? obj.tree.itemData(item) : null; - - switch (eventName) { - // When a node is added in the browser tree, we need to - // load the registered scripts - case "added": - if (d) { - /* Loading all the scripts registered to be loaded on this node */ - if (obj.scripts && obj.scripts[d._type]) { - var scripts = _.extend({}, obj.scripts[d._type]); - - /* - * We can remove it from the Browser.scripts object as - * these're about to be loaded. - * - * This will make sure that we check for the script to be - * loaded only once. - * - */ - delete obj.scripts[d._type]; - } - } - break; - } - var node; if (d && obj.Nodes[d._type]) { node = obj.Nodes[d._type]; - /* If the node specific callback returns false, we will also return - * false for further processing. - */ + /* If the node specific callback returns false, we will also return + * false for further processing. + */ if (_.isObject(node.callbacks) && - eventName in node.callbacks && + eventName in node.callbacks && typeof node.callbacks[eventName] == 'function' && !node.callbacks[eventName].apply( - node, [item, d, obj, options, eventName])) { + node, [item, d, obj, options, eventName])) { return false; } /* Raise tree events for the nodes */ try { node.trigger( - 'browser-node.' + eventName, node, item, d - ); + 'browser-node.' + eventName, node, item, d + ); } catch (e) { - console.log(e); + console.warn(e.stack || e); } } try { obj.Events.trigger( - 'pgadmin-browser:tree', eventName, item, d - ); + 'pgadmin-browser:tree', eventName, item, d + ); obj.Events.trigger( - 'pgadmin-browser:tree:' + eventName, item, d, node - ); + 'pgadmin-browser:tree:' + eventName, item, d, node + ); } catch (e) { - console.log(e); + console.warn(e.stack || e); } return true; }); @@ -508,9 +479,9 @@ define( url: url_for('misc.ping'), type:'POST', success: function() {}, - error: function() {} - }); - }, 300000); + error: function() {}, + }); + }, 300000); obj.Events.on('pgadmin:browser:tree:add', obj.onAddTreeNode, obj); obj.Events.on('pgadmin:browser:tree:update', obj.onUpdateTreeNode, obj); obj.Events.on('pgadmin:browser:tree:refresh', obj.onRefreshTreeNode, obj); @@ -525,8 +496,8 @@ define( icon: icon, above: (above_separator === true), below: (below_separator === true), - single: single - } + single: single, + }; }, // This will hold preference data (Works as a cache object) @@ -542,17 +513,17 @@ define( _.each(m.applies, function(a) { /* We do support menu type only from this list */ if ($.inArray(a, [ - 'context', 'file', 'edit', 'object', - 'management', 'tools', 'help']) >= 0) { + 'context', 'file', 'edit', 'object', + 'management', 'tools', 'help']) >= 0) { var menus; - // If current node is not visible in browser tree - // then return from here + // If current node is not visible in browser tree + // then return from here if(!checkNodeVisibility(self, m.node)) { - return; + return; } else if(_.has(m, 'module') && !_.isUndefined(m.module)) { - // If module to which this menu applies is not visible in - // browser tree then also we do not display menu + // If module to which this menu applies is not visible in + // browser tree then also we do not display menu if(!checkNodeVisibility(self, m.module.type)) { return; } @@ -575,17 +546,17 @@ define( priority: m.priority, data: m.data, url: m.url, target: m.target, icon: m.icon, enable: (m.enable == '' ? true : (_.isString(m.enable) && - m.enable.toLowerCase() == 'false') ? - false : m.enable), - node: m.node + m.enable.toLowerCase() == 'false') ? + false : m.enable), + node: m.node, }); } } else { - console && console.log && - console.log( - "Developer warning: Category '" + + console.warn( + 'Developer warning: Category \'' + a + - "' is not supported!\nSupported categories are: context, file, edit, object, tools, management, help"); + '\' is not supported!\nSupported categories are: context, file, edit, object, tools, management, help' + ); } }); }); @@ -605,28 +576,28 @@ define( {menu: 'help', id:'#mnu_help'}], function(o) { var $mnu = navbar.children(o.id).first(), - $dropdown = $mnu.children('.dropdown-menu').first(); + $dropdown = $mnu.children('.dropdown-menu').first(); $dropdown.empty(); - var menus = {}; if (pgAdmin.Browser.MenuCreator( $dropdown, obj.menus[o.menu], obj.menu_categories - )) { + )) { $mnu.removeClass('hide'); } }); navbar.children('#mnu_obj').removeClass('hide'); - obj.enable_disable_menus(); + obj.enable_disable_menus(); }, // General function to handle callbacks for object or dialog help. showHelp: function(type, url, node, item, label) { - if (type == "object_help") { + var iframe, pnlProperties; + if (type == 'object_help') { // See if we can find an existing panel, if not, create one var pnlSqlHelp = this.docker.findPanels('pnl_sql_help')[0]; if (pnlSqlHelp == null) { - var pnlProperties = this.docker.findPanels('properties')[0]; + pnlProperties = this.docker.findPanels('properties')[0]; this.docker.addPanel('pnl_sql_help', wcDocker.DOCK.STACKED, pnlProperties); pnlSqlHelp = this.docker.findPanels('pnl_sql_help')[0]; } @@ -641,30 +612,30 @@ define( var major = Math.floor(server.version / 10000), minor = Math.floor(server.version / 100) - (major * 100); - baseUrl = baseUrl.replace('$VERSION$', major + '.' + minor) + baseUrl = baseUrl.replace('$VERSION$', major + '.' + minor); if (!S(baseUrl).endsWith('/')) { - baseUrl = baseUrl + '/' + baseUrl = baseUrl + '/'; } var fullUrl = baseUrl+ url; // Update the panel - var iframe = $(pnlSqlHelp).data('embeddedFrame'); + iframe = $(pnlSqlHelp).data('embeddedFrame'); pnlSqlHelp.title('Help: '+ label); pnlSqlHelp.focus(); iframe.openURL(fullUrl); - } else if(type == "dialog_help") { + } else if(type == 'dialog_help') { if(this.docker) { // See if we can find an existing panel, if not, create one var pnlDialogHelp = this.docker.findPanels('pnl_online_help')[0]; if (pnlDialogHelp == null) { - var pnlProperties = this.docker.findPanels('properties')[0]; + pnlProperties = this.docker.findPanels('properties')[0]; this.docker.addPanel('pnl_online_help', wcDocker.DOCK.STACKED, pnlProperties); pnlDialogHelp = this.docker.findPanels('pnl_online_help')[0]; } // Update the panel - var iframe = $(pnlDialogHelp).data('embeddedFrame'); + iframe = $(pnlDialogHelp).data('embeddedFrame'); pnlDialogHelp.focus(); iframe.openURL(url); @@ -682,17 +653,20 @@ define( var self = this; // If cache is not yet loaded then keep checking if(_.size(self.preferences_cache) == 0) { - var preference_data = setInterval(check_preference, 1000); - - function check_preference() { - if(_.size(self.preferences_cache) > 0) { - clearInterval(preference_data); - return _.findWhere(self.preferences_cache, {'module': module, 'name': preference}); - } - } + var check_preference = function() { + if(_.size(self.preferences_cache) > 0) { + clearInterval(preferenceTimeout); + return _.findWhere( + self.preferences_cache, {'module': module, 'name': preference} + ); + } + }, + preferenceTimeout = setInterval(check_preference, 1000); } else { - return _.findWhere(self.preferences_cache, {'module': module, 'name': preference}); + return _.findWhere( + self.preferences_cache, {'module': module, 'name': preference} + ); } }, @@ -704,58 +678,57 @@ define( success: function(res) { self.preferences_cache = res; }, - error: function(xhr, status, error) { + error: function(xhr) { try { var err = $.parseJSON(xhr.responseText); Alertify.alert(gettext('Preference loading failed.'), err.errormsg ); - } catch (e) {} - } + } catch (e) { console.warn(e.stack || e); } + }, }); }, _findTreeChildNode: function(_i, _d, _o) { var loaded = _o.t.wasLoad(_i), - done = true, - onLoad = function() { - var items = _o.t.children(_i), - i, d, n, idx = 0, size = items.length; - for (; idx < size; idx++) { - i = items.eq(idx); - d = _o.t.itemData(i); - if (d._type === _d._type) { - if (!_o.hasId || d._id == _d._id) { - _o.i = i; - _o.d = _d; - _o.pI.push({coll: false, item: i, d: _d}); - - _o.success(); - return; - } - } else { - n = _o.b.Nodes[d._type]; - // Are we looking at the collection node for the given node? - if ( - n && n.collection_node && d.nodes && + onLoad = function() { + var items = _o.t.children(_i), + i, d, n, idx = 0, size = items.length; + for (; idx < size; idx++) { + i = items.eq(idx); + d = _o.t.itemData(i); + if (d._type === _d._type) { + if (!_o.hasId || d._id == _d._id) { + _o.i = i; + _o.d = _d; + _o.pathOfTreeItems.push({coll: false, item: i, d: _d}); + + _o.success(); + return; + } + } else { + n = _o.b.Nodes[d._type]; + // Are we looking at the collection node for the given node? + if ( + n && n.collection_node && d.nodes && _.indexOf(d.nodes, _d._type) != -1 - ) { - _o.i = i; - _o.d = null; - _o.pI.push({coll: true, item: i, d: d}); - - // Set load to false when the current collection node's inode is false - if (!_o.t.isInode(i)) { - _o.load = false; - } - _o.b._findTreeChildNode(i, _d, _o); - return; + ) { + _o.i = i; + _o.d = null; + _o.pathOfTreeItems.push({coll: true, item: i, d: d}); + + // Set load to false when the current collection node's inode is false + if (!_o.t.isInode(i)) { + _o.load = false; } + _o.b._findTreeChildNode(i, _d, _o); + return; } } - _o.notFound && typeof(_o.notFound) == 'function' && - _o.notFound(_d); - }; + } + _o.notFound && typeof(_o.notFound) == 'function' && + _o.notFound(_d); + }; if (!loaded && _o.load) { _o.t.open(_i, { @@ -769,7 +742,7 @@ define( ) { fail.apply(_o.t, []); } - } + }, }); } else if (loaded) { onLoad(); @@ -783,243 +756,243 @@ define( onAddTreeNode: function(_data, _hierarchy, _opts) { var ctx = { - b: this, // Browser - d: null, // current parent - hasId: true, - i: null, // current item - p: _.toArray(_hierarchy || {}).sort( - function(a, b) { - return (a.priority === b.priority) ? 0 : ( - a.priority < b.priority ? -1 : 1 - ); - } - ), // path of the parent - pI: [], // path Item - t: this.tree, // Tree Api - o: _opts - }, - traversePath = function() { - var ctx = this, i, d; - - ctx.success = traversePath; - if (ctx.p.length) { - d = ctx.p.shift(); - // This is the parent node. - // Replace the parent-id of the data, which could be different - // from the given hierarchy. - if (!ctx.p.length) { - d._id = _data._pid; - ctx.success = addItemNode; - } - ctx.b._findTreeChildNode( - ctx.i, d, ctx - ); - // if parent node is null - if (!_data._pid) { - addItemNode.apply(ctx, arguments); - } + b: this, // Browser + d: null, // current parent + hasId: true, + i: null, // current item + p: _.toArray(_hierarchy || {}).sort( + function(a, b) { + return (a.priority === b.priority) ? 0 : ( + a.priority < b.priority ? -1 : 1 + ); + } + ), // path of the parent + pathOfTreeItems: [], // path Item + t: this.tree, // Tree Api + o: _opts, + }, + traversePath = function() { + var ctx = this, data; + + ctx.success = traversePath; + if (ctx.p.length) { + data = ctx.p.shift(); + // This is the parent node. + // Replace the parent-id of the data, which could be different + // from the given hierarchy. + if (!ctx.p.length) { + data._id = _data._pid; + ctx.success = addItemNode; } - return true; - }.bind(ctx), - addItemNode = function() { - // Append the new data in the tree under the current item. - // We may need to pass it to proper collection node. - var ctx = this, - first = (ctx.i || this.t.wasLoad(ctx.i)) && - this.t.first(ctx.i), - findChildNode = function(success, notFound) { - var ctx = this; - ctx.success = success; - ctx.notFound = notFound; - - ctx.b._findTreeChildNode(ctx.i, _data, ctx); - }.bind(ctx), - selectNode = function() { - this.t.openPath(this.i); - this.t.select(this.i); - if ( - ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' - ) { - ctx.o.success.apply(ctx.t, [ctx.i, _data]); + ctx.b._findTreeChildNode( + ctx.i, data, ctx + ); + // if parent node is null + if (!_data._pid) { + addItemNode.apply(ctx, arguments); + } + } + return true; + }.bind(ctx), + addItemNode = function() { + // Append the new data in the tree under the current item. + // We may need to pass it to proper collection node. + var ctx = this, + first = (ctx.i || this.t.wasLoad(ctx.i)) && + this.t.first(ctx.i), + findChildNode = function(success, notFound) { + var ctx = this; + ctx.success = success; + ctx.notFound = notFound; + + ctx.b._findTreeChildNode(ctx.i, _data, ctx); + }.bind(ctx), + selectNode = function() { + this.t.openPath(this.i); + this.t.select(this.i); + if ( + ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' + ) { + ctx.o.success.apply(ctx.t, [ctx.i, _data]); + } + }.bind(ctx), + addNode = function() { + var ctx = this, + items = ctx.t.children(ctx.i), + s = 0, e = items.length - 1, i, + linearSearch = function() { + while (e >= s) { + i = items.eq(s); + var d = ctx.t.itemData(i); + if ( + pgAdmin.natural_sort( + d._label, _data._label + ) == 1 + ) + return true; + s++; } - }.bind(ctx), - addNode = function() { - var ctx = this, - items = ctx.t.children(ctx.i), - s = 0, e = items.length - 1, i, - linearSearch = function() { - while (e >= s) { - i = items.eq(s); - var d = ctx.t.itemData(i); - if ( - pgAdmin.natural_sort( - d._label, _data._label - ) == 1 - ) - return true; - s++; - } - if (e != items.length - 1) { - i = items.eq(e); - return true; - } - i = null; - return false; - }, - binarySearch = function() { - var d, m; - // Binary search only outperforms Linear search for n > 44. - // Reference: - // https://en.wikipedia.org/wiki/Binary_search_algorithm#cite_note-30 - // - // We will try until it's half. - while (e - s > 22) { - i = items.eq(s); - var d = ctx.t.itemData(i); - if ( - pgAdmin.natural_sort( - d._label, _data._label - ) != -1 - ) - return true; - i = items.eq(e); - d = ctx.t.itemData(i); - if ( - pgAdmin.natural_sort( - d._label, _data._label - ) != 1 - ) - return true; - var m = s + Math.round((e - s) / 2); - i = items.eq(m); - d = ctx.t.itemData(i); - var res = pgAdmin.natural_sort(d._label, _data._label); - if (res == 0) - return true; - - if (res == -1) { - s = m + 1; - e--; - } else { - s++; - e = m - 1; - } - } - return linearSearch(); - }; - - if (binarySearch()) { - ctx.t.before(i, { - itemData: _data, - success: function() { - if ( - ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' - ) { - ctx.o.success.apply(ctx.t, [i, _data]); - } - }, - fail: function() { - console.log('Failed to add before..'); - if ( - ctx.o && ctx.o.fail && typeof(ctx.o.fail) == 'function' - ) { - ctx.o.fail.apply(ctx.t, [i, _data]); - } - } - }); - } else { - var _append = function() { - var ctx = this, - is_parent_loaded_before = ctx.t.wasLoad(ctx.i), - _parent_data = ctx.t.itemData(ctx.i); - - ctx.t.append(ctx.i, { - itemData: _data, - success: function(item, options) { - var i = $(options.items[0]); - // Open the item path only if its parent is loaded - // or parent type is same as nodes - if( - is_parent_loaded_before && - _parent_data && _parent_data._type.search( - _data._type - ) > -1 - ) { - ctx.t.openPath(i); - ctx.t.select(i); - } else { - if (_parent_data) { - // Unload the parent node so that we'll get - // latest data when we try to expand it - ctx.t.unload(ctx.i, { - success: function (item, options) { - // Lets try to load it now - ctx.t.open(item); - } - }); - } - } - if ( - ctx.o && ctx.o.success && - typeof(ctx.o.success) == 'function' - ) { - ctx.o.success.apply(ctx.t, [i, _data]); - } - }, - fail: function() { - console.log('Failed to append'); - if ( - ctx.o && ctx.o.fail && - typeof(ctx.o.fail) == 'function' - ) { - ctx.o.fail.apply(ctx.t, [ctx.i, _data]); - } - } - }); - }.bind(ctx); - - if (ctx.i && !ctx.t.isInode(ctx.i)) { - ctx.t.setInode(ctx.i, {success: _append}); + if (e != items.length - 1) { + i = items.eq(e); + return true; + } + i = null; + return false; + }, + binarySearch = function() { + var d, m, res; + // Binary search only outperforms Linear search for n > 44. + // Reference: + // https://en.wikipedia.org/wiki/Binary_search_algorithm#cite_note-30 + // + // We will try until it's half. + while (e - s > 22) { + i = items.eq(s); + d = ctx.t.itemData(i); + if ( + pgAdmin.natural_sort( + d._label, _data._label + ) != -1 + ) + return true; + i = items.eq(e); + d = ctx.t.itemData(i); + if ( + pgAdmin.natural_sort( + d._label, _data._label + ) != 1 + ) + return true; + m = s + Math.round((e - s) / 2); + i = items.eq(m); + d = ctx.t.itemData(i); + res = pgAdmin.natural_sort(d._label, _data._label); + if (res == 0) + return true; + + if (res == -1) { + s = m + 1; + e--; } else { - // Handle case for node without parent i.e. server-group - // or if parent node's inode is true. - _append(); + s++; + e = m - 1; } } - }.bind(ctx); + return linearSearch(); + }; - // Parent node do not have any children, let me unload it. - if (!first && ctx.t.wasLoad(ctx.i)) { - ctx.t.unload(ctx.i, { - success: function() { - findChildNode( - selectNode, - function() { - var o = this && this.o; + if (binarySearch()) { + ctx.t.before(i, { + itemData: _data, + success: function() { + if ( + ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' + ) { + ctx.o.success.apply(ctx.t, [i, _data]); + } + }, + fail: function() { + console.warn('Failed to add before...', arguments); + if ( + ctx.o && ctx.o.fail && typeof(ctx.o.fail) == 'function' + ) { + ctx.o.fail.apply(ctx.t, [i, _data]); + } + }, + }); + } else { + var _append = function() { + var ctx = this, + is_parent_loaded_before = ctx.t.wasLoad(ctx.i), + _parent_data = ctx.t.itemData(ctx.i); + + ctx.t.append(ctx.i, { + itemData: _data, + success: function(item, options) { + var i = $(options.items[0]); + // Open the item path only if its parent is loaded + // or parent type is same as nodes + if( + is_parent_loaded_before && + _parent_data && _parent_data._type.search( + _data._type + ) > -1 + ) { + ctx.t.openPath(i); + ctx.t.select(i); + } else { + if (_parent_data) { + // Unload the parent node so that we'll get + // latest data when we try to expand it + ctx.t.unload(ctx.i, { + success: function (item) { + // Lets try to load it now + ctx.t.open(item); + }, + }); + } + } if ( - o && o.fail && typeof(o.fail) == 'function' + ctx.o && ctx.o.success && + typeof(ctx.o.success) == 'function' ) { - o.fail.apply(this.t, [this.i, _data]); + ctx.o.success.apply(ctx.t, [i, _data]); } - }.bind(this) - ); - }.bind(this), - fail: function() { - var o = this && this.o; - if ( - o && o.fail && typeof(o.fail) == 'function' - ) { - o.fail.apply(this.t, [this.i, _data]); - } - }.bind(this) - }); - return; - } + }, + fail: function() { + console.warn('Failed to append...', arguments); + if ( + ctx.o && ctx.o.fail && + typeof(ctx.o.fail) == 'function' + ) { + ctx.o.fail.apply(ctx.t, [ctx.i, _data]); + } + }, + }); + }.bind(ctx); - // We can find the collection node using _findTreeChildNode - // indirectly. - findChildNode(selectNode, addNode); - }.bind(ctx); + if (ctx.i && !ctx.t.isInode(ctx.i)) { + ctx.t.setInode(ctx.i, {success: _append}); + } else { + // Handle case for node without parent i.e. server-group + // or if parent node's inode is true. + _append(); + } + } + }.bind(ctx); + + // Parent node do not have any children, let me unload it. + if (!first && ctx.t.wasLoad(ctx.i)) { + ctx.t.unload(ctx.i, { + success: function() { + findChildNode( + selectNode, + function() { + var o = this && this.o; + if ( + o && o.fail && typeof(o.fail) == 'function' + ) { + o.fail.apply(this.t, [this.i, _data]); + } + }.bind(this) + ); + }.bind(this), + fail: function() { + var o = this && this.o; + if ( + o && o.fail && typeof(o.fail) == 'function' + ) { + o.fail.apply(this.t, [this.i, _data]); + } + }.bind(this), + }); + return; + } + + // We can find the collection node using _findTreeChildNode + // indirectly. + findChildNode(selectNode, addNode); + }.bind(ctx); if (!ctx.t.wasInit() || !_data) { return; @@ -1032,487 +1005,488 @@ define( onUpdateTreeNode: function(_old, _new, _hierarchy, _opts) { var ctx = { - b: this, // Browser - d: null, // current parent - i: null, // current item - hasId: true, - p: _.toArray(_hierarchy || {}).sort( - function(a, b) { - return (a.priority === b.priority) ? 0 : ( - a.priority < b.priority ? -1 : 1 - ); + b: this, // Browser + d: null, // current parent + i: null, // current item + hasId: true, + p: _.toArray(_hierarchy || {}).sort( + function(a, b) { + return (a.priority === b.priority) ? 0 : ( + a.priority < b.priority ? -1 : 1 + ); + } + ), // path of the old object + pathOfTreeItems: [], // path items + t: this.tree, // Tree Api + o: _opts, + load: true, + old: _old, + new: _new, + op: null, + }, + errorOut = function() { + var fail = this.o && this.o.fail; + if (fail && typeof(fail) == 'function') { + fail.apply(this.t, [this.i, _new, _old]); + } + }.bind(ctx), + deleteNode = function() { + var self = this, + pathOfTreeItems = this.pathOfTreeItems, + findParent = function() { + if (pathOfTreeItems.length) { + pathOfTreeItems.pop(); + var length = pathOfTreeItems.length; + this.i = (length && pathOfTreeItems[length - 1].item) || null; + this.d = (length && pathOfTreeItems[length - 1].d) || null; + + // It is a collection item, let's find the node item + if (length && pathOfTreeItems[length - 1].coll) { + pathOfTreeItems.pop(); + length = pathOfTreeItems.length; + this.i = (length && pathOfTreeItems[length - 1].item) || null; + this.d = (length && pathOfTreeItems[length - 1].d) || null; + } + } else { + this.i = null; + this.d = null; } - ), // path of the old object - pI: [], // path items - t: this.tree, // Tree Api - o: _opts, - load: true, - old: _old, - new: _new, - op: null - }, - errorOut = function() { - var fail = this.o && this.o.fail; - if (fail && typeof(fail) == 'function') { - fail.apply(this.t, [this.i, _new, _old]); - } - }.bind(ctx), - deleteNode = function() { - var self = this, - pI = this.pI, - findParent = function() { - if (pI.length) { - pI.pop(); - var length = pI.length; - this.i = (length && pI[length - 1].item) || null; - this.d = (length && pI[length - 1].d) || null; - - // It is a collection item, let's find the node item - if (length && pI[length - 1].coll) { - pI.pop(); - length = pI.length; - this.i = (length && pI[length - 1].item) || null; - this.d = (length && pI[length - 1].d) || null; + }.bind(this); + + var _item_parent = (this.i + && this.t.hasParent(this.i) + && this.t.parent(this.i)) || null, + _item_grand_parent = _item_parent ? + (this.t.hasParent(_item_parent) + && this.t.parent(_item_parent)) + : null; + + // Remove the current node first. + if ( + this.i && this.d && this.old._id == this.d._id && + this.old._type == this.d._type + ) { + var _parent = this.t.parent(this.i) || null; + + // If there is no parent then just update the node + if(_parent.length == 0 && ctx.op == 'UPDATE') { + updateNode(); + } else { + var postRemove = function() { + // If item has parent but no grand parent + if (_item_parent && !_item_grand_parent) { + var parent = null; + // We need to search in all parent siblings (eg: server groups) + var parents = this.t.siblings(this.i) || []; + parents.push(this.i[0]); + _.each(parents, function (p) { + var d = self.t.itemData($(p)); + // If new server group found then assign it parent + if(d._id == self.new._pid) { + parent = p; + self.pathOfTreeItems.push({coll: true, item: parent, d: d}); } - } else { - this.i = null; - this.d = null; - } - }.bind(this); + }); - var _item_parent = (this.i - && this.t.hasParent(this.i) - && this.t.parent(this.i)) || null, - _item_grand_parent = _item_parent ? - (this.t.hasParent(_item_parent) - && this.t.parent(_item_parent)) - : null; + if (parent) { + this.load = true; - // Remove the current node first. - if ( - this.i && this.d && this.old._id == this.d._id && - this.old._type == this.d._type - ) { - var _parent = this.t.parent(this.i) || null; + this.success = function() { + addItemNode(); + }.bind(this); + // We can refresh the collection node, but - let's not bother about + // it right now. + this.notFound = errorOut; + + // var _d = {_id: this.new._pid, _type: self.d._type}; + parent = $(parent); + var loaded = this.t.wasLoad(parent), + onLoad = function() { + self.i = parent; + self.d = self.d; + self.pathOfTreeItems.push({coll: false, item: parent, d: self.d}); + self.success(); + return; + }; - // If there is no parent then just update the node - if(_parent.length == 0 && ctx.op == 'UPDATE') { - updateNode(); - } else { - var postRemove = function() { - // If item has parent but no grand parent - if (_item_parent && !_item_grand_parent) { - var parent = null; - // We need to search in all parent siblings (eg: server groups) - var parents = this.t.siblings(this.i) || []; - parents.push(this.i[0]) - _.each(parents, function (p) { - var d = self.t.itemData($(p)); - // If new server group found then assign it parent - if(d._id == self.new._pid) { - parent = p; - self.pI.push({coll: true, item: parent, d: d}); - } - }); + if (!loaded && self.load) { + self.t.open(parent, { + success: onLoad, + unanimated: true, + fail: function() { + var fail = self && self.o && self.o.fail; - if (parent) { - this.load = true; - - this.success = function() { - addItemNode(); - }.bind(this); - // We can refresh the collection node, but - let's not bother about - // it right now. - this.notFound = errorOut; - - var _d = {_id: this.new._pid, _type: self.d._type} - parent = $(parent); - var loaded = this.t.wasLoad(parent), - onLoad = function() { - self.i = parent; - self.d = self.d; - self.pI.push({coll: false, item: parent, d: self.d}); - self.success(); - return; - }; - - if (!loaded && self.load) { - self.t.open(parent, { - success: onLoad, - unanimated: true, - fail: function() { - var fail = self && self.o && self.o.fail; - - if ( - fail && typeof(fail) == 'function' - ) { - fail.apply(self.t, []); - } - } - }); - } else { - onLoad(); - } - } - return; - } else { - // This is for rest of the nodes - var _parentData = this.d; - // Find the grand-parent, or the collection node of parent. - findParent(); - - if (this.i) { - this.load = true; - - this.success = function() { - addItemNode(); - }.bind(this); - // We can refresh the collection node, but - let's not bother about - // it right now. - this.notFound = errorOut; - - // Find the new parent - this.b._findTreeChildNode( - this.i, {_id: this.new._pid, _type: _parentData._type}, this - ); + if ( + fail && typeof(fail) == 'function' + ) { + fail.apply(self.t, []); + } + }, + }); } else { - addItemNode(); + onLoad(); } - return; } - }.bind(this); + return; + } else { + // This is for rest of the nodes + var _parentData = this.d; + // Find the grand-parent, or the collection node of parent. + findParent(); - // If there is a parent then we can remove the node - this.t.remove(this.i, { - success: function() { - // Find the parent - findParent(); - // If server group have no children then close it and set inode - // and unload it so it can fetch new data on next expand - if (_item_parent && !_item_grand_parent && _parent - && self.t.children(_parent).length == 0) { - self.t.setInode(_parent, { - success: function() { - self.t.unload(_parent, {success: function() { - setTimeout(postRemove); - }} - ); - } - }); - } else { - setTimeout(postRemove); - } - return true; + if (this.i) { + this.load = true; + + this.success = function() { + addItemNode(); + }.bind(this); + // We can refresh the collection node, but - let's not bother about + // it right now. + this.notFound = errorOut; + + // Find the new parent + this.b._findTreeChildNode( + this.i, {_id: this.new._pid, _type: _parentData._type}, this + ); + } else { + addItemNode(); } + return; } + }.bind(this); + + // If there is a parent then we can remove the node + this.t.remove(this.i, { + success: function() { + // Find the parent + findParent(); + // If server group have no children then close it and set inode + // and unload it so it can fetch new data on next expand + if (_item_parent && !_item_grand_parent && _parent + && self.t.children(_parent).length == 0) { + self.t.setInode(_parent, { + success: function() { + self.t.unload(_parent, {success: function() { + setTimeout(postRemove); + }} + ); + }, + }); + } else { + setTimeout(postRemove); + } + return true; + }, + } ); } + } + errorOut(); + + }.bind(ctx), + findNewParent = function(_d) { + var findParent = function() { + var pathOfTreeItems = this.pathOfTreeItems; + + if (pathOfTreeItems.length) { + pathOfTreeItems.pop(); + var length = pathOfTreeItems.length; + this.i = (length && pathOfTreeItems[length - 1].item) || null; + this.d = (length && pathOfTreeItems[length - 1].d) || null; + + // It is a collection item, let's find the node item + if (length && pathOfTreeItems[length - 1].coll) { + pathOfTreeItems.pop(); + length = pathOfTreeItems.length; + this.i = (length && pathOfTreeItems[length - 1].item) || null; + this.d = (length && pathOfTreeItems[length - 1].d) || null; + } + } else { + this.i = null; + this.d = null; } - errorOut(); - - }.bind(ctx), - findNewParent = function(_d) { - var findParent = function() { - if (pI.length) { - pI.pop(); - var length = pI.length; - this.i = (length && pI[length - 1].item) || null; - this.d = (length && pI[length - 1].d) || null; + }.bind(this); - // It is a collection item, let's find the node item - if (length && pI[length - 1].coll) { - pI.pop(); - length = pI.length; - this.i = (length && pI[length - 1].item) || null; - this.d = (length && pI[length - 1].d) || null; - } - } else { - this.i = null; - this.d = null; - } + // old parent was not found, can we find the new parent? + if (this.i) { + this.load = true; + this.success = function() { + addItemNode(); }.bind(this); - // old parent was not found, can we find the new parent? - if (this.i) { - this.load = true; - this.success = function() { - addItemNode(); - }.bind(this); - - if (_d._type == old._type) { - // We were already searching the old object under the parent. - findParent(); - _d = this.d; - // Find the grand parent - findParent(); - } - console.log(_d); - _d = this.new._pid; + if (_d._type == this.old._type) { + // We were already searching the old object under the parent. + findParent(); + _d = this.d; + // Find the grand parent + findParent(); + } + _d = this.new._pid; - // We can refresh the collection node, but - let's not bother about - // it right now. - this.notFound = errorOut; + // We can refresh the collection node, but - let's not bother about + // it right now. + this.notFound = errorOut; - // Find the new parent - this.b._findTreeChildNode(this.i, _d, this); - } else { - addItemNode(); - } - }.bind(ctx), - updateNode = function() { - if ( - this.i && this.d && this.new._type == this.d._type - ) { - var self = this, + // Find the new parent + this.b._findTreeChildNode(this.i, _d, this); + } else { + addItemNode(); + } + }.bind(ctx), + updateNode = function() { + if ( + this.i && this.d && this.new._type == this.d._type + ) { + var self = this, _id = this.d._id; - if (this.new._id != this.d._id) { - // Found the new oid, update its node_id - var node_data = this.t.itemData(ctx.i); - node_data._id = _id = this.new._id; - } - if (this.new._id == _id) { - // Found the current - _.extend(this.d, { - '_id': this.new._id, - '_label': this.new._label, - 'label': this.new.label - }); - this.t.setLabel(ctx.i, {label: this.new.label}); - this.t.addIcon(ctx.i, {icon: this.new.icon}); - this.t.setId(ctx.i, {id: this.new.id}); - this.t.openPath(this.i); - this.t.deselect(this.i); - - // select tree item after few milliseconds - setTimeout(function() { - self.t.select(self.i); - }, 10); - } + if (this.new._id != this.d._id) { + // Found the new oid, update its node_id + var node_data = this.t.itemData(ctx.i); + node_data._id = _id = this.new._id; } - var success = this.o && this.o.success; - if (success && typeof(success) == 'function') { - success.apply(this.t, [this.i, _old, _new]); + if (this.new._id == _id) { + // Found the current + _.extend(this.d, { + '_id': this.new._id, + '_label': this.new._label, + 'label': this.new.label, + }); + this.t.setLabel(ctx.i, {label: this.new.label}); + this.t.addIcon(ctx.i, {icon: this.new.icon}); + this.t.setId(ctx.i, {id: this.new.id}); + this.t.openPath(this.i); + this.t.deselect(this.i); + + // select tree item after few milliseconds + setTimeout(function() { + self.t.select(self.i); + }, 10); } - }.bind(ctx), - traversePath = function() { - var ctx = this, i, d; - - ctx.success = traversePath; - if (ctx.p.length) { - d = ctx.p.shift(); - // This is the node, we can now do the required operations. - // We should first delete the existing node, if the parent-id is - // different. - if (!ctx.p.length) { - if (ctx.op == 'RECREATE') { - ctx.load = false; - ctx.success = deleteNode; - ctx.notFound = findNewParent; - } else { - ctx.success = updateNode; - ctx.notFound = errorOut; - } + } + var success = this.o && this.o.success; + if (success && typeof(success) == 'function') { + success.apply(this.t, [this.i, _old, _new]); + } + }.bind(ctx), + traversePath = function() { + var ctx = this, data; + + ctx.success = traversePath; + if (ctx.p.length) { + data = ctx.p.shift(); + // This is the node, we can now do the required operations. + // We should first delete the existing node, if the parent-id is + // different. + if (!ctx.p.length) { + if (ctx.op == 'RECREATE') { + ctx.load = false; + ctx.success = deleteNode; + ctx.notFound = findNewParent; + } else { + ctx.success = updateNode; + ctx.notFound = errorOut; } - ctx.b._findTreeChildNode( - ctx.i, d, ctx - ); - } else if (ctx.p.length == 1) { - ctx.notFound = findNewParent; } - return true; - }.bind(ctx), - addItemNode = function() { - var ctx = this, - first = (ctx.i || this.t.wasLoad(ctx.i)) && - this.t.first(ctx.i), - findChildNode = function(success, notFound) { - var ctx = this; - ctx.success = success; - ctx.notFound = notFound; - - ctx.b._findTreeChildNode(ctx.i, _new, ctx); - }.bind(ctx), - selectNode = function() { - this.t.openPath(this.i); - this.t.select(this.i); - if ( - ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' - ) { - ctx.o.success.apply(ctx.t, [ctx.i, _new]); + ctx.b._findTreeChildNode( + ctx.i, data, ctx + ); + } else if (ctx.p.length == 1) { + ctx.notFound = findNewParent; + } + return true; + }.bind(ctx), + addItemNode = function() { + var ctx = this, + first = (ctx.i || this.t.wasLoad(ctx.i)) && + this.t.first(ctx.i), + findChildNode = function(success, notFound) { + var ctx = this; + ctx.success = success; + ctx.notFound = notFound; + + ctx.b._findTreeChildNode(ctx.i, _new, ctx); + }.bind(ctx), + selectNode = function() { + this.t.openPath(this.i); + this.t.select(this.i); + if ( + ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' + ) { + ctx.o.success.apply(ctx.t, [ctx.i, _new]); + } + }.bind(ctx), + addNode = function() { + var ctx = this, + items = ctx.t.children(ctx.i), + s = 0, e = items.length - 1, i, + linearSearch = function() { + while (e >= s) { + i = items.eq(s); + var d = ctx.t.itemData(i); + if ( + pgAdmin.natural_sort( + d._label, _new._label + ) == 1 + ) + return true; + s++; } - }.bind(ctx), - addNode = function() { - var ctx = this, - items = ctx.t.children(ctx.i), - s = 0, e = items.length - 1, i, - linearSearch = function() { - while (e >= s) { - i = items.eq(s); - var d = ctx.t.itemData(i); - if ( - pgAdmin.natural_sort( - d._label, _new._label - ) == 1 - ) - return true; - s++; - } - if (e != items.length - 1) { - i = items.eq(e); - return true; - } - i = null; - return false; - }, - binarySearch = function() { - while (e - s > 22) { - i = items.eq(s); - var d = ctx.t.itemData(i); - if ( - pgAdmin.natural_sort( - d._label, _new._label - ) != -1 - ) - return true; - i = items.eq(e); - d = ctx.t.itemData(i); - if ( - pgAdmin.natural_sort( - d._label, _new._label - ) != 1 - ) - return true; - var m = s + Math.round((e - s) / 2); - i = items.eq(m); - d = ctx.t.itemData(i); - var res = pgAdmin.natural_sort(d._label, _new._label); - if (res == 0) - return true; - - if (res == -1) { - s = m + 1; - e--; - } else { - s++; - e = m - 1; - } - } - return linearSearch(); - }; - - if (binarySearch()) { - ctx.t.before(i, { - itemData: _new, - success: function() { - var new_item = $(arguments[1].items[0]); - ctx.t.openPath(new_item); - ctx.t.select(new_item); - if ( - ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' - ) { - ctx.o.success.apply(ctx.t, [i, _old, _new]); - } - }, - fail: function() { - console.log('Failed to add before..'); - if ( - ctx.o && ctx.o.fail && typeof(ctx.o.fail) == 'function' - ) { - ctx.o.fail.apply(ctx.t, [i, _old, _new]); - } - } - }); - } else { - var _appendNode = function() { - ctx.t.append(ctx.i, { - itemData: _new, - success: function() { - var new_item = $(arguments[1].items[0]); - ctx.t.openPath(new_item); - ctx.t.select(new_item); - if ( - ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' - ) { - ctx.o.success.apply(ctx.t, [ctx.i, _old, _new]); - } - }, - fail: function() { - console.log('Failed to append'); - if ( - ctx.o && ctx.o.fail && typeof(ctx.o.fail) == 'function' - ) { - ctx.o.fail.apply(ctx.t, [ctx.i, _old, _new]); - } - } - }) - }; - - // If the current node's inode is false - if (ctx.i && !ctx.t.isInode(ctx.i)) { - ctx.t.setInode(ctx.i, {success: _appendNode}); + if (e != items.length - 1) { + i = items.eq(e); + return true; + } + i = null; + return false; + }, + binarySearch = function() { + while (e - s > 22) { + i = items.eq(s); + var d = ctx.t.itemData(i); + if ( + pgAdmin.natural_sort( + d._label, _new._label + ) != -1 + ) + return true; + i = items.eq(e); + d = ctx.t.itemData(i); + if ( + pgAdmin.natural_sort( + d._label, _new._label + ) != 1 + ) + return true; + var m = s + Math.round((e - s) / 2); + i = items.eq(m); + d = ctx.t.itemData(i); + var res = pgAdmin.natural_sort(d._label, _new._label); + if (res == 0) + return true; + + if (res == -1) { + s = m + 1; + e--; } else { - // Handle case for node without parent i.e. server-group - // or if parent node's inode is true. - _appendNode(); + s++; + e = m - 1; } - } - }.bind(ctx); + return linearSearch(); + }; - // Parent node do not have any children, let me unload it. - if (!first && ctx.t.wasLoad(ctx.i)) { - ctx.t.unload(ctx.i, { - success: function() { - findChildNode( - selectNode, - function() { - var o = this && this.o; + if (binarySearch()) { + ctx.t.before(i, { + itemData: _new, + success: function() { + var new_item = $(arguments[1].items[0]); + ctx.t.openPath(new_item); + ctx.t.select(new_item); + if ( + ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' + ) { + ctx.o.success.apply(ctx.t, [i, _old, _new]); + } + }, + fail: function() { + console.warn('Failed to add before..', arguments); + if ( + ctx.o && ctx.o.fail && typeof(ctx.o.fail) == 'function' + ) { + ctx.o.fail.apply(ctx.t, [i, _old, _new]); + } + }, + }); + } else { + var _appendNode = function() { + ctx.t.append(ctx.i, { + itemData: _new, + success: function() { + var new_item = $(arguments[1].items[0]); + ctx.t.openPath(new_item); + ctx.t.select(new_item); if ( - o && o.fail && typeof(o.fail) == 'function' + ctx.o && ctx.o.success && typeof(ctx.o.success) == 'function' ) { - o.fail.apply(this.t, [this.i, _old, _new]); + ctx.o.success.apply(ctx.t, [ctx.i, _old, _new]); } - }.bind(this) - ); - }.bind(this), - fail: function() { - var o = this && this.o; - if ( - o && o.fail && typeof(o.fail) == 'function' - ) { - o.fail.apply(this.t, [this.i, _old, _new]); - } - }.bind(this) - }); - return; - } + }, + fail: function() { + console.warn('Failed to append...', arguments); + if ( + ctx.o && ctx.o.fail && typeof(ctx.o.fail) == 'function' + ) { + ctx.o.fail.apply(ctx.t, [ctx.i, _old, _new]); + } + }, + }); + }; - // We can find the collection node using _findTreeChildNode - // indirectly. - findChildNode(selectNode, addNode); - }.bind(ctx); + // If the current node's inode is false + if (ctx.i && !ctx.t.isInode(ctx.i)) { + ctx.t.setInode(ctx.i, {success: _appendNode}); + } else { + // Handle case for node without parent i.e. server-group + // or if parent node's inode is true. + _appendNode(); + } + + } + }.bind(ctx); + + // Parent node do not have any children, let me unload it. + if (!first && ctx.t.wasLoad(ctx.i)) { + ctx.t.unload(ctx.i, { + success: function() { + findChildNode( + selectNode, + function() { + var o = this && this.o; + if ( + o && o.fail && typeof(o.fail) == 'function' + ) { + o.fail.apply(this.t, [this.i, _old, _new]); + } + }.bind(this) + ); + }.bind(this), + fail: function() { + var o = this && this.o; + if ( + o && o.fail && typeof(o.fail) == 'function' + ) { + o.fail.apply(this.t, [this.i, _old, _new]); + } + }.bind(this), + }); + return; + } + + // We can find the collection node using _findTreeChildNode + // indirectly. + findChildNode(selectNode, addNode); + }.bind(ctx); if (!ctx.t.wasInit() || !_new || !_old) { return; } - ctx.pI.push(_old); + ctx.pathOfTreeItems.push(_old); _new._label = _new.label; _new.label = _.escape(_new.label); // We need to check if this is collection node and have // children count, if yes then add count with label too if(ctx.b.Nodes[_new._type].is_collection) { - if ('collection_count' in _old && _old['collection_count'] > 0) { - _new.label = _.escape(_new._label) + - ' (' + _old['collection_count'] + ')' - } + if ('collection_count' in _old && _old['collection_count'] > 0) { + _new.label = _.escape(_new._label) + + ' (' + _old['collection_count'] + ')'; + } } // If server icon/background changes then also we need to re-create it if(_old._type == 'server' && _new._type == 'server' && - ( _old._pid != _new._pid || - _old._label != _new._label || + ( _old._pid != _new._pid || + _old._label != _new._label || _old.icon != _new.icon ) ) { ctx.op = 'RECREATE'; @@ -1528,18 +1502,18 @@ define( onRefreshTreeNode: function(_i, _opts) { var d = _i && this.tree.itemData(_i), - n = d && d._type && this.Nodes[d._type], - ctx = { - b: this, // Browser - d: d, // current parent - i: _i, // current item - p: null, // path of the old object - pI: [], // path items - t: this.tree, // Tree Api - o: _opts - }, - isOpen, - idx = -1; + n = d && d._type && this.Nodes[d._type], + ctx = { + b: this, // Browser + d: d, // current parent + i: _i, // current item + p: null, // path of the old object + pathOfTreeItems: [], // path items + t: this.tree, // Tree Api + o: _opts, + }, + isOpen, + idx = -1; if (!n) { _i = null; @@ -1554,7 +1528,7 @@ define( idx++; if (!idx || (d.inode && d.open)) { return { - _id: d._id, _type: d._type, branch: d.branch, open: d.open + _id: d._id, _type: d._type, branch: d.branch, open: d.open, }; } }); @@ -1573,109 +1547,101 @@ define( if (typeof(fail) == 'function') { fail(); } - } + }, }); return; } var fetchNodeInfo = function(_i, _d, _n) { - var info = _n.getTreeNodeHierarchy(_i), - url = _n.generate_url(_i, 'nodes', _d, true); - - $.ajax({ - url: url, - type: 'GET', - cache: false, - dataType: 'json', - success: function(res) { - // Node information can come as result/data - var data = res.result || res.data; - - data._label = data.label; - data.label = _.escape(data.label); - var d = ctx.t.itemData(ctx.i); - _.extend(d, data); - ctx.t.setLabel(ctx.i, {label: _d.label}); - ctx.t.addIcon(ctx.i, {icon: _d.icon}); - ctx.t.setId(ctx.i, {id: _d.id}); - ctx.t.setInode(ctx.i, {inode: data.inode}); + var info = _n.getTreeNodeHierarchy(_i), + url = _n.generate_url(_i, 'nodes', _d, true); - if ( - _n.can_expand && typeof(_n.can_expand) == 'function' - ) { - if (!_n.can_expand(d)) { - ctx.t.unload(ctx.i); - return; - } - } - ctx.b._refreshNode(ctx, ctx.branch); - var success = (ctx.o && ctx.o.success) || ctx.success; - if (success && typeof(success) == 'function') { - success(); - } - }, - error: function(xhr, error, status) { - if ( - !Alertify.pgHandleItemError( - xhr, error, status, {item: _i, info: info} - ) - ) { - var msg = xhr.responseText, - contentType = xhr.getResponseHeader('Content-Type'), - msg = xhr.responseText, - jsonResp = ( - contentType && - contentType.indexOf('application/json') == 0 && - $.parseJSON(xhr.responseText) - ) || {}; - - if (xhr.status == 410 && jsonResp.success == 0) { - var p = ctx.t.parent(ctx.i); - - ctx.t.remove(ctx.i, { - success: function() { - if (p) { - // Try to refresh the parent on error - try { - pgBrowser.Events.trigger( - 'pgadmin:browser:tree:refresh', p - ); - } catch(e) {} - } - } - }); - } + $.ajax({ + url: url, + type: 'GET', + cache: false, + dataType: 'json', + success: function(res) { + // Node information can come as result/data + var data = res.result || res.data; + + data._label = data.label; + data.label = _.escape(data.label); + var d = ctx.t.itemData(ctx.i); + _.extend(d, data); + ctx.t.setLabel(ctx.i, {label: _d.label}); + ctx.t.addIcon(ctx.i, {icon: _d.icon}); + ctx.t.setId(ctx.i, {id: _d.id}); + ctx.t.setInode(ctx.i, {inode: data.inode}); + + if ( + _n.can_expand && typeof(_n.can_expand) == 'function' + ) { + if (!_n.can_expand(d)) { + ctx.t.unload(ctx.i); + return; + } + } + ctx.b._refreshNode(ctx, ctx.branch); + var success = (ctx.o && ctx.o.success) || ctx.success; + if (success && typeof(success) == 'function') { + success(); + } + }, + error: function(xhr, error, status) { + if ( + !Alertify.pgHandleItemError( + xhr, error, status, {item: _i, info: info} + ) + ) { + var contentType = xhr.getResponseHeader('Content-Type'), + jsonResp = ( + contentType && + contentType.indexOf('application/json') == 0 && + $.parseJSON(xhr.responseText) + ) || {}; + + if (xhr.status == 410 && jsonResp.success == 0) { + var p = ctx.t.parent(ctx.i); - Alertify.pgNotifier( - error, xhr, gettext("Error retrieving details for the node."), - function() { - console.log(arguments); + ctx.t.remove(ctx.i, { + success: function() { + if (p) { + // Try to refresh the parent on error + try { + pgBrowser.Events.trigger( + 'pgadmin:browser:tree:refresh', p + ); + } catch (e) { console.warn(e.stack || e); } } - ); - } + }, + }); } - }); - }.bind(this); + + Alertify.pgNotifier( + error, xhr, gettext('Error retrieving details for the node.'), + function() { console.warn(arguments); } + ); + } + }, + }); + }.bind(this); if (n && n.collection_node) { var p = ctx.i = this.tree.parent(_i), - unloadNode = function() { - this.tree.unload(_i, { - success: function() { - _i = p; - d = ctx.d = ctx.t.itemData(ctx.i); - n = ctx.b.Nodes[d._type]; - _i = p; - fetchNodeInfo(_i, d, n); - }, - fail: function() { - console.log(arguments); - } - }); - }.bind(this); + unloadNode = function() { + this.tree.unload(_i, { + success: function() { + _i = p; + d = ctx.d = ctx.t.itemData(ctx.i); + n = ctx.b.Nodes[d._type]; + _i = p; + fetchNodeInfo(_i, d, n); + }, + fail: function() { console.warn(arguments); }, + }); + }.bind(this); if (!this.tree.isInode(_i)) { - this.tree.setInode(_i, { - success: unloadNode - }); + this.tree.setInode(_i, { success: unloadNode }); } else { unloadNode(); } @@ -1683,15 +1649,15 @@ define( this.tree.unload(_i, { success: fetchNodeInfo.bind(this, _i, d, n), fail: function() { - console.log(arguments); - } + console.warn(arguments); + }, }); } else if (!this.tree.isInode(_i) && d.inode) { this.tree.setInode(_i, { success: fetchNodeInfo.bind(this, _i, d, n), fail: function() { - console.log(arguments); - } + console.warn(arguments); + }, }); } else { fetchNodeInfo(_i, d, n); @@ -1702,8 +1668,8 @@ define( var tree = pgBrowser.tree; if(_parentNode && _collType) { var children = tree.children(_parentNode), - idx = 0, size = children.length, - childNode, childNodeData; + idx = 0, size = children.length, + childNode, childNodeData; _parentNode = null; @@ -1719,10 +1685,9 @@ define( } if (_parentNode) { - var children = tree.children(_parentNode), - idx = 0, size = children.length, - childNode, childNodeData, - prevChildNode; + children = tree.children(_parentNode); + idx = 0; + size = children.length; for (; idx < size; idx++) { childNode = children.eq(idx); @@ -1739,7 +1704,7 @@ define( removeTreeNode: function(_node, _selectNext, _parentNode) { var tree = pgBrowser.tree, - nodeToSelect = null; + nodeToSelect = null; if (!_node) return false; @@ -1766,9 +1731,9 @@ define( findSiblingTreeNode: function(_node, _id) { var tree = pgBrowser.tree, - parentNode = tree.parent(_node), - siblings = tree.children(parentNode), - idx = 0, nodeData, node; + parentNode = tree.parent(_node), + siblings = tree.children(parentNode), + idx = 0, nodeData, node; for(; idx < siblings.length; idx++) { node = siblings.eq(idx); @@ -1782,8 +1747,8 @@ define( findParentTreeNodeByType: function(_node, _parentType) { var tree = pgBrowser.tree, - nodeData, - node = _node; + nodeData, + node = _node; do { nodeData = tree.itemData(node); @@ -1797,9 +1762,9 @@ define( findChildCollectionTreeNode: function(_node, _collType) { var tree = pgBrowser.tree, - nodeData, idx = 0, - node = _node, - children = _node && tree.children(_node); + nodeData, idx = 0, + node = _node, + children = _node && tree.children(_node); if (!children || !children.length) return null; @@ -1816,57 +1781,54 @@ define( addChildTreeNodes: function(_treeHierarchy, _node, _type, _arrayIds, _callback) { var module = _type in pgBrowser.Nodes && pgBrowser.Nodes[_type], - childTreeInfo = _arrayIds.length && _.extend( - {}, _.mapObject( - _treeHierarchy, function(_val, _key) { - _val.priority -= 1; return _val; - }) - ), - arrayChildNodeData = [], - fetchNodeInfo = function(_callback) { - if (!_arrayIds.length) { - if (_callback) { - _callback(); - } - return; + childTreeInfo = _arrayIds.length && _.extend( + {}, _.mapObject(_treeHierarchy, function(_val) { + _val.priority -= 1; return _val; + })), + arrayChildNodeData = [], + fetchNodeInfo = function(_callback) { + if (!_arrayIds.length) { + if (_callback) { + _callback(); } + return; + } - var childDummyInfo = { - '_id': _arrayIds.pop(), '_type': _type, 'priority': 0 - }, - childNodeUrl; - childTreeInfo[_type] = childDummyInfo; + var childDummyInfo = { + '_id': _arrayIds.pop(), '_type': _type, 'priority': 0, + }, + childNodeUrl; - childNodeUrl = module.generate_url( - null, 'nodes', childDummyInfo, true, childTreeInfo - ); - console.debug("Fetching node information using: ", childNodeUrl); - - $.ajax({ - url: childNodeUrl, - dataType: "json", - success: function(res) { - if (res.success) { - arrayChildNodeData.push(res.data); - } - fetchNodeInfo(_callback); - }, - error: function(xhr, status, error) { - try { - var err = $.parseJSON(xhr.responseText); - if (err.success == 0) { - Alertify.error(err.errormsg); - } - } catch (e) {} - fetchNodeInfo(_callback); + childTreeInfo[_type] = childDummyInfo; + childNodeUrl = module.generate_url( + null, 'nodes', childDummyInfo, true, childTreeInfo + ); + + $.ajax({ + url: childNodeUrl, + dataType: 'json', + success: function(res) { + if (res.success) { + arrayChildNodeData.push(res.data); } - }); - }; + fetchNodeInfo(_callback); + }, + error: function(xhr) { + try { + var err = $.parseJSON(xhr.responseText); + if (err.success == 0) { + Alertify.error(err.errormsg); + } + } catch (e) { console.warn(e.stack || e); } + fetchNodeInfo(_callback); + }, + }); + }; if (!module) { - console.warning( - "Developer: Couldn't find the module for the given child: ", + console.warn( + 'Developer: Couldn\'t find the module for the given child: ', _.clone(arguments) ); return; @@ -1874,7 +1836,6 @@ define( if (pgBrowser.tree.wasLoad(_node) || pgBrowser.tree.isLeaf(_node)) { fetchNodeInfo(function() { - console.log('Append this nodes:', arrayChildNodeData); _.each(arrayChildNodeData, function(_nodData) { pgBrowser.Events.trigger( 'pgadmin:browser:tree:add', _nodData, _treeHierarchy @@ -1894,111 +1855,111 @@ define( _refreshNode: function(_ctx, _d) { var traverseNodes = function(_d) { - var _ctx = this, idx = 0, ctx, d, - size = (_d.branch && _d.branch.length) || 0, - findNode = function(_i, __d, __ctx) { - setTimeout( - function() { - __ctx.b._findTreeChildNode(_i, __d, __ctx); - }, 0 - ); - }; + var _ctx = this, idx = 0, ctx, d, + size = (_d.branch && _d.branch.length) || 0, + findNode = function(_i, __d, __ctx) { + setTimeout( + function() { + __ctx.b._findTreeChildNode(_i, __d, __ctx); + }, 0 + ); + }; - for (; idx < size; idx++) { - d = _d.branch[idx]; - var n = _ctx.b.Nodes[d._type]; - ctx = { - b: _ctx.b, - t: _ctx.t, - pI: [], - i: _ctx.i, - d: d, - select: _ctx.select, - hasId: n && !n.collection_node, - o: _ctx.o, - load: true - }; - ctx.success = function() { - this.b._refreshNode.call(this.b, this, this.d); - }.bind(ctx) - findNode(_ctx.i, d, ctx); - } - }.bind(_ctx, _d); + for (; idx < size; idx++) { + d = _d.branch[idx]; + var n = _ctx.b.Nodes[d._type]; + ctx = { + b: _ctx.b, + t: _ctx.t, + pathOfTreeItems: [], + i: _ctx.i, + d: d, + select: _ctx.select, + hasId: n && !n.collection_node, + o: _ctx.o, + load: true, + }; + ctx.success = function() { + this.b._refreshNode.call(this.b, this, this.d); + }.bind(ctx); + findNode(_ctx.i, d, ctx); + } + }.bind(_ctx, _d); - if (!_d || !_d.open) - return; + if (!_d || !_d.open) + return; - if (!_ctx.t.isOpen(_ctx.i)) { - _ctx.t.open(_ctx.i, { - unanimated: true, - success: traverseNodes, - fail: function() { /* Do nothing */ } - }); - } else { - traverseNodes(); - } + if (!_ctx.t.isOpen(_ctx.i)) { + _ctx.t.open(_ctx.i, { + unanimated: true, + success: traverseNodes, + fail: function() { /* Do nothing */ }, + }); + } else { + traverseNodes(); + } }, editor_shortcut_keys: { // Autocomplete sql command - "Ctrl-Space": "autocomplete", - "Cmd-Space": "autocomplete", + 'Ctrl-Space': 'autocomplete', + 'Cmd-Space': 'autocomplete', - // Select All text - "Ctrl-A": "selectAll", - "Cmd-A": "selectAll", + // Select All text + 'Ctrl-A': 'selectAll', + 'Cmd-A': 'selectAll', - // Redo text - "Ctrl-Y": "redo", - "Cmd-Y": "redo", + // Redo text + 'Ctrl-Y': 'redo', + 'Cmd-Y': 'redo', - // Undo text - "Ctrl-Z": "undo", - "Cmd-Z": "undo", + // Undo text + 'Ctrl-Z': 'undo', + 'Cmd-Z': 'undo', - // Delete Line - "Ctrl-D": "deleteLine", - "Cmd-D": "deleteLine", + // Delete Line + 'Ctrl-D': 'deleteLine', + 'Cmd-D': 'deleteLine', - // Go to start/end of Line - "Alt-Left": "goLineStart", - "Alt-Right": "goLineEnd", + // Go to start/end of Line + 'Alt-Left': 'goLineStart', + 'Alt-Right': 'goLineEnd', - // Move word by word left/right - "Ctrl-Alt-Left": "goGroupLeft", - "Cmd-Alt-Left": "goGroupLeft", - "Ctrl-Alt-Right": "goGroupRight", - "Cmd-Alt-Right": "goGroupRight", + // Move word by word left/right + 'Ctrl-Alt-Left': 'goGroupLeft', + 'Cmd-Alt-Left': 'goGroupLeft', + 'Ctrl-Alt-Right': 'goGroupRight', + 'Cmd-Alt-Right': 'goGroupRight', - // Allow user to delete Tab(s) - "Shift-Tab": "indentLess" + // Allow user to delete Tab(s) + 'Shift-Tab': 'indentLess', }, editor_options: { tabSize: pgBrowser.utils.tabSize, wrapCode: pgBrowser.utils.wrapCode, insert_pair_brackets: pgBrowser.utils.insertPairBrackets, brace_matching: pgBrowser.utils.braceMatching, - indent_with_tabs: pgBrowser.utils.is_indent_with_tabs - } + indent_with_tabs: pgBrowser.utils.is_indent_with_tabs, + }, }); - /* Remove paste event mapping from CodeMirror's emacsy KeyMap binding - * specific to Mac LineNumber:5797 - lib/Codemirror.js - * It is preventing default paste event(Cmd-V) from triggering - * in runtime. - */ - delete CodeMirror.keyMap.emacsy["Ctrl-V"]; + /* Remove paste event mapping from CodeMirror's emacsy KeyMap binding + * specific to Mac LineNumber:5797 - lib/Codemirror.js + * It is preventing default paste event(Cmd-V) from triggering + * in runtime. + */ + delete CodeMirror.keyMap.emacsy['Ctrl-V']; // Use spaces instead of tab if (pgBrowser.utils.useSpaces == 'True') { - pgAdmin.Browser.editor_shortcut_keys.Tab = "insertSoftTab"; + pgAdmin.Browser.editor_shortcut_keys.Tab = 'insertSoftTab'; } window.onbeforeunload = function(ev) { var e = ev || window.event, - msg = S(gettext('Are you sure you wish to close the %s browser?')).sprintf(pgBrowser.utils.app_name).value(); + msg = S(gettext('Are you sure you wish to close the %s browser?')).sprintf(pgBrowser.utils.app_name).value(); // For IE and Firefox prior to version 4 if (e) { diff --git a/web/pgadmin/browser/static/js/collection.js b/web/pgadmin/browser/static/js/collection.js index c0cb0eb4..05f0edd5 100644 --- a/web/pgadmin/browser/static/js/collection.js +++ b/web/pgadmin/browser/static/js/collection.js @@ -1,7 +1,7 @@ define([ 'sources/gettext', 'jquery', 'underscore', 'underscore.string', 'sources/pgadmin', 'backbone', 'alertify', 'backform', 'backgrid', 'sources/browser/generate_url', 'pgadmin.backform', 'pgadmin.backgrid', - 'pgadmin.browser.node' + 'pgadmin.browser.node', ], function(gettext, $, _, S, pgAdmin, Backbone, Alertify, Backform, Backgrid, generateUrl) { var pgBrowser = pgAdmin.Browser = pgAdmin.Browser || {}; @@ -13,145 +13,145 @@ define([ pgBrowser.Collection = function() {}; - _.extend( - pgBrowser.Collection, - _.clone(pgBrowser.Node), { - /////// - // Initialization function - // Generally - used to register the menus for this type of node. - // - // Also, look at pgAdmin.Browser.add_menus(...) function. - // - // Collection will not have 'Properties' menu. - // - // NOTE: Override this for each node for initialization purpose - Init: function() { - if (this.node_initialized) - return; - this.node_initialized = true; - pgAdmin.Browser.add_menus([{ - name: 'refresh', node: this.type, module: this, - applies: ['object', 'context'], callback: 'refresh', - priority: 1, label: gettext('Refresh...'), - icon: 'fa fa-refresh' - }]); + _.extend( + pgBrowser.Collection, + _.clone(pgBrowser.Node), { + /////// + // Initialization function + // Generally - used to register the menus for this type of node. + // + // Also, look at pgAdmin.Browser.add_menus(...) function. + // + // Collection will not have 'Properties' menu. + // + // NOTE: Override this for each node for initialization purpose + Init: function() { + if (this.node_initialized) + return; + this.node_initialized = true; + pgAdmin.Browser.add_menus([{ + name: 'refresh', node: this.type, module: this, + applies: ['object', 'context'], callback: 'refresh', + priority: 1, label: gettext('Refresh...'), + icon: 'fa fa-refresh', + }]); - // show query tool only in context menu of supported nodes. - if (pgAdmin.DataGrid && pgAdmin.unsupported_nodes) { - if (_.indexOf(pgAdmin.unsupported_nodes, this.type) == -1) { - pgAdmin.Browser.add_menus([{ - name: 'show_query_tool', node: this.type, module: this, - applies: ['context'], callback: 'show_query_tool', - priority: 998, label: gettext('Query Tool...'), - icon: 'fa fa-bolt' - }]); + // show query tool only in context menu of supported nodes. + if (pgAdmin.DataGrid && pgAdmin.unsupported_nodes) { + if (_.indexOf(pgAdmin.unsupported_nodes, this.type) == -1) { + pgAdmin.Browser.add_menus([{ + name: 'show_query_tool', node: this.type, module: this, + applies: ['context'], callback: 'show_query_tool', + priority: 998, label: gettext('Query Tool...'), + icon: 'fa fa-bolt', + }]); + } } - } - }, - hasId: false, - is_collection: true, - collection_node: true, - // A collection will always have a collection of statistics, when the node - // it represent will have some statistics. - hasCollectiveStatistics: true, - showProperties: function(item, data, panel) { - var that = this, - j = panel.$container.find('.obj_properties').first(), - view = j.data('obj-view'), - content = $('
') + }, + hasId: false, + is_collection: true, + collection_node: true, + // A collection will always have a collection of statistics, when the node + // it represent will have some statistics. + hasCollectiveStatistics: true, + showProperties: function(item, data, panel) { + var that = this, + j = panel.$container.find('.obj_properties').first(), + view = j.data('obj-view'), + content = $('
') .addClass('pg-prop-content col-xs-12'), - node = pgBrowser.Nodes[that.node], - // This will be the URL, used for object manipulation. - urlBase = this.generate_url(item, 'properties', data), - collection = new (node.Collection.extend({ - url: urlBase, - model: node.model - }))(), - info = this.getTreeNodeHierarchy.apply(this, [item]), - gridSchema = Backform.generateGridColumnsFromModel( + node = pgBrowser.Nodes[that.node], + // This will be the URL, used for object manipulation. + urlBase = this.generate_url(item, 'properties', data), + collection = new (node.Collection.extend({ + url: urlBase, + model: node.model, + }))(), + info = this.getTreeNodeHierarchy.apply(this, [item]), + gridSchema = Backform.generateGridColumnsFromModel( info, node.model, 'properties', that.columns ), - // Initialize a new Grid instance - grid = new Backgrid.Grid({ - columns: gridSchema.columns, - collection: collection, - className: "backgrid table-bordered" - }), - gridView = { - 'remove': function() { - if (this.grid) { - if (this.grid.collection) { - this.grid.collection.reset(null, {silent: true}); - delete (this.grid.collection); + // Initialize a new Grid instance + grid = new Backgrid.Grid({ + columns: gridSchema.columns, + collection: collection, + className: 'backgrid table-bordered', + }), + gridView = { + 'remove': function() { + if (this.grid) { + if (this.grid.collection) { + this.grid.collection.reset(null, {silent: true}); + delete (this.grid.collection); + } + delete (this.grid); + this.grid = null; } - delete (this.grid); - this.grid = null; - } - }, - grid: grid - }; + }, + grid: grid, + }; - if (view) { - // Avoid unnecessary reloads - if (_.isEqual($(panel).data('node-prop'), urlBase)) { - return; - } + if (view) { + // Avoid unnecessary reloads + if (_.isEqual($(panel).data('node-prop'), urlBase)) { + return; + } - // Cache the current IDs for next time - $(panel).data('node-prop', urlBase); + // Cache the current IDs for next time + $(panel).data('node-prop', urlBase); - // Reset the data object - j.data('obj-view', null); - } + // Reset the data object + j.data('obj-view', null); + } - // Make sure the HTML element is empty. - j.empty(); - j.data('obj-view', gridView); + // Make sure the HTML element is empty. + j.empty(); + j.data('obj-view', gridView); - // Render subNode grid - content.append(grid.render().$el); - j.append(content); + // Render subNode grid + content.append(grid.render().$el); + j.append(content); - // Fetch Data - collection.fetch({ - reset: true, - error: function(xhr, error, message) { - pgBrowser.Events.trigger( - 'pgadmin:collection:retrieval:error', 'properties', xhr, error, message, item, that - ); - if ( - !Alertify.pgHandleItemError(xhr, error, message, {item: item, info: info}) - ) { - Alertify.pgNotifier( - error, xhr, - S( - gettext("Error retrieving properties - %s.") - ).sprintf(message || that.label).value(), - function() { - console.log(arguments); - } + // Fetch Data + collection.fetch({ + reset: true, + error: function(xhr, error, message) { + pgBrowser.Events.trigger( + 'pgadmin:collection:retrieval:error', 'properties', xhr, error, + message, item, that ); - } - } - }) - }, - generate_url: function(item, type) { - /* - * Using list, and collection functions of a node to get the nodes - * under the collection, and properties of the collection respectively. - */ - var opURL = { - 'properties': 'obj', 'children': 'nodes', - }, - self = this; - var collectionPickFunction = function (treeInfoValue, treeInfoKey) { - return (treeInfoKey != self.type); - }; - var treeInfo = this.getTreeNodeHierarchy(item); - var actionType = type in opURL ? opURL[type] : type; - return generateUrl.generate_url(pgAdmin.Browser.URL, treeInfo, actionType, self.node, collectionPickFunction); - }, - }); + if (!Alertify.pgHandleItemError( + xhr, error, message, {item: item, info: info} + )) { + Alertify.pgNotifier(error, xhr, S( + gettext('Error retrieving properties - %s.') + ).sprintf(message || that.label).value(), function() { + console.warn(arguments); + }); + } + }, + }); + }, + generate_url: function(item, type) { + /* + * Using list, and collection functions of a node to get the nodes + * under the collection, and properties of the collection respectively. + */ + var opURL = { + 'properties': 'obj', 'children': 'nodes', + }, + self = this; + var collectionPickFunction = function (treeInfoValue, treeInfoKey) { + return (treeInfoKey != self.type); + }; + var treeInfo = this.getTreeNodeHierarchy(item); + var actionType = type in opURL ? opURL[type] : type; + return generateUrl.generate_url( + pgAdmin.Browser.URL, treeInfo, actionType, self.node, + collectionPickFunction + ); + }, + }); return pgBrowser.Collection; }); diff --git a/web/pgadmin/browser/static/js/datamodel.js b/web/pgadmin/browser/static/js/datamodel.js index 9545b87f..b20bf118 100644 --- a/web/pgadmin/browser/static/js/datamodel.js +++ b/web/pgadmin/browser/static/js/datamodel.js @@ -1,1283 +1,1304 @@ -define( - ['underscore', 'underscore.string', 'sources/pgadmin', 'jquery', 'backbone'], -function(_, S, pgAdmin, $, Backbone) { +define([ + 'underscore', 'underscore.string', 'sources/pgadmin', 'jquery', 'backbone', +], function(_, S, pgAdmin, $, Backbone) { var pgBrowser = pgAdmin.Browser = pgAdmin.Browser || {}; pgBrowser.DataModel = Backbone.Model.extend({ - /* - * Parsing the existing data - */ - on_server: false, - parse: function(res) { - var self = this; - if (res && _.isObject(res) && 'node' in res && res['node']) { - self.tnode = _.extend({}, res.node); - delete res.node; - } - var objectOp = function(schema) { - if (schema && _.isArray(schema)) { - _.each(schema, function(s) { - var obj, val; - switch(s.type) { - case 'collection': - obj = self.get(s.id); - val = res[s.id]; - if (_.isArray(val) || _.isObject(val)) { - if (!obj || !(obj instanceof Backbone.Collection)) { - obj = new (pgBrowser.Node.Collection)(val, { - model: ((_.isString(s.model) && - s.model in pgBrowser.Nodes) ? - pgBrowser.Nodes[s.model].model : s.model), - top: self.top || self, - handler: self, - parse: true, - silent: true, - attrName: s.id - }); - - /* - * Nested collection models may or may not have idAttribute. - * So to decide whether model is new or not set 'on_server' - * flag on such models. - */ - - self.set(s.id, obj, {silent: true, parse: true, on_server : true}); - } else { - /* - * Nested collection models may or may not have idAttribute. - * So to decide whether model is new or not set 'on_server' - * flag on such models. - */ - obj.reset(val, {silent: true, parse: true, on_server : true}); - } - } - else { - obj = null; - } - self.set(s.id, obj, {silent: true}); - res[s.id] = obj; - break; - case 'model': - obj = self.get(s.id); - val = res[s.id]; - if (!_.isUndefined(val) && !_.isNull(val)) { - if (!obj || !(obj instanceof Backbone.Model)) { - if (_.isString(s.model) && - s.model in pgBrowser.Nodes[s.model]) { - obj = new (pgBrowser.Nodes[s.model].Model)( - obj, { - silent: true, top: self.top || self, handler: self, - attrName: s.id - } - ); - } else { - obj = new (s.model)(obj, { - silent: true, top: self.top || self, handler: self, - attrName: s.id - }); - } - } - obj.set(val, {parse: true, silent: true}); + /* + * Parsing the existing data + */ + on_server: false, + parse: function(res) { + var self = this; + if (res && _.isObject(res) && 'node' in res && res['node']) { + self.tnode = _.extend({}, res.node); + delete res.node; + } + var objectOp = function(schema) { + if (schema && _.isArray(schema)) { + _.each(schema, function(s) { + var obj, val; + switch (s.type) { + case 'collection': + obj = self.get(s.id); + val = res[s.id]; + if (_.isArray(val) || _.isObject(val)) { + if (!obj || !(obj instanceof Backbone.Collection)) { + obj = new(pgBrowser.Node.Collection)(val, { + model: ((_.isString(s.model) && + s.model in pgBrowser.Nodes) ? + pgBrowser.Nodes[s.model].model : s.model), + top: self.top || self, + handler: self, + parse: true, + silent: true, + attrName: s.id, + }); + + /* + * Nested collection models may or may not have idAttribute. + * So to decide whether model is new or not set 'on_server' + * flag on such models. + */ + + self.set(s.id, obj, { + silent: true, + parse: true, + on_server: true, + }); + } else { + /* + * Nested collection models may or may not have idAttribute. + * So to decide whether model is new or not set 'on_server' + * flag on such models. + */ + obj.reset(val, { + silent: true, + parse: true, + on_server: true, + }); + } + } else { + obj = null; + } + self.set(s.id, obj, { + silent: true, + }); + res[s.id] = obj; + break; + case 'model': + obj = self.get(s.id); + val = res[s.id]; + if (!_.isUndefined(val) && !_.isNull(val)) { + if (!obj || !(obj instanceof Backbone.Model)) { + if (_.isString(s.model) && + s.model in pgBrowser.Nodes[s.model]) { + obj = new(pgBrowser.Nodes[s.model].Model)( + obj, { + silent: true, + top: self.top || self, + handler: self, + attrName: s.id, + } + ); } else { - obj = null; + obj = new(s.model)(obj, { + silent: true, + top: self.top || self, + handler: self, + attrName: s.id, + }); } - res[s.id] = obj; - break; - case 'nested': - objectOp(s.schema); - - break; - default: - break; + } + obj.set(val, { + parse: true, + silent: true, + }); + } else { + obj = null; } - }); - } - }; + res[s.id] = obj; + break; + case 'nested': + objectOp(s.schema); + + break; + default: + break; + } + }); + } + }; - objectOp(self.schema); + objectOp(self.schema); - return res; - }, - isNew: function() { - if (this.has(this.idAttribute)) { - return !this.has(this.idAttribute); - } - return !this.on_server; - }, - primary_key: function() { - if (this.keys && _.isArray(this.keys)) { - var res = {}, self = this; - - _.each(self.keys, function(k) { - res[k] = self.attributes[k]; - }); + return res; + }, + isNew: function() { + if (this.has(this.idAttribute)) { + return !this.has(this.idAttribute); + } + return !this.on_server; + }, + primary_key: function() { + if (this.keys && _.isArray(this.keys)) { + var res = {}, + self = this; + + _.each(self.keys, function(k) { + res[k] = self.attributes[k]; + }); - return JSON.stringify(res); - } - return this.cid; - }, - initialize: function(attributes, options) { - var self = this; - self._previous_key_values = {}; - - if (!_.isUndefined(options) && 'on_server' in options && options.on_server) { - self.on_server = true; - } + return JSON.stringify(res); + } + return this.cid; + }, + initialize: function(attributes, options) { + var self = this; + self._previous_key_values = {}; + + if (!_.isUndefined(options) && 'on_server' in options && options.on_server) { + self.on_server = true; + } - Backbone.Model.prototype.initialize.apply(self, arguments); + Backbone.Model.prototype.initialize.apply(self, arguments); - if (_.isUndefined(options) || _.isNull(options)) { - options = attributes || {}; - attributes = null; - } + if (_.isUndefined(options) || _.isNull(options)) { + options = attributes || {}; + attributes = null; + } - self.sessAttrs = {}; - self.fieldData = {}; - self.origSessAttrs = {}; - self.objects = []; - self.arrays = []; - self.attrName = options.attrName, + self.sessAttrs = {}; + self.fieldData = {}; + self.origSessAttrs = {}; + self.objects = []; + self.arrays = []; + self.attrName = options.attrName, self.top = (options.top || self.collection && self.collection.top || self.collection || self); - self.handler = options.handler || - (self.collection && self.collection.handler); - self.trackChanges = false; - self.errorModel = new Backbone.Model(); - self.node_info = options.node_info; - - var obj; - var objectOp = function(schema) { - if (schema && _.isArray(schema)) { - _.each(schema, function(s) { - - switch(s.type) { - case 'int': - case 'numeric': - self.fieldData[s.id] = { - id: s.id, - label: s.label, - type: s.type, - min: s.min || undefined, - max: s.max || undefined - } - break; - default: - self.fieldData[s.id] = { - id: s.id, - label: s.label, - type: s.type - } + self.handler = options.handler || + (self.collection && self.collection.handler); + self.trackChanges = false; + self.errorModel = new Backbone.Model(); + self.node_info = options.node_info; + + var obj; + var objectOp = function(schema) { + if (schema && _.isArray(schema)) { + _.each(schema, function(s) { + + switch (s.type) { + case 'int': + case 'numeric': + self.fieldData[s.id] = { + id: s.id, + label: s.label, + type: s.type, + min: s.min || undefined, + max: s.max || undefined, + }; + break; + default: + self.fieldData[s.id] = { + id: s.id, + label: s.label, + type: s.type, + }; + } + + switch (s.type) { + case 'array': + self.arrays.push(s.id); + + break; + case 'collection': + obj = self.get(s.id); + if (!obj || !(obj instanceof pgBrowser.Node.Collection)) { + if (_.isString(s.model) && + s.model in pgBrowser.Nodes) { + var node = pgBrowser.Nodes[s.model]; + obj = new(node.Collection)(obj, { + model: node.model, + top: self.top || self, + handler: self, + attrName: s.id, + }); + } else { + obj = new(pgBrowser.Node.Collection)(obj, { + model: s.model, + top: self.top || self, + handler: self, + attrName: s.id, + }); + } } - switch(s.type) { - case 'array': - self.arrays.push(s.id); - - break; - case 'collection': - obj = self.get(s.id) - if (!obj || !(obj instanceof pgBrowser.Node.Collection)) { - if (_.isString(s.model) && - s.model in pgBrowser.Nodes) { - var node = pgBrowser.Nodes[s.model]; - obj = new (node.Collection)(obj, { - model: node.model, + obj.name = s.id; + self.objects.push(s.id); + self.set(s.id, obj, { + silent: true, + }); + + break; + case 'model': + obj = self.get(s.id); + if (!obj || !(obj instanceof Backbone.Model)) { + if (_.isString(s.model) && + s.model in pgBrowser.Nodes[s.model]) { + obj = new(pgBrowser.Nodes[s.model].Model)( + obj, { top: self.top || self, handler: self, - attrName: s.id - }); - } else { - obj = new (pgBrowser.Node.Collection)(obj, { - model: s.model, + attrName: s.id, + } + ); + } else { + obj = new(s.model)( + obj, { top: self.top || self, handler: self, - attrName: s.id + attrName: s.id, }); - } - } + } + } - obj.name = s.id; - self.objects.push(s.id); - self.set(s.id, obj, {silent: true}); - - break; - case 'model': - obj = self.get(s.id) - if (!obj || !(obj instanceof Backbone.Model)) { - if (_.isString(s.model) && - s.model in pgBrowser.Nodes[s.model]) { - obj = new (pgBrowser.Nodes[s.model].Model)( - obj, { - top: self.top || self, handler: self, attrName: s.id - } - ); - } else { - obj = new (s.model)( - obj, { - top: self.top || self, handler: self, attrName: s.id - }); - } - } + obj.name = s.id; + self.objects.push(s.id); + self.set(s.id, obj, { + silent: true, + }); - obj.name = s.id; - self.objects.push(s.id); - self.set(s.id, obj, {silent: true}); + break; + case 'nested': + objectOp(s.schema); + break; + default: + return; + } + }); + } + }; + objectOp(self.schema); - break; - case 'nested': - objectOp(s.schema); - break; - default: - return; - } - }); - } - }; - objectOp(self.schema); + if (self.handler && self.handler.trackChanges) { + self.startNewSession(); + } - if (self.handler && self.handler.trackChanges) { - self.startNewSession(); - } + if ('keys' in self && _.isArray(self.keys)) { + _.each(self.keys, function(key) { + self.on('change:' + key, function(m) { + self._previous_key_values[key] = m.previous(key); + }); + }); + } + return self; + }, + // Create a reset function, which allow us to remove the nested object. + reset: function(opts) { + var obj; - if ('keys' in self && _.isArray(self.keys)) { - _.each(self.keys, function(key) { - self.on("change:" + key, function(m) { - self._previous_key_values[key] = m.previous(key); - }) - }) - } - return self; - }, - // Create a reset function, which allow us to remove the nested object. - reset: function(opts) { - var obj; - - if (opts && opts.stop) - this.stopSession(); - - for(var id in this.objects) { - obj = this.get(id); - - if (obj) { - if (obj instanceof pgBrowser.DataModel) { - obj.reset(opts); - } else if (obj instanceof Backbone.Model) { - obj.clear(opts); - } else if (obj instanceof pgBrowser.DataCollection) { - obj.reset(opts); - } else if (obj instanceof Backbone.Collection) { - obj.each(function(m) { - if (m instanceof Backbone.DataModel) { - obj.reset(); - obj.clear(opts); - } - }); - if (!(opts instanceof Array)){ opts = [opts] } - Backbone.Collection.prototype.reset.apply(obj, opts); + if (opts && opts.stop) + this.stopSession(); + + for (var id in this.objects) { + obj = this.get(id); + + if (obj) { + if (obj instanceof pgBrowser.DataModel) { + obj.reset(opts); + } else if (obj instanceof Backbone.Model) { + obj.clear(opts); + } else if (obj instanceof pgBrowser.DataCollection) { + obj.reset(opts); + } else if (obj instanceof Backbone.Collection) { + obj.each(function(m) { + if (m instanceof Backbone.DataModel) { + obj.reset(); + obj.clear(opts); + } + }); + if (!(opts instanceof Array)) { + opts = [opts]; } + Backbone.Collection.prototype.reset.apply(obj, opts); } } - this.clear(opts); - }, - sessChanged: function() { - var self = this; - - return (_.size(self.sessAttrs) > 0 || - _.some(self.objects, function(k) { - var obj = self.get(k); - if (!(_.isNull(obj) || _.isUndefined(obj))) { - return obj.sessChanged(); - } - return false; - })); - }, - sessValid: function() { - var self = this; - // Perform default validations. - if ('default_validate' in self && typeof(self.default_validate) == 'function' && - _.isString(self.default_validate())) { - return false; - } - - if ('validate' in self && _.isFunction(self.validate) && - _.isString(self.validate.apply(self))) { + } + this.clear(opts); + }, + sessChanged: function() { + var self = this; + + return (_.size(self.sessAttrs) > 0 || + _.some(self.objects, function(k) { + var obj = self.get(k); + if (!(_.isNull(obj) || _.isUndefined(obj))) { + return obj.sessChanged(); + } return false; - } - return true; - }, - set: function(key, val, options) { - var opts = _.isObject(key) ? val : options; + })); + }, + sessValid: function() { + var self = this; + // Perform default validations. + if ('default_validate' in self && typeof(self.default_validate) == 'function' && + _.isString(self.default_validate())) { + return false; + } - this._changing = true; - this._previousAttributes = _.clone(this.attributes); - this.changed = {}; + if ('validate' in self && _.isFunction(self.validate) && + _.isString(self.validate.apply(self))) { + return false; + } + return true; + }, + set: function(key, val, options) { + var opts = _.isObject(key) ? val : options; - var res = Backbone.Model.prototype.set.call(this, key, val, options); - this._changing = false; + this._changing = true; + this._previousAttributes = _.clone(this.attributes); + this.changed = {}; - if ((opts&& opts.internal) || !this.trackChanges) { - return true; - } + var res = Backbone.Model.prototype.set.call(this, key, val, options); + this._changing = false; - if (key != null && res) { - var attrs = {}, - self = this, - msg; + if ((opts && opts.internal) || !this.trackChanges) { + return true; + } - var attrChanged = function(v, k) { - if (k in self.objects) { - return; - } - attrs[k] = v; - if (_.isEqual(self.origSessAttrs[k], v)) { - delete self.sessAttrs[k]; - } else { - self.sessAttrs[k] = v; - } - }; + if (key != null && res) { + var attrs = {}, + self = this, + msg; - // Handle both `"key", value` and `{key: value}` -style arguments. - if (typeof key === 'object') { - _.each(key, attrChanged); + var attrChanged = function(v, k) { + if (k in self.objects) { + return; + } + attrs[k] = v; + if (_.isEqual(self.origSessAttrs[k], v)) { + delete self.sessAttrs[k]; } else { - attrChanged(val, key); + self.sessAttrs[k] = v; } + }; - self.trigger('pgadmin-session:set', self, attrs); - if (!options || !options.silent) { - self.trigger('change', self, options); - } + // Handle both `"key", value` and `{key: value}` -style arguments. + if (typeof key === 'object') { + _.each(key, attrChanged); + } else { + attrChanged(val, key); + } - // Perform default validations. + self.trigger('pgadmin-session:set', self, attrs); + if (!options || !options.silent) { + self.trigger('change', self, options); + } - if ('default_validate' in self && typeof(self.default_validate) == 'function') { - msg = self.default_validate(); - } + // Perform default validations. + + if ('default_validate' in self && typeof(self.default_validate) == 'function') { + msg = self.default_validate(); + } - if ('validate' in self && typeof(self['validate']) === 'function') { + if ('validate' in self && typeof(self['validate']) === 'function') { - if (!msg) { - msg = self.validate(_.keys(attrs)); - } + if (!msg) { + msg = self.validate(_.keys(attrs)); + } + } + + /* + * If any parent present, we will need to inform the parent - that + * I have some issues/fixed the issue. + * + * If not parent found, we will raise the issue + */ + if (_.size(self.errorModel.attributes) == 0) { + if (self.collection || self.handler) { + (self.collection || self.handler).trigger( + 'pgadmin-session:model:valid', self, (self.collection || self.handler) + ); + } else { + self.trigger('pgadmin-session:valid', self.sessChanged(), self); + } + } else { + msg = msg || _.values(self.errorModel.attributes)[0]; + if (self.collection || self.handler) { + (self.collection || self.handler).trigger( + 'pgadmin-session:model:invalid', msg, self, (self.collection || self.handler) + ); + } else { + self.trigger('pgadmin-session:invalid', msg, self); } + } + + return res; + } + return res; + }, + /* + * We do support modified data only through session by tracking changes. + * + * In normal mode, we will use the toJSON function of Backbone.Model. + * In session mode, we will return all the modified data only. And, the + * objects (collection, and model) will be return as stringified JSON, + * only from the parent object. + */ + toJSON: function(session, method) { + var self = this, + res, isNew = self.isNew(); + + session = (typeof(session) != 'undefined' && session == true); + + if (!session || isNew) { + res = Backbone.Model.prototype.toJSON.call(this, arguments); + } else { + res = {}; + res[self.idAttribute || '_id'] = self.get(self.idAttribute || '_id'); + res = _.extend(res, self.sessAttrs); + } + /* + * We do have number objects (models, collections), which needs to be + * converted to JSON data manually. + */ + _.each( + self.objects, + function(k) { + var obj = self.get(k); /* - * If any parent present, we will need to inform the parent - that - * I have some issues/fixed the issue. - * - * If not parent found, we will raise the issue + * For session changes, we only need the modified data to be + * transformed to JSON data. */ - if (_.size(self.errorModel.attributes) == 0) { - if (self.collection || self.handler) { - (self.collection || self.handler).trigger( - 'pgadmin-session:model:valid', self, (self.collection || self.handler) - ); - } else { - self.trigger('pgadmin-session:valid', self.sessChanged(), self); + if (session) { + if (res[k] instanceof Array) { + res[k] = JSON.stringify(res[k]); + } else if ((obj && obj.sessChanged && obj.sessChanged()) || isNew) { + res[k] = obj && obj.toJSON(!isNew); + /* + * We will run JSON.stringify(..) only from the main object, + * not for the JSON object within the objects, that only when + * HTTP method is 'GET'. + * + * We do stringify the object, so that - it will not be + * translated to wierd format using jQuery. + */ + if (obj && method && method == 'GET') { + res[k] = JSON.stringify(res[k]); } } else { - msg = msg || _.values(self.errorModel.attributes)[0]; - if (self.collection || self.handler) { - (self.collection || self.handler).trigger( - 'pgadmin-session:model:invalid', msg, self, (self.collection || self.handler) - ); - } else { - self.trigger('pgadmin-session:invalid', msg, self); - } + delete res[k]; } + } else if (!(res[k] instanceof Array)) { + res[k] = (obj && obj.toJSON()); + } + }); + if (session) { + _.each( + self.arrays, + function(a) { + /* + * For session changes, we only need the modified data to be + * transformed to JSON data. + */ + if (res[a] && res[a] instanceof Array) { + res[a] = JSON.stringify(res[a]); + } + }); + } + return res; + }, + startNewSession: function() { + var self = this; + + if (self.trackChanges) { + self.trigger('pgadmin-session:stop', self); + self.off('pgadmin-session:model:invalid', self.onChildInvalid); + self.off('pgadmin-session:model:valid', self.onChildValid); + self.off('pgadmin-session:changed', self.onChildChanged); + self.off('pgadmin-session:added', self.onChildChanged); + self.off('pgadmin-session:removed', self.onChildChanged); + } - return res; - } - return res; - }, - /* - * We do support modified data only through session by tracking changes. - * - * In normal mode, we will use the toJSON function of Backbone.Model. - * In session mode, we will return all the modified data only. And, the - * objects (collection, and model) will be return as stringified JSON, - * only from the parent object. - */ - toJSON: function(session, method) { - var self = this, res, isNew = self.isNew(); - - session = (typeof(session) != "undefined" && session == true); + self.trackChanges = true; + self.sessAttrs = {}; + self.origSessAttrs = _.clone(self.attributes); - if (!session || isNew) { - res = Backbone.Model.prototype.toJSON.call(this, arguments); - } else { - res = {}; - res[self.idAttribute || '_id'] = self.get(self.idAttribute || '_id'); - res = _.extend(res, self.sessAttrs); - } + _.each(self.objects, function(o) { + var obj = self.get(o); - /* - * We do have number objects (models, collections), which needs to be - * converted to JSON data manually. - */ - _.each( - self.objects, - function(k) { - var obj = self.get(k); - /* - * For session changes, we only need the modified data to be - * transformed to JSON data. - */ - if (session) { - if (res[k] instanceof Array) { - res[k] = JSON.stringify(res[k]); - } else if ((obj && obj.sessChanged && obj.sessChanged()) || isNew) { - res[k] = obj && obj.toJSON(!isNew); - /* - * We will run JSON.stringify(..) only from the main object, - * not for the JSON object within the objects, that only when - * HTTP method is 'GET'. - * - * We do stringify the object, so that - it will not be - * translated to wierd format using jQuery. - */ - if (obj && method && method == 'GET') { - res[k] = JSON.stringify(res[k]); - } - } else { - delete res[k]; - } - } else if (!(res[k] instanceof Array)) { - res[k] = (obj && obj.toJSON()); - } - }); - if (session) { - _.each( - self.arrays, - function(a) { - /* - * For session changes, we only need the modified data to be - * transformed to JSON data. - */ - if (res[a] && res[a] instanceof Array) { - res[a] = JSON.stringify(res[a]); - } - }); - } - return res; - }, - startNewSession: function() { - var self = this; - - if (self.trackChanges) { - self.trigger('pgadmin-session:stop', self); - self.off('pgadmin-session:model:invalid', self.onChildInvalid); - self.off('pgadmin-session:model:valid', self.onChildValid); - self.off('pgadmin-session:changed', self.onChildChanged); - self.off('pgadmin-session:added', self.onChildChanged); - self.off('pgadmin-session:removed', self.onChildChanged); + if (_.isUndefined(obj) || _.isNull(obj)) { + return; } - self.trackChanges = true; - self.sessAttrs = {}; - self.origSessAttrs = _.clone(self.attributes); + delete self.origSessAttrs[o]; - var res = false; - - _.each(self.objects, function(o) { - var obj = self.get(o); + if (obj && 'startNewSession' in obj && _.isFunction(obj.startNewSession)) { + obj.startNewSession(); + } + }); + + // Let people know, I have started session hanlding + self.trigger('pgadmin-session:start', self); + + // Let me listen to the my child invalid/valid messages + self.on('pgadmin-session:model:invalid', self.onChildInvalid); + self.on('pgadmin-session:model:valid', self.onChildValid); + self.on('pgadmin-session:changed', self.onChildChanged); + self.on('pgadmin-session:added', self.onChildChanged); + self.on('pgadmin-session:removed', self.onChildChanged); + }, + + onChildInvalid: function(msg, obj) { + var self = this; + + if (self.trackChanges && obj) { + var objName = obj.attrName; + + if (!objName) { + var hasPrimaryKey = obj.primary_key && + typeof(obj.primary_key) === 'function'; + var key = hasPrimaryKey ? obj.primary_key() : obj.cid, + comparator = hasPrimaryKey ? + function(k) { + var o = self.get('k'); - if (_.isUndefined(obj) || _.isNull(obj)) { - return; - } + if (o && o.primary_key() === key) { + objName = k; + return true; + } - delete self.origSessAttrs[o]; + return false; + } : + function(k) { + var o = self.get(k); - if (obj && 'startNewSession' in obj && _.isFunction(obj.startNewSession)) { - obj.startNewSession(); - } - }); + if (o.cid === key) { + objName = k; + return true; + } - // Let people know, I have started session hanlding - self.trigger('pgadmin-session:start', self); - - // Let me listen to the my child invalid/valid messages - self.on('pgadmin-session:model:invalid', self.onChildInvalid); - self.on('pgadmin-session:model:valid', self.onChildValid); - self.on('pgadmin-session:changed', self.onChildChanged); - self.on('pgadmin-session:added', self.onChildChanged); - self.on('pgadmin-session:removed', self.onChildChanged); - }, - - onChildInvalid: function(msg, obj) { - var self = this; - - if (self.trackChanges && obj) { - var objName = obj.attrName; - - if (!objName) { - var hasPrimaryKey = obj.primary_key && - typeof(obj.primary_key) === 'function'; - var key = hasPrimaryKey ? obj.primary_key() : obj.cid, - comparator = hasPrimaryKey ? - function(k) { - var o = self.get('k'); - - if (o && o.primary_key() === key) { - objName = k; - return true; - } - - return false; - } : - function(k) { - var o = self.get(k); - - if (o.cid === key) { - objName = k; - return true; - } - - return false; - }; - _.findIndex(self.objects, comparator); - } + return false; + }; + _.findIndex(self.objects, comparator); + } - if (objName) { - /* - * Update the error message for this object. - */ - self.errorModel.set(objName, msg); + if (objName) { + /* + * Update the error message for this object. + */ + self.errorModel.set(objName, msg); - if (self.handler) { - (self.handler).trigger('pgadmin-session:model:invalid', msg, self, self.handler); - } else { - self.trigger('pgadmin-session:invalid', msg, self); - } + if (self.handler) { + (self.handler).trigger('pgadmin-session:model:invalid', msg, self, self.handler); + } else { + self.trigger('pgadmin-session:invalid', msg, self); } } + } - return this; - }, - onChildValid: function(obj) { - var self = this; - - if (self.trackChanges && obj) { - var objName = obj.attrName; - - if (!objName) { - var hasPrimaryKey = (obj.primary_key && - (typeof(obj.primary_key) === 'function')); - var key = hasPrimaryKey ? obj.primary_key() : obj.cid, - comparator = hasPrimaryKey ? - function(k) { - var o = self.get('k'); - - if (o && o.primary_key() === key) { - objName = k; - return true; - } + return this; + }, + onChildValid: function(obj) { + var self = this; - return false; - } : - function(k) { - var o = self.get('k'); + if (self.trackChanges && obj) { + var objName = obj.attrName; - if (o && o.cid === key) { - objName = k; - return true; - } + if (!objName) { + var hasPrimaryKey = (obj.primary_key && + (typeof(obj.primary_key) === 'function')); + var key = hasPrimaryKey ? obj.primary_key() : obj.cid, + comparator = hasPrimaryKey ? + function(k) { + var o = self.get('k'); - return false; - }; + if (o && o.primary_key() === key) { + objName = k; + return true; + } - _.findIndex(self.objects, comparator); - } + return false; + } : + function(k) { + var o = self.get('k'); - var msg = null, - validate = function(m, attrs) { - if ('default_validate' in m && typeof(m.default_validate) == 'function') { - msg = m.default_validate(); - if (_.isString(msg)) { - return msg; - } - } + if (o && o.cid === key) { + objName = k; + return true; + } - if ('validate' in m && typeof(m.validate) == 'function') { - msg = m.validate(attrs); + return false; + }; - return msg; - } - return null; - }; + _.findIndex(self.objects, comparator); + } - if (obj instanceof Backbone.Collection) { - for (var idx in obj.models) { - if (validate(obj.models[idx])) - break; + var msg = null, + validate = function(m, attrs) { + if ('default_validate' in m && typeof(m.default_validate) == 'function') { + msg = m.default_validate(); + if (_.isString(msg)) { + return msg; + } } - } else if (obj instanceof Backbone.Model) { - validate(obj); - } - if (objName && self.errorModel.has(objName)) { - if (!msg) { - self.errorModel.unset(objName); - } else { - self.errorModel.set(objName, msg); + if ('validate' in m && typeof(m.validate) == 'function') { + msg = m.validate(attrs); + + return msg; } + return null; + }; + + if (obj instanceof Backbone.Collection) { + for (var idx in obj.models) { + if (validate(obj.models[idx])) + break; } + } else if (obj instanceof Backbone.Model) { + validate(obj); + } - /* - * The object is valid, but does this has any effect on parent? - * Let's validate this object itself, before making it clear. - * - * We will trigger validation information. - */ - if (_.size(self.errorModel.attributes) == 0 && - !validate(self, (objName && [objName]))) { - if (self.handler) { - (self.handler).trigger('pgadmin-session:model:valid', self, self.handler); - } else { - self.trigger( - 'pgadmin-session:valid', self.sessChanged(), self - ); - } + if (objName && self.errorModel.has(objName)) { + if (!msg) { + self.errorModel.unset(objName); } else { - msg = msg || _.values(self.errorModel.attributes)[0]; - - if (self.handler) { - (self.handler).trigger( - 'pgadmin-session:model:invalid', msg, self, self.handler - ); - } else { - self.trigger('pgadmin-session:invalid', msg, self); - } + self.errorModel.set(objName, msg); } } - }, - onChildChanged: function(obj) { - var self = this; + /* + * The object is valid, but does this has any effect on parent? + * Let's validate this object itself, before making it clear. + * + * We will trigger validation information. + */ + if (_.size(self.errorModel.attributes) == 0 && + !validate(self, (objName && [objName]))) { + if (self.handler) { + (self.handler).trigger('pgadmin-session:model:valid', self, self.handler); + } else { + self.trigger( + 'pgadmin-session:valid', self.sessChanged(), self + ); + } + } else { + msg = msg || _.values(self.errorModel.attributes)[0]; - if (self.trackChanges && self.collection) { - (self.collection).trigger('change', self); + if (self.handler) { + (self.handler).trigger( + 'pgadmin-session:model:invalid', msg, self, self.handler + ); + } else { + self.trigger('pgadmin-session:invalid', msg, self); + } } - }, + } + }, - stopSession: function() { - var self = this; + onChildChanged: function() { + var self = this; - if (self.trackChanges) { - self.off('pgadmin-session:model:invalid', self.onChildInvalid); - self.off('pgadmin-session:model:valid', self.onChildValid); - self.off('pgadmin-session:changed', self.onChildChanged); - self.off('pgadmin-session:added', self.onChildChanged); - self.off('pgadmin-session:removed', self.onChildChanged); - } + if (self.trackChanges && self.collection) { + (self.collection).trigger('change', self); + } + }, - self.trackChanges = false; - self.sessAttrs = {}; - self.origSessAttrs = {}; + stopSession: function() { + var self = this; - _.each(self.objects, function(o) { - var obj = self.get(o); + if (self.trackChanges) { + self.off('pgadmin-session:model:invalid', self.onChildInvalid); + self.off('pgadmin-session:model:valid', self.onChildValid); + self.off('pgadmin-session:changed', self.onChildChanged); + self.off('pgadmin-session:added', self.onChildChanged); + self.off('pgadmin-session:removed', self.onChildChanged); + } - if (_.isUndefined(obj) || _.isNull(obj)) { - return; - } + self.trackChanges = false; + self.sessAttrs = {}; + self.origSessAttrs = {}; - self.origSessAttrs[o] = null; - delete self.origSessAttrs[o]; + _.each(self.objects, function(o) { + var obj = self.get(o); - if (obj && 'stopSession' in obj && _.isFunction(obj.stopSession)) { - obj.stopSession(); - } - }); + if (_.isUndefined(obj) || _.isNull(obj)) { + return; + } - self.trigger('pgadmin-session:stop'); - }, - default_validate: function() { - var msg, field, value, type; + self.origSessAttrs[o] = null; + delete self.origSessAttrs[o]; - for (var i = 0, keys = _.keys(this.attributes), l = keys.length; - i max_value) { - return S(pgAdmin.Browser.messages.MUST_LESS_EQ).sprintf(label, max_value).value(); - } - return null; - }, - number_validate: function (value, field) { - var pattern = new RegExp("^-?[0-9]+(\.?[0-9]*)?$"); - if (!pattern.test(value)) { - return S(pgAdmin.Browser.messages.MUST_BE_NUM).sprintf(field.label).value() - } - return this.check_min_max(value, field) - }, - integer_validate: function(value, field) { - var pattern = new RegExp("^-?[0-9]*$"); - if (!pattern.test(value)) { - return S(pgAdmin.Browser.messages.MUST_BE_INT).sprintf(field.label).value() - } - return this.check_min_max(value, field) } - }); + return null; + }, + + check_min_max: function(value, field) { + var label = field.label, + min_value = field.min, + max_value = field.max; + + if (min_value && value < min_value) { + return S(pgAdmin.Browser.messages.MUST_GR_EQ).sprintf(label, min_value).value(); + } else if (max_value && value > max_value) { + return S(pgAdmin.Browser.messages.MUST_LESS_EQ).sprintf(label, max_value).value(); + } + return null; + }, + number_validate: function(value, field) { + var pattern = new RegExp('^-?[0-9]+(\.?[0-9]*)?$'); + if (!pattern.test(value)) { + return S(pgAdmin.Browser.messages.MUST_BE_NUM).sprintf(field.label).value(); + } + return this.check_min_max(value, field); + }, + integer_validate: function(value, field) { + var pattern = new RegExp('^-?[0-9]*$'); + if (!pattern.test(value)) { + return S(pgAdmin.Browser.messages.MUST_BE_INT).sprintf(field.label).value(); + } + return this.check_min_max(value, field); + }, + }); - pgBrowser.DataCollection = Backbone.Collection.extend({ - // Model collection - initialize: function(attributes, options) { - var self = this; + pgBrowser.DataCollection = Backbone.Collection.extend({ + // Model collection + initialize: function(attributes, options) { + var self = this; - options = options || {}; - /* - * Session changes will be kept in this object. - */ - self.sessAttrs = { - 'changed': [], - 'added': [], - 'deleted': [], - 'invalid': [] - }; - self.top = options.top || self; - self.attrName = options.attrName; - self.handler = options.handler; - self.trackChanges = false; + options = options || {}; + /* + * Session changes will be kept in this object. + */ + self.sessAttrs = { + 'changed': [], + 'added': [], + 'deleted': [], + 'invalid': [], + }; + self.top = options.top || self; + self.attrName = options.attrName; + self.handler = options.handler; + self.trackChanges = false; - /* - * Listen to the model changes for the session changes. - */ - self.on('add', self.onModelAdd); - self.on('remove', self.onModelRemove); - self.on('change', self.onModelChange); + /* + * Listen to the model changes for the session changes. + */ + self.on('add', self.onModelAdd); + self.on('remove', self.onModelRemove); + self.on('change', self.onModelChange); - /* - * We need to start the session, if the handler is already in session - * tracking mode. - */ - if (self.handler && self.handler.trackChanges) { - self.startNewSession(); - } + /* + * We need to start the session, if the handler is already in session + * tracking mode. + */ + if (self.handler && self.handler.trackChanges) { + self.startNewSession(); + } - return self; - }, - startNewSession: function() { - var self = this, - msg; + return self; + }, + startNewSession: function() { + var self = this, + msg; - if (self.trackChanges) { - // We're stopping the existing session. - self.trigger('pgadmin-session:stop', self); + if (self.trackChanges) { + // We're stopping the existing session. + self.trigger('pgadmin-session:stop', self); - self.off('pgadmin-session:model:invalid', self.onModelInvalid); - self.off('pgadmin-session:model:valid', self.onModelValid); - } + self.off('pgadmin-session:model:invalid', self.onModelInvalid); + self.off('pgadmin-session:model:valid', self.onModelValid); + } - self.trackChanges = true; - self.sessAttrs = { - 'changed': [], - 'added': [], - 'deleted': [], - 'invalid': [] - }; + self.trackChanges = true; + self.sessAttrs = { + 'changed': [], + 'added': [], + 'deleted': [], + 'invalid': [], + }; + + _.each(self.models, function(m) { + if ('startNewSession' in m && _.isFunction(m.startNewSession)) { + m.startNewSession(); + } - _.each(self.models, function(m) { - if ('startNewSession' in m && _.isFunction(m.startNewSession)) { - m.startNewSession(); - } + if ('default_validate' in m && typeof(m.default_validate) == 'function') { + msg = m.default_validate(); + } - if ('default_validate' in m && typeof(m.default_validate) == 'function') { - msg = m.default_validate(); - } + if (_.isString(msg)) { + self.sessAttrs['invalid'][m.cid] = msg; + } else if ('validate' in m && typeof(m.validate) === 'function') { + msg = m.validate(); - if (_.isString(msg)) { + if (msg) { self.sessAttrs['invalid'][m.cid] = msg; - } else if ('validate' in m && typeof(m.validate) === 'function') { - msg = m.validate(); - - if (msg) { - self.sessAttrs['invalid'][m.cid] = msg; - } } - }); + } + }); - // Let people know, I have started session hanlding - self.trigger('pgadmin-session:start', self); + // Let people know, I have started session hanlding + self.trigger('pgadmin-session:start', self); - self.on('pgadmin-session:model:invalid', self.onModelInvalid); - self.on('pgadmin-session:model:valid', self.onModelValid); - }, - onModelInvalid: function(msg, m) { - var self = this, - invalidModels = self.sessAttrs['invalid']; + self.on('pgadmin-session:model:invalid', self.onModelInvalid); + self.on('pgadmin-session:model:valid', self.onModelValid); + }, + onModelInvalid: function(msg, m) { + var self = this, + invalidModels = self.sessAttrs['invalid']; - if (self.trackChanges) { - // Do not add the existing invalid object - invalidModels[m.cid] = msg; + if (self.trackChanges) { + // Do not add the existing invalid object + invalidModels[m.cid] = msg; - // Inform the parent that - I am an invalid model. - if (self.handler) { - (self.handler).trigger('pgadmin-session:model:invalid', msg, self, self.handler); - } else { - self.trigger('pgadmin-session:invalid', msg, self); - } + // Inform the parent that - I am an invalid model. + if (self.handler) { + (self.handler).trigger('pgadmin-session:model:invalid', msg, self, self.handler); + } else { + self.trigger('pgadmin-session:invalid', msg, self); } + } - return true; - }, - onModelValid: function(m) { - var self = this, - invalidModels = self.sessAttrs['invalid']; - - if (self.trackChanges) { - // Now check uniqueness of current model with other models. - var isUnique = self.checkDuplicateWithModel(m); + return true; + }, + onModelValid: function(m) { + var self = this, + invalidModels = self.sessAttrs['invalid']; - // If unique then find the object the invalid list, if found remove it from the list - // and inform the parent that - I am a valid object now. + if (self.trackChanges) { + // Now check uniqueness of current model with other models. + var isUnique = self.checkDuplicateWithModel(m); - if (isUnique && m.cid in invalidModels) { - delete invalidModels[m.cid]; - } + // If unique then find the object the invalid list, if found remove it from the list + // and inform the parent that - I am a valid object now. - if (isUnique) { - this.triggerValidationEvent.apply(this); - } + if (isUnique && m.cid in invalidModels) { + delete invalidModels[m.cid]; } - return true; - }, - stopSession: function() { - var self = this; - - self.trackChanges = false; - self.sessAttrs = { - 'changed': [], - 'added': [], - 'deleted': [], - 'invalid': [] - }; + if (isUnique) { + this.triggerValidationEvent.apply(this); + } + } - _.each(self.models, function(m) { - if ('stopSession' in m && _.isFunction(m.stopSession)) { - m.stopSession(); - } + return true; + }, + stopSession: function() { + var self = this; + + self.trackChanges = false; + self.sessAttrs = { + 'changed': [], + 'added': [], + 'deleted': [], + 'invalid': [], + }; + + _.each(self.models, function(m) { + if ('stopSession' in m && _.isFunction(m.stopSession)) { + m.stopSession(); + } + }); + }, + sessChanged: function() { + return ( + this.sessAttrs['changed'].length > 0 || + this.sessAttrs['added'].length > 0 || + this.sessAttrs['deleted'].length > 0 + ); + }, + /* + * We do support the changes through session tracking in general. + * + * In normal mode, we will use the general toJSON(..) function of + * Backbone.Colletion. + * + * In session mode, we will return session changes as: + * We will be returning the session changes as: + * { + * 'added': [JSON of each new model], + * 'delete': [JSON of each deleted model], + * 'changed': [JSON of each modified model with session changes] + * } + */ + toJSON: function(session) { + var self = this; + session = (typeof(session) != 'undefined' && session == true); + + if (!session) { + return Backbone.Collection.prototype.toJSON.call(self); + } else { + var res = {}; + + res['added'] = []; + _.each(this.sessAttrs['added'], function(o) { + res['added'].push(o.toJSON()); }); - }, - sessChanged: function() { - return ( - this.sessAttrs['changed'].length > 0 || - this.sessAttrs['added'].length > 0 || - this.sessAttrs['deleted'].length > 0 - ); - }, - /* - * We do support the changes through session tracking in general. - * - * In normal mode, we will use the general toJSON(..) function of - * Backbone.Colletion. - * - * In session mode, we will return session changes as: - * We will be returning the session changes as: - * { - * 'added': [JSON of each new model], - * 'delete': [JSON of each deleted model], - * 'changed': [JSON of each modified model with session changes] - * } - */ - toJSON: function(session) { - var self = this, - session = (typeof(session) != "undefined" && session == true); + if (res['added'].length == 0) { + delete res['added']; + } + res['changed'] = []; + _.each(self.sessAttrs['changed'], function(o) { + res['changed'].push(o.toJSON(true)); + }); + if (res['changed'].length == 0) { + delete res['changed']; + } + res['deleted'] = []; + _.each(self.sessAttrs['deleted'], function(o) { + res['deleted'].push(o.toJSON()); + }); + if (res['deleted'].length == 0) { + delete res['deleted']; + } - if (!session) { - return Backbone.Collection.prototype.toJSON.call(self); + return (_.size(res) == 0 ? null : res); + } + }, + // Override the reset function, so that - we can reset the model + // properly. + reset: function(opts) { + if (opts && opts.stop) + this.stopSession(); + this.each(function(m) { + if (!m) + return; + if (m instanceof pgBrowser.DataModel) { + m.reset(opts); } else { - var res = {}; - - res['added'] = []; - _.each(this.sessAttrs['added'], function(o) { - res['added'].push(o.toJSON()); - }); - if (res['added'].length == 0) { - delete res['added']; - } - res['changed'] = []; - _.each(self.sessAttrs['changed'], function(o) { - res['changed'].push(o.toJSON(true)); - }); - if (res['changed'].length == 0) { - delete res['changed']; - } - res['deleted'] = []; - _.each(self.sessAttrs['deleted'], function(o) { - res['deleted'].push(o.toJSON()); - }); - if (res['deleted'].length == 0) { - delete res['deleted']; - } - - return (_.size(res) == 0 ? null : res); + m.clear(opts); } - }, - // Override the reset function, so that - we can reset the model - // properly. - reset: function(opts) { - if (opts && opts.stop) - this.stopSession(); - this.each(function(m) { - if (!m) - return; - if (m instanceof pgBrowser.DataModel) { - m.reset(opts); - } else { - m.clear(opts); - } - }); - Backbone.Collection.prototype.reset.apply(this, arguments); - }, - objFindInSession: function(m, type) { - var hasPrimaryKey = m.primary_key && - typeof(m.primary_key) == 'function', - key = hasPrimaryKey ? m.primary_key() : m.cid, - comparator = hasPrimaryKey ? function(o) { - return (o.primary_key() === key); - } : function(o) { - return (o.cid === key); - }; + }); + Backbone.Collection.prototype.reset.apply(this, arguments); + }, + objFindInSession: function(m, type) { + var hasPrimaryKey = m.primary_key && + typeof(m.primary_key) == 'function', + key = hasPrimaryKey ? m.primary_key() : m.cid, + comparator = hasPrimaryKey ? function(o) { + return (o.primary_key() === key); + } : function(o) { + return (o.cid === key); + }; - return (_.findIndex(this.sessAttrs[type], comparator)); - }, - onModelAdd: function(obj) { - if (!this.trackChanges) - return true; + return (_.findIndex(this.sessAttrs[type], comparator)); + }, + onModelAdd: function(obj) { + if (!this.trackChanges) + return true; - var self = this, - msg, - isAlreadyInvalid = (_.size(self.sessAttrs['invalid']) != 0), - idx = self.objFindInSession(obj, 'deleted'); + var self = this, + msg, + idx = self.objFindInSession(obj, 'deleted'); - // Hmm.. - it was originally deleted from this collection, we should - // remove it from the 'deleted' list. - if (idx >= 0) { - var origObj = self.sessAttrs['deleted'][idx]; + // Hmm.. - it was originally deleted from this collection, we should + // remove it from the 'deleted' list. + if (idx >= 0) { + var origObj = self.sessAttrs['deleted'][idx]; - obj.origSessAttrs = _.clone(origObj.origSessAttrs); - obj.attributes = _.extend(obj.attributes, origObj.attributes); - obj.sessAttrs = _.clone(origObj.sessAttrs); + obj.origSessAttrs = _.clone(origObj.origSessAttrs); + obj.attributes = _.extend(obj.attributes, origObj.attributes); + obj.sessAttrs = _.clone(origObj.sessAttrs); - self.sessAttrs['deleted'].splice(idx, 1); + self.sessAttrs['deleted'].splice(idx, 1); - // It has been changed originally! - if ((!'sessChanged' in obj) || obj.sessChanged()) { - self.sessAttrs['changed'].push(obj); - } + // It has been changed originally! + if ((!('sessChanged' in obj)) || obj.sessChanged()) { + self.sessAttrs['changed'].push(obj); + } - (self.handler || self).trigger('pgadmin-session:added', self, obj); + (self.handler || self).trigger('pgadmin-session:added', self, obj); - if ('default_validate' in obj && typeof(obj.default_validate) == 'function') { - msg = obj.default_validate(); - } + if ('default_validate' in obj && typeof(obj.default_validate) == 'function') { + msg = obj.default_validate(); + } - if (_.isString(msg)) { - (self.sessAttrs['invalid'])[obj.cid] = msg; - } else if ('validate' in obj && typeof(obj.validate) === 'function') { - msg = obj.validate(); + if (_.isString(msg)) { + (self.sessAttrs['invalid'])[obj.cid] = msg; + } else if ('validate' in obj && typeof(obj.validate) === 'function') { + msg = obj.validate(); - if (msg) { - (self.sessAttrs['invalid'])[obj.cid] = msg; - } + if (msg) { + (self.sessAttrs['invalid'])[obj.cid] = msg; } - } else { + } + } else { - if ('default_validate' in obj && typeof(obj.default_validate) == 'function') { - msg = obj.default_validate(); - } + if ('default_validate' in obj && typeof(obj.default_validate) == 'function') { + msg = obj.default_validate(); + } - if (_.isString(msg)) { - (self.sessAttrs['invalid'])[obj.cid] = msg; - } else if ('validate' in obj && typeof(obj.validate) === 'function') { - msg = obj.validate(); + if (_.isString(msg)) { + (self.sessAttrs['invalid'])[obj.cid] = msg; + } else if ('validate' in obj && typeof(obj.validate) === 'function') { + msg = obj.validate(); - if (msg) { - (self.sessAttrs['invalid'])[obj.cid] = msg; - } + if (msg) { + (self.sessAttrs['invalid'])[obj.cid] = msg; } - self.sessAttrs['added'].push(obj); - - /* - * Session has been changed - */ - (self.handler || self).trigger('pgadmin-session:added', self, obj); } + self.sessAttrs['added'].push(obj); - // Let the parent/listener know about my status (valid/invalid). - this.triggerValidationEvent.apply(this); + /* + * Session has been changed + */ + (self.handler || self).trigger('pgadmin-session:added', self, obj); + } + // Let the parent/listener know about my status (valid/invalid). + this.triggerValidationEvent.apply(this); + + return true; + }, + onModelRemove: function(obj) { + if (!this.trackChanges) return true; - }, - onModelRemove: function(obj) { - if (!this.trackChanges) - return true; - /* Once model is removed from collection clear its errorModel as it's no longer relevant - * for us. Otherwise it creates problem in 'clearInvalidSessionIfModelValid' function. - */ - obj.errorModel.clear(); + /* Once model is removed from collection clear its errorModel as it's no longer relevant + * for us. Otherwise it creates problem in 'clearInvalidSessionIfModelValid' function. + */ + obj.errorModel.clear(); - var self = this, - invalidModels = self.sessAttrs['invalid'], - copy = _.clone(obj), - idx = self.objFindInSession(obj, 'added'); + var self = this, + invalidModels = self.sessAttrs['invalid'], + copy = _.clone(obj), + idx = self.objFindInSession(obj, 'added'); - // We need to remove it from the invalid object list first. - if (obj.cid in invalidModels) { - delete invalidModels[obj.cid]; - } + // We need to remove it from the invalid object list first. + if (obj.cid in invalidModels) { + delete invalidModels[obj.cid]; + } - // Hmm - it was newly added, we can safely remove it. - if (idx >= 0) { - self.sessAttrs['added'].splice(idx, 1); + // Hmm - it was newly added, we can safely remove it. + if (idx >= 0) { + self.sessAttrs['added'].splice(idx, 1); - (self.handler || self).trigger('pgadmin-session:removed', self, copy); + (self.handler || self).trigger('pgadmin-session:removed', self, copy); - self.checkDuplicateWithModel(copy); + self.checkDuplicateWithModel(copy); - // Let the parent/listener know about my status (valid/invalid). - this.triggerValidationEvent.apply(this); + // Let the parent/listener know about my status (valid/invalid). + this.triggerValidationEvent.apply(this); - return true; - } + return true; + } - // Hmm - it was changed in this session, we should remove it from the - // changed models. - idx = self.objFindInSession(obj, 'changed'); + // Hmm - it was changed in this session, we should remove it from the + // changed models. + idx = self.objFindInSession(obj, 'changed'); - if (idx >= 0) { - self.sessAttrs['changed'].splice(idx, 1); - (self.handler || self).trigger('pgadmin-session:removed', self, copy); - } else { - (self.handler || self).trigger('pgadmin-session:removed', self, copy); - } + if (idx >= 0) { + self.sessAttrs['changed'].splice(idx, 1); + (self.handler || self).trigger('pgadmin-session:removed', self, copy); + } else { + (self.handler || self).trigger('pgadmin-session:removed', self, copy); + } - self.sessAttrs['deleted'].push(obj); + self.sessAttrs['deleted'].push(obj); - self.checkDuplicateWithModel(obj); + self.checkDuplicateWithModel(obj); - // Let the parent/listener know about my status (valid/invalid). - this.triggerValidationEvent.apply(this); + // Let the parent/listener know about my status (valid/invalid). + this.triggerValidationEvent.apply(this); - /* - * This object has been remove, we need to check (if we still have any - * other invalid message pending). - */ + /* + * This object has been remove, we need to check (if we still have any + * other invalid message pending). + */ - return true; - }, - triggerValidationEvent: function() { - var self = this, - msg = null, - invalidModels = self.sessAttrs['invalid'], - validModels = []; - - for (var key in invalidModels) { - msg = invalidModels[key]; - if (msg) { - break; - } - else { - // Hmm.. - // How come - you have been assigned in invalid list. - // I will make a list of it, and remove it later. - validModels.push(key); - } + return true; + }, + triggerValidationEvent: function() { + var self = this, + msg = null, + invalidModels = self.sessAttrs['invalid'], + validModels = []; + + for (var key in invalidModels) { + msg = invalidModels[key]; + if (msg) { + break; + } else { + // Hmm.. + // How come - you have been assigned in invalid list. + // I will make a list of it, and remove it later. + validModels.push(key); } + } - // Let's remove the un - for (key in validModels) { - delete invalidModels[validModels[key]]; - } + // Let's remove the un + for (key in validModels) { + delete invalidModels[validModels[key]]; + } - if (!msg) { - if (self.handler) { - self.handler.trigger('pgadmin-session:model:valid', self, self.handler); - } else { - self.trigger('pgadmin-session:valid', self.sessChanged(), self); - } + if (!msg) { + if (self.handler) { + self.handler.trigger('pgadmin-session:model:valid', self, self.handler); } else { - if (self.handler) { - self.handler.trigger('pgadmin-session:model:invalid', msg, self, self.handler); - } else { - self.trigger('pgadmin-session:invalid', msg, self); - } + self.trigger('pgadmin-session:valid', self.sessChanged(), self); } - }, - onModelChange: function(obj) { - var self = this; + } else { + if (self.handler) { + self.handler.trigger('pgadmin-session:model:invalid', msg, self, self.handler); + } else { + self.trigger('pgadmin-session:invalid', msg, self); + } + } + }, + onModelChange: function(obj) { + var self = this; - if (!this.trackChanges || !(obj instanceof pgBrowser.Node.Model)) - return true; + if (!this.trackChanges || !(obj instanceof pgBrowser.Node.Model)) + return true; - var idx = self.objFindInSession(obj, 'added'); + var idx = self.objFindInSession(obj, 'added'); - // It was newly added model, we don't need to add into the changed - // list. - if (idx >= 0) { - (self.handler || self).trigger('pgadmin-session:changed', self, obj); + // It was newly added model, we don't need to add into the changed + // list. + if (idx >= 0) { + (self.handler || self).trigger('pgadmin-session:changed', self, obj); - return true; - } + return true; + } - idx = self.objFindInSession(obj, 'changed'); + idx = self.objFindInSession(obj, 'changed'); - if (!'sessChanged' in obj) { - (self.handler || self).trigger('pgadmin-session:changed', self, obj); - - if (idx >= 0) { - return true; - } - - self.sessAttrs['changed'].push(obj); + if (!('sessChanged' in obj)) { + (self.handler || self).trigger('pgadmin-session:changed', self, obj); + if (idx >= 0) { return true; } - if (idx >= 0) { + self.sessAttrs['changed'].push(obj); - if (!obj.sessChanged()) { - // This object is no more updated, removing it from the changed - // models list. - self.sessAttrs['changed'].splice(idx, 1); + return true; + } - (self.handler || self).trigger('pgadmin-session:changed',self, obj); - return true; - } + if (idx >= 0) { - (self.handler || self).trigger('pgadmin-session:changed',self, obj); + if (!obj.sessChanged()) { + // This object is no more updated, removing it from the changed + // models list. + self.sessAttrs['changed'].splice(idx, 1); + (self.handler || self).trigger('pgadmin-session:changed', self, obj); return true; } - if (obj.sessChanged()) { - self.sessAttrs['changed'].push(obj); - (self.handler || self).trigger('pgadmin-session:changed', self, obj); - } + (self.handler || self).trigger('pgadmin-session:changed', self, obj); return true; - }, - - /* - * This function will check if given model is unique or duplicate in - * collection and set/clear duplicate errors on models. - */ - checkDuplicateWithModel: function(model) { - if (!('keys' in model) || _.isEmpty(model.keys)) { - return true; - } + } - var self = this, - condition = {}, - previous_condition = {}; + if (obj.sessChanged()) { + self.sessAttrs['changed'].push(obj); + (self.handler || self).trigger('pgadmin-session:changed', self, obj); + } - _.each(model.keys, function(key) { - condition[key] = model.get(key); - if(key in model._previous_key_values) { - previous_condition[key] = model._previous_key_values[key]; - } else { - previous_condition[key] = model.previous(key); - } - }); + return true; + }, - // Reset previously changed values. - model._previous_key_values = {}; + /* + * This function will check if given model is unique or duplicate in + * collection and set/clear duplicate errors on models. + */ + checkDuplicateWithModel: function(model) { + if (!('keys' in model) || _.isEmpty(model.keys)) { + return true; + } - var old_conflicting_models = self.where(previous_condition); + var self = this, + condition = {}, + previous_condition = {}; - if (old_conflicting_models.length == 1) { - var m = old_conflicting_models[0]; - self.clearInvalidSessionIfModelValid(m); + _.each(model.keys, function(key) { + condition[key] = model.get(key); + if (key in model._previous_key_values) { + previous_condition[key] = model._previous_key_values[key]; + } else { + previous_condition[key] = model.previous(key); } + }); - var new_conflicting_models = self.where(condition); - if (new_conflicting_models.length == 0) { - self.clearInvalidSessionIfModelValid(model); - } else if (new_conflicting_models.length == 1) { - self.clearInvalidSessionIfModelValid(model); - self.clearInvalidSessionIfModelValid(new_conflicting_models[0]); - } else { - var msg = "Duplicate rows."; - setTimeout(function() { - _.each(new_conflicting_models, function(m) { - self.trigger( - 'pgadmin-session:model:invalid', msg, m, self.handler - ); - m.trigger( - 'pgadmin-session:model:duplicate', m, msg - ); - }); - }, 10); + // Reset previously changed values. + model._previous_key_values = {}; - return false; - } - return true; - }, - clearInvalidSessionIfModelValid: function(m) { - var errors = m.errorModel.attributes, - invalidModels = this.sessAttrs['invalid']; + var old_conflicting_models = self.where(previous_condition); - m.trigger('pgadmin-session:model:unique', m - ); - if (_.size(errors) == 0) { - delete invalidModels[m.cid]; - } else { - invalidModels[m.cid] = errors[Object.keys(errors)[0]]; - } + if (old_conflicting_models.length == 1) { + var m = old_conflicting_models[0]; + self.clearInvalidSessionIfModelValid(m); + } + + var new_conflicting_models = self.where(condition); + if (new_conflicting_models.length == 0) { + self.clearInvalidSessionIfModelValid(model); + } else if (new_conflicting_models.length == 1) { + self.clearInvalidSessionIfModelValid(model); + self.clearInvalidSessionIfModelValid(new_conflicting_models[0]); + } else { + var msg = 'Duplicate rows.'; + setTimeout(function() { + _.each(new_conflicting_models, function(m) { + self.trigger( + 'pgadmin-session:model:invalid', msg, m, self.handler + ); + m.trigger( + 'pgadmin-session:model:duplicate', m, msg + ); + }); + }, 10); + + return false; + } + return true; + }, + clearInvalidSessionIfModelValid: function(m) { + var errors = m.errorModel.attributes, + invalidModels = this.sessAttrs['invalid']; + + m.trigger('pgadmin-session:model:unique', m); + if (_.size(errors) == 0) { + delete invalidModels[m.cid]; + } else { + invalidModels[m.cid] = errors[Object.keys(errors)[0]]; } - }); + }, + }); - pgBrowser.Events = _.extend({}, Backbone.Events); + pgBrowser.Events = _.extend({}, Backbone.Events); - return pgBrowser; -}); + return pgBrowser; +}); \ No newline at end of file diff --git a/web/pgadmin/browser/static/js/error.js b/web/pgadmin/browser/static/js/error.js index ed29590d..6066ff03 100644 --- a/web/pgadmin/browser/static/js/error.js +++ b/web/pgadmin/browser/static/js/error.js @@ -10,7 +10,7 @@ function(gettext, _, alertify, pgAdmin) { \
\ @@ -23,21 +23,21 @@ function(gettext, _, alertify, pgAdmin) { \
\
' + unescape(info) + '
\
\
\ - ' + '; } text += ''; alertify.alert( title, text - ) + ); }, }); diff --git a/web/pgadmin/browser/static/js/frame.js b/web/pgadmin/browser/static/js/frame.js index 1431033d..1e94c8b5 100644 --- a/web/pgadmin/browser/static/js/frame.js +++ b/web/pgadmin/browser/static/js/frame.js @@ -1,18 +1,21 @@ -define( - ['underscore', 'sources/pgadmin', 'wcdocker'], -function(_, pgAdmin) { +define([ + 'underscore', 'sources/pgadmin', 'jquery', 'wcdocker', +], function(_, pgAdmin, $) { - var pgBrowser = pgAdmin.Browser = pgAdmin.Browser || {}; + var pgBrowser = pgAdmin.Browser = pgAdmin.Browser || {}, + wcDocker = window.wcDocker, + wcIFrame = window.wcIFrame; pgAdmin.Browser.Frame = function(options) { var defaults = [ 'name', 'title', 'width', 'height', 'showTitle', 'isCloseable', - 'isPrivate', 'url', 'icon', 'onCreate']; + 'isPrivate', 'url', 'icon', 'onCreate', + ]; _.extend(this, _.pick(options, defaults)); - } + }; _.extend(pgAdmin.Browser.Frame.prototype, { - name:'', + name: '', title: '', width: 300, height: 600, @@ -37,7 +40,7 @@ function(_, pgAdmin) { if (myPanel.showTitle == false) myPanel.title(false); - myPanel.icon(that.icon) + myPanel.icon(that.icon); myPanel.closeable(!!that.isCloseable); @@ -75,22 +78,23 @@ function(_, pgAdmin) { } _.each([ - wcDocker.EVENT.UPDATED, wcDocker.EVENT.VISIBILITY_CHANGED, - wcDocker.EVENT.BEGIN_DOCK, wcDocker.EVENT.END_DOCK, - wcDocker.EVENT.GAIN_FOCUS, wcDocker.EVENT.LOST_FOCUS, - wcDocker.EVENT.CLOSED, wcDocker.EVENT.BUTTON, - wcDocker.EVENT.ATTACHED, wcDocker.EVENT.DETACHED, - wcDocker.EVENT.MOVE_STARTED, wcDocker.EVENT.MOVE_ENDED, - wcDocker.EVENT.MOVED, wcDocker.EVENT.RESIZE_STARTED, - wcDocker.EVENT.RESIZE_ENDED, wcDocker.EVENT.RESIZED, - wcDocker.EVENT.SCROLLED], function(ev) { - myPanel.on(ev, that.eventFunc.bind(myPanel, ev)); - }); + wcDocker.EVENT.UPDATED, wcDocker.EVENT.VISIBILITY_CHANGED, + wcDocker.EVENT.BEGIN_DOCK, wcDocker.EVENT.END_DOCK, + wcDocker.EVENT.GAIN_FOCUS, wcDocker.EVENT.LOST_FOCUS, + wcDocker.EVENT.CLOSED, wcDocker.EVENT.BUTTON, + wcDocker.EVENT.ATTACHED, wcDocker.EVENT.DETACHED, + wcDocker.EVENT.MOVE_STARTED, wcDocker.EVENT.MOVE_ENDED, + wcDocker.EVENT.MOVED, wcDocker.EVENT.RESIZE_STARTED, + wcDocker.EVENT.RESIZE_ENDED, wcDocker.EVENT.RESIZED, + wcDocker.EVENT.SCROLLED, + ], function(ev) { + myPanel.on(ev, that.eventFunc.bind(myPanel, ev)); + }); if (that.onCreate && _.isFunction(that.onCreate)) { - that.onCreate.apply(that, [myPanel, frame, $container]); + that.onCreate.apply(that, [myPanel, frame]); } - } + }, }); } }, @@ -106,9 +110,9 @@ function(_, pgAdmin) { pgBrowser.Events.trigger('pgadmin-browser:frame-' + name + ':' + eventName, this, arguments); } } catch (e) { - console.log(e); + console.warn(e.stack || e); } - } + }, }); return pgAdmin.Browser.Frame; diff --git a/web/pgadmin/browser/static/js/menu.js b/web/pgadmin/browser/static/js/menu.js index 8b96e209..db3b92a3 100644 --- a/web/pgadmin/browser/static/js/menu.js +++ b/web/pgadmin/browser/static/js/menu.js @@ -1,6 +1,6 @@ -define( - ['underscore', 'underscore.string', 'sources/pgadmin', 'jquery'], -function(_, S, pgAdmin, $) { +define([ + 'underscore', 'underscore.string', 'sources/pgadmin', 'jquery', +], function(_, S, pgAdmin, $) { 'use strict'; pgAdmin.Browser = pgAdmin.Browser || {}; @@ -8,14 +8,14 @@ function(_, S, pgAdmin, $) { // Individual menu-item class var MenuItem = pgAdmin.Browser.MenuItem = function(opts) { var menu_opts = [ - 'name', 'label', 'priority', 'module', 'callback', 'data', 'enable', - 'category', 'target', 'url'/* Do not show icon in the menus, 'icon' */, 'node' - ], - defaults = { - url: '#', - target: '_self', - enable: true - }; + 'name', 'label', 'priority', 'module', 'callback', 'data', 'enable', + 'category', 'target', 'url' /* Do not show icon in the menus, 'icon' */ , 'node', + ], + defaults = { + url: '#', + target: '_self', + enable: true, + }; _.extend(this, defaults, _.pick(opts, menu_opts)); }; @@ -36,7 +36,7 @@ function(_, S, pgAdmin, $) { name: this.label, /* icon: this.icon || this.module && (this.module.type), */ disabled: this.is_disabled, - callback: this.context_menu_callback.bind(this, item) + callback: this.context_menu_callback.bind(this, item), }; return this.$el; @@ -47,19 +47,21 @@ function(_, S, pgAdmin, $) { */ create_el: function(node, item) { var url = $('', { - 'id': this.name, - 'href': this.url, - 'target': this.target, - 'data-toggle': 'pg-menu' - }).data('pgMenu', { - module: this.module || pgAdmin.Browser, - cb: this.callback, - data: this.data - }).addClass('menu-link'); + 'id': this.name, + 'href': this.url, + 'target': this.target, + 'data-toggle': 'pg-menu', + }).data('pgMenu', { + module: this.module || pgAdmin.Browser, + cb: this.callback, + data: this.data, + }).addClass('menu-link'); this.is_disabled = this.disabled(node, item); if (this.icon) { - url.append($('', {'class': this.icon})); + url.append($('', { + 'class': this.icon, + })); } var textSpan = $('').text(' ' + this.label); @@ -73,7 +75,7 @@ function(_, S, pgAdmin, $) { this.applyStyle(); }, - applyDisabledStyle: function () { + applyDisabledStyle: function() { var span = this.$el.find('span'); var icon = this.$el.find('i'); @@ -84,7 +86,7 @@ function(_, S, pgAdmin, $) { icon.removeClass('font-white'); }, - applyEnabledStyle: function () { + applyEnabledStyle: function() { var element = this.$el; var span = this.$el.find('span'); @@ -93,11 +95,15 @@ function(_, S, pgAdmin, $) { element.find('i').addClass('font-white'); element.find('i').removeClass('font-gray-4'); - span.mouseover(function () { element.addClass('bg-gray-5'); }); - span.mouseout(function () { element.removeClass('bg-gray-5'); }); + span.mouseover(function() { + element.addClass('bg-gray-5'); + }); + span.mouseout(function() { + element.removeClass('bg-gray-5'); + }); }, - applyStyle: function () { + applyStyle: function() { if (this.is_disabled) { this.applyDisabledStyle(); } else { @@ -121,7 +127,7 @@ function(_, S, pgAdmin, $) { this.$el.removeClass('disabled'); } - if(this.$el) { + if (this.$el) { this.applyStyle(); } @@ -129,7 +135,7 @@ function(_, S, pgAdmin, $) { name: this.label, /* icon: this.icon || (this.module && this.module.type), */ disabled: this.is_disabled, - callback: this.context_menu_callback.bind(this, item) + callback: this.context_menu_callback.bind(this, item), }; }, @@ -137,11 +143,12 @@ function(_, S, pgAdmin, $) { * This will be called when context-menu is clicked. */ context_menu_callback: function(item) { - var o = this, cb; + var o = this, + cb; if (o.module['callbacks'] && ( - o.callback in o.module['callbacks'] - )) { + o.callback in o.module['callbacks'] + )) { cb = o.module['callbacks'][o.callback]; } else if (o.callback in o.module) { cb = o.module[o.callback]; @@ -150,8 +157,7 @@ function(_, S, pgAdmin, $) { cb.apply(o.module, [o.data, item]); } else { pgAdmin.Browser.report_error( - S('Developer Warning: Callback - "%s" not found!'). - sprintf(o.cb).value() + S('Developer Warning: Callback - "%s" not found!').sprintf(o.cb).value() ); } }, @@ -169,8 +175,8 @@ function(_, S, pgAdmin, $) { return true; } if (_.isArray(this.node) ? ( - _.indexOf(this.node, node) == -1 - ) : (this.node != node._type)) { + _.indexOf(this.node, node) == -1 + ) : (this.node != node._type)) { return true; } } @@ -181,7 +187,7 @@ function(_, S, pgAdmin, $) { if (this.module && _.isFunction(this.module[this.enable])) return !(this.module[this.enable]).apply(this.module, [node, item, this.data]); return false; - } + }, }); /* @@ -202,59 +208,65 @@ function(_, S, pgAdmin, $) { pgAdmin.Browser.MenuGroup = function(opts, items, prev, ctx) { var template = _.template([ - '<% if (above) { %>
<% } %>', - '', - '<% if (below) { %>
<% } %>',].join('\n')), - data = { - 'label': opts.label, - 'icon': opts.icon, - 'above': opts.above && !prev, - 'below': opts.below, - }, m, - $el = $(template(data)), - $menu = $el.find('.dropdown-menu'), - submenus = {}, - ctxId = 1; - - ctx = _.uniqueId(ctx + '_sub_'); - - // Sort by alphanumeric ordered first - items.sort(function(a, b) {return a.label.localeCompare(b.label);}); - // Sort by priority - items.sort(function(a, b) {return a.priority - b.priority;}); - - for (var idx in items) { - m = items[idx]; - $menu.append(m.$el); - if (!m.is_disabled) { - submenus[ctx + ctxId] = m.context; - } - ctxId++; + '<% if (above) { %>
<% } %>', + '', + '<% if (below) { %>
<% } %>', + ].join('\n')), + data = { + 'label': opts.label, + 'icon': opts.icon, + 'above': opts.above && !prev, + 'below': opts.below, + }, + m, + $el = $(template(data)), + $menu = $el.find('.dropdown-menu'), + submenus = {}, + ctxId = 1; + + ctx = _.uniqueId(ctx + '_sub_'); + + // Sort by alphanumeric ordered first + items.sort(function(a, b) { + return a.label.localeCompare(b.label); + }); + // Sort by priority + items.sort(function(a, b) { + return a.priority - b.priority; + }); + + for (var idx in items) { + m = items[idx]; + $menu.append(m.$el); + if (!m.is_disabled) { + submenus[ctx + ctxId] = m.context; } + ctxId++; + } - var is_disabled = (_.size(submenus) == 0); - - return { - $el: $el, - priority: opts.priority || 10, - label: opts.label, - above: data['above'], - below: opts.below, - is_disabled: is_disabled, - context: { - name: opts.label, - icon: opts.icon, - items: submenus, - disabled: is_disabled - } - }; + var is_disabled = (_.size(submenus) == 0); + + return { + $el: $el, + priority: opts.priority || 10, + label: opts.label, + above: data['above'], + below: opts.below, + is_disabled: is_disabled, + context: { + name: opts.label, + icon: opts.icon, + items: submenus, + disabled: is_disabled, + }, + }; }; /* @@ -274,26 +286,31 @@ function(_, S, pgAdmin, $) { * * Returns if any menu generated for the given input. */ - pgAdmin.Browser.MenuCreator = function($mnu, menus, categories, d, item, menu_items) { - var groups = {'common': []}, - common, idx = 0, j, item, - ctxId = _.uniqueId('ctx_'), - update_menuitem = function(m) { - if (m instanceof MenuItem) { - if (m.$el) { - m.$el.remove(); - delete m.$el; - } - m.generate(d, item); - var group = groups[m.category || 'common'] = - groups[m.category || 'common'] || []; - group.push(m); - } else { - for (var key in m) { - update_menuitem(m[key]); - } + pgAdmin.Browser.MenuCreator = function( + $mnu, menus, categories, d, item, menu_items + ) { + var groups = { + 'common': [], + }, + common, idx = 0, + ctxId = _.uniqueId('ctx_'), + update_menuitem = function(m) { + if (m instanceof MenuItem) { + if (m.$el) { + m.$el.remove(); + delete m.$el; + } + m.generate(d, item); + var group = groups[m.category || 'common'] = + groups[m.category || 'common'] || []; + group.push(m); + } else { + for (var key in m) { + update_menuitem(m[key]); } - }, ctxIdx = 1; + } + }, + ctxIdx = 1; for (idx in menus) { update_menuitem(menus[idx]); @@ -307,10 +324,13 @@ function(_, S, pgAdmin, $) { var prev = true; - for (name in groups) { + for (var name in groups) { var g = groups[name], - c = categories[name] || {'label': name, single: false}, - menu_group = pgAdmin.Browser.MenuGroup(c, g, prev, ctxId); + c = categories[name] || { + 'label': name, + single: false, + }, + menu_group = pgAdmin.Browser.MenuGroup(c, g, prev, ctxId); if (g.length <= 1 && !c.single) { prev = false; @@ -327,9 +347,13 @@ function(_, S, pgAdmin, $) { // Menu with lowest value has the highest priority. If the priority is // same, then - it will be ordered by label. // Sort by alphanumeric ordered first - common.sort(function(a, b) {return a.label.localeCompare(b.label);}); + common.sort(function(a, b) { + return a.label.localeCompare(b.label); + }); // Sort by priority - common.sort(function(a, b) {return a.priority - b.priority;}); + common.sort(function(a, b) { + return a.priority - b.priority; + }); var len = _.size(common); for (idx in common) { @@ -360,15 +384,15 @@ function(_, S, pgAdmin, $) { // MENU PUBLIC CLASS DEFINITION // ============================== - var Menu = function (element, options) { - this.$element = $(element); - this.options = $.extend({}, Menu.DEFAULTS, options); + var Menu = function(element, options) { + this.$element = $(element); + this.options = $.extend({}, Menu.DEFAULTS, options); this.isLoading = false; - } + }; - Menu.DEFAULTS = {} + Menu.DEFAULTS = {}; - Menu.prototype.toggle = function (ev) { + Menu.prototype.toggle = function(ev) { var $parent = this.$element.closest('.menu-item'); if ($parent.hasClass('disabled')) { ev.preventDefault(); @@ -384,43 +408,43 @@ function(_, S, pgAdmin, $) { pgAdmin.Browser.report_error('Developer Warning: Callback - "' + d.cb + '" not found!'); } } - } + }; // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option, ev) { - return this.each(function () { - var $this = $(this); - var data = $this.data('pg.menu'); + return this.each(function() { + var $this = $(this); + var data = $this.data('pg.menu'); var options = typeof option == 'object' && option; if (!data) $this.data('pg.menu', (data = new Menu(this, options))); data.toggle(ev); - }) + }); } var old = $.fn.button; - $.fn.pgmenu = Plugin; + $.fn.pgmenu = Plugin; $.fn.pgmenu.Constructor = Menu; // BUTTON NO CONFLICT // ================== - $.fn.pgmenu.noConflict = function () { + $.fn.pgmenu.noConflict = function() { $.fn.pgmenu = old; return this; - } + }; // MENU DATA-API // ============= $(document) - .on('click.pg.menu.data-api', '[data-toggle^="pg-menu"]', function (ev) { + .on('click.pg.menu.data-api', '[data-toggle^="pg-menu"]', function(ev) { var $menu = $(ev.target); if (!$menu.hasClass('menu-link')) $menu = $menu.closest('.menu-link'); @@ -429,7 +453,7 @@ function(_, S, pgAdmin, $) { .on( 'focus.pg.menu.data-api blur.pg.menu.data-api', '[data-toggle^="pg-menu"]', - function (e) { + function(e) { $(e.target).closest('.menu').toggleClass( 'focus', /^focus(in)?$/.test(e.type) ); diff --git a/web/pgadmin/browser/static/js/node.js b/web/pgadmin/browser/static/js/node.js index 83a55413..a57b2ca3 100644 --- a/web/pgadmin/browser/static/js/node.js +++ b/web/pgadmin/browser/static/js/node.js @@ -1,15 +1,14 @@ -define( - 'pgadmin.browser.node', [ - 'sources/gettext', 'jquery', 'underscore', 'underscore.string', 'sources/pgadmin', - 'pgadmin.browser.menu', 'backbone', 'pgadmin.alertifyjs', 'pgadmin.browser.datamodel', - 'backform', 'sources/browser/generate_url', 'pgadmin.browser.utils', 'pgadmin.backform' +define('pgadmin.browser.node', [ + 'sources/gettext', 'jquery', 'underscore', 'underscore.string', 'sources/pgadmin', + 'pgadmin.browser.menu', 'backbone', 'pgadmin.alertifyjs', 'pgadmin.browser.datamodel', + 'backform', 'sources/browser/generate_url', 'pgadmin.browser.utils', 'pgadmin.backform', ], function(gettext, $, _, S, pgAdmin, Menu, Backbone, Alertify, pgBrowser, Backform, generateUrl) { var wcDocker = window.wcDocker, keyCode = { ENTER: 13, ESCAPE: 27, - F1: 112 + F1: 112, }; // It has already been defined. @@ -34,7 +33,9 @@ define( // The constructor function for the new subclass is defined to simply call // the parent's constructor. - child = function(){ return parent.apply(this, arguments); }; + child = function() { + return parent.apply(this, arguments); + }; // Add static properties to the constructor function, if supplied. _.extend(child, parent, _.omit(props, 'callbacks')); @@ -43,12 +44,12 @@ define( child.callbacks = _.extend({}, parent.callbacks, props.callbacks); var bindToChild = function(cb) { - if (typeof(child.callbacks[cb]) == 'function') { - child.callbacks[cb] = child.callbacks[cb].bind(child); - } - }, - callbacks = _.keys(child.callbacks); - for(var idx = 0; idx < callbacks.length; idx++) bindToChild(callbacks[idx]); + if (typeof(child.callbacks[cb]) == 'function') { + child.callbacks[cb] = child.callbacks[cb].bind(child); + } + }, + callbacks = _.keys(child.callbacks); + for (var idx = 0; idx < callbacks.length; idx++) bindToChild(callbacks[idx]); // Registering the node by calling child.Init(...) function child.Init.apply(child); @@ -87,84 +88,123 @@ define( self.node_initialized = true; pgAdmin.Browser.add_menus([{ - name: 'refresh', node: self.type, module: self, - applies: ['object', 'context'], callback: 'refresh', - priority: 1, label: gettext('Refresh...'), - icon: 'fa fa-refresh' + name: 'refresh', + node: self.type, + module: self, + applies: ['object', 'context'], + callback: 'refresh', + priority: 1, + label: gettext('Refresh...'), + icon: 'fa fa-refresh', }]); if (self.canEdit) { pgAdmin.Browser.add_menus([{ - name: 'show_obj_properties', node: self.type, module: self, - applies: ['object', 'context'], callback: 'show_obj_properties', - priority: 999, label: gettext('Properties...'), - data: {'action': 'edit'}, icon: 'fa fa-pencil-square-o' - }]); + name: 'show_obj_properties', + node: self.type, + module: self, + applies: ['object', 'context'], + callback: 'show_obj_properties', + priority: 999, + label: gettext('Properties...'), + data: { + 'action': 'edit', + }, + icon: 'fa fa-pencil-square-o', + }]); } if (self.canDrop) { pgAdmin.Browser.add_menus([{ - name: 'delete_object', node: self.type, module: self, - applies: ['object', 'context'], callback: 'delete_obj', - priority: 2, label: gettext('Delete/Drop'), - data: {'url': 'drop'}, icon: 'fa fa-trash', + name: 'delete_object', + node: self.type, + module: self, + applies: ['object', 'context'], + callback: 'delete_obj', + priority: 2, + label: gettext('Delete/Drop'), + data: { + 'url': 'drop', + }, + icon: 'fa fa-trash', enable: _.isFunction(self.canDrop) ? function() { return !!(self.canDrop.apply(self, arguments)); - } : (!!self.canDrop) + } : (!!self.canDrop), }]); + if (self.canDropCascade) { pgAdmin.Browser.add_menus([{ - name: 'delete_object_cascade', node: self.type, module: self, - applies: ['object', 'context'], callback: 'delete_obj', - priority: 3, label: gettext('Drop Cascade'), - data: {'url': 'delete'}, icon: 'fa fa-trash', + name: 'delete_object_cascade', + node: self.type, + module: self, + applies: ['object', 'context'], + callback: 'delete_obj', + priority: 3, + label: gettext('Drop Cascade'), + data: { + 'url': 'delete', + }, + icon: 'fa fa-trash', enable: _.isFunction(self.canDropCascade) ? - function() { return self.canDropCascade.apply(self, arguments); } : (!!self.canDropCascade) + function() { + return self.canDropCascade.apply(self, arguments); + } : (!!self.canDropCascade), }]); } } - // show query tool only in context menu of supported nodes. - if (true) { - if (_.indexOf(pgAdmin.unsupported_nodes, self.type) == -1) { - pgAdmin.Browser.add_menus([{ - name: 'show_query_tool', node: self.type, module: self, - applies: ['context'], callback: 'show_query_tool', - priority: 998, label: gettext('Query Tool...'), - icon: 'fa fa-bolt', - enable: function(itemData, item, data) { - if (itemData._type == 'database' && itemData.allowConn) - return true; - else if(itemData._type != 'database') - return true; - else - return false; - } - }]); - } + // Show query tool only in context menu of supported nodes. + if (_.indexOf(pgAdmin.unsupported_nodes, self.type) == -1) { + pgAdmin.Browser.add_menus([{ + name: 'show_query_tool', + node: self.type, + module: self, + applies: ['context'], + callback: 'show_query_tool', + priority: 998, + label: gettext('Query Tool...'), + icon: 'fa fa-bolt', + enable: function(itemData) { + if (itemData._type == 'database' && itemData.allowConn) + return true; + else if (itemData._type != 'database') + return true; + else + return false; + }, + }]); } // This will add options of scripts eg:'CREATE Script' - if (self.hasScriptTypes && _.isArray(self.hasScriptTypes) - && self.hasScriptTypes.length > 0) { - // For each script type create menu - _.each(self.hasScriptTypes, function(stype) { - - var type_label = S( - gettext("%s Script") - ).sprintf(stype.toUpperCase()).value(), - stype = stype.toLowerCase(); - - // Adding menu for each script type - pgAdmin.Browser.add_menus([{ - name: 'show_script_' + stype, node: self.type, module: self, - applies: ['object', 'context'], callback: 'show_script', - priority: 4, label: type_label, category: 'Scripts', - data: {'script': stype}, icon: 'fa fa-pencil', - enable: self.check_user_permission - }]); - }); + if (self.hasScriptTypes && _.isArray(self.hasScriptTypes) && + self.hasScriptTypes.length > 0) { + // For each script type create menu + _.each(self.hasScriptTypes, function(stype) { + + var type_label = S( + gettext('%s Script') + ).sprintf(stype.toUpperCase()).value(); + + stype = stype.toLowerCase(); + + // Adding menu for each script type + pgAdmin.Browser.add_menus([{ + name: 'show_script_' + stype, + node: self.type, + module: self, + applies: ['object', 'context'], + callback: 'show_script', + priority: 4, + label: type_label, + category: 'Scripts', + data: { + 'script': stype, + }, + icon: 'fa fa-pencil', + enable: self.check_user_permission, + }]); + }); } }, /////// @@ -185,23 +225,23 @@ define( var node = pgBrowser.Nodes[itemData._type], parentData = node.getTreeNodeHierarchy(item); - if ( _.indexOf(['create','insert','update', 'delete'], data.script) != -1) { + if (_.indexOf(['create', 'insert', 'update', 'delete'], data.script) != -1) { if (itemData.type == 'role' && parentData.server.user.can_create_role) { return true; } else if ( - ( + ( parentData.server && ( - parentData.server.user.is_superuser || - parentData.server.user.can_create_db) - ) || - ( + parentData.server.user.is_superuser || + parentData.server.user.can_create_db) + ) || + ( parentData.schema && parentData.schema.can_create - ) - ) { - return true; + ) + ) { + return true; } else { - return false; + return false; } } else { return true; @@ -240,20 +280,26 @@ define( // We know - which data model to be used for this object. var info = this.getTreeNodeHierarchy.apply(this, [item]), - newModel = new (this.model.extend({urlRoot: urlBase})) ( - attrs, {node_info: info} - ), - fields = Backform.generateViewSchema( - info, newModel, type, this, node - ); + newModel = new(this.model.extend({ + urlRoot: urlBase, + }))( + attrs, { + node_info: info, + } + ), + fields = Backform.generateViewSchema( + info, newModel, type, this, node + ); if (type == 'create' || type == 'edit') { if (callback && ctx) { - callback = callback.bind(ctx); + callback = callback.bind(ctx); } else { callback = function() { - console.log("Broke something!!! Why we don't have the callback or the context???"); + console.warn( + 'Broke something!!! Why we don\'t have the callback or the context???' + ); }; } @@ -270,10 +316,10 @@ define( \ \ '; - if(!_.isUndefined(that.statusBar)) { - that.statusBar.html(alertMessage).css("visibility", "visible"); - that.statusBar.find("a.close-error").bind("click", function(e) { - this.empty().css("visibility", "hidden"); + if (!_.isUndefined(that.statusBar)) { + that.statusBar.html(alertMessage).css('visibility', 'visible'); + that.statusBar.find('a.close-error').bind('click', function() { + this.empty().css('visibility', 'hidden'); }.bind(that.statusBar)); } callback(true); @@ -281,10 +327,10 @@ define( return true; }; - var onSessionValidated = function(sessHasChanged) { + var onSessionValidated = function(sessHasChanged) { - if(!_.isUndefined(that.statusBar)) { - that.statusBar.empty().css("visibility", "hidden"); + if (!_.isUndefined(that.statusBar)) { + that.statusBar.empty().css('visibility', 'hidden'); } callback(false, sessHasChanged); @@ -304,13 +350,17 @@ define( // It is used to show, edit, create the object in the // properties tab. view = new Backform.Fieldset({ - el: el, model: newModel, schema: fields + el: el, + model: newModel, + schema: fields, }); } else { // This generates a view to be used by the node dialog // (for create/edit operation). view = new Backform.Dialog({ - el: el, model: newModel, schema: fields + el: el, + model: newModel, + schema: fields, }); } @@ -322,9 +372,9 @@ define( if (!newModel.isNew()) { // This is definetely not in create mode - var msgDiv = '
'+ - gettext("Retrieving data from the server...") + '
', - $msgDiv = $(msgDiv); + var msgDiv = '
' + + gettext('Retrieving data from the server...') + '
', + $msgDiv = $(msgDiv); var timer = setTimeout(function(ctx) { // notify user if request is taking longer than 1 second @@ -334,46 +384,45 @@ define( }, 1000, ctx); newModel.fetch({ - success: function(res, msg, xhr) { - // clear timeout and remove message + success: function() { + // Clear timeout and remove message clearTimeout(timer); $msgDiv.addClass('hidden'); - // We got the latest attributes of the - // object. Render the view now. + // We got the latest attributes of the object. Render the view + // now. view.render(); setFocusOnEl(); newModel.startNewSession(); }, error: function(xhr, error, message) { var _label = that && item ? - that.getTreeNodeHierarchy( - item - )[that.type].label : ''; + that.getTreeNodeHierarchy( + item + )[that.type].label : ''; pgBrowser.Events.trigger( 'pgadmin:node:retrieval:error', 'properties', xhr, error, message, item ); - if ( - !Alertify.pgHandleItemError( - xhr, error, message, {item: item, info: info} - ) - ) { + if (!Alertify.pgHandleItemError( + xhr, error, message, { + item: item, + info: info, + } + )) { Alertify.pgNotifier( error, xhr, S( - gettext("Error retrieving properties - %s") + gettext('Error retrieving properties - %s') ).sprintf(message || _label).value(), - function() { - console.log(arguments); - } + function() {} ); } // Close the panel (if could not fetch properties) if (cancelFunc) { cancelFunc(); } - } + }, }); } else { // Yay - render the view now! @@ -398,28 +447,30 @@ define( var events = {}; events[wcDocker.EVENT.RESIZE_ENDED] = function() { var $container = this.$container.find('.obj_properties').first(), - v = $container.data('obj-view'); + v = $container.data('obj-view'); if (v && v.model && v.model) { v.model.trigger( 'pg-browser-resized', { - 'view': v, 'panel': this, 'container': $container - }); + 'view': v, + 'panel': this, + 'container': $container, + }); } }; p = new pgBrowser.Panel({ - name: 'node_props', - showTitle: true, - isCloseable: true, - isPrivate: true, - elContainer: true, - content: '
' + gettext('Please wait while we fetch information about the node from the server...') + '
', - onCreate: function(myPanel, $container) { - $container.addClass('pg-no-overflow'); - }, - events: events + name: 'node_props', + showTitle: true, + isCloseable: true, + isPrivate: true, + elContainer: true, + content: '
' + gettext('Please wait while we fetch information about the node from the server...') + '
', + onCreate: function(myPanel, $container) { + $container.addClass('pg-no-overflow'); + }, + events: events, }); p.load(pgBrowser.docker); }, @@ -481,36 +532,40 @@ define( return; var self = this, - isParent = (_.isArray(this.parent_type) ? - function(d) { - return (_.indexOf(self.parent_type, d._type) != -1); - } : function(d) { - return (self.parent_type == d._type); - }), - addPanel = function() { - var d = window.document, - b = d.body, - el = d.createElement('div'); - - d.body.insertBefore(el, d.body.firstChild); - - var pW = screen.width < 800 ? '95%' : '500px', - pH = screen.height < 600 ? '95%' : '550px', - w = pgAdmin.toPx(el, self.width || pW, 'width', true), - h = pgAdmin.toPx(el, self.height|| pH, 'height', true), - x = (b.offsetWidth - w) / 2, - y = (b.offsetHeight - h) / 2; - - var p = pgBrowser.docker.addPanel( - 'node_props', wcDocker.DOCK.FLOAT, undefined, - {w: w + 'px', h: h + 'px', x: x + 'px', y: y + 'px'} - ); + isParent = (_.isArray(this.parent_type) ? + function(d) { + return (_.indexOf(self.parent_type, d._type) != -1); + } : function(d) { + return (self.parent_type == d._type); + }), + addPanel = function() { + var d = window.document, + b = d.body, + el = d.createElement('div'); + + d.body.insertBefore(el, d.body.firstChild); + + var pW = screen.width < 800 ? '95%' : '500px', + pH = screen.height < 600 ? '95%' : '550px', + w = pgAdmin.toPx(el, self.width || pW, 'width', true), + h = pgAdmin.toPx(el, self.height || pH, 'height', true), + x = (b.offsetWidth - w) / 2, + y = (b.offsetHeight - h) / 2; + + var p = pgBrowser.docker.addPanel( + 'node_props', wcDocker.DOCK.FLOAT, undefined, { + w: w + 'px', + h: h + 'px', + x: x + 'px', + y: y + 'px', + } + ); - b.removeChild(el); - // delete(el); + b.removeChild(el); + // delete(el); - return p; - }; + return p; + }; if (args.action == 'create') { // If we've parent, we will get the information of it for @@ -554,8 +609,8 @@ define( if (!d) return; - l = S( gettext('Create - %s')).sprintf( - [this.label]).value(); + l = S(gettext('Create - %s')).sprintf( + [this.label]).value(); p = addPanel(); setTimeout(function() { @@ -563,7 +618,7 @@ define( }, 10); } else { if (pgBrowser.Node.panels && pgBrowser.Node.panels[d.id] && - pgBrowser.Node.panels[d.id].$container) { + pgBrowser.Node.panels[d.id].$container) { var p = pgBrowser.Node.panels[d.id]; /** TODO :: * Run in edit mode (if asked) only when it is @@ -608,11 +663,13 @@ define( }, // Delete the selected object delete_obj: function(args, item) { - var input = args || {'url':'drop'}, - obj = this, - t = pgBrowser.tree, - i = input.item || item || t.selected(), - d = i && i.length == 1 ? t.itemData(i) : undefined; + var input = args || { + 'url': 'drop', + }, + obj = this, + t = pgBrowser.tree, + i = input.item || item || t.selected(), + d = i && i.length == 1 ? t.itemData(i) : undefined; if (!d) return; @@ -626,28 +683,28 @@ define( var msg, title; if (input.url == 'delete') { - msg = S( gettext('Are you sure you want to drop %s "%s" and all the objects that depend on it?')) + msg = S(gettext('Are you sure you want to drop %s "%s" and all the objects that depend on it?')) .sprintf(obj.label.toLowerCase(), d.label).value(); - title = S( gettext('DROP CASCADE %s?')).sprintf(obj.label).value(); + title = S(gettext('DROP CASCADE %s?')).sprintf(obj.label).value(); if (!(_.isFunction(obj.canDropCascade) ? - obj.canDropCascade.apply(obj, [d, i]) : obj.canDropCascade)) { - Alertify.error( - S( gettext('The %s "%s" cannot be dropped.')) - .sprintf(obj.label, d.label).value(), - 10 - ); + obj.canDropCascade.apply(obj, [d, i]) : obj.canDropCascade)) { + Alertify.error( + S(gettext('The %s "%s" cannot be dropped.')) + .sprintf(obj.label, d.label).value(), + 10 + ); return; } } else { - msg = S( gettext('Are you sure you want to drop %s "%s"?')) + msg = S(gettext('Are you sure you want to drop %s "%s"?')) .sprintf(obj.label.toLowerCase(), d.label).value(); - title = S( gettext('DROP %s?')).sprintf(obj.label).value(); + title = S(gettext('DROP %s?')).sprintf(obj.label).value(); if (!(_.isFunction(obj.canDrop) ? obj.canDrop.apply(obj, [d, i]) : obj.canDrop)) { Alertify.error( - S( gettext('The %s "%s" cannot be dropped.')) + S(gettext('The %s "%s" cannot be dropped.')) .sprintf(obj.label, d.label).value(), 10 ); @@ -658,7 +715,7 @@ define( function() { $.ajax({ url: obj.generate_url(i, input.url, d, true), - type:'DELETE', + type: 'DELETE', success: function(res) { if (res.success == 0) { pgBrowser.report_error(res.errormsg, res.info); @@ -674,16 +731,18 @@ define( try { var data = $.parseJSON(jqx.responseText); msg = data.errormsg; - } catch (e) {} + } catch (e) { + console.warn(e.stack || e); + } } pgBrowser.report_error( - S( gettext('Error dropping %s: "%s"')) - .sprintf(obj.label, objName) - .value(), msg); - } + S(gettext('Error dropping %s: "%s"')) + .sprintf(obj.label, objName) + .value(), msg); + }, }); }, - null).show() + null).show(); }, // Callback for creating script(s) & opening them in Query editor show_script: function(args, item) { @@ -700,19 +759,18 @@ define( * Make sure - we're using the correct version of node */ obj = pgBrowser.Nodes[d._type]; - var objName = d.label, - sql_url; + var sql_url; // URL for script type - if(scriptType == 'insert') { + if (scriptType == 'insert') { sql_url = 'insert_sql'; - } else if(scriptType == 'update') { + } else if (scriptType == 'update') { sql_url = 'update_sql'; - } else if(scriptType == 'delete') { + } else if (scriptType == 'delete') { sql_url = 'delete_sql'; - } else if(scriptType == 'select') { + } else if (scriptType == 'select') { sql_url = 'select_sql'; - } else if(scriptType == 'exec') { + } else if (scriptType == 'exec') { sql_url = 'exec_sql'; } else { // By Default get CREATE SQL @@ -727,8 +785,7 @@ define( // Callback to render query editor show_query_tool: function(args, item) { - var obj = this, - t = pgBrowser.tree, + var t = pgBrowser.tree, i = item || t.selected(), d = i && i.length == 1 ? t.itemData(i) : undefined; @@ -750,31 +807,31 @@ define( if (data && data._type && data._type == 'server') { var element = $(item).find('span.aciTreeItem').first() || null, // First element will be icon and second will be colour code - bgcolor = data.icon.split(" ")[1] || null, - fgcolor = data.icon.split(" ")[2] || ''; + bgcolor = data.icon.split(' ')[1] || null, + fgcolor = data.icon.split(' ')[2] || ''; - if(bgcolor) { + if (bgcolor) { // li tag for the current branch var first_level_element = element.parents()[3] || null, dynamic_class = 'pga_server_' + data._id + '_bgcolor', style_tag; // Prepare dynamic style tag - style_tag = ""; + style_tag += ''; // Prepare dynamic style tag using template $('#' + dynamic_class).remove(); - $(style_tag).appendTo("head"); + $(style_tag).appendTo('head'); - if(first_level_element) + if (first_level_element) $(first_level_element).addClass(dynamic_class); } } @@ -782,10 +839,10 @@ define( added: function(item, data, browser) { var b = browser || pgBrowser, - t = b.tree, - pItem = t.parent(item), - pData = pItem && t.itemData(pItem), - pNode = pData && pgBrowser.Nodes[pData._type]; + t = b.tree, + pItem = t.parent(item), + pData = pItem && t.itemData(pItem), + pNode = pData && pgBrowser.Nodes[pData._type]; // Check node is a collection or not. if (pNode && pNode.is_collection) { @@ -801,7 +858,7 @@ define( pItem, { label: ( _.escape(pData._label) + ' (' + pData.collection_count + ')' - ) + ), } ); } @@ -818,46 +875,46 @@ define( // + Dependencies // + Statistics var b = browser || pgBrowser, - t = b.tree, - d = data || t.itemData(item); + t = b.tree, + d = data || t.itemData(item); // Update the menu items pgAdmin.Browser.enable_disable_menus.apply(b, [item]); if (d && b) { if ('properties' in b.panels && - b.panels['properties'] && - b.panels['properties'].panel && - b.panels['properties'].panel.isVisible()) { + b.panels['properties'] && + b.panels['properties'].panel && + b.panels['properties'].panel.isVisible()) { // Show object properties (only when the 'properties' tab // is active). this.showProperties(item, d, b.panels['properties'].panel); } if ('sql' in b.panels && - b.panels['sql'] && - b.panels['sql'].panel && - b.panels['sql'].panel.isVisible()) { + b.panels['sql'] && + b.panels['sql'].panel && + b.panels['sql'].panel.isVisible()) { // TODO:: Show reverse engineered query for this object (when 'sql' // tab is active.) } if ('statistics' in b.panels && - b.panels['statistics'] && - b.panels['statistics'].panel && - b.panels['statistics'].panel.isVisible()) { + b.panels['statistics'] && + b.panels['statistics'].panel && + b.panels['statistics'].panel.isVisible()) { // TODO:: Show statistics for this object (when the 'statistics' // tab is active.) } if ('dependencies' in b.panels && - b.panels['dependencies'] && - b.panels['dependencies'].panel && - b.panels['dependencies'].panel.isVisible()) { + b.panels['dependencies'] && + b.panels['dependencies'].panel && + b.panels['dependencies'].panel.isVisible()) { // TODO:: Show dependencies for this object (when the // 'dependencies' tab is active.) } if ('dependents' in b.panels && - b.panels['dependents'] && - b.panels['dependents'].panel && - b.panels['dependents'].panel.isVisible()) { + b.panels['dependents'] && + b.panels['dependents'].panel && + b.panels['dependents'].panel.isVisible()) { // TODO:: Show dependents for this object (when the 'dependents' // tab is active.) } @@ -867,10 +924,10 @@ define( }, removed: function(item) { var self = this, - t = pgBrowser.tree, - pItem = t.parent(item), - pData = pItem && t.itemData(pItem), - pNode = pData && pgBrowser.Nodes[pData._type]; + t = pgBrowser.tree, + pItem = t.parent(item), + pData = pItem && t.itemData(pItem), + pNode = pData && pgBrowser.Nodes[pData._type]; // Check node is a collection or not. if ( @@ -881,33 +938,33 @@ define( pItem, { label: ( _.escape(pData._label) + ' (' + pData.collection_count + ')' - ) + ), } ); } - setTimeout(function() { self.clear_cache.apply(self, item); }, 0); + setTimeout(function() { + self.clear_cache.apply(self, item); + }, 0); }, unloaded: function(item) { var self = this, - t = pgBrowser.tree, - data = item && t.itemData(item); + t = pgBrowser.tree, + data = item && t.itemData(item); // In case of unload remove the collection counter - if (self.is_collection && 'collection_count' in data) - { + if (self.is_collection && 'collection_count' in data) { delete data.collection_count; - t.setLabel(item, {label: _.escape(data._label)}); + t.setLabel(item, { + label: _.escape(data._label), + }); } }, - refresh: function(cmd, i) { - var self = this, - t = pgBrowser.tree, - item = i || t.selected(), - d = t.itemData(item); - - pgBrowser.Events.trigger('pgadmin:browser:tree:refresh', item); - } + refresh: function(cmd, _item) { + pgBrowser.Events.trigger( + 'pgadmin:browser:tree:refresh', _item || pgBrowser.tree.selected() + ); + }, }, /********************************************************************** * A hook (not a callback) to show object properties in given HTML @@ -922,61 +979,59 @@ define( j = panel.$container.find('.obj_properties').first(), view = j.data('obj-view'), content = $('
') - .addClass('pg-prop-content col-xs-12'); - - // Handle key press events for Cancel, save and help button - var handleKeyDown = function(event, context) { - // If called on panel other than node_props, return - if (panel && panel['_type'] !== 'node_props') return; - - switch (event.which) { - case keyCode.ESCAPE: - closePanel(); - break; - case keyCode.ENTER: - // Return if event is fired from child element - if (event.target !== context) return; - if (view && view.model && view.model.sessChanged()) { - var btn = $(event.target).closest('.obj_properties') - .find('.pg-prop-btn-group') - .find('button.btn-primary'); - onSave.call(this, view, btn); - } - break; - case keyCode.F1: - onDialogHelp(); - break; - default: - break; - } - }.bind(panel); + .addClass('pg-prop-content col-xs-12'); - setTimeout(function() { - // Register key press events with panel element - panel.$container.find('.backform-tab').on("keydown", function(event) { - handleKeyDown(event, this); - }); - }, 200); // wait for panel tab to render - - // Template function to create the status bar - var createStatusBar = function(location){ - var statusBar = $('
').addClass( - 'pg-prop-status-bar' - ).appendTo(j); - statusBar.css("visibility", "hidden"); - if (location == "header") { - statusBar.appendTo(that.header); - } else { - statusBar.prependTo(that.footer); - } - that.statusBar = statusBar; - return statusBar; + // Handle key press events for Cancel, save and help button + var handleKeyDown = function(event, context) { + // If called on panel other than node_props, return + if (panel && panel['_type'] !== 'node_props') return; + + switch (event.which) { + case keyCode.ESCAPE: + closePanel(); + break; + case keyCode.ENTER: + // Return if event is fired from child element + if (event.target !== context) return; + if (view && view.model && view.model.sessChanged()) { + var btn = $(event.target).closest('.obj_properties') + .find('.pg-prop-btn-group') + .find('button.btn-primary'); + onSave.call(this, view, btn); + } + break; + case keyCode.F1: + onDialogHelp(); + break; + default: + break; + } + }.bind(panel); + + setTimeout(function() { + // Register key press events with panel element + panel.$container.find('.backform-tab').on('keydown', function(event) { + handleKeyDown(event, this); + }); + }, 200); // wait for panel tab to render + + // Template function to create the status bar + var createStatusBar = function(location) { + var statusBar = $('
').addClass( + 'pg-prop-status-bar' + ).appendTo(j); + statusBar.css('visibility', 'hidden'); + if (location == 'header') { + statusBar.appendTo(that.header); + } else { + statusBar.prependTo(that.footer); + } + that.statusBar = statusBar; + return statusBar; }.bind(panel), // Template function to create the button-group createButtons = function(buttons, location, extraClasses) { - var panel = this; - - // arguments must be non-zero length array of type + // Arguments must be non-zero length array of type // object, which contains following attributes: // label, type, extraClasses, register if (buttons && _.isArray(buttons) && buttons.length > 0) { @@ -984,19 +1039,19 @@ define( // div area. var btnGroup = $('
').addClass( - 'pg-prop-btn-group' - ), + 'pg-prop-btn-group' + ), // Template used for creating a button tmpl = _.template([ '' - ].join(' ')); - if (location == "header"){ - btnGroup.appendTo(that.header); - }else{ - btnGroup.appendTo(that.footer); + '<% if (label != "") { %> <%-label%><% } %>', + ].join(' ')); + if (location == 'header') { + btnGroup.appendTo(that.header); + } else { + btnGroup.appendTo(that.footer); } if (extraClasses) { btnGroup.addClass(extraClasses); @@ -1007,7 +1062,7 @@ define( // icon may not present for this button if (!btn.icon) { - btn.icon = ""; + btn.icon = ''; } var b = $(tmpl(btn)); btnGroup.append(b); @@ -1024,12 +1079,10 @@ define( // Avoid unnecessary reloads var panel = this, - i = tree.selected(), - d = i && tree.itemData(i), - n_type = d._type, - n_value = -1, - n = i && d && pgBrowser.Nodes[d._type], - treeHierarchy = n.getTreeNodeHierarchy(i); + i = tree.selected(), + d = i && tree.itemData(i), + n = i && d && pgBrowser.Nodes[d._type], + treeHierarchy = n.getTreeNodeHierarchy(i); if (_.isEqual($(panel).data('node-prop'), treeHierarchy)) { return; @@ -1045,7 +1098,11 @@ define( // creating new view. if (view) { // Release the view - view.remove({data: true, internal: true, silent: true}); + view.remove({ + data: true, + internal: true, + silent: true, + }); // Deallocate the view // delete view; view = null; @@ -1055,11 +1112,11 @@ define( // Make sure the HTML element is empty. j.empty(); that.header = $('
').addClass( - 'pg-prop-header' - ).appendTo(j); + 'pg-prop-header' + ).appendTo(j); that.footer = $('
').addClass( - 'pg-prop-footer' - ).appendTo(j); + 'pg-prop-footer' + ).appendTo(j); // Create a view to show the properties in fieldsets view = that.getView(item, 'properties', content, data, 'fieldset', undefined, j); if (view) { @@ -1071,7 +1128,8 @@ define( var buttons = []; buttons.push({ - label: '', type: 'edit', + label: '', + type: 'edit', tooltip: gettext('Edit'), extraClasses: ['btn-default'], icon: 'fa fa-lg fa-pencil-square-o', @@ -1080,11 +1138,12 @@ define( btn.click(function() { onEdit(); }); - } + }, }); buttons.push({ - label: '', type: 'help', + label: '', + type: 'help', tooltip: gettext('SQL help for this object type.'), extraClasses: ['btn-default', 'pull-right'], icon: 'fa fa-lg fa-info', @@ -1093,7 +1152,7 @@ define( btn.click(function() { onSqlHelp(); }); - } + }, }); createButtons(buttons, 'header', 'pg-prop-btn-group-above bg-gray-2 border-gray-3'); @@ -1101,7 +1160,6 @@ define( j.append(content); }.bind(panel), onSqlHelp = function() { - var panel = this; // See if we can find an existing panel, if not, create one var pnlSqlHelp = pgBrowser.docker.findPanels('pnl_sql_help')[0]; @@ -1124,17 +1182,17 @@ define( url = url.replace('$VERSION$', major + '.' + minor); if (!S(url).endsWith('/')) { - url = url + '/' + url = url + '/'; } if (that.sqlCreateHelp == '' && that.sqlAlterHelp != '') { - url = url + that.sqlAlterHelp + url = url + that.sqlAlterHelp; } else if (that.sqlCreateHelp != '' && that.sqlAlterHelp == '') { - url = url + that.sqlCreateHelp + url = url + that.sqlCreateHelp; } else { if (view.model.isNew()) { - url = url + that.sqlCreateHelp + url = url + that.sqlCreateHelp; } else { - url = url + that.sqlAlterHelp + url = url + that.sqlAlterHelp; } } @@ -1147,7 +1205,6 @@ define( }.bind(panel), onDialogHelp = function() { - var panel = this; // See if we can find an existing panel, if not, create one var pnlDialogHelp = pgBrowser.docker.findPanels('pnl_online_help')[0]; @@ -1168,13 +1225,12 @@ define( var m = view.model, d = m.toJSON(true), // Generate a timer for the request - timer = setTimeout(function(){ + timer = setTimeout(function() { $('.obj_properties').addClass('show_progress'); - }, 1000), - saveBtn = saveBtn; + }, 1000); // Prevent subsequent save operation by disabling Save button - if(saveBtn) + if (saveBtn) $(saveBtn).prop('disabled', true); if (d && !_.isEmpty(d)) { @@ -1197,29 +1253,29 @@ define( pnlDependencies = pgBrowser.docker.findPanels('dependencies')[0], pnlDependents = pgBrowser.docker.findPanels('dependents')[0]; - if(pnlProperties) - $(pnlProperties).removeData('node-prop'); - if(pnlSql) - $(pnlSql).removeData('node-prop'); - if(pnlStats) - $(pnlStats).removeData('node-prop'); - if(pnlDependencies) - $(pnlDependencies).removeData('node-prop'); - if(pnlDependents) - $(pnlDependents).removeData('node-prop'); + if (pnlProperties) + $(pnlProperties).removeData('node-prop'); + if (pnlSql) + $(pnlSql).removeData('node-prop'); + if (pnlStats) + $(pnlStats).removeData('node-prop'); + if (pnlDependencies) + $(pnlDependencies).removeData('node-prop'); + if (pnlDependents) + $(pnlDependents).removeData('node-prop'); }, error: function(m, jqxhr) { Alertify.pgNotifier( - "error", jqxhr, - gettext("Error saving properties") + 'error', jqxhr, + gettext('Error saving properties') ); // Hide progress cursor $('.obj_properties').removeClass('show_progress'); clearTimeout(timer); - if(saveBtn) + if (saveBtn) $(saveBtn).prop('disabled', false); - } + }, }); } }.bind(panel), @@ -1234,7 +1290,11 @@ define( // creating the new view. if (view) { // Release the view - view.remove({data: true, internal: true, silent: true}); + view.remove({ + data: true, + internal: true, + silent: true, + }); // Deallocate the view view = null; // Reset the data object @@ -1244,17 +1304,17 @@ define( j.empty(); that.header = $('
').addClass( - 'pg-prop-header' - ).appendTo(j) + 'pg-prop-header' + ).appendTo(j); that.footer = $('
').addClass( - 'pg-prop-footer' - ).appendTo(j); + 'pg-prop-footer' + ).appendTo(j); var updateButtons = function(hasError, modified) { var btnGroup = this.find('.pg-prop-btn-group'), - btnSave = btnGroup.find('button.btn-primary'), - btnReset = btnGroup.find('button.btn-warning'); + btnSave = btnGroup.find('button.btn-primary'), + btnReset = btnGroup.find('button.btn-warning'); if (hasError || !modified) { btnSave.prop('disabled', true); @@ -1280,14 +1340,15 @@ define( j.data('obj-view', view); panel.icon( - _.isFunction(that['node_image']) ? - (that['node_image']).apply(that, [data, view.model]) : - (that['node_image'] || ('icon-' + that.type)) - ); + _.isFunction(that['node_image']) ? + (that['node_image']).apply(that, [data, view.model]) : + (that['node_image'] || ('icon-' + that.type)) + ); // Create proper buttons createButtons([{ - label: '', type: 'help', + label: '', + type: 'help', tooltip: gettext('SQL help for this object type.'), extraClasses: ['btn-default', 'pull-left'], icon: 'fa fa-lg fa-info', @@ -1296,9 +1357,10 @@ define( btn.click(function() { onSqlHelp(); }); - } - },{ - label: '', type: 'help', + }, + }, { + label: '', + type: 'help', tooltip: gettext('Help for this dialog.'), extraClasses: ['btn-default', 'pull-left'], icon: 'fa fa-lg fa-question', @@ -1307,9 +1369,10 @@ define( btn.click(function() { onDialogHelp(); }); - } - },{ - label: gettext('Save'), type: 'save', + }, + }, { + label: gettext('Save'), + type: 'save', tooltip: gettext('Save this object.'), extraClasses: ['btn-primary'], icon: 'fa fa-lg fa-save', @@ -1319,9 +1382,10 @@ define( btn.click(function() { onSave.call(this, view, btn); }); - } - },{ - label: gettext('Cancel'), type: 'cancel', + }, + }, { + label: gettext('Cancel'), + type: 'cancel', tooltip: gettext('Cancel changes to this object.'), extraClasses: ['btn-danger'], icon: 'fa fa-lg fa-close', @@ -1332,20 +1396,23 @@ define( panel.$container.removeAttr('action-mode'); onCancelFunc.call(arguments); }); - } - },{ - label: gettext('Reset'), type: 'reset', + }, + }, { + label: gettext('Reset'), + type: 'reset', tooltip: gettext('Reset the fields on this dialog.'), extraClasses: ['btn-warning'], icon: 'fa fa-lg fa-recycle', disabled: true, register: function(btn) { btn.click(function() { - setTimeout(function() { editFunc.call(); }, 0); + setTimeout(function() { + editFunc.call(); + }, 0); }); - } - }],'footer' ,'pg-prop-btn-group-below bg-gray-2 border-gray-3'); - }; + }, + }], 'footer', 'pg-prop-btn-group-below bg-gray-2 border-gray-3'); + } // Create status bar. createStatusBar('footer'); @@ -1363,11 +1430,13 @@ define( }.bind(panel), updateTreeItem = function(that) { var _old = data, - _new = _.clone(view.model.tnode), - info = _.clone(view.model.node_info); + _new = _.clone(view.model.tnode), + info = _.clone(view.model.node_info); // Clear the cache for this node now. - setTimeout(function() { that.clear_cache.apply(that, item); }, 0); + setTimeout(function() { + that.clear_cache.apply(that, item); + }, 0); pgBrowser.Events.trigger( 'pgadmin:browser:tree:update', @@ -1381,25 +1450,27 @@ define( 'pgadmin:browser:node:' + _newNodeData._type + ':updated', _item, _newNodeData, _oldNodeData ); - } + }, } ); closePanel(); }, saveNewNode = function(that) { var panel = this, - j = panel.$container.find('.obj_properties').first(), - view = j.data('obj-view'); + j = panel.$container.find('.obj_properties').first(), + view = j.data('obj-view'); // Clear the cache for this node now. - setTimeout(function() { that.clear_cache.apply(that, item); }, 0); + setTimeout(function() { + that.clear_cache.apply(that, item); + }, 0); try { pgBrowser.Events.trigger( 'pgadmin:browser:tree:add', _.clone(view.model.tnode), _.clone(view.model.node_info) ); } catch (e) { - console.log(e); + console.warn(e.stack || e); } closePanel(); }.bind(panel, that), @@ -1408,7 +1479,7 @@ define( setTimeout(function() { that.callbacks.show_obj_properties.apply(that, [{ 'action': 'edit', - 'item': item + 'item': item, }]); }, 0); }, @@ -1417,7 +1488,7 @@ define( onEdit = editFunc.bind(panel); if (action) { - if (action == 'create'){ + if (action == 'create') { onCancelFunc = closePanel; onSaveFunc = saveNewNode; } @@ -1435,10 +1506,14 @@ define( if (panel.closeable()) { var onCloseFunc = function() { var j = this.$container.find('.obj_properties').first(), - view = j && j.data('obj-view'); + view = j && j.data('obj-view'); if (view) { - view.remove({data: true, internal: true, silent: true}); + view.remove({ + data: true, + internal: true, + silent: true, + }); } }.bind(panel); panel.on(wcDocker.EVENT.CLOSED, onCloseFunc); @@ -1452,7 +1527,7 @@ define( if (this.parent_type == d._type) { return i; } - while(t.hasParent(i)) { + while (t.hasParent(i)) { i = t.parent(i); d = t.itemData(i); @@ -1463,7 +1538,7 @@ define( if (_.indexOf(this.parent_type, d._type) >= 0) { return i; } - while(t.hasParent(i)) { + while (t.hasParent(i)) { i = t.parent(i); d = t.itemData(i); @@ -1488,9 +1563,13 @@ define( generate_url: function(item, type, d, with_id, info) { var opURL = { - 'create': 'obj', 'drop': 'obj', 'edit': 'obj', - 'properties': 'obj', 'statistics': 'stats' - }, self = this, + 'create': 'obj', + 'drop': 'obj', + 'edit': 'obj', + 'properties': 'obj', + 'statistics': 'stats', + }, + self = this, priority = -Infinity; var treeInfo = (_.isUndefined(item) || _.isNull(item)) ? @@ -1515,7 +1594,7 @@ define( }); } } - var nodePickFunction = function (treeInfoValue) { + var nodePickFunction = function(treeInfoValue) { return (treeInfoValue.priority <= priority); }; return generateUrl.generate_url(pgBrowser.URL, treeInfo, actionType, self.type, nodePickFunction, itemID); @@ -1526,14 +1605,14 @@ define( Model: pgBrowser.DataModel, getTreeNodeHierarchy: function(i) { var idx = 0, - res = {}, - t = pgBrowser.tree, - d; + res = {}, + t = pgBrowser.tree, + d; do { d = t.itemData(i); if (d._type in pgBrowser.Nodes && pgBrowser.Nodes[d._type].hasId) { res[d._type] = _.extend({}, d, { - 'priority': idx + 'priority': idx, }); idx -= 1; } @@ -1544,38 +1623,39 @@ define( }, cache: function(url, node_info, level, data) { var cached = this.cached = this.cached || {}, - hash = url, - min_priority = ( - node_info && node_info[level] && node_info[level].priority - ) || 0; + hash = url, + min_priority = ( + node_info && node_info[level] && node_info[level].priority + ) || 0; if (node_info) { - _.each( - _.sortBy( - _.values( - _.pick( - node_info, - function(v, k, o) { - return (v.priority <= min_priority); - })), - function(o) { return o.priority; }), - function(o) { - hash = S('%s/%s').sprintf(hash, encodeURI(o._id)).value(); - }); + _.each(_.sortBy(_.values(_.pick( + node_info, + function(v) { + return (v.priority <= min_priority); + } + )), function(o) { + return o.priority; + }), function(o) { + hash = S('%s/%s').sprintf(hash, encodeURI(o._id)).value(); + }); } if (_.isUndefined(data)) { var res = cached[hash]; if (!_.isUndefined(res) && - (res.at - Date.now() > 300000)) { + (res.at - Date.now() > 300000)) { res = undefined; } return res; } - res = cached[hash] = {data: data, at: Date.now(), level: level}; - + res = cached[hash] = { + data: data, + at: Date.now(), + level: level, + }; return res; }, clear_cache: function(item) { @@ -1611,7 +1691,7 @@ define( } return this.parent_type; } - } + }, }); return pgAdmin.Browser.Node; diff --git a/web/pgadmin/browser/static/js/node.ui.js b/web/pgadmin/browser/static/js/node.ui.js index 7aca37ce..227b4571 100644 --- a/web/pgadmin/browser/static/js/node.ui.js +++ b/web/pgadmin/browser/static/js/node.ui.js @@ -1,10 +1,7 @@ define([ 'sources/gettext', 'jquery', 'underscore', 'sources/pgadmin', 'backbone', 'backform', - 'alertify', 'backgrid', 'select2', 'pgadmin.browser.node' -], -function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { - - var pgBrowser = pgAdmin.Browser; + 'alertify', 'backgrid', 'select2', 'pgadmin.browser.node', +], function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { /* * Define the selectAll adapter for select2. @@ -15,11 +12,11 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { $.fn.select2.amd.define('select2/selectAllAdapter', [ 'select2/utils', 'select2/dropdown', - 'select2/dropdown/attachBody' - ], function (Utils, Dropdown, AttachBody) { + 'select2/dropdown/attachBody', + ], function(Utils, Dropdown, AttachBody) { - function SelectAll() { } - SelectAll.prototype.render = function (decorated) { + function SelectAll() {} + SelectAll.prototype.render = function(decorated) { var self = this, $rendered = decorated.call(this), $selectAll = $([ @@ -27,41 +24,43 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { ' style="width: 49%;margin: 0 0.5%;">', '', '', - gettext("Select All"), - '' + gettext('Select All'), + '', ].join('')), $unselectAll = $([ '' + gettext('Unselect All'), + '', ].join('')), $btnContainer = $( '
' ).append($selectAll).append($unselectAll); - if (!this.$element.prop("multiple")) { + if (!this.$element.prop('multiple')) { // this isn't a multi-select -> don't add the buttons! return $rendered; } $rendered.find('.select2-dropdown').prepend($btnContainer); - $selectAll.on('click', function (e) { - var $results = $rendered.find('.select2-results__option[aria-selected=false]'); - $results.each(function () { - self.trigger('select', { - data: $(this).data('data') - }); - }); + $selectAll.on('click', function() { + $rendered.find('.select2-results__option[aria-selected=false]').each( + function() { + self.trigger('select', { + data: $(this).data('data'), + }); + } + ); self.trigger('close'); }); - $unselectAll.on('click', function (e) { - var $results = $rendered.find('.select2-results__option[aria-selected=true]'); - $results.each(function () { - self.trigger('unselect', { - data: $(this).data('data') - }); - }); + $unselectAll.on('click', function() { + $rendered.find('.select2-results__option[aria-selected=true]').each( + function() { + self.trigger('unselect', { + data: $(this).data('data'), + }); + } + ); self.trigger('close'); }); return $rendered; @@ -89,98 +88,98 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { * data to proper 'label', 'value' format. */ var NodeAjaxOptionsControl = Backform.NodeAjaxOptionsControl = - Backform.Select2Control.extend({ - defaults: _.extend(Backform.Select2Control.prototype.defaults, { - url: undefined, - transform: undefined, - url_with_id: false, - select2: { - allowClear: true, - placeholder: 'Select from the list', - width: 'style' - } - }), - initialize: function() { - /* - * Initialization from the original control. - */ - Backform.Select2Control.prototype.initialize.apply(this, arguments); - - /* - * We're about to fetch the options required for this control. - */ - var self = this, + Backform.Select2Control.extend({ + defaults: _.extend(Backform.Select2Control.prototype.defaults, { + url: undefined, + transform: undefined, + url_with_id: false, + select2: { + allowClear: true, + placeholder: 'Select from the list', + width: 'style', + }, + }), + initialize: function() { + /* + * Initialization from the original control. + */ + Backform.Select2Control.prototype.initialize.apply(this, arguments); + + /* + * We're about to fetch the options required for this control. + */ + var self = this, url = self.field.get('url') || self.defaults.url, m = self.model.top || self.model; - // Hmm - we found the url option. - // That means - we needs to fetch the options from that node. - if (url) { - var node = this.field.get('schema_node'), + // Hmm - we found the url option. + // That means - we needs to fetch the options from that node. + if (url) { + var node = this.field.get('schema_node'), node_info = this.field.get('node_info'), with_id = this.field.get('url_with_id') || false, full_url = node.generate_url.apply( node, [ - null, url, this.field.get('node_data'), with_id, node_info + null, url, this.field.get('node_data'), with_id, node_info, ]), cache_level, cache_node = this.field.get('cache_node'); - cache_node = (cache_node && pgAdmin.Browser.Nodes[cache_node]) || node; + cache_node = (cache_node && pgAdmin.Browser.Nodes[cache_node]) || node; - if (this.field.has('cache_level')) { - cache_level = this.field.get('cache_level'); - } else { - cache_level = cache_node.cache_level(node_info, with_id); - } + if (this.field.has('cache_level')) { + cache_level = this.field.get('cache_level'); + } else { + cache_level = cache_node.cache_level(node_info, with_id); + } - /* - * We needs to check, if we have already cached data for this url. - * If yes - use that, and do not bother about fetching it again, - * and use it. - */ - var data = cache_node.cache(node.type + '#' + url, node_info, cache_level); + /* + * We needs to check, if we have already cached data for this url. + * If yes - use that, and do not bother about fetching it again, + * and use it. + */ + var data = cache_node.cache(node.type + '#' + url, node_info, cache_level); - if (this.field.get('version_compatible') && + if (this.field.get('version_compatible') && (_.isUndefined(data) || _.isNull(data))) { - m.trigger('pgadmin:view:fetching', m, self.field); - $.ajax({ - async: false, - url: full_url, - success: function(res) { - /* - * We will cache this data for short period of time for avoiding - * same calls. - */ - data = cache_node.cache(node.type + '#' + url, node_info, cache_level, res.data); - }, - error: function() { - m.trigger('pgadmin:view:fetch:error', m, self.field); - } - }); - m.trigger('pgadmin:view:fetched', m, self.field); - } - // To fetch only options from cache, we do not need time from 'at' - // attribute but only options. - // - // It is feasible that the data may not have been fetched. - data = (data && data.data) || []; - - /* - * Transform the data - */ - var transform = this.field.get('transform') || self.defaults.transform; - if (transform && _.isFunction(transform)) { - // We will transform the data later, when rendering. - // It will allow us to generate different data based on the - // dependencies. - self.field.set('options', transform.bind(self, data)); - } else { - self.field.set('options', data); + m.trigger('pgadmin:view:fetching', m, self.field); + $.ajax({ + async: false, + url: full_url, + success: function(res) { + /* + * We will cache this data for short period of time for avoiding + * same calls. + */ + data = cache_node.cache(node.type + '#' + url, node_info, cache_level, res.data); + }, + error: function() { + m.trigger('pgadmin:view:fetch:error', m, self.field); + }, + }); + m.trigger('pgadmin:view:fetched', m, self.field); + } + // To fetch only options from cache, we do not need time from 'at' + // attribute but only options. + // + // It is feasible that the data may not have been fetched. + data = (data && data.data) || []; + + /* + * Transform the data + */ + var transform = this.field.get('transform') || self.defaults.transform; + if (transform && _.isFunction(transform)) { + // We will transform the data later, when rendering. + // It will allow us to generate different data based on the + // dependencies. + self.field.set('options', transform.bind(self, data)); + } else { + self.field.set('options', data); + } } - } - } - }); + }, + }); var formatNode = function(opt) { if (!opt.id) { @@ -189,14 +188,14 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { var optimage = $(opt.element).data('image'); - if(!optimage){ + if (!optimage) { return opt.text; } else { return $('').append( - $('', {class: "wcTabIcon " + optimage}) - ).append( - $('').text(opt.text) - ); + $('', { + class: 'wcTabIcon ' + optimage, + }) + ).append($('').text(opt.text)); } }; @@ -207,27 +206,29 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { filter: undefined, transform: function(rows) { var self = this, - node = self.field.get('schema_node'), - res = [], - filter = self.field.get('filter') || function() { return true; }; + node = self.field.get('schema_node'), + res = [], + filter = self.field.get('filter') || function() { + return true; + }; filter = filter.bind(self); _.each(rows, function(r) { if (filter(r)) { var l = (_.isFunction(node['node_label']) ? - (node['node_label']).apply(node, [r, self.model, self]) : - r.label), - image= (_.isFunction(node['node_image']) ? - (node['node_image']).apply( - node, [r, self.model, self] - ) : - (node['node_image'] || ('icon-' + node.type))); + (node['node_label']).apply(node, [r, self.model, self]) : + r.label), + image = (_.isFunction(node['node_image']) ? + (node['node_image']).apply( + node, [r, self.model, self] + ) : + (node['node_image'] || ('icon-' + node.type))); res.push({ 'value': r._id, 'image': image, - 'label': l + 'label': l, }); } }); @@ -239,62 +240,64 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { placeholder: 'Select from the list', width: 'style', templateResult: formatNode, - templateSelection: formatNode - } - }) + templateSelection: formatNode, + }, + }), }); - - var NodeListByNameControl = Backform.NodeListByNameControl = NodeListByIdControl.extend({ + Backform.NodeListByNameControl = NodeListByIdControl.extend({ defaults: _.extend({}, NodeListByIdControl.prototype.defaults, { transform: function(rows) { var self = this, - node = self.field.get('schema_node'), - res = [], - filter = self.field.get('filter') || function() { return true; }; + node = self.field.get('schema_node'), + res = [], + filter = self.field.get('filter') || function() { + return true; + }; filter = filter.bind(self); _.each(rows, function(r) { if (filter(r)) { var l = (_.isFunction(node['node_label']) ? - (node['node_label']).apply(node, [r, self.model, self]) : - r.label), - image = (_.isFunction(node['node_image']) ? - (node['node_image']).apply( - node, [r, self.model, self] - ) : - (node['node_image'] || ('icon-' + node.type))); + (node['node_label']).apply(node, [r, self.model, self]) : + r.label), + image = (_.isFunction(node['node_image']) ? + (node['node_image']).apply( + node, [r, self.model, self] + ) : + (node['node_image'] || ('icon-' + node.type))); res.push({ 'value': r.label, 'image': image, - 'label': l + 'label': l, }); } }); return res; - } - }) + }, + }), }); /* * Global function to make visible particular dom element in it's parent * with given class. */ - $.fn.pgMakeVisible = function( cls ) { + $.fn.pgMakeVisible = function(cls) { return this.each(function() { if (!this || !$(this.length)) return; - var top, p = $(this), hasScrollbar = function(j) { - if (j && j.length > 0) { - return j.get(0).scrollHeight > j.height(); - } - return false; - }; + var top, p = $(this), + hasScrollbar = function(j) { + if (j && j.length > 0) { + return j.get(0).scrollHeight > j.height(); + } + return false; + }; // check if p is not empty - while(p && p.length > 0) { + while (p && p.length > 0) { top = p.get(0).offsetTop + p.height(); p = p.parent(); if (hasScrollbar(p)) { @@ -327,40 +330,41 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { select2: { allowClear: true, placeholder: 'Select from the list', - width: 'style' + width: 'style', }, opt: { label: null, value: null, image: null, - selected: false - } + selected: false, + }, }), template: _.template( '' ), - initialize: function () { + initialize: function() { Backgrid.Extension.Select2Cell.prototype.initialize.apply(this, arguments); var url = this.column.get('url') || this.defaults.url, - is_options_cached = _.has(this.column.attributes, 'options_cached'), - options_cached = is_options_cached && this.column.get('options_cached'); + is_options_cached = _.has(this.column.attributes, 'options_cached'), + options_cached = is_options_cached && this.column.get('options_cached'); // Hmm - we found the url option. // That means - we needs to fetch the options from that node. if (url && !options_cached) { var self = this, - m = this.model, column = this.column, - eventHandler = m.top || m, - node = column.get('schema_node'), - node_info = column.get('node_info'), - with_id = column.get('url_with_id') || false, - full_url = node.generate_url.apply( - node, [ - null, url, column.get('node_data'), with_id, node_info - ]), - cache_level, - cache_node = column.get('cache_node'); + m = this.model, + column = this.column, + eventHandler = m.top || m, + node = column.get('schema_node'), + node_info = column.get('node_info'), + with_id = column.get('url_with_id') || false, + full_url = node.generate_url.apply( + node, [ + null, url, column.get('node_data'), with_id, node_info, + ]), + cache_level, + cache_node = column.get('cache_node'); cache_node = (cache_node && pgAdmin.Browser.Nodes[cache_node]) || node; @@ -378,7 +382,7 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { var data = cache_node.cache(node.type + '#' + url, node_info, cache_level); if (column.get('version_compatible') && - (_.isUndefined(data) || _.isNull(data))) { + (_.isUndefined(data) || _.isNull(data))) { eventHandler.trigger('pgadmin:view:fetching', m, column); $.ajax({ async: false, @@ -392,7 +396,7 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { }, error: function() { eventHandler.trigger('pgadmin:view:fetch:error', m, column); - } + }, }); eventHandler.trigger('pgadmin:view:fetched', m, column); } @@ -415,41 +419,43 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { column.set('options', data); } - if(is_options_cached) { + if (is_options_cached) { column.set('options_cached', true); } } - } + }, }); - var NodeListByIdCell = Backgrid.Extension.NodeListByIdCell = NodeAjaxOptionsCell.extend({ + Backgrid.Extension.NodeListByIdCell = NodeAjaxOptionsCell.extend({ controlClassName: 'pgadmin-node-select backgrid-cell', defaults: _.extend({}, NodeAjaxOptionsCell.prototype.defaults, { url: 'nodes', filter: undefined, transform: function(rows, control) { var self = control || this, - node = self.column.get('schema_node'), - res = [], - filter = self.column.get('filter') || function() { return true; }; + node = self.column.get('schema_node'), + res = [], + filter = self.column.get('filter') || function() { + return true; + }; filter = filter.bind(self); _.each(rows, function(r) { if (filter(r)) { var l = (_.isFunction(node['node_label']) ? - (node['node_label']).apply(node, [r, self.model, self]) : - r.label), - image= (_.isFunction(node['node_image']) ? - (node['node_image']).apply( - node, [r, self.model, self] - ) : - (node['node_image'] || ('icon-' + node.type))); + (node['node_label']).apply(node, [r, self.model, self]) : + r.label), + image = (_.isFunction(node['node_image']) ? + (node['node_image']).apply( + node, [r, self.model, self] + ) : + (node['node_image'] || ('icon-' + node.type))); res.push({ 'value': r._id, 'image': image, - 'label': l + 'label': l, }); } }); @@ -460,40 +466,41 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { placeholder: 'Select from the list', width: 'style', templateResult: formatNode, - templateSelection: formatNode - } - }) + templateSelection: formatNode, + }, + }), }); - - var NodeListByNameCell = Backgrid.Extension.NodeListByNameCell = NodeAjaxOptionsCell.extend({ + Backgrid.Extension.NodeListByNameCell = NodeAjaxOptionsCell.extend({ controlClassName: 'pgadmin-node-select backgrid-cell', defaults: _.extend({}, NodeAjaxOptionsCell.prototype.defaults, { url: 'nodes', filter: undefined, transform: function(rows, control) { var self = control || this, - node = self.column.get('schema_node'), - res = [], - filter = self.column.get('filter') || function() { return true; }; + node = self.column.get('schema_node'), + res = [], + filter = self.column.get('filter') || function() { + return true; + }; filter = filter.bind(self); _.each(rows, function(r) { if (filter(r)) { var l = (_.isFunction(node['node_label']) ? - (node['node_label']).apply(node, [r, self.model, self]) : - r.label), - image= (_.isFunction(node['node_image']) ? - (node['node_image']).apply( - node, [r, self.model, self] - ) : - (node['node_image'] || ('icon-' + node.type))); + (node['node_label']).apply(node, [r, self.model, self]) : + r.label), + image = (_.isFunction(node['node_image']) ? + (node['node_image']).apply( + node, [r, self.model, self] + ) : + (node['node_image'] || ('icon-' + node.type))); res.push({ 'value': r.label, 'image': image, - 'label': l + 'label': l, }); } }); @@ -504,13 +511,13 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { placeholder: 'Select from the list', width: 'style', templateResult: formatNode, - templateSelection: formatNode - } - }) + templateSelection: formatNode, + }, + }), }); - // Extend the browser's node model class to create a option/value pair - var MultiSelectAjaxCell = Backgrid.Extension.MultiSelectAjaxCell = Backgrid.Extension.NodeAjaxOptionsCell.extend({ + // Extend the browser's node model class to create a option/value pair + Backgrid.Extension.MultiSelectAjaxCell = Backgrid.Extension.NodeAjaxOptionsCell.extend({ defaults: _.extend({}, NodeAjaxOptionsCell.prototype.defaults, { transform: undefined, url_with_id: false, @@ -518,19 +525,19 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { allowClear: true, placeholder: 'Select from the list', width: 'style', - multiple: true + multiple: true, }, opt: { label: null, value: null, image: null, - selected: false - } + selected: false, + }, }), getValueFromDOM: function() { var res = []; - this.$el.find("select").find(':selected').each(function() { + this.$el.find('select').find(':selected').each(function() { res.push($(this).attr('value')); }); @@ -541,15 +548,15 @@ function(gettext, $, _, pgAdmin, Backbone, Backform, Alertify, Backgrid) { /* * Control to select multiple columns. */ - var MultiSelectAjaxControl = Backform.MultiSelectAjaxControl = NodeAjaxOptionsControl.extend({ + Backform.MultiSelectAjaxControl = NodeAjaxOptionsControl.extend({ defaults: _.extend({}, NodeAjaxOptionsControl.prototype.defaults, { select2: { multiple: true, allowClear: true, - width: 'style' - } - }) + width: 'style', + }, + }), }); return Backform; -}); +}); \ No newline at end of file diff --git a/web/pgadmin/browser/static/js/panel.js b/web/pgadmin/browser/static/js/panel.js index 3a9f22d4..f0850676 100644 --- a/web/pgadmin/browser/static/js/panel.js +++ b/web/pgadmin/browser/static/js/panel.js @@ -1,66 +1,67 @@ define( - ['underscore', 'sources/pgadmin', 'wcdocker'], -function(_, pgAdmin) { - - var pgBrowser = pgAdmin.Browser = pgAdmin.Browser || {}; - - pgAdmin.Browser.Panel = function(options) { - var defaults = [ - 'name', 'title', 'width', 'height', 'showTitle', 'isCloseable', - 'isPrivate', 'content', 'icon', 'events', 'onCreate', 'elContainer', - 'canHide', 'limit' - ]; - _.extend(this, _.pick(options, defaults)); - } - - _.extend(pgAdmin.Browser.Panel.prototype, { - name:'', - title: '', - width: 300, - height: 600, - showTitle: true, - isCloseable: true, - isPrivate: false, - content: '', - icon: '', - panel: null, - onCreate: null, - elContainer: false, - limit: null, - load: function(docker, title) { - var that = this; - if (!that.panel) { - docker.registerPanelType(that.name, { - title: that.title, - isPrivate: that.isPrivate, - limit: that.limit, - onCreate: function(myPanel) { - $(myPanel).data('pgAdminName', that.name); - myPanel.initSize(that.width, that.height); - - if (!that.showTitle) - myPanel.title(false); - else { - myPanel.title(title || that.title); - if (that.icon != '') - myPanel.icon(that.icon) - } - - var $container = $('
', { - 'class': 'pg-panel-content' - }).append($(that.content)); - - myPanel.closeable(!!that.isCloseable); - myPanel.layout().addItem($container); - that.panel = myPanel; - if (that.events && _.isObject(that.events)) { - _.each(that.events, function(v, k) { - if (v && _.isFunction(v)) { - myPanel.on(k, v); - } - }); - } - _.each([ + ['underscore', 'sources/pgadmin', 'jquery', 'wcdocker'], + function(_, pgAdmin, $) { + + var pgBrowser = pgAdmin.Browser = pgAdmin.Browser || {}, + wcDocker = window.wcDocker; + + pgAdmin.Browser.Panel = function(options) { + var defaults = [ + 'name', 'title', 'width', 'height', 'showTitle', 'isCloseable', + 'isPrivate', 'content', 'icon', 'events', 'onCreate', 'elContainer', + 'canHide', 'limit', + ]; + _.extend(this, _.pick(options, defaults)); + }; + + _.extend(pgAdmin.Browser.Panel.prototype, { + name: '', + title: '', + width: 300, + height: 600, + showTitle: true, + isCloseable: true, + isPrivate: false, + content: '', + icon: '', + panel: null, + onCreate: null, + elContainer: false, + limit: null, + load: function(docker, title) { + var that = this; + if (!that.panel) { + docker.registerPanelType(that.name, { + title: that.title, + isPrivate: that.isPrivate, + limit: that.limit, + onCreate: function(myPanel) { + $(myPanel).data('pgAdminName', that.name); + myPanel.initSize(that.width, that.height); + + if (!that.showTitle) + myPanel.title(false); + else { + myPanel.title(title || that.title); + if (that.icon != '') + myPanel.icon(that.icon); + } + + var $container = $('
', { + 'class': 'pg-panel-content', + }).append($(that.content)); + + myPanel.closeable(!!that.isCloseable); + myPanel.layout().addItem($container); + that.panel = myPanel; + if (that.events && _.isObject(that.events)) { + _.each(that.events, function(v, k) { + if (v && _.isFunction(v)) { + myPanel.on(k, v); + } + }); + } + _.each([ wcDocker.EVENT.UPDATED, wcDocker.EVENT.VISIBILITY_CHANGED, wcDocker.EVENT.BEGIN_DOCK, wcDocker.EVENT.END_DOCK, wcDocker.EVENT.GAIN_FOCUS, wcDocker.EVENT.LOST_FOCUS, @@ -69,109 +70,117 @@ function(_, pgAdmin) { wcDocker.EVENT.MOVE_STARTED, wcDocker.EVENT.MOVE_ENDED, wcDocker.EVENT.MOVED, wcDocker.EVENT.RESIZE_STARTED, wcDocker.EVENT.RESIZE_ENDED, wcDocker.EVENT.RESIZED, - wcDocker.EVENT.SCROLLED], function(ev) { - myPanel.on(ev, that.eventFunc.bind(myPanel, ev)); - }); - - if (that.onCreate && _.isFunction(that.onCreate)) { - that.onCreate.apply(that, [myPanel, $container]); - } - - if (that.elContainer) { - myPanel.pgElContainer = $container; - $container.addClass('pg-el-container'); - _.each([ - wcDocker.EVENT.RESIZED, wcDocker.EVENT.ATTACHED, - wcDocker.EVENT.DETACHED, wcDocker.EVENT.VISIBILITY_CHANGED + wcDocker.EVENT.SCROLLED, ], function(ev) { - myPanel.on(ev, that.resizedContainer.bind(myPanel)); + myPanel.on(ev, that.eventFunc.bind(myPanel, ev)); }); - that.resizedContainer.apply(myPanel); - } - - // Bind events only if they are configurable - if (that.canHide) { - _.each([wcDocker.EVENT.CLOSED, wcDocker.EVENT.VISIBILITY_CHANGED], - function(ev) { - myPanel.on(ev, that.handleVisibility.bind(myPanel, ev)); + + if (that.onCreate && _.isFunction(that.onCreate)) { + that.onCreate.apply(that, [myPanel, $container]); + } + + if (that.elContainer) { + myPanel.pgElContainer = $container; + $container.addClass('pg-el-container'); + _.each([ + wcDocker.EVENT.RESIZED, wcDocker.EVENT.ATTACHED, + wcDocker.EVENT.DETACHED, wcDocker.EVENT.VISIBILITY_CHANGED, + ], function(ev) { + myPanel.on(ev, that.resizedContainer.bind(myPanel)); }); - } + that.resizedContainer.apply(myPanel); + } + + // Bind events only if they are configurable + if (that.canHide) { + _.each([wcDocker.EVENT.CLOSED, wcDocker.EVENT.VISIBILITY_CHANGED], + function(ev) { + myPanel.on(ev, that.handleVisibility.bind(myPanel, ev)); + }); + } + }, + }); + } + }, + eventFunc: function(eventName) { + var name = $(this).data('pgAdminName'); + + try { + pgBrowser.Events.trigger( + 'pgadmin-browser:panel', eventName, this, arguments + ); + pgBrowser.Events.trigger( + 'pgadmin-browser:panel:' + eventName, this, arguments + ); + + if (name) { + pgBrowser.Events.trigger( + 'pgadmin-browser:panel-' + name, eventName, this, arguments + ); + pgBrowser.Events.trigger( + 'pgadmin-browser:panel-' + name + ':' + eventName, this, arguments + ); } - }); - } - }, - eventFunc: function(eventName) { - var name = $(this).data('pgAdminName'); - - try { - pgBrowser.Events.trigger('pgadmin-browser:panel', eventName, this, arguments); - pgBrowser.Events.trigger('pgadmin-browser:panel:' + eventName, this, arguments); - - if (name) { - pgBrowser.Events.trigger('pgadmin-browser:panel-' + name, eventName, this, arguments); - pgBrowser.Events.trigger('pgadmin-browser:panel-' + name + ':' + eventName, this, arguments); + } catch (e) { + console.warn(e.stack || e); } - } catch (e) { - console.log(e); - } - }, - resizedContainer: function() { - var p = this; - - if (p.pgElContainer && !p.pgResizeTimeout) { - if (!p.isVisible()) { - clearTimeout(p.pgResizeTimeout); - p.pgResizeTimeout = null; + }, + resizedContainer: function() { + var p = this; - return; - } - p.pgResizeTimeout = setTimeout( - function() { - var w = p.width(); + if (p.pgElContainer && !p.pgResizeTimeout) { + if (!p.isVisible()) { + clearTimeout(p.pgResizeTimeout); p.pgResizeTimeout = null; - if (w <= 480) { - w = 'xs'; - } else if (w < 600) { - w = 'sm'; - } else if (w < 768) { - w = 'md'; - } else { - w = 'lg'; - } - - p.pgElContainer.attr('el', w); - }, - 100 - ); - } - }, - handleVisibility: function(eventName) { - // Currently this function only works with dashboard panel but - // as per need it can be extended - if (this._type != 'dashboard' || _.isUndefined(pgAdmin.Dashboard)) - return; - - if (eventName == 'panelClosed') { - pgBrowser.save_current_layout(pgBrowser); - pgAdmin.Dashboard.toggleVisibility(false); - } - else if (eventName == 'panelVisibilityChanged') { - if (pgBrowser.tree) { + return; + } + p.pgResizeTimeout = setTimeout( + function() { + var w = p.width(); + p.pgResizeTimeout = null; + + if (w <= 480) { + w = 'xs'; + } else if (w < 600) { + w = 'sm'; + } else if (w < 768) { + w = 'md'; + } else { + w = 'lg'; + } + + p.pgElContainer.attr('el', w); + }, + 100 + ); + } + }, + handleVisibility: function(eventName) { + // Currently this function only works with dashboard panel but + // as per need it can be extended + if (this._type != 'dashboard' || _.isUndefined(pgAdmin.Dashboard)) + return; + + if (eventName == 'panelClosed') { pgBrowser.save_current_layout(pgBrowser); - var selectedNode = pgBrowser.tree.selected(); - // Discontinue this event after first time visible - this.off(wcDocker.EVENT.VISIBILITY_CHANGED); - if (!_.isUndefined(pgAdmin.Dashboard)) - pgAdmin.Dashboard.toggleVisibility(true); - // Explicitly trigger tree selected event when we add the tab. - pgBrowser.Events.trigger('pgadmin-browser:tree:selected', selectedNode, - pgBrowser.tree.itemData(selectedNode), pgBrowser.Node); + pgAdmin.Dashboard.toggleVisibility(false); + } else if (eventName == 'panelVisibilityChanged') { + if (pgBrowser.tree) { + pgBrowser.save_current_layout(pgBrowser); + var selectedNode = pgBrowser.tree.selected(); + // Discontinue this event after first time visible + this.off(wcDocker.EVENT.VISIBILITY_CHANGED); + if (!_.isUndefined(pgAdmin.Dashboard)) + pgAdmin.Dashboard.toggleVisibility(true); + // Explicitly trigger tree selected event when we add the tab. + pgBrowser.Events.trigger('pgadmin-browser:tree:selected', selectedNode, + pgBrowser.tree.itemData(selectedNode), pgBrowser.Node); + } } - } - } + }, - }); + }); - return pgAdmin.Browser.Panel; -}); + return pgAdmin.Browser.Panel; + }); diff --git a/web/pgadmin/browser/static/js/wizard.js b/web/pgadmin/browser/static/js/wizard.js index 2f2209a7..56b1edf2 100644 --- a/web/pgadmin/browser/static/js/wizard.js +++ b/web/pgadmin/browser/static/js/wizard.js @@ -1,20 +1,29 @@ -define( - ['underscore', 'backbone', 'sources/pgadmin', 'pgadmin.browser', 'sources/gettext'], -function(_, Backbone, pgAdmin, pgBrowser, gettext) { +define([ + 'underscore', 'jquery', 'backbone', 'sources/pgadmin', 'pgadmin.browser', + 'sources/gettext', +], function(_, $, Backbone, pgAdmin, pgBrowser, gettext) { - pgBrowser = pgBrowser || pgAdmin.Browser || {}; + var wcDocker = window.wcDocker; /* Wizard individual Page Model */ - var WizardPage = pgBrowser.WizardPage = Backbone.Model.extend({ + pgBrowser.WizardPage = Backbone.Model.extend({ defaults: { - id: undefined, /* Id */ - page_title: undefined, /* Page Title */ - view: undefined, /* A Backbone View */ - html: undefined, /* HTML tags to be rendered */ - image: undefined, /* Left hand side image */ - disable_prev: false, /* Previous Button Flag */ - disable_next: false, /* Next Button Flag */ - disable_cancel: false, /* Cancel Button Flag */ + id: undefined, + /* Id */ + page_title: undefined, + /* Page Title */ + view: undefined, + /* A Backbone View */ + html: undefined, + /* HTML tags to be rendered */ + image: undefined, + /* Left hand side image */ + disable_prev: false, + /* Previous Button Flag */ + disable_next: false, + /* Next Button Flag */ + disable_cancel: false, + /* Cancel Button Flag */ show_progress_bar: '', /* Callback for OnLoad */ onLoad: function() { @@ -24,119 +33,124 @@ function(_, Backbone, pgAdmin, pgBrowser, gettext) { beforeNext: function() { return true; }, - onNext: function(){}, + onNext: function() {}, onBefore: function() {}, /* Callback for before Previous */ beforePrev: function() { return true; - } - } + }, + }, }); - var Wizard = pgBrowser.Wizard = Backbone.View.extend({ + pgBrowser.Wizard = Backbone.View.extend({ options: { - title: 'Wizard', /* Main Wizard Title */ - image: 'left_panel.png', /* TODO:: We can use default image here */ - curr_page: 0, /* Current Page to Load */ + title: 'Wizard', + /* Main Wizard Title */ + image: 'left_panel.png', + /* TODO:: We can use default image here */ + curr_page: 0, + /* Current Page to Load */ disable_next: false, disable_prev: false, disable_finish: false, disable_cancel: false, - show_header_cancel_btn: false, /* show cancel button at wizard header */ - show_header_maximize_btn: false, /* show maximize button at wizard header */ + show_header_cancel_btn: false, + /* show cancel button at wizard header */ + show_header_maximize_btn: false, + /* show maximize button at wizard header */ dialog_api: null, height: 400, width: 650, show_left_panel: true, - wizard_help: '' + wizard_help: '', }, tmpl: _.template( - "
" - + "
" - + "
" - + "
" - + "

<%= this.options.title %> -" - + " <%= page_title %>

" - + "
" - + " <% if (this.options.show_header_cancel_btn) { %>" - + "
" - + " " - + " <% if (this.options.show_header_maximize_btn) { %>" - + " " - + " <% } %>" - + "
" - + " <% } %>" - + "
" - + "
" - + "
" - + " <% if (this.options.show_left_panel) { %>" - + "
" - + " " + gettext("Left panel logo") + "
" - + " <% } %>" - + "
" - + " <% if ( typeof show_description != 'undefined'){ %>" - + "
" - + " <%= show_description %>" - + "
" - + " <% } %>" - + "
<% if (show_progress_bar) { %>" - + "

<%= show_progress_bar %>

<% } %>" - + "
" - + "
" - + "
" - + "
" - + "
" - + " " - + " " - + "
"), + '
' + + '
' + + '
' + + '
' + + '

<%= this.options.title %> -' + + ' <%= page_title %>

' + + '
' + + ' <% if (this.options.show_header_cancel_btn) { %>' + + '
' + + ' ' + + ' <% } %>' + + '
' + + ' <% } %>' + + '
' + + '
' + + '
' + + ' <% if (this.options.show_left_panel) { %>' + + '
' + + ' ' + gettext('Left panel logo') + '
' + + ' <% } %>' + + '
' + + ' <% if ( typeof show_description != "undefined"){ %>' + + '
' + + ' <%= show_description %>' + + '
' + + ' <% } %>' + + '
<% if (show_progress_bar) { %>' + + '

<%= show_progress_bar %>

<% } %>' + + '
' + + '
' + + '
' + + '
' + + '
' + + ' ' + + ' ' + + '
'), events: { - "click button.wizard-next" : "nextPage", - "click button.wizard-back" : "prevPage", - "click button.wizard-cancel" : "onCancel", - "click button.wizard-cancel-event" : "onCancel", - "click button.wizard-maximize-event" : "onMaximize", - "click button.wizard-finish" : "finishWizard", - "click button.wizard-help" : "onDialogHelp", - "click a.close-error" : "closeErrorMsg", + 'click button.wizard-next': 'nextPage', + 'click button.wizard-back': 'prevPage', + 'click button.wizard-cancel': 'onCancel', + 'click button.wizard-cancel-event': 'onCancel', + 'click button.wizard-maximize-event': 'onMaximize', + 'click button.wizard-finish': 'finishWizard', + 'click button.wizard-help': 'onDialogHelp', + 'click a.close-error': 'closeErrorMsg', }, initialize: function(options) { this.options = _.extend({}, this.options, options.options); @@ -150,15 +164,17 @@ function(_, Backbone, pgAdmin, pgBrowser, gettext) { this.options.disable_prev = (this.options.disable_prev ? true : this.evalASFunc(this.currPage.disable_prev)); this.options.disable_cancel = (this.currPage.canCancel ? true : this.evalASFunc(this.currPage.disable_cancel)); - var that = this; - /* HTML Content */ - if (data.html) { data.content = data.html; } + if (data.html) { + data.content = data.html; + } /* Backbone View */ - else if (data.view) { data.content = data.view.render().el;} + else if (data.view) { + data.content = data.view.render().el; + } $(this.el).html(this.tmpl(data)); - $(this.el).find(".wizard-right-panel_content").html(data.content); + $(this.el).find('.wizard-right-panel_content').html(data.content); /* OnLoad Callback */ this.onLoad(); @@ -166,15 +182,16 @@ function(_, Backbone, pgAdmin, pgBrowser, gettext) { return this; }, nextPage: function() { - if (!this.beforeNext()) { return false; } + if (!this.beforeNext()) { + return false; + } var page_id = this.onNext(); - if (page_id ) { + if (page_id) { this.currPage = this.collection.get(page_id).toJSON(); this.options.curr_page = this.collection.indexOf(this.collection.get(page_id)); - } - else if (this.options.curr_page < (this.collection.length-1)) { + } else if (this.options.curr_page < (this.collection.length - 1)) { this.options.curr_page = this.options.curr_page + 1; this.currPage = this.collection.at(this.options.curr_page).toJSON(); } @@ -185,15 +202,16 @@ function(_, Backbone, pgAdmin, pgBrowser, gettext) { return this.render(); }, prevPage: function() { - if (!this.beforePrev()) { return false; } + if (!this.beforePrev()) { + return false; + } var page_id = this.onPrev(); - if (page_id){ + if (page_id) { this.currPage = this.collection.get(page_id).toJSON(); this.options.curr_page = this.collection.indexOf(this.collection.get(page_id)); - } - else if (this.options.curr_page > 0) { + } else if (this.options.curr_page > 0) { this.options.curr_page = this.options.curr_page - 1; this.currPage = this.collection.at(this.options.curr_page).toJSON(); } @@ -212,41 +230,37 @@ function(_, Backbone, pgAdmin, pgBrowser, gettext) { return true; }, enableDisableNext: function(disable) { - if (typeof(disable) != 'undefined') { - this.options.disable_next = disable; - } - else if (this.options.curr_page >= (this.collection.length-1)) { - this.options.disable_next = true; - } - else { - this.options.disable_next = false; - } + if (typeof(disable) != 'undefined') { + this.options.disable_next = disable; + } else if (this.options.curr_page >= (this.collection.length - 1)) { + this.options.disable_next = true; + } else { + this.options.disable_next = false; + } }, enableDisablePrev: function(disable) { - if (typeof(disable) != 'undefined') { - this.options.disable_prev = disable; - } - else if (this.options.curr_page <= 0) { - this.options.disable_prev = true; - } - else { - this.options.disable_prev = false; - } + if (typeof(disable) != 'undefined') { + this.options.disable_prev = disable; + } else if (this.options.curr_page <= 0) { + this.options.disable_prev = true; + } else { + this.options.disable_prev = false; + } }, closeErrorMsg: function() { $(this.el).find('.pg-prop-status-bar .alert-text').empty(); - $(this.el).find('.pg-prop-status-bar').css("visibility", "hidden"); + $(this.el).find('.pg-prop-status-bar').css('visibility', 'hidden'); }, - beforeNext: function(){ + beforeNext: function() { return this.evalASFunc(this.currPage.beforeNext); }, - beforePrev: function(){ + beforePrev: function() { return this.evalASFunc(this.currPage.beforePrev); }, - onPrev: function(){ + onPrev: function() { return this.evalASFunc(this.currPage.onPrev); }, - onNext: function(){ + onNext: function() { return this.evalASFunc(this.currPage.onNext); }, onLoad: function() { @@ -261,12 +275,12 @@ function(_, Backbone, pgAdmin, pgBrowser, gettext) { }, onMaximize: function() { var dialog_api = this.options.dialog_api, - old_classes, _el = this.$el.find('.wizard-maximize-event'); + _el = this.$el.find('.wizard-maximize-event'); // If no dialog api found then return - if(!dialog_api) return; + if (!dialog_api) return; - if(dialog_api.isMaximized()) { + if (dialog_api.isMaximized()) { // toggle the icon _el.removeClass('ajs-maximized'); dialog_api.restore(); @@ -297,7 +311,7 @@ function(_, Backbone, pgAdmin, pgBrowser, gettext) { pnlDialogHelp.focus(); iframe.openURL(this.options.wizard_help); - } + }, }); return pgBrowser;