manifold: imprved plugin class with helpers for naming HTML tags in plugins
[myslice.git] / manifold / js / manifold.js
1 // utilities 
2 function debug_dict_keys (msg, o) {
3     var keys=[];
4     for (var k in o) keys.push(k);
5     messages.debug ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) messages.debug ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     messages.debug ("debug_value: " + msg + " " + value);
12 }
13 function debug_query (msg, query) {
14     if (query === undefined) messages.debug ("debug_query: " + msg + " -> undefined");
15     else if (query == null) messages.debug ("debug_query: " + msg + " -> null");
16     else if ('query_uuid' in query) messages.debug ("debug_query: " + msg + query.__repr());
17     else messages.debug ("debug_query: " + msg + " query= " + query);
18 }
19
20 /* ------------------------------------------------------------ */
21
22 // Constants that should be somehow moved to a plugin.js file
23 var FILTER_ADDED   = 1;
24 var FILTER_REMOVED = 2;
25 var CLEAR_FILTERS  = 3;
26 var FIELD_ADDED    = 4;
27 var FIELD_REMOVED  = 5;
28 var CLEAR_FIELDS   = 6;
29 var NEW_RECORD     = 7;
30 var CLEAR_RECORDS  = 8;
31
32 var IN_PROGRESS    = 101;
33 var DONE           = 102;
34
35 /* Update requests from plugins */
36 var SET_ADD        = 201;
37 var SET_REMOVED    = 202;
38
39 /* Query status */
40 var STATUS_NONE               = 500; // Query has not been started yet
41 var STATUS_GET_IN_PROGRESS    = 501; // Query has been sent, no result has been received
42 var STATUS_GET_RECEIVED       = 502; // Success
43 var STATUS_GET_ERROR          = 503; // Error
44 var STATUS_UPDATE_PENDING     = 504;
45 var STATUS_UPDATE_IN_PROGRESS = 505;
46 var STATUS_UPDATE_RECEIVED    = 506;
47 var STATUS_UPDATE_ERROR       = 507;
48 // outdated ?
49
50 // A structure for storing queries
51
52
53
54 function QueryExt(query, parent_query, main_query) {
55
56     /* Constructor */
57     if (typeof query == "undefined")
58         throw "Must pass a query in QueryExt constructor";
59     this.query            = query
60     this.parent_query_ext = (typeof parent_query == "undefined") ? false : parent_query
61     this.main_query_ext   = (typeof main_query   == "undefined") ? false : main_query
62     
63     this.status       = null;
64     this.results      = null;
65     this.update_query = null; // null unless we are a main_query (aka parent_query == null); only main_query_fields can be updated...
66 }
67
68 function QueryStore() {
69
70     this.main_queries     = {};
71     this.analyzed_queries = {};
72
73     /* Insertion */
74
75     this.insert = function(query)
76     {
77         if (query.analyzed_query == null) {
78             query.analyze_subqueries();
79         }
80
81         query_ext = new QueryExt(query, null, null)
82         manifold.query_store.main_queries[query.query_uuid] = query_ext;
83
84         // We also need to insert all queries and subqueries from the analyzed_query
85         // XXX We need the root of all subqueries
86         query.iter_subqueries(function(sq, data, parent_query) {
87             if (parent_query)
88                 parent_query_ext = manifold.query_store.find_analyzed_query_ext(parent_query.query_uuid);
89             else
90                 parent_query_ext = null;
91             // XXX parent_query_ext == false
92             // XXX main.subqueries = {} # Normal, we need analyzed_query
93             sq_ext = new QueryExt(sq, parent_query_ext, query_ext)
94             manifold.query_store.analyzed_queries[sq.query_uuid] = sq_ext;
95         });
96     }
97
98     /* Searching */
99
100     this.find_query_ext = function(query_uuid)
101     {
102         return this.main_queries[query_uuid];
103     }
104
105     this.find_query = function(query_uuid)
106     {
107         return this.find_query_ext(query_uuid).query;
108     }
109
110     this.find_analyzed_query_ext = function(query_uuid)
111     {
112         return this.analyzed_queries[query_uuid];
113     }
114
115     this.find_analyzed_query = function(query_uuid)
116     {
117         return this.find_analyzed_query_ext(query_uuid).query;
118     }
119 }
120
121 /*!
122  * This namespace holds functions for globally managing query objects
123  * \Class Manifold
124  */
125 var manifold = {
126
127     /************************************************************************** 
128      * Helper functions
129      **************************************************************************/ 
130
131     separator: '__',
132
133     spin_presets: {},
134
135     spin: function(locator, active /*= true */) {
136         active = typeof active !== 'undefined' ? active : true;
137         try {
138             if (active) {
139                 $(locator).spin(manifold.spin_presets);
140             } else {
141                 $(locator).spin(false);
142             }
143         } catch (err) { messages.debug("Cannot turn spins on/off " + err); }
144     },
145
146     /************************************************************************** 
147      * Query management
148      **************************************************************************/ 
149
150     query_store: new QueryStore(),
151
152     // XXX Remaining functions are deprecated since they are replaced by the query store
153
154     /*!
155      * Associative array storing the set of queries active on the page
156      * \memberof Manifold
157      */
158     all_queries: {},
159
160     /*!
161      * Insert a query in the global hash table associating uuids to queries.
162      * If the query has no been analyzed yet, let's do it.
163      * \fn insert_query(query)
164      * \memberof Manifold
165      * \param ManifoldQuery query Query to be added
166      */
167     insert_query : function (query) { 
168         // NEW API
169         manifold.query_store.insert(query);
170
171         // FORMER API
172         if (query.analyzed_query == null) {
173             query.analyze_subqueries();
174         }
175         manifold.all_queries[query.query_uuid]=query;
176     },
177
178     /*!
179      * Returns the query associated to a UUID
180      * \fn find_query(query_uuid)
181      * \memberof Manifold
182      * \param string query_uuid The UUID of the query to be returned
183      */
184     find_query : function (query_uuid) { 
185         return manifold.all_queries[query_uuid];
186     },
187
188     /************************************************************************** 
189      * Query execution
190      **************************************************************************/ 
191
192     // trigger a query asynchroneously
193     proxy_url : '/manifold/proxy/json/',
194
195     asynchroneous_debug : true,
196
197     /**
198      * \brief We use js function closure to be able to pass the query (array)
199      * to the callback function used when data is received
200      */
201     success_closure: function(query, publish_uuid, callback /*domid*/)
202     {
203         return function(data, textStatus) {
204             manifold.asynchroneous_success(data, query, publish_uuid, callback /*domid*/);
205         }
206     },
207
208     // Executes all async. queries
209     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
210     asynchroneous_exec : function (query_publish_dom_tuples) {
211         // start spinners
212
213         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
214         //try {
215         //    if (manifold.asynchroneous_debug) 
216         //   messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
217         //    jQuery('.need-spin').spin(manifold.spin_presets);
218         //} catch (err) { messages.debug("Cannot turn on spins " + err); }
219         
220         // Loop through input array, and use publish_uuid to publish back results
221         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
222             var query=manifold.find_query(tuple.query_uuid);
223             var query_json=JSON.stringify (query);
224             var publish_uuid=tuple.publish_uuid;
225             // by default we publish using the same uuid of course
226             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
227             if (manifold.asynchroneous_debug) {
228                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
229                 messages.debug("... ctd... with actual query= " + query.__repr());
230             }
231
232             query.iter_subqueries(function (sq) {
233                 manifold.raise_record_event(sq.query_uuid, IN_PROGRESS);
234             });
235
236             // not quite sure what happens if we send a string directly, as POST data is named..
237             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
238                 jQuery.post(manifold.proxy_url, {'json':query_json} , manifold.success_closure(query, publish_uuid, tuple.callback /*domid*/));
239         })
240     },
241
242     /**
243      * \brief Forward a query to the manifold backend
244      * \param query (dict) the query to be executed asynchronously
245      * \param callback (function) the function to be called when the query terminates
246      * Deprecated:
247      * \param domid (string) the domid to be notified about the results (null for using the pub/sub system
248      */
249     forward: function(query, callback /*domid*/) {
250         var query_json = JSON.stringify(query);
251         $.post(manifold.proxy_url, {'json': query_json} , manifold.success_closure(query, query.query_uuid, callback/*domid*/));
252     },
253
254     /*!
255      * Returns whether a query expects a unique results.
256      * This is the case when the filters contain a key of the object
257      * \fn query_expects_unique_result(query)
258      * \memberof Manifold
259      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
260      */
261     query_expects_unique_result: function(query) {
262         /* XXX we need functions to query metadata */
263         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
264         /* TODO requires keys in metadata */
265         return true;
266     },
267
268     /*!
269      * Publish result
270      * \fn publish_result(query, results)
271      * \memberof Manifold
272      * \param ManifoldQuery query Query which has received results
273      * \param array results results corresponding to query
274      */
275     publish_result: function(query, result) {
276         if (typeof result === 'undefined')
277             result = [];
278
279         // NEW PLUGIN API
280         manifold.raise_record_event(query.query_uuid, CLEAR_RECORDS);
281         $.each(result, function(i, record) {
282             manifold.raise_record_event(query.query_uuid, NEW_RECORD, record);
283         });
284         manifold.raise_record_event(query.query_uuid, DONE);
285
286         // OLD PLUGIN API BELOW
287         /* Publish an update announce */
288         var channel="/results/" + query.query_uuid + "/changed";
289         if (manifold.asynchroneous_debug)
290             messages.debug("publishing result on " + channel);
291         jQuery.publish(channel, [result, query]);
292     },
293
294     /*!
295      * Recursively publish result
296      * \fn publish_result_rec(query, result)
297      * \memberof Manifold
298      * \param ManifoldQuery query Query which has received result
299      * \param array result result corresponding to query
300      */
301     publish_result_rec: function(query, result) {
302         /* If the result is not unique, only publish the top query;
303          * otherwise, publish the main object as well as subqueries
304          * XXX how much recursive are we ?
305          */
306         if (manifold.query_expects_unique_result(query)) {
307             /* Also publish subqueries */
308             jQuery.each(query.subqueries, function(object, subquery) {
309                 manifold.publish_result_rec(subquery, result[0][object]);
310                 /* TODO remove object from result */
311             });
312         }
313         manifold.publish_result(query, result);
314     },
315
316     // if set domid allows the result to be directed to just one plugin
317     // most of the time publish_uuid will be query.query_uuid
318     // however in some cases we wish to publish the result under a different uuid
319     // e.g. an updater wants to publish its result as if from the original (get) query
320     asynchroneous_success : function (data, query, publish_uuid, callback /*domid*/) {
321         // xxx should have a nicer declaration of that enum in sync with the python code somehow
322
323         /* If a callback has been specified, we redirect results to it */
324         if (!!callback) { callback(data); return; }
325
326         if (data.code == 2) { // ERROR
327             // We need to make sense of error codes here
328             alert("Your session has expired, please log in again");
329             window.location="/logout/";
330             return;
331         }
332         if (data.code == 1) { // WARNING
333             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
334             // publish error code and text message on a separate channel for whoever is interested
335             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
336
337             $("#notifications").notify("create", "sticky", {
338               title: 'Warning',
339               text: data.description
340             },{
341               expires: false,
342               speed: 1000
343             });
344             
345         }
346         // once everything is checked we can use the 'value' part of the manifoldresult
347         var result=data.value;
348         if (result) {
349             //if (!!callback /* domid */) {
350             //    /* Directly inform the requestor */
351             //    if (manifold.asynchroneous_debug) messages.debug("directing result to callback");
352             //    callback(result);
353             //    //if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
354             //    //jQuery('#' + domid).trigger('results', [result]);
355             //} else {
356                 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
357                 /* query is the query we sent to the backend; we need to find the
358                  * corresponding analyezd_query in manifold.all_queries
359                  */
360                 tmp_query = manifold.find_query(query.query_uuid);
361                 manifold.publish_result_rec(tmp_query.analyzed_query, result);
362             //}
363
364         }
365     },
366
367     /************************************************************************** 
368      * Plugin API helpers
369      **************************************************************************/ 
370
371     raise_event_handler: function(type, query_uuid, event_type, value)
372     {
373         if (type == 'query') {
374             var channels = [ manifold.get_query_channel(query_uuid), manifold.get_query_channel('*') ];
375         } else if (type == 'record') {
376             var channels = [ manifold.get_record_channel(query_uuid), manifold.get_record_channel('*') ];
377
378         } else {
379             throw 'Incorrect type for manifold.raise_event()';
380         }
381         $.each(channels, function(i, channel) {
382             if (value === undefined)
383                 $('.plugin').trigger(channel, [event_type]);
384             else
385                 $('.plugin').trigger(channel, [event_type, value]);
386         });
387     },
388
389     raise_query_event: function(query_uuid, event_type, value)
390     {
391         manifold.raise_event_handler('query', query_uuid, event_type, value);
392     },
393
394     raise_record_event: function(query_uuid, event_type, value)
395     {
396         manifold.raise_event_handler('record', query_uuid, event_type, value);
397     },
398
399
400     raise_event: function(query_uuid, event_type, value)
401     {
402         // Query uuid has been updated with the key of a new element
403         query_ext    = manifold.query_store.find_analyzed_query_ext(query_uuid);
404         query = query_ext.query;
405
406         switch(event_type) {
407             case SET_ADD:
408                 // update is only possible is the query is not pending, etc
409                 // CHECK status !
410
411                 // XXX we can only update subqueries of the main query. Check !
412                 // assert query_ext.parent_query == query_ext.main_query
413                 update_query = query_ext.parent_query_ext.update_query;
414
415                 // NOTE: update might modify the fields in Get
416                 // NOTE : we have to modify all child queries
417                 // NOTE : parts of a query might not be started (eg slice.measurements, how to handle ?)
418
419                 // if everything is done right, update_query should not be null. It is updated when we received results from the get query
420                 // object = the same as get
421                 // filter = key : update a single object for now
422                 // fields = the same as get
423
424                 break;
425             case SET_REMOVED:
426                 // Query uuid has been updated with the key of a removed element
427                 break;
428             case FILTER_ADDED:
429                 break;
430             case FILTER_REMOVED:
431                 break;
432             case FIELD_ADDED:
433                 main_query = query_ext.main_query_ext.query;
434                 main_update_query = query_ext.main_query_ext.update_query;
435                 query.select(value);
436
437                 // Here we need the full path through all subqueries
438                 path = ""
439                 // XXX We might need the query name in the QueryExt structure
440                 main_query.select(value);
441
442                 // XXX When is an update query associated ?
443                 // XXX main_update_query.select(value);
444
445                 break;
446
447             case FIELD_REMOVED:
448                 query = query_ext.query;
449                 main_query = query_ext.main_query_ext.query;
450                 main_update_query = query_ext.main_query_ext.update_query;
451                 query.unselect(value);
452                 main_query.unselect(value);
453
454                 // We need to inform about changes in these queries to the respective plugins
455                 // Note: query & main_query have the same UUID
456                 manifold.raise_query_event(query_uuid, event_type, value);
457                 break;
458         }
459         // We need to inform about changes in these queries to the respective plugins
460         // Note: query, main_query & update_query have the same UUID
461         manifold.raise_query_event(query_uuid, event_type, value);
462         // We are targeting the same object with get and update
463         // The notion of query is bad, we should have a notion of destination, and issue queries on the destination
464         // NOTE: Editing a subquery == editing a local view on the destination
465
466         // XXX We might need to run the new query again and manage the plugins in the meantime with spinners...
467         // For the time being, we will collect all columns during the first query
468     },
469
470     /* Publish/subscribe channels for internal use */
471     get_query_channel:  function(uuid) { return '/query/'  + uuid },
472     get_record_channel: function(uuid) { return '/record/' + uuid },
473
474 }; // manifold object
475 /* ------------------------------------------------------------ */
476
477 (function($) {
478
479     /* NEW PLUGIN API
480      * 
481      * NOTE: Since we don't have a plugin class, we are extending all jQuery
482      * plugins...
483      */
484
485     /*!
486      * \brief Associates a query handler to the current plugin
487      * \param uuid (string) query uuid
488      * \param handler (function) handler callback
489      */
490     $.fn.set_query_handler = function(uuid, handler)
491     {
492         this.on(manifold.get_query_channel(uuid), handler);
493     }
494
495     $.fn.set_record_handler = function(uuid, handler)
496     {
497         this.on(manifold.get_record_channel(uuid), handler);
498     }
499
500     // OLD PLUGIN API: extend jQuery/$ with pubsub capabilities
501     // https://gist.github.com/661855
502     var o = $({});
503     $.subscribe = function( channel, selector, data, fn) {
504       /* borrowed from jQuery */
505       if ( data == null && fn == null ) {
506           // ( channel, fn )
507           fn = selector;
508           data = selector = undefined;
509       } else if ( fn == null ) {
510           if ( typeof selector === "string" ) {
511               // ( channel, selector, fn )
512               fn = data;
513               data = undefined;
514           } else {
515               // ( channel, data, fn )
516               fn = data;
517               data = selector;
518               selector = undefined;
519           }
520       }
521       /* </ugly> */
522   
523       /* We use an indirection function that will clone the object passed in
524        * parameter to the subscribe callback 
525        * 
526        * FIXME currently we only clone query objects which are the only ones
527        * supported and editable, we might have the same issue with results but
528        * the page load time will be severely affected...
529        */
530       o.on.apply(o, [channel, selector, data, function() { 
531           for(i = 1; i < arguments.length; i++) {
532               if ( arguments[i].constructor.name == 'ManifoldQuery' )
533                   arguments[i] = arguments[i].clone();
534           }
535           fn.apply(o, arguments);
536       }]);
537     };
538   
539     $.unsubscribe = function() {
540       o.off.apply(o, arguments);
541     };
542   
543     $.publish = function() {
544       o.trigger.apply(o, arguments);
545     };
546   
547 }(jQuery));
548
549 /* ------------------------------------------------------------ */
550
551 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
552 //make sure to expose csrf in our outcoming ajax/post requests
553 $.ajaxSetup({ 
554      beforeSend: function(xhr, settings) {
555          function getCookie(name) {
556              var cookieValue = null;
557              if (document.cookie && document.cookie != '') {
558                  var cookies = document.cookie.split(';');
559                  for (var i = 0; i < cookies.length; i++) {
560                      var cookie = jQuery.trim(cookies[i]);
561                      // Does this cookie string begin with the name we want?
562                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
563                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
564                      break;
565                  }
566              }
567          }
568          return cookieValue;
569          }
570          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
571              // Only send the token to relative URLs i.e. locally.
572              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
573          }
574      } 
575 });
576