tweaked resources_selected rendering - removed the +/- column that has no content...
[unfold.git] / plugins / resources_selected / static / js / resources_selected.js
1 /**
2  * MySlice ResourcesSelected plugin
3  * Version: 0.1.0
4  * URL: http://www.myslice.info
5  * Description: display of selected resources
6  * Requires: 
7  * Author: The MySlice Team
8  * Copyright: Copyright 2012 UPMC Sorbonne Universités
9  * License: GPLv3
10  */
11
12 (function( $ ){
13
14     // XXX record selected (multiple selection ?)
15     // XXX record disabled ?
16     // XXX out of sync plugin ?
17     // XXX out of date record ?
18     // record tags ???
19     //
20     // criticality of the absence of a handler in a plugin
21     // non-critical only can have switch case
22     // 
23     // Record state through the query cycle
24
25
26     var ResourcesSelected = Plugin.extend({
27
28         init: function(options, element)
29         {
30             this._super(options, element);
31
32             var self = this;
33             this.table = this.elmt('table').dataTable({
34 //                sDom: "<'row'<'col-md-5'l><'col-md-1'r><'col-md-6'f>>t<'row'<'col-md-5'i><'col-md-7'p>>",
35                 sPaginationType: 'full_numbers',
36                 bAutoWidth: true,
37                 //bJQueryUI      : true,
38                 //bRetrieve      : true,
39 //                sScrollX       : '100%',                 // Horizontal scrolling 
40 //                bSortClasses   : false,              // Disable style for the sorted column
41 //                aaSorting      : [[ 0, 'asc' ]],        // Default sorting on URN
42 //                fnDrawCallback: function() {      // Reassociate close click every time the table is redrawn
43 //                    /* Prevent to loop on click while redrawing table  */
44 //                    $('.ResourceSelectedClose').unbind('click');
45 //                    /* Handle clicks on close span */
46 //                    /* Reassociate close click every time the table is redrawn */
47 //                    $('.ResourceSelectedClose').bind('click', self, self._close_click);
48 //                }
49              });
50             
51             // XXX This should not be done at init...
52             console.log("elmt(update) is " + this.elmt('update'));
53
54             this.elmt('update').click(this, this.do_update);
55             this.elmt('refresh').click(this, this.do_refresh);
56             this.elmt('reset').click(this, this.do_reset);
57             this.elmt('clear_annotations').click(this, this.do_clear_annotations);
58
59             this.listen_query(options.query_uuid);
60         },
61
62         /*************************** PLUGIN EVENTS ****************************/
63
64         /***************************** GUI EVENTS *****************************/
65
66         do_update: function(e) 
67         {
68             console.log ("in do_update");
69             var self = e.data;
70             // XXX check that the query is not disabled
71             manifold.raise_event(self.options.query_uuid, RUN_UPDATE);
72         },
73
74         do_refresh: function(e)
75         {
76             throw 'Not implemented';
77         },
78
79         do_reset: function(e)
80         {
81             throw 'Not implemented';
82         },
83
84         do_clear_annotations: function(e)
85         {
86             throw 'Not implemented';
87         },
88         
89         /************************** GUI MANIPULATION **************************/
90
91         
92         set_button_state: function(name, state)
93         {
94             this.elmt(name).attr('disabled', state ? false : 'disabled');
95         },
96
97         clear: function()
98         {
99
100         },
101
102         find_row: function(key)
103         {
104             // key in third position, column id = 2
105             var KEY_POS = 2;
106
107             var cols = $.grep(this.table.fnSettings().aoData, function(col) {
108                 return (col._aData[KEY_POS] == key);
109             } );
110
111             if (cols.length == 0)
112                 return null;
113             if (cols.length > 1)
114                 throw "Too many same-key rows in ResourceSelected plugin";
115
116             return cols[0];
117         },
118
119         set_state: function(data)
120         {
121             var action;
122             var msg;
123             var button = '';
124
125             var row;
126
127             switch(data.request) {
128                 case FIELD_REQUEST_ADD_RESET:
129                 case FIELD_REQUEST_REMOVE_RESET:
130                     // find line and delete it
131                     row = this.find_row(data.value);
132                     if (row)
133                         this.table.fnDeleteRow(row.nTr);
134                     return;
135                 case FIELD_REQUEST_CHANGE:
136                     action = 'UPDATE';
137                     break;
138                 case FIELD_REQUEST_ADD:
139                     action = 'ADD';
140                     break;
141                 case FIELD_REQUEST_REMOVE:
142                     action = 'REMOVE';
143                     break;
144             }
145
146             switch(data.status) {
147                 case FIELD_REQUEST_PENDING:
148                     msg   = 'PENDING';
149                     button = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='" + data.key + "'/>";
150                     break;
151                 case FIELD_REQUEST_SUCCESS:
152                     msg   = 'SUCCESS';
153                     break;
154                 case FIELD_REQUEST_FAILURE:
155                     msg   = 'FAILURE';
156                     break;
157             }
158
159             var status = msg + status;
160
161             // find line
162             // if no, create it, else replace it
163             // XXX it's not just about adding lines, but sometimes removing some
164             // XXX how do we handle status reset ?
165             row = this.find_row(data.value);
166             newline = [
167                 action,
168                 data.key,
169                 data.value,
170                 msg,
171                 button
172             ];
173             if (!row) {
174                 // XXX second parameter refresh = false can improve performance. todo in hazelnut also
175                 this.table.fnAddData(newline);
176                 row = this.find_row(data.value);
177             } else {
178                 // Update row text...
179                 this.table.fnUpdate(newline, row.nTr);
180             }
181
182             // Change cell color according to status
183             if (row) {
184                 $(row.nTr).removeClass('add remove')
185                 var cls = action.toLowerCase();
186                 if (cls)
187                     $(row.nTr).addClass(cls);
188             }
189         },
190
191         /*************************** QUERY HANDLER ****************************/
192
193         // NONE
194
195         /*************************** RECORD HANDLER ***************************/
196
197         on_new_record: function(record)
198         {
199             // if (not and update) {
200
201                 // initial['resource'], initial['lease'] ?
202                 this.initial.push(record.urn);
203
204                 // We simply add to the table
205             // } else {
206                 //                 \ this.initial_resources
207                 //                  \
208                 // this.             \
209                 // current_resources  \    YES    |   NO
210                 // --------------------+----------+---------
211                 //       YES           | attached | added
212                 //       NO            | removed  |   /
213                 // 
214
215             // }
216         },
217
218         // QUERY STATUS
219         //                                      +-----------------+--------------+
220         //                                      v        R        |              |
221         // +-------+  ?G    +-------+        +-------+        +---+---+          |
222         // |       | -----> |       |  !G    |       |        |       |    DA    |
223         // |  ND   |        |  PG   | -----> |   D   | -----> |  PC   | <------+ |
224         // |       | <----- |       |  ~G    |       |   C    |       |        | | 
225         // +-------+   GE   +-------+        +-------+        +-------+      +------+
226         //                                       ^              ^  |         |      |
227         //                                       | DA        UE |  | ?U      | PCA  |
228         //                                       |              |  v         |      |
229         //                                   +-------+        +-------+      +------+
230         //                                   |       |   !U   |       |         ^
231         //                                   |  AD   | <----- |  PU   | --------+
232         //                                   |       |        |       |   ~U     
233         //                                   +-------+        +-------+          
234         //                                                                       
235         //
236         // LEGEND:
237         // 
238         // Plugins (i) receive state information, (ii) perform actions
239         //
240         // States:                                  Actions:
241         // ND : No data                             ?G : Get query
242         // PG : Pending Get                         !G : Get reply  
243         //  D : Data present                        ~G : Get partial reply
244         // PC : Pending changes                     GE : Get error                            
245         // PU : Pending update                       C : Change request
246         // PCA: Pending change with annotation       R : Reset request
247         // AD : Annotated data                      ?U : Update query
248         //                                          !U : Update reply
249         //                                          ~U : Update partial reply
250         //                                          UE : Update error            
251         //                                          DA : Delete annotation request
252         // NOTE:
253         // - D -> PU directly if the user chooses 'dynamic update'
254         // - Be careful for updates if partial Get success
255
256         // ND: No data == initialization state
257         
258         // PG : Pending get
259         // - on_query_in_progress
260         // NOTE: cannot distinguish get and update here. Is it important ?
261
262         on_query_in_progress: function()
263         {
264             this.spin();
265         },
266
267         // D : Data present
268         // - on_clear_records (Get)
269         // - on_new_record (shared with AD) XXX
270         // - on_query_done
271         // NOTE: cannot distinguish get and update here. Is it important ?
272         // NOTE: Would record key be sufficient for update ?
273
274         on_clear_records: function()
275         {
276             this.clear();
277         },
278
279         on_new_record: function(record)
280         {
281         },
282
283         on_query_done: function()
284         {
285             this.unspin();
286         },
287
288         // PC : Pending changes
289         // NOTE: record_key could be sufficient 
290         on_added_record: function(record)
291         {
292             this.set_record_state(record, RECORD_STATE_ADDED);
293         },
294
295         on_removed_record: function(record_key)
296         {
297             this.set_record_state(RECORD_STATE_REMOVED);
298         },
299
300         // PU : Pending update
301         // - on_query_in_progress (already done)
302         
303         // PCA : Pending change with annotation
304         // NOTE: Manifold will inform the plugin about updates, and thus won't
305         // call new record, even if the same channel UUID is used...
306         // - TODO on_updated_record
307         // - Key and confirmation could be sufficient, or key and record state
308         // XXX move record state to the manifold plugin API
309
310         on_field_state_changed: function(request, key, value, status)
311         {
312             this.set_state(request, key, value, status);
313         },
314
315         // XXX we will have the requests for change
316         // XXX + the requests to move into the query cycle = the buttons aforementioned
317
318         // XXX what happens in case of updates ? not implemented yet
319         // XXX we want resources and leases
320         // listen for SET_ADD and SET_REMOVE for slice query
321
322         /************************** PRIVATE METHODS ***************************/
323
324         _close_click: function(e)
325         {
326             var self = e.data;
327
328             //jQuery.publish('selected', 'add/'+key_value);
329             // this.parentNode is <td> this.parentNode.parentNode is <tr> 
330             // this.parentNode.parentNode.firstChild is the first cell <td> of this line <tr>
331             // this.parentNode.parentNode.firstChild.firstChild is the text in that cell
332             //var firstCellVal=this.parentNode.parentNode.firstChild.firstChild.data;
333             var remove_urn = this.id; 
334             var current_resources = event.data.instance.current_resources;
335             var list_resources = $.grep(current_resources, function(x) {return x.urn != remove_urn});
336             //jQuery.publish('selected', 'cancel/'+this.id+'/'+get_value(firstCellVal));
337             $.publish('/update-set/' + event.data.instance.options.resource_query_uuid, [list_resources, true]);
338         },
339
340         /******************************** TODO ********************************/
341
342         update_resources: function(resources, change)
343         {
344             console.log("update_resources");
345             var my_oTable = this.table.dataTable();
346             var prev_resources = this.current_resources; 
347
348             /*
349              * The first time the query is advertised, don't do anything.  The
350              * component will learn nodes in the slice through the manifest
351              * received through the other subscription 
352              */
353              if (!change)
354                 return;
355              // ioi: Refubrished
356              var initial = this.initial_resources;
357              //var r_removed  = []; //
358              /*-----------------------------------------------------------------------
359                 TODO: remove this dirty hack !!!
360              */
361              resources = jQuery.map(resources, function(x){
362                 if(!('timeslot' in x)){x.timeslot=0;}
363                 return x;
364              });
365              /*
366                 TODO: handle generic keys instead of specific stuff
367                       ex: urn
368                           urn-lease
369              */
370              var initial_urn = $.map(initial, function(x){return x.urn;});
371              var resources_urn = $.map(resources, function(x){return x.urn;});
372              var r_removed = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) == -1 });
373              var r_attached = $.grep(initial, function (x) { return $.inArray(x.urn, resources_urn) > -1 });
374              var r_added = $.grep(resources, function (x) { return $.inArray(x.urn, initial_urn) == -1 });
375              exists = false; // ioi
376              /*-----------------------------------------------------------------------*/
377
378              my_oTable.fnClearTable();
379              /*
380                 TODO: factorization of this code !!!
381              */
382              $.each(r_added, function(i, r) { 
383                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
384                 var type = 'add';  
385                 // Create the resource objects
386                 // ioi: refubrished
387                 var urn = r.urn;
388                 time = r.timeslot;
389                               
390                 var SPAN = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+urn+"'/>";
391                 var slot = "<span id='resource_"+urn+"'>" + time + "</span>"; //ioi
392                 // ioi
393                 var newline=Array();
394                 newline.push(type, urn, slot, SPAN); // ioi
395                 var line = my_oTable.fnAddData(newline);
396                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
397                 nTr.className = type;
398              });
399              $.each(r_attached, function(i, r) {  
400                 //var type = (typeof initial == 'undefined' || r.node != initial.node) ? 'add' : 'attached';
401                 var type = 'attached';
402                 // Create the resource objects
403                 // ioi: refubrished
404                 var node = r.urn;
405                 time = r.timeslot;
406
407                 var SPAN = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+node+"'/>";
408                 var slot = "<span id='resource_"+node+"'>" + time + "</span>"; //ioi
409                 // ioi
410                 var newline=Array();
411                 newline.push(type, node, slot, SPAN); // ioi
412                 var line = my_oTable.fnAddData(newline);
413                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
414                 nTr.className = type;
415              });
416              $.each(r_removed, function(i, r) { 
417                 // The list contains objects
418                 // ioi: refubrished
419                 var node = r.urn;
420                 var time = r.timeslot;
421                     
422                 var SPAN = "<span class='ui-icon ui-icon-close ResourceSelectedClose' id='"+node+"'/>";
423                 var slot = "<span id='resource_"+node+"'>" + time + "</span>";
424                 // ioi
425                 var newline=Array();
426                 newline.push('remove', node, slot, SPAN); // ioi
427                 var line = my_oTable.fnAddData(newline);
428                 var nTr = my_oTable.fnSettings().aoData[ line[0] ].nTr;
429                 nTr.className = 'remove';
430              });
431
432              this.current_resources = $.merge(r_attached,r_added);
433
434              /* Allow the user to update the slice */
435              //jQuery('#updateslice-' + data.ResourceSelected.plugin_uuid).prop('disabled', false);
436
437         }, // update_resources
438
439     });
440
441     $.plugin('ResourcesSelected', ResourcesSelected);
442
443 })(jQuery);