fixed hazelnut checkbox management
[myslice.git] / plugins / hazelnut / hazelnut.js
index 5f1c27a..d1a470f 100644 (file)
@@ -9,6 +9,10 @@
  * Expression) that maps it to the dollar sign so it can't be overwritten by
  * another library in the scope of its execution.
  */
+
+// TEMP
+var ELEMENT_KEY = 'resource_hrn';
+
 (function($){
 
     var debug=false;
 
                 var $this = $(this);
 
-                /* Events */
-                $this.on('show.Datatables', methods.show);
-
                 /* An object that will hold private variables and methods */
                 var hazelnut = new Hazelnut (options);
                 $this.data('Hazelnut', hazelnut);
-                var query_channel   = '/query/' + options.query_uuid + '/changed';
-                var update_channel  = '/update-set/' + options.query_uuid;
-                var results_channel = '/results/' + options.query_uuid + '/changed';
-
-                // xxx not tested yet
-                $.subscribe(query_channel,  function(e, query) { hazelnut.set_query(query); });
-                // xxx not tested yet
-                $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
-                // expected to work
-                $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
-                if (debug)
-                    messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
+
+                /* Events */
+                $this.on('show.Datatables', methods.show);
+
+                // This is the new plugin API meant to replace the weird publish_subscribe mechanism
+                $this.set_query_handler(options.query_uuid, hazelnut.query_handler);
+                $this.set_record_handler(options.query_uuid, hazelnut.record_handler); 
+                $this.set_record_handler(options.query_all_uuid, hazelnut.record_handler_all); 
+
+//                /* Subscriptions */
+//                var query_channel   = '/query/' + options.query_uuid + '/changed';
+//                var update_channel  = '/update-set/' + options.query_uuid;
+//                var results_channel = '/results/' + options.query_uuid + '/changed';
+//
+//                // xxx not tested yet
+//                $.subscribe(query_channel,  function(e, query) { hazelnut.set_query(query); });
+//                // xxx not tested yet
+//                $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
+//                // expected to work
+//                $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
+//                if (debug)
+//                    messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
 
             }); // this.each
         }, // init
         this.query_update = null;
         this.current_resources = Array();
 
+        // query status
+        this.received_all = false;
+        this.received_set = false;
+        this.in_set_buffer = Array();
+
         var object = this;
 
         /* Transforms the table into DataTable, and keep a pointer to it */
 
         /* methods */
 
