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