plugins: updated js framework + googlemaps and hazelnut to better handle sets and...
authorJordan Augé <jordan.auge@lip6.fr>
Tue, 20 Aug 2013 15:02:42 +0000 (17:02 +0200)
committerJordan Augé <jordan.auge@lip6.fr>
Tue, 20 Aug 2013 15:02:42 +0000 (17:02 +0200)
manifold/js/manifold-query.js
manifold/js/manifold.js
manifold/js/plugin.js
plugins/googlemaps/static/css/googlemaps.css
plugins/googlemaps/static/googlemaps.html
plugins/googlemaps/static/js/googlemaps.js
plugins/hazelnut/static/js/hazelnut.js
plugins/tabs/static/js/tabs.js

index 6036c38..4da77da 100644 (file)
@@ -42,8 +42,29 @@ INSERT INTO object VALUES(field=value)
     }  
 
     this.clone = function() {
-        q = new ManifoldQuery();
-        return jQuery.extend(true, q, this);
+        // 
+        var q = new ManifoldQuery();
+        q.action     = this.action;
+        q.object     = this.object;
+        q.timestamp  = this.timestamp;
+        q.filters    = this.filters.slice();
+        q.fields     = this.fields.slice();
+        q.query_uuid = this.query_uuid;
+
+        if (this.analyzed_query)
+            q.analyzed_query = this.analyzed_query.clone();
+        else
+            q.analyzed_query = null;
+
+        if (this.subqueries) {
+            q.subqueries = {}
+            for (method in this.subqueries)
+                q.subqueries[method] = this.subqueries[method].clone();
+        }
+
+        // deep extend not working for custom objects
+        // $.extend(true, q, this);
+        return q;
     }
 
     this.add_filter = function(key, op, value) {
index bd34726..b2df24b 100644 (file)
@@ -818,6 +818,21 @@ var manifold = {
                 manifold.raise_record_event(query_uuid, event_type, value);
 
                 // b) subqueries eventually (dot in the key)
+                // Let's unfold 
+                var path_array = value.key.split('.');
+                var value_key = value.key.split('.');
+
+                var cur_query = query;
+                if (cur_query.analyzed_query)
+                    cur_query = cur_query.analyzed_query;
+                $.each(path_array, function(i, method) {
+                    cur_query = cur_query.subqueries[method];
+                    value_key.shift(); // XXX check that method is indeed shifted
+                });
+                value.key = value_key;
+
+                manifold.raise_record_event(cur_query.query_uuid, event_type, value);
+
                 // XXX make this DOT a global variable... could be '/'
                 break;
 
index 85b2478..dd12379 100644 (file)
@@ -200,6 +200,50 @@ var Plugin = Class.extend({
         return array[1];
     },
 
+    id_from_key: function(key_field, value)
+    {
+        
+        return key_field + manifold.separator + unfold.escape_id(value).replace(/\\/g, '');
+    },
+
+    id_from_record: function(method, record)
+    {
+        var keys = manifold.metadata.get_key(method);
+        if (!keys)
+            return;
+        if (keys.length > 1)
+            return;
+
+        var key = keys[0];
+        switch (Object.toType(key)) {
+            case 'string':
+                if (!(key in record))
+                    return null;
+                return this.id_from_key(key, record[key]);
+    
+            default:
+                throw 'Not implemented';
+        }
+    },
+
+    key_from_id: function(id)
+    {
+        // NOTE this works only for simple keys
+
+        var array;
+        if (typeof id === 'string') {
+            array = id.split(manifold.separator);
+        } else { // We suppose we have an array ('object')
+            array = id;
+        }
+
+        // arguments has the initial id but lacks the key field name (see id_from_key), so we are even
+        // we finally add +1 for the plugin_uuid at the beginning
+        return array[arguments.length + 1];
+    },
+
+    /* SPIN */
+
     spin: function()
     {
         manifold.spin(this.element);
@@ -210,4 +254,11 @@ var Plugin = Class.extend({
         manifold.spin(this.element, false);
     },
 
+    /* TEMPLATE */
+
+    load_template: function(name, ctx)
+    {
+        return Mustache.render(this.el(name).html(), ctx);
+    },
+
 });
index 6a82854..4399c1e 100644 (file)
@@ -9,7 +9,7 @@
   /*width: 800px;*/
 }
 
-#map {
+.map {
   /*width: 800px;*/
   height: 500px;
 }
index d0bb5d6..4aee23b 100644 (file)
@@ -1,2 +1,11 @@
-{# keep the original skeleton but this probably won't support several instances in the same page #}
-<div id='map-container'><div id='map'></div></div>
+<div id='{{domid}}__map-container'>
+    <div class='map' id='{{domid}}__map'></div>
+
+    <!-- TEMPLATE -->
+    <div id='{{domid}}__template' class='template'>
+        <div class="map-button" style="cursor:pointer;">
+            <span class='ui-icon {% templatetag openvariable %} action_class {% templatetag closevariable%}' style="clear:both; float:left;"></span>
+            {% templatetag openvariable %} action_message {% templatetag closevariable %}
+        </div>';
+    </div>
+</div>
index d72e277..aefd2cb 100644 (file)
             this.received_set = false;
             this.in_set_buffer = Array();
 
+            // key -> { marker, checked }
+            this.map_markers = {}
+
             /* XXX Events XXX */
-            this.$element.on('show.Datatables', this.on_show);
+            this.el().on('show', this, this.on_show);
             // TODO in destructor
             // $(window).unbind('Hazelnut');
 
+            var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
+            this.method = query.object;
+
+            var keys = manifold.metadata.get_key(this.method);
+            this.key = (keys && keys.length == 1) ? keys[0] : null;
+
             /* Setup query and record handlers */
             this.listen_query(options.query_uuid);
             this.listen_query(options.query_all_uuid, 'all');
 
         /* PLUGIN EVENTS */
 
-        on_show: function()
+        on_show: function(e)
         {
-            google.maps.event.trigger(map, 'resize');
+            var self = e.data;
+            google.maps.event.trigger(self.map, 'resize');
         }, // on_show
 
         /* GUI EVENTS */
@@ -46,9 +56,7 @@
          */
         initialize_map: function()
         {
-            this.map = null;
             this.markerCluster = null;
-            this.markers = [];
             this.coords = new Array();
 
             var myLatlng = new google.maps.LatLng(this.options.latitude, this.options.longitude);
                 mapTypeId: google.maps.MapTypeId.ROADMAP
             }
       
-            this.map = new google.maps.Map(document.getElementById("map"), myOptions);
+            var id = this.options.plugin_uuid + manifold.separator + 'map';
+            this.map = new google.maps.Map(document.getElementById(id), myOptions);
             this.infowindow = new google.maps.InfoWindow();
         }, // initialize_map
 
+        set_checkbox: function(record, checked)
+        {
+            var key_value;
+            /* The function accepts both records and their key */
+            switch (manifold.get_type(record)) {
+                case TYPE_VALUE:
+                    key_value = record;
+                    break;
+                case TYPE_RECORD:
+                    /* XXX Test the key before ? */
+                    key_value = record[this.key];
+                    break;
+                default:
+                    throw "Not implemented";
+                    break;
+            }
+
+            // we cannot directly edit html, since nothing but marker is displayed
+            //var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
+            //checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
+            //$(checkbox_id, this.table.fnGetNodes()).attr('checked', checked);
+
+            var dict_info = this.map_markers[unfold.escape_id(key_value).replace(/\\/g, '')];
+
+            /* Default: swap check status */
+            if (typeof checked === 'undefined')
+                dict_info.in_set = !dict_info.in_set;
+            else
+                dict_info.in_set = checked;
+
+            // Update the marker content
+            dict_info.marker.content = this.get_marker_content(dict_info.record, checked);
+
+            // Update opened infowindow
+            // XXX Factor this code
+            this.infowindow.close();
+            this.infowindow.setContent(dict_info.marker.content);
+            this.infowindow.open(this.map, dict_info.marker);
+            this.els('map-button').unbind('click').click(this, this._button_click);
+
+            //var button = this.checkbox(record, checked);
+            //this.el('checkbox', this.id_from_record(method, record)).html(button);
+        }, 
+
+        checkbox: function(record, checked) 
+        {
+            if (typeof checked === 'undefined')
+                checked = false;
+
+            var method  = manifold.query_store.find_analyzed_query(this.options.query_uuid).object;
+            var action = checked ? 'checked' : 'del';
+            var ctx = {
+                action_class  : checked ? 'ui-icon-circle-minus' : 'ui-icon-circle-plus',
+                action_message: checked ? 'Remove from slice' : 'Add to slice',
+            };
+            var button = this.load_template('template', ctx);
+
+            var id_record = this.id_from_record(method, record);
+            if (!id_record)
+                return 'ERROR';
+            var id = this.id('checkbox', this.id_from_record(method, record));
+            return "<div id='" + id + "'>" + button + "</div>";
+        },
+        
+        get_marker_content: function(record, checked)
+        {
+            return '<p><b>' + this.method + '</b>: ' + get_value(record['resource_hrn']) + '<br/><b>network</b>: ' + get_value(record['network'])+'</p>' + this.checkbox(record, checked);
+        },
+
         /**
          */
         new_record: function(record)
                 // get the coordinate object
                 var myLatlng = new google.maps.LatLng(lat, lng);
             }
-            // If the node is attached to the slice, action will be Remove; else action will be add to slice
-            if (typeof(record['sliver']) != 'undefined') {
-                data.current_resources.push(record['urn']);
-                action="del";
-                action_class="ui-icon-circle-minus";
-                action_message="Remove from slice";
-            }else{
-                action="add";
-                action_class="ui-icon-circle-plus";
-                action_message="Add to slice";
-            }
             // XXX not working
             if (!(record['latitude'])) {
                 return true;
                     position: myLatlng,
                     title: get_value(record['hostname']),
                     // This should be done by the rendering
-                    content: '<p>Agent: ' + get_value(record['ip']) + ' (' + get_value(record['resource_hrn']) + ')<br/>Platform: ' + get_value(record['platform'])+'</p>' +
-                            '<div class="map-button" id="'+action+'/'+get_value(record['resource_hrn'])+'" style="cursor:pointer;">'+
-                            '<span class="ui-icon '+action_class+'" style="clear:both;float:left;"></span>'+action_message+
-                            '</div>'
+                    content: this.get_marker_content(record, false),
                 }); 
 
                 this.addInfoWindow(marker, this.map);
