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()) {
132 } else if (key === 'size') {
133 that.set_perpage(val);
134 if (that.submitted()) {
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]);
148 // The following PubSub code is modified from the jQuery manual:
149 // http://api.jquery.com/jQuery.Callbacks/
152 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
153 // team.queue("eventName").publish(arg1, arg2, ...);
158 var callbacks = $.Callbacks();
160 publish: callbacks.fire,
161 subscribe: callbacks.add,
162 unsubscribe: callbacks.remove
170 function _log(fn, s) {
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);
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) };
186 that.info("making new widget team");
188 // pz2.js event handlers:
195 function onBytarget(data) {
196 that.info("bytarget");
197 queue("targets").publish(data);
200 function onStat(data) {
201 queue("stat").publish(data);
202 var hitcount = parseInt(data.hits[0], 10);
203 if (!m_gotRecords && hitcount > 0) {
205 queue("firstrecords").publish(hitcount);
207 if (parseInt(data.activeclients[0], 10) === 0) {
208 that.info("complete");
209 queue("complete").publish(hitcount);
213 function onTerm(data) {
215 queue("facets").publish(data);
218 function onShow(data, teamName) {
220 m_totalRecordCount = data.merged;
221 that.info("found " + m_totalRecordCount + " records");
222 queue("pager").publish(data);
223 queue("records").publish(data);
226 function onRecord(data, args, teamName) {
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
236 m_currentRecordData = data;
237 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
238 var html = renderDetails(m_currentRecordData);
239 $(recordDiv).append(html);
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));
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(',')
256 params.oninit = onInit;
257 if (m_queues.targets) {
258 params.onbytarget = onBytarget;
259 that.info("setting bytarget callback");
261 if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
262 params.onstat = onStat;
263 that.info("setting stat callback");
265 if (m_queues.facets && config.facets.length) {
266 params.onterm = onTerm;
267 that.info("setting term callback");
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;
277 m_paz = new pz2(params);
278 that.info("created main pz2 object");
282 // Used by the Records widget and onRecord()
283 function recordElementId(s) {
284 return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
286 that.recordElementId = recordElementId;
288 // Used by onRecord(), showDetails() and renderDetails()
289 function recordDetailsId(s) {
290 return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
294 that.targetFiltered = function(id) {
295 return m_state.filters.targetFiltered(id);
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();
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();
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();
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();
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();
342 that.showPage = function(pageNum) {
343 m_state.page = pageNum;
344 m_paz.showPage(m_state.page - 1);
345 that.warn("fragment: " + that.urlFragment());
349 that.pagerNext = function() {
350 if (m_totalRecordCount - m_state.size * m_state.page > 0) {
353 that.warn("fragment: " + that.urlFragment());
358 that.pagerPrev = function() {
359 if (m_paz.showPrev() != false) {
361 that.warn("fragment: " + that.urlFragment());
366 that.reShow = function() {
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());
374 function resetPage() {
376 m_totalRecordCount = 0;
377 m_gotRecords = false;
379 that.resetPage = resetPage;
382 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
383 that.info("newSearch: " + query);
385 if (config.use_service_proxy && !mkws.authenticated) {
386 alert("searching before authentication");
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
395 that.newSearch = newSearch;
398 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
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));
407 var pp2filter = m_state.filters.pp2filter();
408 var pp2limit = m_state.filters.pp2limit(limit);
409 var pp2catLimit = m_state.filters.pp2catLimit();
411 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
415 if (pp2limit) params.limit = pp2limit;
416 if (maxrecs) params.maxrecs = maxrecs;
418 if (!mkws.config.use_service_proxy)
419 alert("can't narrow search by torusquery when not authenticated");
420 params.torusquery = torusquery;
423 that.info("triggerSearch(" + m_state.query + "): filters = " + m_state.filters.toJSON() + ", " +
424 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
426 m_paz.search(m_state.query, m_state.size, m_state.sort, pp2filter, undefined, params);
427 queue("searchtriggered").publish();
429 // ### not really the right place for this but it will do for now.
430 that.warn("fragment: " + that.urlFragment());
433 // fetch record details to be retrieved from the record queue
434 that.fetchDetails = function(recId) {
435 that.info("fetchDetails() requesting record '" + recId + "'");
437 that.warn("fragment: " + that.urlFragment());
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');
450 if (targets) $(targets).show();
451 if (results) $(results).hide();
452 if (blanket) $(blanket).hide();
453 if (motd) $(motd).hide();
456 if (targets) $(targets).hide();
457 if (results) $(results).show();
458 if (blanket) $(blanket).show();
459 if (motd) $(motd).hide();
462 alert("Unknown view '" + view + "'");
465 that.switchView = switchView;
468 // detailed record drawing
469 that.showDetails = function(recId) {
470 var oldRecordId = m_state.recid;
471 m_state.recid = recId;
473 // remove current detailed view if any
474 findnode('#' + recordDetailsId(oldRecordId)).remove();
476 // if the same clicked, just hide
477 if (recId == oldRecordId) {
479 m_currentRecordData = null;
482 // request the record
483 that.info("showDetails() requesting record '" + recId + "'");
488 // Finds the node of the specified class within the current team
489 function findnode(selector, teamName) {
490 teamName = teamName || m_teamName;
492 if (teamName === 'AUTO') {
493 selector = (selector + '.mkws-team-' + teamName + ',' +
494 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
496 selector = selector + '.mkws-team-' + teamName;
499 var node = $(selector);
500 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
505 function widgetNode(type) {
506 var w = that.widget(type);
507 return w ? w.node : undefined;
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>';
516 that.renderDetails = renderDetails;
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];
524 m_templateText[name] = text;
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];
534 var template = m_template[name];
535 if (template === undefined && Handlebars.compile) {
537 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
538 if (node && node.length < 1) {
539 node = $(".mkws-template-" + name);
541 if (node) source = node.html();
542 if (!source) source = m_templateText[name];
544 template = Handlebars.compile(source);
545 that.info("compiled template '" + name + "'");
548 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
549 if (template === undefined && Handlebars.templates) {
550 template = Handlebars.templates["mkws-template-" + name];
552 if (template === undefined && mkws.defaultTemplates) {
553 template = mkws.defaultTemplates[name];
556 m_template[name] = template;
560 that.info("No MKWS template for " + name);
564 that.loadTemplate = loadTemplate;
567 that.addWidget = function(w) {
568 if (m_widgets[w.type] === undefined) {
569 m_widgets[w.type] = [ w ];
571 m_widgets[w.type].push(w);
575 that.widget = function(type) {
576 var list = m_widgets[type];
580 if (list.length > 1) {
581 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
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) {