-        this.set_query = function(query) {
-            messages.info('hazelnut.set_query');
-            var options = this.options;
-            /* Compare current and advertised query to get added and removed fields */
-            previous_query = this.current_query;
-            /* Save the query as the current query */
-            this.current_query = query;
-            if (debug)
-                messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
-
-            /* We check all necessary fields : in column editor I presume XXX */
-            // XXX ID naming has no plugin_uuid
-            if (typeof(query.fields) != 'undefined') {        
-                $.each (query.fields, function(index, value) { 
-                    if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
-                        $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
-                });
-            }
-
-            /* Process updates in filters / current_query must be updated before this call for filtering ! */
-            this.table.fnDraw();
-
-            /*
-             * Process updates in fields
-             */
-            if (typeof(query.fields) != 'undefined') {     
-                /* DataTable Settings */
-                var oSettings = this.table.dataTable().fnSettings();
-                var cols = oSettings.aoColumns;
-                var colnames = cols.map(function(x) {return x.sTitle});
-                colnames = $.grep(colnames, function(value) {return value != "+/-";});
-
-                if (previous_query == null) {
-                    var added_fields = query.fields;
-                    var removed_fields = colnames;            
-                    removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
-                } else {
-                    var tmp = previous_query.diff_fields(query);
-                    var added_fields = tmp.added;
-                    var removed_fields = tmp.removed;
-                }
-
-                /* Hide/unhide columns to match added/removed fields */
-                var object = this;
-                $.each(added_fields, function (index, field) {            
-                    var index = object.getColIndex(field,cols);
-                    if(index != -1)
-                        object.table.fnSetColumnVis(index, true);
-                });
-                $.each(removed_fields, function (index, field) {
-                    var index = object.getColIndex(field,cols);
-                    if(index != -1)
-                        object.table.fnSetColumnVis(index, false);
-                });            
-            }
-        }
-
-        this.set_resources = function(resources, instance) {
-            if (debug)
-                messages.debug("entering hazelnut.set_resources");
-            var options = this.options;
-            var previous_resources = this.current_resources;
-            this.current_resources = resources;
-    
-            /* We uncheck all checkboxes ... */
-            $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
-            /* ... and check the ones specified in the resource list */
-            $.each(this.current_resources, function(index, urn) {
-                $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
-            });
-            
-        }
+// DEPRECATED //        this.set_query = function(query) {
+// DEPRECATED //            messages.info('hazelnut.set_query');
+// DEPRECATED //            var options = this.options;
+// DEPRECATED //            /* Compare current and advertised query to get added and removed fields */
+// DEPRECATED //            previous_query = this.current_query;
+// DEPRECATED //            /* Save the query as the current query */
+// DEPRECATED //            this.current_query = query;
+// DEPRECATED //            if (debug)
+// DEPRECATED //                messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
+// DEPRECATED //
+// DEPRECATED //            /* We check all necessary fields : in column editor I presume XXX */
+// DEPRECATED //            // XXX ID naming has no plugin_uuid
+// DEPRECATED //            if (typeof(query.fields) != 'undefined') {        
+// DEPRECATED //                $.each (query.fields, function(index, value) { 
+// DEPRECATED //                    if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
+// DEPRECATED //                        $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
+// DEPRECATED //                });
+// DEPRECATED //            }
+// DEPRECATED //
+// DEPRECATED //            /* Process updates in filters / current_query must be updated before this call for filtering ! */
+// DEPRECATED //            this.table.fnDraw();
+// DEPRECATED //
+// DEPRECATED //            /*
+// DEPRECATED //             * Process updates in fields
+// DEPRECATED //             */
+// DEPRECATED //            if (typeof(query.fields) != 'undefined') {     
+// DEPRECATED //                /* DataTable Settings */
+// DEPRECATED //                var oSettings = this.table.dataTable().fnSettings();
+// DEPRECATED //                var cols = oSettings.aoColumns;
+// DEPRECATED //                var colnames = cols.map(function(x) {return x.sTitle});
+// DEPRECATED //                colnames = $.grep(colnames, function(value) {return value != "+/-";});
+// DEPRECATED //
+// DEPRECATED //                if (previous_query == null) {
+// DEPRECATED //                    var added_fields = query.fields;
+// DEPRECATED //                    var removed_fields = colnames;            
+// DEPRECATED //                    removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
+// DEPRECATED //                } else {
+// DEPRECATED //                    var tmp = previous_query.diff_fields(query);
+// DEPRECATED //                    var added_fields = tmp.added;
+// DEPRECATED //                    var removed_fields = tmp.removed;
+// DEPRECATED //                }
+// DEPRECATED //
+// DEPRECATED //                /* Hide/unhide columns to match added/removed fields */
+// DEPRECATED //                var object = this;
+// DEPRECATED //                $.each(added_fields, function (index, field) {            
+// DEPRECATED //                    var index = object.getColIndex(field,cols);
+// DEPRECATED //                    if(index != -1)
+// DEPRECATED //                        object.table.fnSetColumnVis(index, true);
+// DEPRECATED //                });
+// DEPRECATED //                $.each(removed_fields, function (index, field) {
+// DEPRECATED //                    var index = object.getColIndex(field,cols);
+// DEPRECATED //                    if(index != -1)
+// DEPRECATED //                        object.table.fnSetColumnVis(index, false);
+// DEPRECATED //                });            
+// DEPRECATED //            }
+// DEPRECATED //        }
+
+// DEPRECATED //        this.set_resources = function(resources, instance) {
+// DEPRECATED //            if (debug)
+// DEPRECATED //                messages.debug("entering hazelnut.set_resources");
+// DEPRECATED //            var options = this.options;
+// DEPRECATED //            var previous_resources = this.current_resources;
+// DEPRECATED //            this.current_resources = resources;
+// DEPRECATED //    
+// DEPRECATED //            /* We uncheck all checkboxes ... */
+// DEPRECATED //            $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
+// DEPRECATED //            /* ... and check the ones specified in the resource list */
+// DEPRECATED //            $.each(this.current_resources, function(index, urn) {
+// DEPRECATED //                $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
+// DEPRECATED //            });
+// DEPRECATED //            
+// DEPRECATED //        }
 
         /**
          * @brief Determine index of key in the table columns 
             return (tabIndex.length > 0) ? tabIndex[0] : -1;
         }
     
-        /**
-         * @brief
-         * XXX will be removed/replaced
-         */
-        this.selected_changed = function(e, change) {
-        if (debug) messages.debug("entering hazelnut.selected_changed");
-            var actions = change.split("/");
-            if (actions.length > 1) {
-                var oNodes = this.table.fnGetNodes();
-                var myNode = $.grep(oNodes, function(value) {
-                    if (value.id == actions[1]) { return value; }
-                });                
-                if( myNode.length>0 ) {
-                    if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
-                        checked='';
-                    else
-                        checked="checked='checked' ";
-                    var newValue = this.checkbox(actions[1], 'node', checked, false);
-                    var columnPos = this.table.fnSettings().aoColumns.length - 1;
-                    this.table.fnUpdate(newValue, myNode[0], columnPos);
-                    this.table.fnDraw();
-                }
-            }
-        }
+// DEPRECATED //        /**
+// DEPRECATED //         * @brief
+// DEPRECATED //         * XXX will be removed/replaced
+// DEPRECATED //         */
+// DEPRECATED //        this.selected_changed = function(e, change) {
+// DEPRECATED //        if (debug) messages.debug("entering hazelnut.selected_changed");
+// DEPRECATED //            var actions = change.split("/");
+// DEPRECATED //            if (actions.length > 1) {
+// DEPRECATED //                var oNodes = this.table.fnGetNodes();
+// DEPRECATED //                var myNode = $.grep(oNodes, function(value) {
+// DEPRECATED //                    if (value.id == actions[1]) { return value; }
+// DEPRECATED //                });                
+// DEPRECATED //                if( myNode.length>0 ) {
+// DEPRECATED //                    if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
+// DEPRECATED //                        checked='';
+// DEPRECATED //                    else
+// DEPRECATED //                        checked="checked='checked' ";
+// DEPRECATED //                    var newValue = this.checkbox(actions[1], 'node', checked, false);
+// DEPRECATED //                    var columnPos = this.table.fnSettings().aoColumns.length - 1;
+// DEPRECATED //                    this.table.fnUpdate(newValue, myNode[0], columnPos);
+// DEPRECATED //                    this.table.fnDraw();
+// DEPRECATED //                }
+// DEPRECATED //            }
+// DEPRECATED //        }
     
         this.update_plugin = function(e, rows) {
-        // e.data is what we passed in second argument to subscribe
-        // so here it is the jquery object attached to the plugin <div>
-        var $plugindiv=e.data;
-        if (debug) messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
-        // clear the spinning wheel: look up an ancestor that has the need-spin class
-        // do this before we might return
-        $plugindiv.closest('.need-spin').spin(false);
+            // e.data is what we passed in second argument to subscribe
+            // so here it is the jquery object attached to the plugin <div>
+            var $plugindiv=e.data;
+            if (debug)
+                messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
+            // clear the spinning wheel: look up an ancestor that has the need-spin class
+            // do this before we might return
+            $plugindiv.closest('.need-spin').spin(false);
 
             var options = this.options;
             var hazelnut = this;
     
-        /* if we get no result, or an error, try to make that clear, and exit */
+            /* if we get no result, or an error, try to make that clear, and exit */
             if (rows.length==0) {
-        if (debug) messages.debug("Empty result on hazelnut " + this.options.domid);
-        var placeholder=$(this.table).find("td.dataTables_empty");
-        console.log("placeholder "+placeholder);
-        if (placeholder.length==1) placeholder.html(unfold.warning("Empty result"));
-        else               this.table.html(unfold.warning("Empty result"));
-                return;
+                if (debug) 
+                    messages.debug("Empty result on hazelnut " + this.options.domid);
+                var placeholder=$(this.table).find("td.dataTables_empty");
+                console.log("placeholder "+placeholder);
+                if (placeholder.length==1) 
+                    placeholder.html(unfold.warning("Empty result"));
+                else
+                    this.table.html(unfold.warning("Empty result"));
+                    return;
             } else if (typeof(rows[0].error) != 'undefined') {
-        // we now should have another means to report errors that this inline/embedded hack
-        if (debug) messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
+                // we now should have another means to report errors that this inline/embedded hack
+                if (debug) 
+                    messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
                 this.table.html(unfold.error(rows[0].error));
                 return;
             }
 
-        /* 
-         * fill the dataTables object
-         * we cannot set html content directly here, need to use fnAddData
-         */
+            /* 
+             * fill the dataTables object
+             * we cannot set html content directly here, need to use fnAddData
+             */
             var lines = new Array();
     
             this.current_resources = Array();
     
             $.each(rows, function(index, row) {
-        // this models a line in dataTables, each element in the line describes a cell
+                // this models a line in dataTables, each element in the line describes a cell
                 line = new Array();
      
                 // go through table headers to get column names we want
                 // in order (we have temporarily hack some adjustments in names)
-                var cols = hazelnut.table.fnSettings().aoColumns;
+                var cols = object.table.fnSettings().aoColumns;
                 var colnames = cols.map(function(x) {return x.sTitle})
                 var nb_col = cols.length;
-        /* if we've requested checkboxes, then forget about the checkbox column for now */
+                /* if we've requested checkboxes, then forget about the checkbox column for now */
                 if (options.checkboxes) nb_col -= 1;
 
-        /* fill in stuff depending on the column name */
+                /* fill in stuff depending on the column name */
                 for (var j = 0; j < nb_col; j++) {
                     if (typeof colnames[j] == 'undefined') {
                         line.push('...');
                     }
                 }
     
-        /* catch up with the last column if checkboxes were requested */
+                /* catch up with the last column if checkboxes were requested */
                 if (options.checkboxes) {
                     var checked = '';
-            // xxx problem is, we don't get this 'sliver' thing set apparently
+                    // xxx problem is, we don't get this 'sliver' thing set apparently
                     if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
                         checked = 'checked ';
-                        hazelnut.current_resources.push(row['urn']);
+                        hazelnut.current_resources.push(row[ELEMENT_KEY]);
                     }
                     // Use a key instead of hostname (hard coded...)
-                    line.push(hazelnut.checkbox(options.plugin_uuid, row['urn'], row['type'], checked, false));
+                    line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
                 }
     
                 lines.push(line);
     
             });
     
