loadTemplate returns null when defaultTemplate can't come up with
[mkws-moved-to-github.git] / src / mkws-team.js
1 // Factory function for team objects. As much as possible, this uses
2 // only member variables (prefixed "m_") and inner functions with
3 // private scope.
4 //
5 // Some functions are visible as member-functions to be called from
6 // outside code -- specifically, from generated HTML. These functions
7 // are that.switchView(), showDetails(), limitTarget(), limitQuery(),
8 // limitCategory(), delimitTarget(), delimitQuery(), showPage(),
9 // pagerPrev(), pagerNext().
10 //
11 function team($, teamName) {
12   var that = {};
13   var m_teamName = teamName;
14   var m_submitted = false;
15   var m_query; // initially undefined
16   var m_sortOrder; // will be set below
17   var m_perpage; // will be set below
18   var m_filterSet = filterSet(that);
19   var m_totalRecordCount = 0;
20   var m_currentPage = 1;
21   var m_currentRecordId = '';
22   var m_currentRecordData = null;
23   var m_logTime = {
24     // Timestamps for logging
25     "start": $.now(),
26     "last": $.now()
27   };
28   var m_paz; // will be initialised below
29   var m_templateText = {}; // widgets can register templates to be compiled
30   var m_template = {}; // compiled templates, from any source
31   var m_config = mkws.objectInheritingFrom(mkws.config);
32   var m_widgets = {}; // Maps widget-type to array of widget objects
33   var m_gotRecords = false;
34
35   that.toString = function() { return '[Team ' + teamName + ']'; };
36
37   // Accessor methods for individual widgets: readers
38   that.name = function() { return m_teamName; };
39   that.submitted = function() { return m_submitted; };
40   that.sortOrder = function() { return m_sortOrder; };
41   that.perpage = function() { return m_perpage; };
42   that.totalRecordCount = function() { return m_totalRecordCount; };
43   that.currentPage = function() { return m_currentPage; };
44   that.currentRecordId = function() { return m_currentRecordId; };
45   that.currentRecordData = function() { return m_currentRecordData; };
46   that.filters = function() { return m_filterSet; };
47   that.config = function() { return m_config; };
48
49   // Accessor methods for individual widgets: writers
50   that.set_sortOrder = function(val) { m_sortOrder = val };
51   that.set_perpage = function(val) { m_perpage = val };
52
53
54   // The following PubSub code is modified from the jQuery manual:
55   // http://api.jquery.com/jQuery.Callbacks/
56   //
57   // Use as:
58   //    team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
59   //    team.queue("eventName").publish(arg1, arg2, ...);
60   //
61   var queues = {};
62   function queue(id) {
63     if (!queues[id]) {
64       var callbacks = $.Callbacks();
65       queues[id] = {
66         publish: callbacks.fire,
67         subscribe: callbacks.add,
68         unsubscribe: callbacks.remove
69       };
70     }
71     return queues[id];
72   };
73   that.queue = queue;
74
75
76   function log(s) {
77     var now = $.now();
78     var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
79                      ((now - m_logTime.last)/1000).toFixed(3) + ") ");
80     m_logTime.last = now;
81     mkws.log(m_teamName + ": " + timestamp + s);
82     that.queue("log").publish(m_teamName, timestamp, s);
83   }
84   that.log = log;
85
86
87   log("making new widget team");
88
89   m_sortOrder = m_config.sort_default;
90   m_perpage = m_config.perpage_default;
91
92   // create a parameters array and pass it to the pz2's constructor
93   // then register the form submit event with the pz2.search function
94   // autoInit is set to true on default
95   m_paz = new pz2({ "windowid": teamName,
96                     "pazpar2path": m_config.pazpar2_url,
97                     "usesessions" : m_config.use_service_proxy ? false : true,
98                     "oninit": onInit,
99                     "onbytarget": onBytarget,
100                     "onstat": onStat,
101                     "onterm": (m_config.facets.length ? onTerm : undefined),
102                     "onshow": onShow,
103                     "onrecord": onRecord,
104                     "showtime": 500,            //each timer (show, stat, term, bytarget) can be specified this way
105                     "termlist": m_config.facets.join(',')
106                   });
107   log("created main pz2 object");
108
109   // pz2.js event handlers:
110   function onInit() {
111     log("init");
112     m_paz.stat();
113     m_paz.bytarget();
114   }
115
116   function onBytarget(data) {
117     log("bytarget");
118     queue("targets").publish(data);
119   }
120
121   function onStat(data) {
122     queue("stat").publish(data);
123     var hitcount = parseInt(data.hits[0], 10);
124     if (!m_gotRecords && hitcount > 0) {
125       m_gotRecords = true;
126       queue("firstrecords").publish(hitcount);
127     }
128     if (parseInt(data.activeclients[0], 10) === 0) {
129       log("complete");
130       queue("complete").publish(hitcount);
131     }
132   }
133
134   function onTerm(data) {
135     log("term");
136     queue("termlists").publish(data);
137   }
138
139   function onShow(data, teamName) {
140     log("show");
141     m_totalRecordCount = data.merged;
142     log("found " + m_totalRecordCount + " records");
143     queue("pager").publish(data);
144     queue("records").publish(data);
145   }
146
147   function onRecord(data, args, teamName) {
148     log("record");
149     // FIXME: record is async!!
150     clearTimeout(m_paz.recordTimer);
151     var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
152     if (detRecordDiv.length) {
153       // in case on_show was faster to redraw element
154       return;
155     }
156     m_currentRecordData = data;
157     var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
158     var html = renderDetails(m_currentRecordData);
159     $(recordDiv).append(html);
160   }
161
162
163   // Used by the Records widget and onRecord()
164   function recordElementId(s) {
165     return 'mkwsRec_' + s.replace(/[^a-z0-9]/ig, '_');
166   }
167   that.recordElementId = recordElementId;
168
169   // Used by onRecord(), showDetails() and renderDetails()
170   function recordDetailsId(s) {
171     return 'mkwsDet_' + s.replace(/[^a-z0-9]/ig, '_');
172   }
173
174
175   that.targetFiltered = function(id) {
176     return m_filterSet.targetFiltered(id);
177   };
178
179
180   that.limitTarget = function(id, name) {
181     log("limitTarget(id=" + id + ", name=" + name + ")");
182     m_filterSet.add(targetFilter(id, name));
183     if (m_query) triggerSearch();
184     return false;
185   };
186
187
188   that.limitQuery = function(field, value) {
189     log("limitQuery(field=" + field + ", value=" + value + ")");
190     m_filterSet.add(fieldFilter(field, value));
191     if (m_query) triggerSearch();
192     return false;
193   };
194
195
196   that.limitCategory = function(id) {
197     log("limitCategory(id=" + id + ")");
198     // Only one category filter at a time
199     m_filterSet.removeMatching(function(f) { return f.type === 'category' });
200     if (id !== '') m_filterSet.add(categoryFilter(id));
201     if (m_query) triggerSearch();
202     return false;
203   };
204
205
206   that.delimitTarget = function(id) {
207     log("delimitTarget(id=" + id + ")");
208     m_filterSet.removeMatching(function(f) { return f.type === 'target' });
209     if (m_query) triggerSearch();
210     return false;
211   };
212
213
214   that.delimitQuery = function(field, value) {
215     log("delimitQuery(field=" + field + ", value=" + value + ")");
216     m_filterSet.removeMatching(function(f) { return f.type == 'field' &&
217                                              field == f.field && value == f.value });
218     if (m_query) triggerSearch();
219     return false;
220   };
221
222
223   that.showPage = function(pageNum) {
224     m_currentPage = pageNum;
225     m_paz.showPage(m_currentPage - 1);
226   };
227
228
229   that.pagerNext = function() {
230     if (m_totalRecordCount - m_perpage*m_currentPage > 0) {
231       m_paz.showNext();
232       m_currentPage++;
233     }
234   };
235
236
237   that.pagerPrev = function() {
238     if (m_paz.showPrev() != false)
239       m_currentPage--;
240   };
241
242
243   that.reShow = function() {
244     resetPage();
245     m_paz.show(0, m_perpage, m_sortOrder);
246   };
247
248
249   function resetPage() {
250     m_currentPage = 1;
251     m_totalRecordCount = 0;
252     m_gotRecords = false;
253   }
254   that.resetPage = resetPage;
255
256
257   function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
258     log("newSearch: " + query);
259
260     if (m_config.use_service_proxy && !mkws.authenticated) {
261       alert("searching before authentication");
262       return;
263     }
264
265     m_filterSet.removeMatching(function(f) { return f.type !== 'category' });
266     triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
267     switchView('records'); // In case it's configured to start off as hidden
268     m_submitted = true;
269   }
270   that.newSearch = newSearch;
271
272
273   function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
274     resetPage();
275     queue("navi").publish();
276
277     // Continue to use previous query/sort-order unless new ones are specified
278     if (query) m_query = query;
279     if (sortOrder) m_sortOrder = sortOrder;
280     if (perpage) m_perpage = perpage;
281     if (targets) m_filterSet.add(targetFilter(targets, targets));
282
283     var pp2filter = m_filterSet.pp2filter();
284     var pp2limit = m_filterSet.pp2limit(limit);
285     var pp2catLimit = m_filterSet.pp2catLimit();
286     if (pp2catLimit) {
287       pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
288     }
289
290     var params = {};
291     if (pp2limit) params.limit = pp2limit;
292     if (maxrecs) params.maxrecs = maxrecs;
293     if (torusquery) {
294       if (!mkws.config.use_service_proxy)
295         alert("can't narrow search by torusquery when Service Proxy is not in use");
296       params.torusquery = torusquery;
297     }
298
299     log("triggerSearch(" + m_query + "): filters = " + m_filterSet.toJSON() + ", " +
300         "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
301
302     m_paz.search(m_query, m_perpage, m_sortOrder, pp2filter, undefined, params);
303   }
304
305
306   // switching view between targets and records
307   function switchView(view) {
308     var targets = widgetNode('Targets');
309     var results = widgetNode('Results') || widgetNode('Records');
310     var blanket = widgetNode('Blanket');
311     var motd    = widgetNode('MOTD');
312
313     switch(view) {
314     case 'targets':
315       if (targets) $(targets).show();
316       if (results) $(results).hide();
317       if (blanket) $(blanket).hide();
318       if (motd) $(motd).hide();
319       break;
320     case 'records':
321       if (targets) $(targets).hide();
322       if (results) $(results).show();
323       if (blanket) $(blanket).show();
324       if (motd) $(motd).hide();
325       break;
326     default:
327       alert("Unknown view '" + view + "'");
328     }
329   }
330   that.switchView = switchView;
331
332
333   // detailed record drawing
334   that.showDetails = function(recId) {
335     var oldRecordId = m_currentRecordId;
336     m_currentRecordId = recId;
337
338     // remove current detailed view if any
339     findnode('#' + recordDetailsId(oldRecordId)).remove();
340
341     // if the same clicked, just hide
342     if (recId == oldRecordId) {
343       m_currentRecordId = '';
344       m_currentRecordData = null;
345       return;
346     }
347     // request the record
348     log("showDetails() requesting record '" + recId + "'");
349     m_paz.record(recId);
350   };
351
352
353   // Finds the node of the specified class within the current team
354   function findnode(selector, teamName) {
355     teamName = teamName || m_teamName;
356
357     if (teamName === 'AUTO') {
358       selector = (selector + '.mkwsTeam_' + teamName + ',' +
359                   selector + ':not([class^="mkwsTeam"],[class*=" mkwsTeam"])');
360     } else {
361       selector = selector + '.mkwsTeam_' + teamName;
362     }
363
364     var node = $(selector);
365     //log('findnode(' + selector + ') found ' + node.length + ' nodes');
366     return node;
367   }
368
369
370   function widgetNode(type) {
371     var w = that.widget(type);
372     return w ? w.node : undefined;
373   }
374
375   function renderDetails(data, marker) {
376     var template = loadTemplate("Record");
377     var details = template(data);
378     return '<div class="mkwsDetails mkwsTeam_' + m_teamName + '" ' +
379       'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
380   }
381   that.renderDetails = renderDetails;
382
383
384   that.registerTemplate = function(name, text) {
385     m_templateText[name] = text;
386   };
387
388
389   function loadTemplate(name, fallbackString) {
390     var template = m_template[name];
391
392     if (template === undefined) {
393       // Fall back to generic template if there is no team-specific one
394       var source;
395       var node = $(".mkwsTemplate_" + name + " .mkwsTeam_" + that.name());
396       if (node && node.length < 1) {
397         node = $(".mkwsTemplate_" + name);
398       }
399       if (node) {
400         source = node.html();
401       }
402
403       // If the template is not defined in HTML, check the following
404       // in order: template registered in the team by a widget;
405       // fallback string provided on this invocation; global default.
406       if (!source) {
407         source = m_templateText[name];
408       }
409       if (!source) {
410         source = fallbackString;
411       }
412       if (!source) {
413         source = mkws.defaultTemplate(name);
414       }
415
416       if (!source) return null;
417       template = Handlebars.compile(source);
418       log("compiled template '" + name + "'");
419       m_template[name] = template;
420     }
421
422     return template;
423   }
424   that.loadTemplate = loadTemplate;
425
426
427   that.addWidget = function(w) {
428     if (m_widgets[w.type] === undefined) {
429       m_widgets[w.type] = [ w ];
430     } else {
431       m_widgets[w.type].push(w);
432     }
433   }
434
435   that.widget = function(type) {
436     var list = m_widgets[type];
437
438     if (!list)
439       return undefined;
440     if (list.length > 1) {
441       alert("widget('" + type + "') finds " + list.length + " widgets: using first");
442     }
443     return list[0];
444   }
445
446   that.visitWidgets = function(callback) {
447     for (var type in m_widgets) {
448       var list = m_widgets[type];
449       for (var i = 0; i < list.length; i++) {
450         var res = callback(type, list[i]);
451         if (res !== undefined) {
452           return res;
453         }
454       }
455     }
456     return undefined;
457   }
458
459
460   return that;
461 };