-                this.markers.push(marker);
+                var key_value = (this.key in record) ? record[this.key] : null;
+                if (!key_value)
+                    return;
+                this.map_markers[unfold.escape_id(key_value).replace(/\\/g, '')] = {
+                    marker: marker,
+                    in_set: false,
+                    record: record,
+                    value: key_value
+                }
             //}
 
         }, // new_record
                 self.infowindow.open(map, marker);
                 // onload of the infowindow on the map, bind a click on a button
                 google.maps.event.addListener(self.infowindow, 'domready', function() {
-                    jQuery('.map-button').unbind('click');
+                    self.els('map-button').unbind('click').click(self, self._button_click);
 //                    jQuery(".map-button").click({instance: instance_, infoWindow: object.infowindow}, button_click);                     
                 });
             });
         }, // addInfoWindow
 
-        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);
-        }, // set_checkbox
-
 
         /*************************** QUERY HANDLER ****************************/
 
             this.received_set = true;
         },
 
+        on_field_state_changed: function(data)
+        {
+            switch(data.request) {
+                case FIELD_REQUEST_ADD:
+                    this.set_checkbox(data.value, true);
+                    break;
+                case FIELD_REQUEST_REMOVE:
+                    this.set_checkbox(data.value, false);
+                    break;
+                case FIELD_REQUEST_RESET:
+                    this.set_checkbox(data.value); // swap
+                    break;
+                default:
+                    break;
+            }
+        },
+
+
         // all
 
         on_all_new_record: function(record)
         {
 
             // MarkerClusterer
-            this.markerCluster = new MarkerClusterer(this.map, this.markers, {zoomOnClick: false});
+            var markers = [];
+            $.each(this.map_markers, function (k, v) { markers.push(v.marker); });
+
+            this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
-                var markers = cluster.getMarkers();
+                var cluster_markers = cluster.getMarkers();
                 var bounds  = new google.maps.LatLngBounds();
-              /* 
-              * date: 24/05/2012
-              * author: lbaron
-              * Firefox JS Error - replaced $.each by JQuery.each
-              */                  
-              jQuery.each(markers, function(i, marker){
-                  bounds.extend(marker.getPosition()); 
-              });
-
-              //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
-              this.map.fitBounds(bounds);
+                /* 
+                * date: 24/05/2012
+                * author: lbaron
+                * Firefox JS Error - replaced $.each by JQuery.each
+                */                  
+                jQuery.each(cluster_markers, function(i, marker){
+                    bounds.extend(marker.getPosition()); 
+                });
+
+                //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
+                this.map.fitBounds(bounds);
             });
 
             var self = this;
             if (this.received_set) {
                 /* XXX needed ? XXX We uncheck all checkboxes ... */
-                $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
+                //$("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
 
                 /* ... and check the ones specified in the resource list */
                 $.each(this.in_set_buffer, function(i, record) {
-                    self.set_checkbox(record);
+                    self.set_checkbox(record, true);
                 });
 
                 this.unspin();
 
         _button_click: function(e)
         {
-            var op_value=this.id.split("/");
-            if(op_value.length>0) {
-                var value = op_value[1];
-                manifold.raise_event(this.options.query_uuid, (op_value[0] == 'add')?SET_ADD:SET_REMOVED, value);
-            }
-        } // button_click
+            var self   = e.data;
+
+            var escaped_key = self.key_from_id($(this).parent().attr('id'), 'checkbox');
+            var info_dict = self.map_markers[escaped_key];
+            var in_set = info_dict.in_set;
+            var value = info_dict.value;
+
+            var escaped_key = self.map_markers[self.key_from_id($(this).parent().attr('id'), 'checkbox')]
+            manifold.raise_event(self.options.query_uuid, (in_set) ? SET_REMOVED : SET_ADD, value);
+        } // _button_click
 
     });
 