-        this.table.fnClearTable();
-        if (debug) messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
+            this.table.fnClearTable();
+            if (debug)
+                messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
             this.table.fnAddData(lines);
+        
+        };
+
+        this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str)
+        {
+            var result="";
+            if (header === null)
+                header = '';
+            // Prefix id with plugin_uuid
+            result += "<input";
+            result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
+            result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header).replace(/\\/g, '')  + "'";
+            result += " name='" + unfold.get_value(field) + "'";
+            result += " type='checkbox'";
+            result += selected_str;
+            result += disabled_str;
+            result += " autocomplete='off'";
+            result += " value='" + unfold.get_value(header) + "'";
+            result += "></input>";
+            return result;
+        };
+
+        ////////////////////////////////////////////////////////////////////////
+        // New plugin API (in tests)
+
+        // TODO : signal empty/non empty table
+
+        this.new_record = function(record)
+        {
+            // this models a line in dataTables, each element in the line describes a cell
+            line = new Array();
+     
+            // go through table headers to get column names we want
+            // in order (we have temporarily hack some adjustments in names)
+            var cols = object.table.fnSettings().aoColumns;
+            var colnames = cols.map(function(x) {return x.sTitle})
+            var nb_col = cols.length;
+            /* if we've requested checkboxes, then forget about the checkbox column for now */
+            if (options.checkboxes) nb_col -= 1;
+
+            /* fill in stuff depending on the column name */
+            for (var j = 0; j < nb_col; j++) {
+                if (typeof colnames[j] == 'undefined') {
+                    line.push('...');
+                } else if (colnames[j] == 'hostname') {
+                    if (record['type'] == 'resource,link')
+                        //TODO: we need to add source/destination for links
+                        line.push('');
+                    else
+                        line.push(record['hostname']);
+                } else {
+                    if (record[colnames[j]])
+                        line.push(record[colnames[j]]);
+                    else
+                        line.push('');
+                }
+            }
+    
+            /* catch up with the last column if checkboxes were requested */
+            if (options.checkboxes) {
+                var checked = '';
+                // xxx problem is, we don't get this 'sliver' thing set apparently
+                if (typeof(record['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
+                    checked = 'checked ';
+                    hazelnut.current_resources.push(record[ELEMENT_KEY]);
+                }
+                // Use a key instead of hostname (hard coded...)
+                line.push(object.checkbox(options.plugin_uuid, record[ELEMENT_KEY], record['type'], checked, false));
+            }
     
+            // XXX Is adding an array of lines more efficient ?
+            this.table.fnAddData(line);
+
         };
 
-        this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
-        var result="";
-            // Preafix id with plugin_uuid
-        result += "<input";
-        result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
-        result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
-        result += " name='" + unfold.get_value(field) + "'";
-        result += " type='checkbox'";
-        result += selected_str;
-        result += disabled_str;
-        result += " autocomplete='off'";
-        result += " value='" + unfold.get_value(header) + "'";
-        result += "></input>";
-        return result;
+        this.set_checkbox = function(record)
+        {
+            // XXX urn should be replaced by the key
+            // XXX we should enforce that both queries have the same key !!
+            checkbox_id = "#hazelnut-checkbox-" + object.options.plugin_uuid + "-" + unfold.escape_id(record[ELEMENT_KEY].replace(/\\/g, ''))
+            $(checkbox_id, object.table.fnGetNodes()).attr('checked', true);
+        }
+
+        this.record_handler = function(e, event_type, record)
+        {
+            // elements in set
+            switch(event_type) {
+                case NEW_RECORD:
+                    /* NOTE in fact we are doing a join here */
+                    if (object.received_all)
+                        // update checkbox for record
+                        object.set_checkbox(record);
+                    else
+                        // store for later update of checkboxes
+                        object.in_set_buffer.push(record);
+                    break;
+                case CLEAR_RECORDS:
+                    // nothing to do here
+                    break;
+                case IN_PROGRESS:
+                    manifold.spin($(this));
+                    break;
+                case DONE:
+                    if (object.received_all)
+                        manifold.spin($(this), false);
+                    object.received_set = true;
+                    break;
+            }
+        };
+
+        this.record_handler_all = function(e, event_type, record)
+        {
+            // all elements
+            switch(event_type) {
+                case NEW_RECORD:
+                    // Add the record to the table
+                    object.new_record(record);
+                    break;
+                case CLEAR_RECORDS:
+                    object.table.fnClearTable();
+                    break;
+                case IN_PROGRESS:
+                    manifold.spin($(this));
+                    break;
+                case DONE:
+                    if (object.received_set) {
+                        /* XXX needed ? XXX We uncheck all checkboxes ... */
+                        $("[id^='datatables-checkbox-" + object.options.plugin_uuid +"']").attr('checked', false);
+
+                        /* ... and check the ones specified in the resource list */
+                        $.each(object.in_set_buffer, function(i, record) {
+                            object.set_checkbox(record);
+                        });
+
+                        manifold.spin($(this), false);
+                    }
+                    object.received_all = true;
+                    break;
+            }
         };
+
+        this.query_handler = function(e, event_type, query)
+        {
+            // This replaces the complex set_query function
+            // The plugin does not need to remember the query anymore
+            switch(event_type) {
+                // Filters
+                case FILTER_ADDED:
+                case FILTER_REMOVED:
+                case CLEAR_FILTERS:
+                    // XXX Here we might need to maintain the list of filters !
+                    /* Process updates in filters / current_query must be updated before this call for filtering ! */
+                    object.table.fnDraw();
+                    break;
+
+                // Fields
+                /* Hide/unhide columns to match added/removed fields */
+                case FIELD_ADDED:
+                    var object = this;
+                    $.each(added_fields, function (index, field) {            
+                        var index = object.getColIndex(field,cols);
+                        if(index != -1)
+                            object.table.fnSetColumnVis(index, true);
+                    });
+                    break;
+                case FIELD_REMOVED:
+                    var object = this;
+                    $.each(removed_fields, function (index, field) {
+                        var index = object.getColIndex(field,cols);
+                        if(index != -1)
+                            object.table.fnSetColumnVis(index, false);
+                    });            
+                    break;
+                case CLEAR_FIELDS:
+                    alert('Hazelnut::clear_fields() not implemented');
+                    break;
+            } // switch
+
+
+        }
     } // constructor
 
     /***************************************************************************
     }
 
     function check_click (e) {
+
         var object = e.data.instance;
-        var value = this.value;
+
+        /* The key of the object to be added */
+        // XXX What about multiple keys ?
+        var value = this.value; 
+
+        // NEW PLUGIN API
+        manifold.raise_event(object.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, value);
+        
+        // OLD PLUGIN API BELOW
 
         if (this.checked) {
             object.current_resources.push(value);