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