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