Comment out old, no-longer-needed debugging.
[mkws-moved-to-github.git] / src / mkws-team.js
1 "use strict";
2 // Factory function for team objects. As much as possible, this uses
3 // only member variables (prefixed "m_") and inner functions with
4 // private scope.
5 //
6 // Some functions are visible as member-functions to be called from
7 // outside code -- specifically, from generated HTML. These functions
8 // are that.switchView(), showDetails(), limitTarget(), limitQuery(),
9 // limitCategory(), delimitTarget(), delimitQuery(), showPage(),
10 // pagerPrev(), pagerNext().
11 //
12 // Before the team can be used for searching and related operations,
13 // its pz2 object must be created by calling team.makePz2().
14 //
15 mkws.makeTeam = function($, teamName) {
16   var that = {};
17
18   // Member variables are separated into two categories
19
20   // 1. Persistent state (to be coded in URL fragment)
21   var m_state = {
22     query: null,                // initially undefined
23     sort: null,                 // will be set below
24     size: null,                 // will be set below
25     page: 1,
26     recid: '',
27     filters: filterSet(that)
28   }
29
30   // 2. Internal state (not to be coded)
31   var m_teamName = teamName;
32   var m_paz; // will be initialised below
33   var m_submitted = false;
34   var m_totalRecordCount = 0;
35   var m_currentRecordData = null;
36   var m_logTime = {
37     // Timestamps for logging
38     "start": $.now(),
39     "last": $.now()
40   };
41   var m_templateText = {}; // widgets can register templates to be compiled
42   var m_template = {}; // compiled templates, from any source
43   var m_widgets = {}; // Maps widget-type to array of widget objects
44   var m_gotRecords = false;
45   
46   var config = mkws.objectInheritingFrom(mkws.config);
47   that.config = config;
48
49   that.toString = function() { return '[Team ' + teamName + ']'; };
50
51   // Accessor methods for individual widgets: readers
52   that.name = function() { return m_teamName; };
53   that.submitted = function() { return m_submitted; };
54   that.sortOrder = function() { return m_state.sort; };
55   that.perpage = function() { return m_state.size; };
56   that.query = function() { return m_state.query; };
57   that.totalRecordCount = function() { return m_totalRecordCount; };
58   that.currentPage = function() { return m_state.page; };
59   that.currentRecordId = function() { return m_state.recid; };
60   that.currentRecordData = function() { return m_currentRecordData; };
61   that.filters = function() { return m_state.filters; };
62   that.gotRecords = function() { return m_gotRecords; };
63
64   // Accessor methods for individual widgets: writers
65   that.set_sortOrder = function(val) { m_state.sort = val };
66   that.set_perpage = function(val) { m_state.size = val };
67
68   m_state.sort = config.sort_default;
69   m_state.size = config.perpage_default;
70
71   var m_default = $.extend(true, {}, m_state);
72   var tmp = m_default.filters;
73   delete m_default.filters;
74   $.extend(m_default, tmp.fragmentItems());
75
76   that.urlFragment = function(overrides) {
77     var s;
78
79     // Expand the filterSet into a set of key=value properties 
80     var state = $.extend(true, {}, m_state, overrides ? overrides : {});
81     var tmp = state.filters;
82     delete state.filters;
83     $.extend(state, tmp.fragmentItems());
84
85     for (var key in state) {
86       if (state.hasOwnProperty(key) &&
87           state[key] != m_default[key]) {
88         if (!s) {
89           var s = 'mkws';
90           if (m_teamName !== 'AUTO') s += m_teamName;
91           s += '=';
92         } else {
93           s += "@";
94         }
95
96         // ### how do we need to quote this?
97         s += key + '=' + state[key];
98       }
99     }
100
101     return s;
102   }
103
104
105   // The following PubSub code is modified from the jQuery manual:
106   // http://api.jquery.com/jQuery.Callbacks/
107   //
108   // Use as:
109   //    team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
110   //    team.queue("eventName").publish(arg1, arg2, ...);
111   //
112   var m_queues = {};
113   function queue(id) {
114     if (!m_queues[id]) {
115       var callbacks = $.Callbacks();
116       m_queues[id] = {
117         publish: callbacks.fire,
118         subscribe: callbacks.add,
119         unsubscribe: callbacks.remove
120       };
121     }
122     return m_queues[id];
123   };
124   that.queue = queue;
125
126
127   function _log(fn, s) {
128     var now = $.now();
129     var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
130                      ((now - m_logTime.last)/1000).toFixed(3) + ") ");
131     m_logTime.last = now;
132     fn.call(mkws.log, m_teamName + ": " + timestamp + s);
133     that.queue("log").publish(m_teamName, timestamp, s);
134   }
135
136   that.trace = function(x) { _log(mkws.trace, x) };
137   that.debug = function(x) { _log(mkws.debug, x) };
138   that.info = function(x) { _log(mkws.info, x) };
139   that.warn = function(x) { _log(mkws.warn, x) };
140   that.error = function(x) { _log(mkws.error, x) };
141   that.fatal = function(x) { _log(mkws.fatal, x) };
142
143   that.info("making new widget team");
144
145   // pz2.js event handlers:
146   function onInit() {
147     that.info("init");
148     m_paz.stat();
149     m_paz.bytarget();
150   }
151
152   function onBytarget(data) {
153     that.info("bytarget");
154     queue("targets").publish(data);
155   }
156
157   function onStat(data) {
158     queue("stat").publish(data);
159     var hitcount = parseInt(data.hits[0], 10);
160     if (!m_gotRecords && hitcount > 0) {
161       m_gotRecords = true;
162       queue("firstrecords").publish(hitcount);
163     }
164     if (parseInt(data.activeclients[0], 10) === 0) {
165       that.info("complete");
166       queue("complete").publish(hitcount);
167     }
168   }
169
170   function onTerm(data) {
171     that.info("term");
172     queue("facets").publish(data);
173   }
174
175   function onShow(data, teamName) {
176     that.info("show");
177     m_totalRecordCount = data.merged;
178     that.info("found " + m_totalRecordCount + " records");
179     queue("pager").publish(data);
180     queue("records").publish(data);
181   }
182
183   function onRecord(data, args, teamName) {
184     that.info("record");
185     // FIXME: record is async!!
186     clearTimeout(m_paz.recordTimer);
187     queue("record").publish(data);
188     var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
189     if (detRecordDiv.length) {
190       // in case on_show was faster to redraw element
191       return;
192     }
193     m_currentRecordData = data;
194     var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
195     var html = renderDetails(m_currentRecordData);
196     $(recordDiv).append(html);
197   }
198
199
200   // create a parameters array and pass it to the pz2's constructor
201   // then register the form submit event with the pz2.search function
202   // autoInit is set to true on default
203   that.makePz2 = function() {
204     that.debug("m_queues=" + $.toJSON(m_queues));
205     var params = {
206       "windowid": teamName,
207       "pazpar2path": mkws.pazpar2_url(),
208       "usesessions" : config.use_service_proxy ? false : true,
209       "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
210       "termlist": config.facets.join(',')
211     };
212
213     params.oninit = onInit;
214     if (m_queues.targets) {
215       params.onbytarget = onBytarget;
216       that.info("setting bytarget callback");
217     }
218     if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
219       params.onstat = onStat;
220       that.info("setting stat callback");
221     }
222     if (m_queues.facets && config.facets.length) {
223       params.onterm = onTerm;
224       that.info("setting term callback");
225     }
226     if (m_queues.records) {
227       that.info("setting show callback");
228       params.onshow = onShow;
229       // Record callback is subscribed from records callback
230       that.info("setting record callback");
231       params.onrecord = onRecord;
232     }
233
234     m_paz = new pz2(params);
235     that.info("created main pz2 object");
236   }
237
238
239   // Used by the Records widget and onRecord()
240   function recordElementId(s) {
241     return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
242   }
243   that.recordElementId = recordElementId;
244
245   // Used by onRecord(), showDetails() and renderDetails()
246   function recordDetailsId(s) {
247     return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
248   }
249
250
251   that.targetFiltered = function(id) {
252     return m_state.filters.targetFiltered(id);
253   };
254
255
256   that.limitTarget = function(id, name) {
257     that.info("limitTarget(id=" + id + ", name=" + name + ")");
258     m_state.filters.add(targetFilter(id, name));
259     if (m_state.query) triggerSearch();
260     return false;
261   };
262
263
264   that.limitQuery = function(field, value) {
265     that.info("limitQuery(field=" + field + ", value=" + value + ")");
266     m_state.filters.add(fieldFilter(field, value));
267     if (m_state.query) triggerSearch();
268     return false;
269   };
270
271
272   that.limitCategory = function(id) {
273     that.info("limitCategory(id=" + id + ")");
274     // Only one category filter at a time
275     m_state.filters.removeMatching(function(f) { return f.type === 'category' });
276     if (id !== '') m_state.filters.add(categoryFilter(id));
277     if (m_state.query) triggerSearch();
278     return false;
279   };
280
281
282   that.delimitTarget = function(id) {
283     that.info("delimitTarget(id=" + id + ")");
284     m_state.filters.removeMatching(function(f) { return f.type === 'target' });
285     if (m_state.query) triggerSearch();
286     return false;
287   };
288
289
290   that.delimitQuery = function(field, value) {
291     that.info("delimitQuery(field=" + field + ", value=" + value + ")");
292     m_state.filters.removeMatching(function(f) { return f.type == 'field' &&
293                                              field == f.field && value == f.value });
294     if (m_state.query) triggerSearch();
295     return false;
296   };
297
298
299   that.showPage = function(pageNum) {
300     m_state.page = pageNum;
301     m_paz.showPage(m_state.page - 1);
302     that.warn("fragment: " + that.urlFragment());
303   };
304
305
306   that.pagerNext = function() {
307     if (m_totalRecordCount - m_state.size * m_state.page > 0) {
308       m_paz.showNext();
309       m_state.page++;
310       that.warn("fragment: " + that.urlFragment());
311     }
312   };
313
314
315   that.pagerPrev = function() {
316     if (m_paz.showPrev() != false) {
317       m_state.page--;
318       that.warn("fragment: " + that.urlFragment());
319     }
320   };
321
322
323   that.reShow = function() {
324     resetPage();
325     m_paz.show(0, m_state.size, m_state.sort);
326     // ### not really the right place for this but it will do for now.
327     that.warn("fragment: " + that.urlFragment());
328   };
329
330
331   function resetPage() {
332     m_state.page = 1;
333     m_totalRecordCount = 0;
334     m_gotRecords = false;
335   }
336   that.resetPage = resetPage;
337
338
339   function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
340     that.info("newSearch: " + query);
341
342     if (config.use_service_proxy && !mkws.authenticated) {
343       alert("searching before authentication");
344       return;
345     }
346
347     m_state.filters.removeMatching(function(f) { return f.type !== 'category' });
348     triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
349     switchView('records'); // In case it's configured to start off as hidden
350     m_submitted = true;
351   }
352   that.newSearch = newSearch;
353
354
355   function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
356     resetPage();
357
358     // Continue to use previous query/sort-order unless new ones are specified
359     if (query) m_state.query = query;
360     if (sortOrder) m_state.sort = sortOrder;
361     if (perpage) m_state.size = perpage;
362     if (targets) m_state.filters.add(targetFilter(targets, targets));
363
364     var pp2filter = m_state.filters.pp2filter();
365     var pp2limit = m_state.filters.pp2limit(limit);
366     var pp2catLimit = m_state.filters.pp2catLimit();
367     if (pp2catLimit) {
368       pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
369     }
370
371     var params = {};
372     if (pp2limit) params.limit = pp2limit;
373     if (maxrecs) params.maxrecs = maxrecs;
374     if (torusquery) {
375       if (!mkws.config.use_service_proxy)
376         alert("can't narrow search by torusquery when not authenticated");
377       params.torusquery = torusquery;
378     }
379
380     that.info("triggerSearch(" + m_state.query + "): filters = " + m_state.filters.toJSON() + ", " +
381         "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
382
383     m_paz.search(m_state.query, m_state.size, m_state.sort, pp2filter, undefined, params);
384     queue("searchtriggered").publish();
385
386     // ### not really the right place for this but it will do for now.
387     that.warn("fragment: " + that.urlFragment());
388   }
389
390   // fetch record details to be retrieved from the record queue
391   that.fetchDetails = function(recId) {
392     that.info("fetchDetails() requesting record '" + recId + "'");
393     m_paz.record(recId);
394     that.warn("fragment: " + that.urlFragment());
395   };
396
397
398   // switching view between targets and records
399   function switchView(view) {
400     var targets = widgetNode('targets');
401     var results = widgetNode('results') || widgetNode('records');
402     var blanket = widgetNode('blanket');
403     var motd    = widgetNode('motd');
404
405     switch(view) {
406     case 'targets':
407       if (targets) $(targets).show();
408       if (results) $(results).hide();
409       if (blanket) $(blanket).hide();
410       if (motd) $(motd).hide();
411       break;
412     case 'records':
413       if (targets) $(targets).hide();
414       if (results) $(results).show();
415       if (blanket) $(blanket).show();
416       if (motd) $(motd).hide();
417       break;
418     default:
419       alert("Unknown view '" + view + "'");
420     }
421   }
422   that.switchView = switchView;
423
424
425   // detailed record drawing
426   that.showDetails = function(recId) {
427     var oldRecordId = m_state.recid;
428     m_state.recid = recId;
429
430     // remove current detailed view if any
431     findnode('#' + recordDetailsId(oldRecordId)).remove();
432
433     // if the same clicked, just hide
434     if (recId == oldRecordId) {
435       m_state.recid = '';
436       m_currentRecordData = null;
437       return;
438     }
439     // request the record
440     that.info("showDetails() requesting record '" + recId + "'");
441     m_paz.record(recId);
442   };
443
444
445   // Finds the node of the specified class within the current team
446   function findnode(selector, teamName) {
447     teamName = teamName || m_teamName;
448
449     if (teamName === 'AUTO') {
450       selector = (selector + '.mkws-team-' + teamName + ',' +
451                   selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
452     } else {
453       selector = selector + '.mkws-team-' + teamName;
454     }
455
456     var node = $(selector);
457     //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
458     return node;
459   }
460
461
462   function widgetNode(type) {
463     var w = that.widget(type);
464     return w ? w.node : undefined;
465   }
466
467   function renderDetails(data, marker) {
468     var template = loadTemplate("details");
469     var details = template(data);
470     return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
471       'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
472   }
473   that.renderDetails = renderDetails;
474
475
476   that.registerTemplate = function(name, text) {
477     if(mkws._old2new.hasOwnProperty(name)) {
478       that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
479       name = mkws._old2new[name];
480     }
481     m_templateText[name] = text;
482   };
483
484
485   function loadTemplate(name, fallbackString) {
486     if(mkws._old2new.hasOwnProperty(name)) {
487        that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
488        name = mkws._old2new[name];
489     }
490
491     var template = m_template[name];
492     if (template === undefined && Handlebars.compile) {
493       var source;
494       var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
495       if (node && node.length < 1) {
496         node = $(".mkws-template-" + name);
497       }
498       if (node) source = node.html();
499       if (!source) source = m_templateText[name];
500       if (source) {
501         template = Handlebars.compile(source);
502         that.info("compiled template '" + name + "'");
503       }
504     }
505     //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
506     if (template === undefined && Handlebars.templates) {
507       template = Handlebars.templates["mkws-template-" + name];
508     }
509     if (template === undefined && mkws.defaultTemplates) {
510       template = mkws.defaultTemplates[name];
511     }
512     if (template) {
513       m_template[name] = template;
514       return template;
515     }
516     else {
517       that.info("No MKWS template for " + name);
518       return null;
519     }  
520   }
521   that.loadTemplate = loadTemplate;
522
523
524   that.addWidget = function(w) {
525     if (m_widgets[w.type] === undefined) {
526       m_widgets[w.type] = [ w ];
527     } else {
528       m_widgets[w.type].push(w);
529     }
530   }
531
532   that.widget = function(type) {
533     var list = m_widgets[type];
534
535     if (!list)
536       return undefined;
537     if (list.length > 1) {
538       alert("widget('" + type + "') finds " + list.length + " widgets: using first");
539     }
540     return list[0];
541   }
542
543   that.visitWidgets = function(callback) {
544     for (var type in m_widgets) {
545       var list = m_widgets[type];
546       for (var i = 0; i < list.length; i++) {
547         var res = callback(type, list[i]);
548         if (res !== undefined) {
549           return res;
550         }
551       }
552     }
553     return undefined;
554   };
555
556   return that;
557 };