index 48a392d..91fe152 100644 (file)
             this.in_set_buffer = Array();
 
             /* XXX Events XXX */
-            this.$element.on('show.Datatables', this.on_show);
+            // this.$element.on('show.Datatables', this.on_show);
+            this.el().on('show', this, this.on_show);
             // Unbind all events using namespacing
             // TODO in destructor
             // $(window).unbind('Hazelnut');
 
+            var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
+            this.method = query.object;
+
+            var keys = manifold.metadata.get_key(this.method);
+            this.key = (keys && keys.length == 1) ? keys[0] : null;
+
             /* Setup query and record handlers */
             this.listen_query(options.query_uuid);
             this.listen_query(options.query_all_uuid, 'all');
 
         /* PLUGIN EVENTS */
 
-        on_show: function()
+        on_show: function(e)
         {
-            // XXX
-            var $this=$(this);
-            // xxx wtf. why [1] ? would expect 0...
-            if (debug)
-                messages.debug("Hitting suspicious line in hazelnut.show");
-            var oTable = $($('.dataTable', $this)[1]).dataTable();
-            oTable.fnAdjustColumnSizing()
+            var self = e.data;
+
+            self.table.fnAdjustColumnSizing()
         
             /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */        
+            /* temp disabled... useful ? -- jordan
             $(this).each(function(i,elt) {
                 if (jQuery(elt).hasClass('dataTables')) {
                     var myDiv=jQuery('#hazelnut-' + this.id).parent();
@@ -63,6 +67,7 @@
                     }
                 }
             });
+            */
         }, // on_show
 
         /* GUI EVENTS */
  // UNUSED ? //         
  // UNUSED ? //         }, // update_plugin
 
