slice page working. added temporarily core and util classes from manifold core
[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 /*!
23  * This namespace holds functions for globally managing query objects
24  * \Class Manifold
25  */
26 var manifold = {
27
28     /*!
29      * Associative array storing the set of queries active on the page
30      * \memberof Manifold
31      */
32     all_queries: {},
33
34     /*!
35      * Insert a query in the global hash table associating uuids to queries.
36      * If the query has no been analyzed yet, let's do it.
37      * \fn insert_query(query)
38      * \memberof Manifold
39      * \param ManifoldQuery query Query to be added
40      */
41     insert_query : function (query) { 
42         if (query.analyzed_query == null) {
43             query.analyze_subqueries();
44         }
45         manifold.all_queries[query.query_uuid]=query;
46     },
47
48     /*!
49      * Returns the query associated to a UUID
50      * \fn find_query(query_uuid)
51      * \memberof Manifold
52      * \param string query_uuid The UUID of the query to be returned
53      */
54     find_query : function (query_uuid) { 
55         return manifold.all_queries[query_uuid];
56     },
57
58     // trigger a query asynchroneously
59     proxy_url : '/manifold/proxy/json/',
60
61     asynchroneous_debug : true,
62
63     // Executes all async. queries
64     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
65     asynchroneous_exec : function (query_publish_dom_tuples) {
66         // start spinners
67
68         // in case the spin stuff was not loaded, let's make sure we proceed to the exit 
69         try {
70             if (manifold.asynchroneous_debug) 
71             messages.debug("Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
72             jQuery('.need-spin').spin(spin_presets);
73         } catch (err) { messages.debug("Cannot turn on spins " + err); }
74         
75         // We use js function closure to be able to pass the query (array) to the
76         // callback function used when data is received
77         var success_closure = function(query, publish_uuid, domid) {
78             return function(data, textStatus) {manifold.asynchroneous_success(data, query, publish_uuid, domid);}};
79         
80         // Loop through input array, and use publish_uuid to publish back results
81         jQuery.each(query_publish_dom_tuples, function(index, tuple) {
82             var query=manifold.find_query(tuple.query_uuid);
83             var query_json=JSON.stringify (query);
84             var publish_uuid=tuple.publish_uuid;
85             // by default we publish using the same uuid of course
86             if (publish_uuid==undefined) publish_uuid=query.query_uuid;
87             if (manifold.asynchroneous_debug) {
88                 messages.debug("sending POST on " + manifold.proxy_url + " to be published on " + publish_uuid);
89                 messages.debug("... ctd... with actual query= " + query.__repr());
90             }
91             // not quite sure what happens if we send a string directly, as POST data is named..
92             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
93                 jQuery.post(manifold.proxy_url, {'json':query_json} , success_closure(query, publish_uuid, tuple.domid));
94         })
95     },
96
97
98     /*!
99      * Returns whether a query expects a unique results.
100      * This is the case when the filters contain a key of the object
101      * \fn query_expects_unique_result(query)
102      * \memberof Manifold
103      * \param ManifoldQuery query Query for which we are testing whether it expects a unique result
104      */
105     query_expects_unique_result: function(query) {
106         /* XXX we need functions to query metadata */
107         //var keys = MANIFOLD_METADATA[query.object]['keys']; /* array of array of field names */
108         /* TODO requires keys in metadata */
109         return true;
110     },
111
112     /*!
113      * Publish result
114      * \fn publish_result(query, results)
115      * \memberof Manifold
116      * \param ManifoldQuery query Query which has received results
117      * \param array results results corresponding to query
118      */
119     publish_result: function(query, result) {
120         /* Publish an update announce */
121         var channel="/results/" + query.query_uuid + "/changed";
122         if (manifold.asynchroneous_debug) messages.debug("publishing result on " + channel);
123         jQuery.publish(channel, [result, query]);
124     },
125
126     /*!
127      * Recursively publish result
128      * \fn publish_result_rec(query, result)
129      * \memberof Manifold
130      * \param ManifoldQuery query Query which has received result
131      * \param array result result corresponding to query
132      */
133     publish_result_rec: function(query, result) {
134         /* If the result is not unique, only publish the top query;
135          * otherwise, publish the main object as well as subqueries
136          * XXX how much recursive are we ?
137          */
138         if (manifold.query_expects_unique_result(query)) {
139             /* Also publish subqueries */
140             jQuery.each(query.subqueries, function(object, subquery) {
141                 manifold.publish_result_rec(subquery, result[0][object]);
142                 /* TODO remove object from result */
143             });
144         }
145         manifold.publish_result(query, result);
146     },
147
148     // if set domid allows the result to be directed to just one plugin
149     // most of the time publish_uuid will be query.query_uuid
150     // however in some cases we wish to publish the result under a different uuid
151     // e.g. an updater wants to publish its result as if from the original (get) query
152     asynchroneous_success : function (data, query, publish_uuid, domid) {
153         // xxx should have a nicer declaration of that enum in sync with the python code somehow
154         if (data.code == 2) { // ERROR
155             alert("Your session has expired, please log in again");
156             window.location="/logout/";
157             return;
158         }
159         if (data.code == 1) { // WARNING
160             messages.error("Some errors have been received from the manifold backend at " + MANIFOLD_URL + " [" + data.description + "]");
161             // publish error code and text message on a separate channel for whoever is interested
162             jQuery.publish("/results/" + publish_uuid + "/failed", [data.code, data.description] );
163         }
164         // once everything is checked we can use the 'value' part of the manifoldresult
165         var result=data.value;
166         if (result) {
167             if (!!domid) {
168                 /* Directly inform the requestor */
169                 if (manifold.asynchroneous_debug) messages.debug("directing result to " + domid);
170                 jQuery('#' + domid).trigger('results', [result]);
171             } else {
172                 /* XXX Jordan XXX I don't need publish_uuid here... What is it used for ? */
173                 /* query is the query we sent to the backend; we need to find the
174                  * corresponding analyezd_query in manifold.all_queries
175                  */
176                 tmp_query = manifold.find_query(query.query_uuid);
177                 manifold.publish_result_rec(tmp_query.analyzed_query, result);
178             }
179
180         }
181     },
182
183 }; // manifold object
184 /* ------------------------------------------------------------ */
185
186 // extend jQuery/$ with pubsub capabilities
187 /* https://gist.github.com/661855 */
188 (function($) {
189
190   var o = $({});
191
192   $.subscribe = function( channel, selector, data, fn) {
193     /* borrowed from jQuery */
194     if ( data == null && fn == null ) {
195         // ( channel, fn )
196         fn = selector;
197         data = selector = undefined;
198     } else if ( fn == null ) {
199         if ( typeof selector === "string" ) {
200             // ( channel, selector, fn )
201             fn = data;
202             data = undefined;
203         } else {
204             // ( channel, data, fn )
205             fn = data;
206             data = selector;
207             selector = undefined;
208         }
209     }
210     /* </ugly> */
211
212     /* We use an indirection function that will clone the object passed in
213      * parameter to the subscribe callback 
214      * 
215      * FIXME currently we only clone query objects which are the only ones
216      * supported and editable, we might have the same issue with results but
217      * the page load time will be severely affected...
218      */
219     o.on.apply(o, [channel, selector, data, function() { 
220         for(i = 1; i < arguments.length; i++) {
221             if ( arguments[i].constructor.name == 'ManifoldQuery' )
222                 arguments[i] = arguments[i].clone();
223         }
224         fn.apply(o, arguments);
225     }]);
226   };
227
228   $.unsubscribe = function() {
229     o.off.apply(o, arguments);
230   };
231
232   $.publish = function() {
233     o.trigger.apply(o, arguments);
234   };
235
236 }(jQuery));
237
238 /* ------------------------------------------------------------ */
239
240 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
241 //make sure to expose csrf in our outcoming ajax/post requests
242 $.ajaxSetup({ 
243      beforeSend: function(xhr, settings) {
244          function getCookie(name) {
245              var cookieValue = null;
246              if (document.cookie && document.cookie != '') {
247                  var cookies = document.cookie.split(';');
248                  for (var i = 0; i < cookies.length; i++) {
249                      var cookie = jQuery.trim(cookies[i]);
250                      // Does this cookie string begin with the name we want?
251                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
252                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
253                      break;
254                  }
255              }
256          }
257          return cookieValue;
258          }
259          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
260              // Only send the token to relative URLs i.e. locally.
261              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
262          }
263      } 
264 });
265