2 // Factory function for team objects. As much as possible, this uses
3 // only member variables (prefixed "m_") and inner functions with
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().
12 // Before the team can be used for searching and related operations,
13 // its pz2 object must be created by calling team.makePz2().
15 mkws.makeTeam = function($, teamName) {
18 // Member variables are separated into two categories
20 // 1. Persistent state (to be coded in URL fragment)
22 query: null, // initially undefined
23 sort: null, // will be set below
24 size: null, // will be set below
27 filters: filterSet(that)
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;
37 // Timestamps for logging
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;
46 var config = mkws.objectInheritingFrom(mkws.config);
49 that.toString = function() { return '[Team ' + teamName + ']'; };
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; };
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 };
68 m_state.sort = config.sort_default;
69 m_state.size = config.perpage_default;
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());
76 that.urlFragment = function(overrides) {
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;
83 $.extend(state, tmp.fragmentItems());
85 for (var key in state) {
86 if (state.hasOwnProperty(key) &&
87 state[key] != m_default[key]) {
90 if (m_teamName !== 'AUTO') s += m_teamName;
96 // ### how do we need to quote this?
97 s += key + '=' + state[key];
104 // ### what quoting do we need to undo? Complement of previous function
105 that.parseFragment = function(s) {
108 var list = s.split('@');
109 for (var i in list) {
110 var a = list[i].split('=');
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()) {
138 // The following PubSub code is modified from the jQuery manual:
139 // http://api.jquery.com/jQuery.Callbacks/
142 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
143 // team.queue("eventName").publish(arg1, arg2, ...);
148 var callbacks = $.Callbacks();
150 publish: callbacks.fire,
151 subscribe: callbacks.add,
152 unsubscribe: callbacks.remove
160 function _log(fn, s) {
162 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
163 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
164 m_logTime.last = now;
165 fn.call(mkws.log, m_teamName + ": " + timestamp + s);
166 that.queue("log").publish(m_teamName, timestamp, s);
169 that.trace = function(x) { _log(mkws.trace, x) };
170 that.debug = function(x) { _log(mkws.debug, x) };
171 that.info = function(x) { _log(mkws.info, x) };
172 that.warn = function(x) { _log(mkws.warn, x) };
173 that.error = function(x) { _log(mkws.error, x) };
174 that.fatal = function(x) { _log(mkws.fatal, x) };
176 that.info("making new widget team");
178 // pz2.js event handlers:
185 function onBytarget(data) {
186 that.info("bytarget");
187 queue("targets").publish(data);
190 function onStat(data) {
191 queue("stat").publish(data);
192 var hitcount = parseInt(data.hits[0], 10);
193 if (!m_gotRecords && hitcount > 0) {
195 queue("firstrecords").publish(hitcount);
197 if (parseInt(data.activeclients[0], 10) === 0) {
198 that.info("complete");
199 queue("complete").publish(hitcount);
203 function onTerm(data) {
205 queue("facets").publish(data);
208 function onShow(data, teamName) {
210 m_totalRecordCount = data.merged;
211 that.info("found " + m_totalRecordCount + " records");
212 queue("pager").publish(data);
213 queue("records").publish(data);
216 function onRecord(data, args, teamName) {
218 // FIXME: record is async!!
219 clearTimeout(m_paz.recordTimer);
220 queue("record").publish(data);
221 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
222 if (detRecordDiv.length) {
223 // in case on_show was faster to redraw element
226 m_currentRecordData = data;
227 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
228 var html = renderDetails(m_currentRecordData);
229 $(recordDiv).append(html);
233 // create a parameters array and pass it to the pz2's constructor
234 // then register the form submit event with the pz2.search function
235 // autoInit is set to true on default
236 that.makePz2 = function() {
237 that.debug("m_queues=" + $.toJSON(m_queues));
239 "windowid": teamName,
240 "pazpar2path": mkws.pazpar2_url(),
241 "usesessions" : config.use_service_proxy ? false : true,
242 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
243 "termlist": config.facets.join(',')
246 params.oninit = onInit;
247 if (m_queues.targets) {
248 params.onbytarget = onBytarget;
249 that.info("setting bytarget callback");
251 if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
252 params.onstat = onStat;
253 that.info("setting stat callback");
255 if (m_queues.facets && config.facets.length) {
256 params.onterm = onTerm;
257 that.info("setting term callback");
259 if (m_queues.records) {
260 that.info("setting show callback");
261 params.onshow = onShow;
262 // Record callback is subscribed from records callback
263 that.info("setting record callback");
264 params.onrecord = onRecord;
267 m_paz = new pz2(params);
268 that.info("created main pz2 object");
272 // Used by the Records widget and onRecord()
273 function recordElementId(s) {
274 return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
276 that.recordElementId = recordElementId;
278 // Used by onRecord(), showDetails() and renderDetails()
279 function recordDetailsId(s) {
280 return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
284 that.targetFiltered = function(id) {
285 return m_state.filters.targetFiltered(id);
289 that.limitTarget = function(id, name) {
290 that.info("limitTarget(id=" + id + ", name=" + name + ")");
291 m_state.filters.add(targetFilter(id, name));
292 if (m_state.query) triggerSearch();
297 that.limitQuery = function(field, value) {
298 that.info("limitQuery(field=" + field + ", value=" + value + ")");
299 m_state.filters.add(fieldFilter(field, value));
300 if (m_state.query) triggerSearch();
305 that.limitCategory = function(id) {
306 that.info("limitCategory(id=" + id + ")");
307 // Only one category filter at a time
308 m_state.filters.removeMatching(function(f) { return f.type === 'category' });
309 if (id !== '') m_state.filters.add(categoryFilter(id));
310 if (m_state.query) triggerSearch();
315 that.delimitTarget = function(id) {
316 that.info("delimitTarget(id=" + id + ")");
317 m_state.filters.removeMatching(function(f) { return f.type === 'target' });
318 if (m_state.query) triggerSearch();
323 that.delimitQuery = function(field, value) {
324 that.info("delimitQuery(field=" + field + ", value=" + value + ")");
325 m_state.filters.removeMatching(function(f) { return f.type == 'field' &&
326 field == f.field && value == f.value });
327 if (m_state.query) triggerSearch();
332 that.showPage = function(pageNum) {
333 m_state.page = pageNum;
334 m_paz.showPage(m_state.page - 1);
335 that.warn("fragment: " + that.urlFragment());
339 that.pagerNext = function() {
340 if (m_totalRecordCount - m_state.size * m_state.page > 0) {
343 that.warn("fragment: " + that.urlFragment());
348 that.pagerPrev = function() {
349 if (m_paz.showPrev() != false) {
351 that.warn("fragment: " + that.urlFragment());
356 that.reShow = function() {
358 m_paz.show(0, m_state.size, m_state.sort);
359 // ### not really the right place for this but it will do for now.
360 that.warn("fragment: " + that.urlFragment());
364 function resetPage() {
366 m_totalRecordCount = 0;
367 m_gotRecords = false;
369 that.resetPage = resetPage;
372 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
373 that.info("newSearch: " + query);
375 if (config.use_service_proxy && !mkws.authenticated) {
376 alert("searching before authentication");
380 m_state.filters.removeMatching(function(f) { return f.type !== 'category' });
381 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
382 switchView('records'); // In case it's configured to start off as hidden
385 that.newSearch = newSearch;
388 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
391 // Continue to use previous query/sort-order unless new ones are specified
392 if (query) m_state.query = query;
393 if (sortOrder) m_state.sort = sortOrder;
394 if (perpage) m_state.size = perpage;
395 if (targets) m_state.filters.add(targetFilter(targets, targets));
397 var pp2filter = m_state.filters.pp2filter();
398 var pp2limit = m_state.filters.pp2limit(limit);
399 var pp2catLimit = m_state.filters.pp2catLimit();
401 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
405 if (pp2limit) params.limit = pp2limit;
406 if (maxrecs) params.maxrecs = maxrecs;
408 if (!mkws.config.use_service_proxy)
409 alert("can't narrow search by torusquery when not authenticated");
410 params.torusquery = torusquery;
413 that.info("triggerSearch(" + m_state.query + "): filters = " + m_state.filters.toJSON() + ", " +
414 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
416 m_paz.search(m_state.query, m_state.size, m_state.sort, pp2filter, undefined, params);
417 queue("searchtriggered").publish();
419 // ### not really the right place for this but it will do for now.
420 that.warn("fragment: " + that.urlFragment());
423 // fetch record details to be retrieved from the record queue
424 that.fetchDetails = function(recId) {
425 that.info("fetchDetails() requesting record '" + recId + "'");
427 that.warn("fragment: " + that.urlFragment());
431 // switching view between targets and records
432 function switchView(view) {
433 var targets = widgetNode('targets');
434 var results = widgetNode('results') || widgetNode('records');
435 var blanket = widgetNode('blanket');
436 var motd = widgetNode('motd');
440 if (targets) $(targets).show();
441 if (results) $(results).hide();
442 if (blanket) $(blanket).hide();
443 if (motd) $(motd).hide();
446 if (targets) $(targets).hide();
447 if (results) $(results).show();
448 if (blanket) $(blanket).show();
449 if (motd) $(motd).hide();
452 alert("Unknown view '" + view + "'");
455 that.switchView = switchView;
458 // detailed record drawing
459 that.showDetails = function(recId) {
460 var oldRecordId = m_state.recid;
461 m_state.recid = recId;
463 // remove current detailed view if any
464 findnode('#' + recordDetailsId(oldRecordId)).remove();
466 // if the same clicked, just hide
467 if (recId == oldRecordId) {
469 m_currentRecordData = null;
472 // request the record
473 that.info("showDetails() requesting record '" + recId + "'");
478 // Finds the node of the specified class within the current team
479 function findnode(selector, teamName) {
480 teamName = teamName || m_teamName;
482 if (teamName === 'AUTO') {
483 selector = (selector + '.mkws-team-' + teamName + ',' +
484 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
486 selector = selector + '.mkws-team-' + teamName;
489 var node = $(selector);
490 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
495 function widgetNode(type) {
496 var w = that.widget(type);
497 return w ? w.node : undefined;
500 function renderDetails(data, marker) {
501 var template = loadTemplate("details");
502 var details = template(data);
503 return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
504 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
506 that.renderDetails = renderDetails;
509 that.registerTemplate = function(name, text) {
510 if(mkws._old2new.hasOwnProperty(name)) {
511 that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
512 name = mkws._old2new[name];
514 m_templateText[name] = text;
518 function loadTemplate(name, fallbackString) {
519 if(mkws._old2new.hasOwnProperty(name)) {
520 that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
521 name = mkws._old2new[name];
524 var template = m_template[name];
525 if (template === undefined && Handlebars.compile) {
527 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
528 if (node && node.length < 1) {
529 node = $(".mkws-template-" + name);
531 if (node) source = node.html();
532 if (!source) source = m_templateText[name];
534 template = Handlebars.compile(source);
535 that.info("compiled template '" + name + "'");
538 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
539 if (template === undefined && Handlebars.templates) {
540 template = Handlebars.templates["mkws-template-" + name];
542 if (template === undefined && mkws.defaultTemplates) {
543 template = mkws.defaultTemplates[name];
546 m_template[name] = template;
550 that.info("No MKWS template for " + name);
554 that.loadTemplate = loadTemplate;
557 that.addWidget = function(w) {
558 if (m_widgets[w.type] === undefined) {
559 m_widgets[w.type] = [ w ];
561 m_widgets[w.type].push(w);
565 that.widget = function(type) {
566 var list = m_widgets[type];
570 if (list.length > 1) {
571 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
576 that.visitWidgets = function(callback) {
577 for (var type in m_widgets) {
578 var list = m_widgets[type];
579 for (var i = 0; i < list.length; i++) {
580 var res = callback(type, list[i]);
581 if (res !== undefined) {