-        checkbox: function (plugin_uuid, header, field, selected_str, disabled_str)
+        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 += " class='hazelnut-checkbox'";
+            result += " id='" + this.id('checkbox', this.id_from_key(this.key, unfold.get_value(header))) + "'";
+             //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 += selected_str;
+            //result += disabled_str;
             result += " autocomplete='off'";
             result += " value='" + unfold.get_value(header) + "'";
             result += "></input>";
             }
     
             /* catch up with the last column if checkboxes were requested */
-            if (this.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]);
-                }
+            if (this.options.checkboxes)
                 // Use a key instead of hostname (hard coded...)
-                line.push(this.checkbox(this.options.plugin_uuid, record[ELEMENT_KEY], record['type'], checked, false));
-            }
+                // XXX remove the empty checked attribute
+                line.push(this.checkbox(this.options.plugin_uuid, record[ELEMENT_KEY], record['type']));
     
             // XXX Is adding an array of lines more efficient ?
             this.table.fnAddData(line);
                 this.table.fnSetColumnVis(index, false);
         },
 
-        set_checkbox: function(record)
+        set_checkbox: function(record, checked)
         {
-            // XXX urn should be replaced by the key
-            // XXX we should enforce that both queries have the same key !!
-            checkbox_id = "#hazelnut-checkbox-" + this.options.plugin_uuid + "-" + unfold.escape_id(record[ELEMENT_KEY].replace(/\\/g, ''))
-            $(checkbox_id, this.table.fnGetNodes()).attr('checked', true);
+            var key_value;
+            /* The function accepts both records and their key */
+            switch (manifold.get_type(record)) {
+                case TYPE_VALUE:
+                    key_value = record;
+                    break;
+                case TYPE_RECORD:
+                    /* XXX Test the key before ? */
+                    key_value = record[this.key];
+                    break;
+                default:
+                    throw "Not implemented";
+                    break;
+            }
+
+
+            var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
+            checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
+
+            var element = $(checkbox_id, this.table.fnGetNodes());
+
+            /* Default: swap check status */
+            if (typeof checked === 'undefined')
+                checked = !(element.is(':checked'));
+
+            element.attr('checked', checked);
         },
 
         /*************************** QUERY HANDLER ****************************/
             /* NOTE in fact we are doing a join here */
             if (this.received_all)
                 // update checkbox for record
