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 // The following PubSub code is modified from the jQuery manual:
118 // http://api.jquery.com/jQuery.Callbacks/
121 // team.queue("eventName").subscribe(function(param1, param2 ...) { ... });
122 // team.queue("eventName").publish(arg1, arg2, ...);
127 var callbacks = $.Callbacks();
129 publish: callbacks.fire,
130 subscribe: callbacks.add,
131 unsubscribe: callbacks.remove
139 function _log(fn, s) {
141 var timestamp = (((now - m_logTime.start)/1000).toFixed(3) + " (+" +
142 ((now - m_logTime.last)/1000).toFixed(3) + ") ");
143 m_logTime.last = now;
144 fn.call(mkws.log, m_teamName + ": " + timestamp + s);
145 that.queue("log").publish(m_teamName, timestamp, s);
148 that.trace = function(x) { _log(mkws.trace, x) };
149 that.debug = function(x) { _log(mkws.debug, x) };
150 that.info = function(x) { _log(mkws.info, x) };
151 that.warn = function(x) { _log(mkws.warn, x) };
152 that.error = function(x) { _log(mkws.error, x) };
153 that.fatal = function(x) { _log(mkws.fatal, x) };
155 that.info("making new widget team");
157 // pz2.js event handlers:
164 function onBytarget(data) {
165 that.info("bytarget");
166 queue("targets").publish(data);
169 function onStat(data) {
170 queue("stat").publish(data);
171 var hitcount = parseInt(data.hits[0], 10);
172 if (!m_gotRecords && hitcount > 0) {
174 queue("firstrecords").publish(hitcount);
176 if (parseInt(data.activeclients[0], 10) === 0) {
177 that.info("complete");
178 queue("complete").publish(hitcount);
182 function onTerm(data) {
184 queue("facets").publish(data);
187 function onShow(data, teamName) {
189 m_totalRecordCount = data.merged;
190 that.info("found " + m_totalRecordCount + " records");
191 queue("pager").publish(data);
192 queue("records").publish(data);
195 function onRecord(data, args, teamName) {
197 // FIXME: record is async!!
198 clearTimeout(m_paz.recordTimer);
199 queue("record").publish(data);
200 var detRecordDiv = findnode(recordDetailsId(data.recid[0]));
201 if (detRecordDiv.length) {
202 // in case on_show was faster to redraw element
205 m_currentRecordData = data;
206 var recordDiv = findnode('.' + recordElementId(m_currentRecordData.recid[0]));
207 var html = renderDetails(m_currentRecordData);
208 $(recordDiv).append(html);
212 // create a parameters array and pass it to the pz2's constructor
213 // then register the form submit event with the pz2.search function
214 // autoInit is set to true on default
215 that.makePz2 = function() {
216 that.debug("m_queues=" + $.toJSON(m_queues));
218 "windowid": teamName,
219 "pazpar2path": mkws.pazpar2_url(),
220 "usesessions" : config.use_service_proxy ? false : true,
221 "showtime": 500, //each timer (show, stat, term, bytarget) can be specified this way
222 "termlist": config.facets.join(',')
225 params.oninit = onInit;
226 if (m_queues.targets) {
227 params.onbytarget = onBytarget;
228 that.info("setting bytarget callback");
230 if (m_queues.stat || m_queues.firstrecords || m_queues.complete) {
231 params.onstat = onStat;
232 that.info("setting stat callback");
234 if (m_queues.facets && config.facets.length) {
235 params.onterm = onTerm;
236 that.info("setting term callback");
238 if (m_queues.records) {
239 that.info("setting show callback");
240 params.onshow = onShow;
241 // Record callback is subscribed from records callback
242 that.info("setting record callback");
243 params.onrecord = onRecord;
246 m_paz = new pz2(params);
247 that.info("created main pz2 object");
251 // Used by the Records widget and onRecord()
252 function recordElementId(s) {
253 return 'mkws-rec_' + s.replace(/[^a-z0-9]/ig, '_');
255 that.recordElementId = recordElementId;
257 // Used by onRecord(), showDetails() and renderDetails()
258 function recordDetailsId(s) {
259 return 'mkws-det_' + s.replace(/[^a-z0-9]/ig, '_');
263 that.targetFiltered = function(id) {
264 return m_state.filters.targetFiltered(id);
268 that.limitTarget = function(id, name) {
269 that.info("limitTarget(id=" + id + ", name=" + name + ")");
270 m_state.filters.add(targetFilter(id, name));
271 if (m_state.query) triggerSearch();
276 that.limitQuery = function(field, value) {
277 that.info("limitQuery(field=" + field + ", value=" + value + ")");
278 m_state.filters.add(fieldFilter(field, value));
279 if (m_state.query) triggerSearch();
284 that.limitCategory = function(id) {
285 that.info("limitCategory(id=" + id + ")");
286 // Only one category filter at a time
287 m_state.filters.removeMatching(function(f) { return f.type === 'category' });
288 if (id !== '') m_state.filters.add(categoryFilter(id));
289 if (m_state.query) triggerSearch();
294 that.delimitTarget = function(id) {
295 that.info("delimitTarget(id=" + id + ")");
296 m_state.filters.removeMatching(function(f) { return f.type === 'target' });
297 if (m_state.query) triggerSearch();
302 that.delimitQuery = function(field, value) {
303 that.info("delimitQuery(field=" + field + ", value=" + value + ")");
304 m_state.filters.removeMatching(function(f) { return f.type == 'field' &&
305 field == f.field && value == f.value });
306 if (m_state.query) triggerSearch();
311 that.showPage = function(pageNum) {
312 m_state.page = pageNum;
313 m_paz.showPage(m_state.page - 1);
314 that.warn("fragment: " + that.urlFragment());
318 that.pagerNext = function() {
319 if (m_totalRecordCount - m_state.size * m_state.page > 0) {
322 that.warn("fragment: " + that.urlFragment());
327 that.pagerPrev = function() {
328 if (m_paz.showPrev() != false) {
330 that.warn("fragment: " + that.urlFragment());
335 that.reShow = function() {
337 m_paz.show(0, m_state.size, m_state.sort);
338 // ### not really the right place for this but it will do for now.
339 that.warn("fragment: " + that.urlFragment());
343 function resetPage() {
345 m_totalRecordCount = 0;
346 m_gotRecords = false;
348 that.resetPage = resetPage;
351 function newSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
352 that.info("newSearch: " + query);
354 if (config.use_service_proxy && !mkws.authenticated) {
355 alert("searching before authentication");
359 m_state.filters.removeMatching(function(f) { return f.type !== 'category' });
360 triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery);
361 switchView('records'); // In case it's configured to start off as hidden
364 that.newSearch = newSearch;
367 function triggerSearch(query, sortOrder, maxrecs, perpage, limit, targets, torusquery) {
370 // Continue to use previous query/sort-order unless new ones are specified
371 if (query) m_state.query = query;
372 if (sortOrder) m_state.sort = sortOrder;
373 if (perpage) m_state.size = perpage;
374 if (targets) m_state.filters.add(targetFilter(targets, targets));
376 var pp2filter = m_state.filters.pp2filter();
377 var pp2limit = m_state.filters.pp2limit(limit);
378 var pp2catLimit = m_state.filters.pp2catLimit();
380 pp2filter = pp2filter ? pp2filter + "," + pp2catLimit : pp2catLimit;
384 if (pp2limit) params.limit = pp2limit;
385 if (maxrecs) params.maxrecs = maxrecs;
387 if (!mkws.config.use_service_proxy)
388 alert("can't narrow search by torusquery when not authenticated");
389 params.torusquery = torusquery;
392 that.info("triggerSearch(" + m_state.query + "): filters = " + m_state.filters.toJSON() + ", " +
393 "pp2filter = " + pp2filter + ", params = " + $.toJSON(params));
395 m_paz.search(m_state.query, m_state.size, m_state.sort, pp2filter, undefined, params);
396 queue("searchtriggered").publish();
398 // ### not really the right place for this but it will do for now.
399 that.warn("fragment: " + that.urlFragment());
402 // fetch record details to be retrieved from the record queue
403 that.fetchDetails = function(recId) {
404 that.info("fetchDetails() requesting record '" + recId + "'");
406 that.warn("fragment: " + that.urlFragment());
410 // switching view between targets and records
411 function switchView(view) {
412 var targets = widgetNode('targets');
413 var results = widgetNode('results') || widgetNode('records');
414 var blanket = widgetNode('blanket');
415 var motd = widgetNode('motd');
419 if (targets) $(targets).show();
420 if (results) $(results).hide();
421 if (blanket) $(blanket).hide();
422 if (motd) $(motd).hide();
425 if (targets) $(targets).hide();
426 if (results) $(results).show();
427 if (blanket) $(blanket).show();
428 if (motd) $(motd).hide();
431 alert("Unknown view '" + view + "'");
434 that.switchView = switchView;
437 // detailed record drawing
438 that.showDetails = function(recId) {
439 var oldRecordId = m_state.recid;
440 m_state.recid = recId;
442 // remove current detailed view if any
443 findnode('#' + recordDetailsId(oldRecordId)).remove();
445 // if the same clicked, just hide
446 if (recId == oldRecordId) {
448 m_currentRecordData = null;
451 // request the record
452 that.info("showDetails() requesting record '" + recId + "'");
457 // Finds the node of the specified class within the current team
458 function findnode(selector, teamName) {
459 teamName = teamName || m_teamName;
461 if (teamName === 'AUTO') {
462 selector = (selector + '.mkws-team-' + teamName + ',' +
463 selector + ':not([class^="mkws-team"],[class*=" mkws-team"])');
465 selector = selector + '.mkws-team-' + teamName;
468 var node = $(selector);
469 //that.debug('findnode(' + selector + ') found ' + node.length + ' nodes');
474 function widgetNode(type) {
475 var w = that.widget(type);
476 return w ? w.node : undefined;
479 function renderDetails(data, marker) {
480 var template = loadTemplate("details");
481 var details = template(data);
482 return '<div class="mkws-details mkwsDetails mkwsTeam_' + m_teamName + '" ' +
483 'id="' + recordDetailsId(data.recid[0]) + '">' + details + '</div>';
485 that.renderDetails = renderDetails;
488 that.registerTemplate = function(name, text) {
489 if(mkws._old2new.hasOwnProperty(name)) {
490 that.warn("registerTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
491 name = mkws._old2new[name];
493 m_templateText[name] = text;
497 function loadTemplate(name, fallbackString) {
498 if(mkws._old2new.hasOwnProperty(name)) {
499 that.warn("loadTemplate: old widget name: " + name + " => " + mkws._old2new[name]);
500 name = mkws._old2new[name];
503 var template = m_template[name];
504 if (template === undefined && Handlebars.compile) {
506 var node = $(".mkws-template-" + name + " .mkws-team-" + that.name());
507 if (node && node.length < 1) {
508 node = $(".mkws-template-" + name);
510 if (node) source = node.html();
511 if (!source) source = m_templateText[name];
513 template = Handlebars.compile(source);
514 that.info("compiled template '" + name + "'");
517 //if (template === undefined) template = mkws_templatesbyteam[m_teamName][name];
518 if (template === undefined && Handlebars.templates) {
519 template = Handlebars.templates["mkws-template-" + name];
521 if (template === undefined && mkws.defaultTemplates) {
522 template = mkws.defaultTemplates[name];
525 m_template[name] = template;
529 that.info("No MKWS template for " + name);
533 that.loadTemplate = loadTemplate;
536 that.addWidget = function(w) {
537 if (m_widgets[w.type] === undefined) {
538 m_widgets[w.type] = [ w ];
540 m_widgets[w.type].push(w);
544 that.widget = function(type) {
545 var list = m_widgets[type];
549 if (list.length > 1) {
550 alert("widget('" + type + "') finds " + list.length + " widgets: using first");
555 that.visitWidgets = function(callback) {
556 for (var type in m_widgets) {
557 var list = m_widgets[type];
558 for (var i = 0; i < list.length; i++) {
559 var res = callback(type, list[i]);
560 if (res !== undefined) {