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