-                this.set_checkbox(record);
+                this.set_checkbox(record, true);
             else
                 // store for later update of checkboxes
                 this.in_set_buffer.push(record);
                 this.unspin();
             this.received_set = true;
         },
+        
+        on_field_state_changed: function(data)
+        {
+            switch(data.request) {
+                case FIELD_REQUEST_ADD:
+                    this.set_checkbox(data.value, true);
+                    break;
+                case FIELD_REQUEST_REMOVE:
+                    this.set_checkbox(data.value, false);
+                    break;
+                case FIELD_REQUEST_RESET:
+                    this.set_checkbox(data.value); // swap
+                    break;
+                default:
+                    break;
+            }
+        },
 
         // all
 
 
                 /* ... and check the ones specified in the resource list */
                 $.each(this.in_set_buffer, function(i, record) {
-                    self.set_checkbox(record);
+                    self.set_checkbox(record, true);
                 });
 
                 this.unspin();
              * Handle clicks on checkboxes: reassociate checkbox click every time
              * the table is redrawn 
              */
-            $('.hazelnut-checkbox-' + this.options.plugin_uuid).unbind('click');
-            $('.hazelnut-checkbox-' + this.options.plugin_uuid).click({instance: this}, this._check_click);
+            this.els('hazelnut-checkbox').unbind('click').click(this, this._check_click);
 
             if (!this.table)
                 return;
         _check_click: function(e) 
         {
 
-            var self = e.data.instance;
+            var self = e.data;
 
             // XXX this.value = key of object to be added... what about multiple keys ?
             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
+            //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
             
         },
 
index bc39890..b5b1cd0 100644 (file)
@@ -3,9 +3,8 @@
     $.fn.Tabs = function( method ) {
 
         $('a[data-toggle="tab"]').on('shown', function (e) {
-          google.maps.event.trigger(map, 'resize');
-          //e.target // current tab
-          //e.relatedTarget // previous tab
+          // find the plugin object inside the tab content referenced by the current tabs
+          $('.plugin', $($(e.target).attr('href'))).trigger('show');
         });
 
     };