uses messages:debug rather than console.log
[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     console.log ("debug_dict_keys: " + msg + " keys= " + keys);
6 }
7 function debug_dict (msg, o) {
8     for (var k in o) console.log ("debug_dict: " + msg + " [" + k + "]=" + o[k]);
9 }
10 function debug_value (msg, value) {
11     console.log ("debug_value: " + msg + " " + value);
12 }
13 function debug_query (msg, query) {
14     if (query === undefined) console.log ("debug_query: " + msg + " -> undefined");
15     else if (query == null) console.log ("debug_query: " + msg + " -> null");
16     else if ('query_uuid' in query) console.log ("debug_query: " + msg + query.__repr());
17     else console.log ("debug_query: " + msg + " query= " + query);
18 }
19
20 /* ------------------------------------------------------------ */
21 // this namespace holds functions for globally managing query objects
22 var manifold = {
23
24     all_queries: {},
25
26     insert_query : function (query) { 
27         manifold.all_queries[query.query_uuid]=query; 
28     },
29     find_query : function (query_uuid) { 
30         return manifold.all_queries[query_uuid];
31     },
32     debug_all_queries : function (msg) {
33         for (var query_uuid in manifold.all_queries) {
34             $.publish("messages:debug","manifold.debug " + msg + " " + query_uuid + " -> " + manifold.all_queries[query_uuid]);
35         }
36     },
37
38     // trigger a query asynchroneously
39     proxy_url : '/manifold/proxy/json/',
40
41     asynchroneous_debug : true,
42
43     // Executes all async. queries
44     // input queries are specified as a list of {'query_uuid': <query_uuid>, 'id': <possibly null>}
45     asynchroneous_exec : function (query_uuid_domids) {
46         // start spinners
47
48         if (manifold.asynchroneous_debug) 
49             $.publish("messages.debug","Turning on spin with " + jQuery(".need-spin").length + " matches for .need-spin");
50         jQuery('.need-spin').spin(spin_presets);
51         
52         // We use js function closure to be able to pass the query (array) to the
53         // callback function used when data is received
54         var success_closure = function(query, id) {
55             return function(data, textStatus) {manifold.asynchroneous_success(data, query, id);}};
56         
57         // Loop through query array and use ajax to send back query_uuid_domids (to frontend) with json
58         jQuery.each(query_uuid_domids, function(index, tuple) {
59             var query=manifold.find_query(tuple.query_uuid);
60             var query_json=JSON.stringify (query);
61             if (manifold.asynchroneous_debug) {
62                 $.publish("messages:debug","sending POST on " + manifold.proxy_url + " with query= " + query.__repr());
63             }
64             // not quite sure what happens if we send a string directly, as POST data is named..
65             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
66             jQuery.post(manifold.proxy_url, {'json':query_json} , success_closure(query, tuple.id));
67         })
68             },
69
70     asynchroneous_success : function (data, query, id) {
71         if (manifold.asynchroneous_debug) 
72             $.publish("messages:debug","received manifold result with code " + data.code);
73         // xxx should have a nicer declaration of that enum in sync with the python code somehow
74         if (data.code == 1) {
75             alert("Your session has expired, please log in again");
76             window.location="/logout/";
77             return;
78         } else if (data.code != 0) {
79             alert("Error received from manifold backend at " + MANIFOLD_URL + " [" + data.output + "]");
80             return;
81         }
82         // once everything is checked we can use the 'value' part of the manifoldresult
83         data=data.value;
84         if (data) {
85             if (!!id) {
86                 /* Directly inform the requestor */
87                 jQuery('#' + id).trigger('results', [data]);
88             } else {
89                 /* Publish an update announce */
90                 jQuery.publish("/results/" + query.query_uuid + "/changed", [data, query]);
91             }
92
93         }
94     },
95
96 }; // manifold object
97 /* ------------------------------------------------------------ */
98
99 // extend jQuery/$ with pubsub capabilities
100 /* https://gist.github.com/661855 */
101 (function($) {
102
103   var o = $({});
104
105   $.subscribe = function( types, selector, data, fn) {
106     /* borrowed from jQuery */
107     if ( data == null && fn == null ) {
108         // ( types, fn )
109         fn = selector;
110         data = selector = undefined;
111     } else if ( fn == null ) {
112         if ( typeof selector === "string" ) {
113             // ( types, selector, fn )
114             fn = data;
115             data = undefined;
116         } else {
117             // ( types, data, fn )
118             fn = data;
119             data = selector;
120             selector = undefined;
121         }
122     }
123     /* </ugly> */
124
125     /* We use an indirection function that will clone the object passed in
126      * parameter to the subscribe callback 
127      * 
128      * FIXME currently we only clone query objects which are the only ones
129      * supported and editable, we might have the same issue with results but
130      * the page load time will be severely affected...
131      */
132     o.on.apply(o, [types, selector, data, function() { 
133         for(i = 1; i < arguments.length; i++) {
134             if ( arguments[i].constructor.name == 'Query' )
135                 arguments[i] = arguments[i].clone();
136         }
137         fn.apply(o, arguments);
138     }]);
139   };
140
141   $.unsubscribe = function() {
142     o.off.apply(o, arguments);
143   };
144
145   $.publish = function() {
146     o.trigger.apply(o, arguments);
147   };
148
149 }(jQuery));
150
151 /* ------------------------------------------------------------ */
152
153 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
154 //make sure to expose csrf in our outcoming ajax/post requests
155 $.ajaxSetup({ 
156      beforeSend: function(xhr, settings) {
157          function getCookie(name) {
158              var cookieValue = null;
159              if (document.cookie && document.cookie != '') {
160                  var cookies = document.cookie.split(';');
161                  for (var i = 0; i < cookies.length; i++) {
162                      var cookie = jQuery.trim(cookies[i]);
163                      // Does this cookie string begin with the name we want?
164                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
165                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
166                      break;
167                  }
168              }
169          }
170          return cookieValue;
171          }
172          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
173              // Only send the token to relative URLs i.e. locally.
174              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
175          }
176      } 
177 });
178