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