actually use spin_presets - make it red
[unfold.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             console.log("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_exec) console.log("Turning spin on with " + jQuery(".need-spin").length + " matches for need-spin");
49         jQuery('.need-spin').spin(spin_presets);
50         
51         // We use js function closure to be able to pass the query (array) to the
52         // callback function used when data is received
53         var success_closure = function(query, id) {
54             return function(data, textStatus) {manifold.asynchroneous_success(data, query, id);}};
55         
56         // Loop through query array and use ajax to send back query_uuid_domids (to frontend) with json
57         jQuery.each(query_uuid_domids, function(index, tuple) {
58             var query=manifold.find_query(tuple.query_uuid);
59             var query_json=JSON.stringify (query);
60             if (manifold.asynchroneous_debug) {
61                 console.log ("sending POST on " + manifold.proxy_url + " with query= " + query.__repr());
62             }
63             // not quite sure what happens if we send a string directly, as POST data is named..
64             // this gets reconstructed on the proxy side with ManifoldQuery.fill_from_POST
65             jQuery.post(manifold.proxy_url, {'json':query_json} , success_closure(query, tuple.id));
66         })
67             },
68
69     asynchroneous_success : function (data, query, id) {
70         if (data) {
71             if (!!id) {
72                 /* Directly inform the requestor */
73                 jQuery('#' + id).trigger('results', [data]);
74             } else {
75                 /* Publish an update announce */
76                 jQuery.publish("/results/" + query.query_uuid + "/changed", [data, query]);
77             }
78
79         }
80     },
81
82 }; // manifold object
83 /* ------------------------------------------------------------ */
84
85 // extend jQuery/$ with pubsub capabilities
86 /* https://gist.github.com/661855 */
87 (function($) {
88
89   var o = $({});
90
91   $.subscribe = function( types, selector, data, fn) {
92     /* borrowed from jQuery */
93     if ( data == null && fn == null ) {
94         // ( types, fn )
95         fn = selector;
96         data = selector = undefined;
97     } else if ( fn == null ) {
98         if ( typeof selector === "string" ) {
99             // ( types, selector, fn )
100             fn = data;
101             data = undefined;
102         } else {
103             // ( types, data, fn )
104             fn = data;
105             data = selector;
106             selector = undefined;
107         }
108     }
109     /* </ugly> */
110
111     /* We use an indirection function that will clone the object passed in
112      * parameter to the subscribe callback 
113      * 
114      * FIXME currently we only clone query objects which are the only ones
115      * supported and editable, we might have the same issue with results but
116      * the page load time will be severely affected...
117      */
118     o.on.apply(o, [types, selector, data, function() { 
119         for(i = 1; i < arguments.length; i++) {
120             if ( arguments[i].constructor.name == 'Query' )
121                 arguments[i] = arguments[i].clone();
122         }
123         fn.apply(o, arguments);
124     }]);
125   };
126
127   $.unsubscribe = function() {
128     o.off.apply(o, arguments);
129   };
130
131   $.publish = function() {
132     o.trigger.apply(o, arguments);
133   };
134
135 }(jQuery));
136
137 /* ------------------------------------------------------------ */
138
139 //http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
140 //make sure to expose csrf in our outcoming ajax/post requests
141 $.ajaxSetup({ 
142      beforeSend: function(xhr, settings) {
143          function getCookie(name) {
144              var cookieValue = null;
145              if (document.cookie && document.cookie != '') {
146                  var cookies = document.cookie.split(';');
147                  for (var i = 0; i < cookies.length; i++) {
148                      var cookie = jQuery.trim(cookies[i]);
149                      // Does this cookie string begin with the name we want?
150                  if (cookie.substring(0, name.length + 1) == (name + '=')) {
151                      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
152                      break;
153                  }
154              }
155          }
156          return cookieValue;
157          }
158          if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
159              // Only send the token to relative URLs i.e. locally.
160              xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
161          }
162      } 
163 });
164