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