Autosearch works again for mkwsTermlists.
[mkws-moved-to-github.git] / src / mkws-widgets.js
1 // Factory function for widget objects.
2 function widget($, team, type, node) {
3     // Static register of attributes that do not contribute to config
4     var ignoreAttrs = {
5         id:1, 'class':1, style:1, name:1, action:1, type:1, size:1,
6         value:1, width:1, valign:1
7     };
8
9     var that = {
10         team: team,
11         type: type,
12         node: node,
13         config: Object.create(team.config())
14     };
15
16     function log(s) {
17         team.log(s);
18     }
19     that.log = log;
20
21     that.toString = function() {
22         return '[Widget ' + team.name() + ':' + type + ']';
23     };
24
25     for (var i = 0; i < node.attributes.length; i++) {
26         var a = node.attributes[i];
27         if (a.name === 'data-mkws-config') {
28             // Treat as a JSON fragment configuring just this widget
29             log(node + ": parsing config fragment '" + a.value + "'");
30             var data;
31             try {
32                 data = $.parseJSON(a.value);
33                 for (var key in data) {
34                     log(node + ": adding config element " + key + "='" + data[key] + "'");
35                     that.config[key] = data[key];
36                 }
37             } catch (err) {
38                 alert("Can't parse " + node + " data-mkws-config as JSON: " + a.value);
39             }
40         } else if (a.name.match (/^data-mkws-/)) {
41             var name = a.name.replace(/^data-mkws-/, '')
42             that.config[name] = a.value;
43             log(node + ": set data-mkws attribute " + name + "='" + a.value + "'");
44         } else if (!ignoreAttrs[a.name]) {
45             that.config[a.name] = a.value;
46             log(node + ": set regular attribute " + a.name + "='" + a.value + "'");
47         }
48     }
49
50     var fn = mkws.promotionFunction(type);
51     if (fn) {
52         fn.call(that);
53         log("made " + type + " widget(node=" + node + ")");
54     } else {
55         log("made UNPROMOTED widget(type=" + type + ", node=" + node + ")");
56     }
57
58     return that;
59 }
60
61
62 // Utility function for use by all widgets that can invoke autosearch.
63 widget.maybeAutosearch = function(widget) {
64     var query = widget.config.autosearch;
65     if (query) {
66         if (query.match(/^!param!/)) {
67             var param = query.replace(/^!param!/, '');
68             query = mkws.getParameterByName(param);
69             widget.log("obtained query '" + query + "' from param '" + param + "'");
70             if (!query) {
71                 alert("This page has a MasterKey widget that needs a query specified by the '" + param + "' parameter");
72             }
73         } else if (query.match(/^!path!/)) {
74             var index = query.replace(/^!path!/, '');
75             var path = window.location.pathname.split('/');
76             query = path[path.length - index];
77             widget.log("obtained query '" + query + "' from path-component '" + index + "'");
78             if (!query) {
79                 alert("This page has a MasterKey widget that needs a query specified by the path-component " + index);
80             }
81         }
82
83         widget.team.queue("ready").subscribe(function() {
84             var sortOrder = widget.config.sort;
85             var perpage = widget.config.perpage;
86             var limit = widget.config.limit;
87             var targets = widget.config.targets;
88             var targetfilter = widget.config.targetfilter;
89             var s = "running auto search: '" + query + "'";
90             if (sortOrder) s += " sorted by '" + sortOrder + "'";
91             if (perpage) s += " with " + perpage + " per page";
92             if (limit) s += " limited by '" + limit + "'";
93             if (targets) s += " in targets '" + targets + "'";
94             if (targetfilter) s += " constrained by targetfilter '" + targetfilter + "'";
95             widget.log(s);
96
97             widget.team.newSearch(query, sortOrder, perpage, limit, targets, targetfilter);
98         });
99     }
100 };
101
102
103 // Functions follow for promoting the regular widget object into
104 // widgets of specific types. These could be moved into their own
105 // source files.
106
107
108 mkws.registerWidgetType('Targets', function() {
109     var that = this;
110     var M = mkws.M;
111
112     this.team.queue("targets").subscribe(function(data) {
113         var table ='<table><thead><tr>' +
114             '<td>' + M('Target ID') + '</td>' +
115             '<td>' + M('Hits') + '</td>' +
116             '<td>' + M('Diags') + '</td>' +
117             '<td>' + M('Records') + '</td>' +
118             '<td>' + M('State') + '</td>' +
119             '</tr></thead><tbody>';
120
121         for (var i = 0; i < data.length; i++) {
122             table += "<tr><td>" + data[i].id +
123                 "</td><td>" + data[i].hits +
124                 "</td><td>" + data[i].diagnostic +
125                 "</td><td>" + data[i].records +
126                 "</td><td>" + data[i].state + "</td></tr>";
127         }
128
129         table += '</tbody></table>';
130         var subnode = $(that.node).children('.mkwsBytarget');
131         subnode.html(table);
132     });
133 });
134
135
136 mkws.registerWidgetType('Stat', function() {
137     var that = this;
138     var M = mkws.M;
139
140     this.team.queue("stat").subscribe(function(data) {
141         if (that.node.length === 0)  alert("huh?!");
142
143         $(that.node).html('<span class="head">' + M('Status info') + '</span>' +
144             ' -- ' +
145             '<span class="clients">' + M('Active clients') + ': ' + data.activeclients + '/' + data.clients + '</span>' +
146             ' -- ' +
147             '<span class="records">' + M('Retrieved records') + ': ' + data.records + '/' + data.hits + '</span>');
148     });
149 });
150
151
152 mkws.registerWidgetType('Termlists', function() {
153     var that = this;
154     var M = mkws.M;
155
156     this.team.queue("termlists").subscribe(function(data) {
157         if (!that.node) {
158             alert("termlists event when there are no termlists");
159             return;
160         }
161
162         // no facets: this should never happen
163         var facets = that.config.facets;
164         if (!facets || facets.length == 0) {
165             alert("onTerm called even though we have no facets: " + $.toJSON(data));
166             $(that.node).hide();
167             return;
168         }
169
170         // display if we first got results
171         $(that.node).show();
172
173         var acc = [];
174         acc.push('<div class="title">' + M('Termlists') + '</div>');
175
176         for (var i = 0; i < facets.length; i++) {
177             if (facets[i] == "xtargets") {
178                 addSingleFacet(acc, "Sources",  data.xtargets, 16, null);
179             } else if (facets[i] == "subject") {
180                 addSingleFacet(acc, "Subjects", data.subject,  10, "subject");
181             } else if (facets[i] == "author") {
182                 addSingleFacet(acc, "Authors",  data.author,   10, "author");
183             } else {
184                 alert("bad facet configuration: '" + facets[i] + "'");
185             }
186         }
187
188         $(that.node).html(acc.join(''));
189
190         function addSingleFacet(acc, caption, data, max, pzIndex) {
191             var teamName = that.team.name();
192             acc.push('<div class="facet mkwsFacet' + caption + ' mkwsTeam_' + teamName + '">');
193             acc.push('<div class="termtitle">' + M(caption) + '</div>');
194             for (var i = 0; i < data.length && i < max; i++) {
195                 acc.push('<div class="term">');
196                 acc.push('<a href="#" ');
197                 var action = '';
198                 if (!pzIndex) {
199                     // Special case: target selection
200                     acc.push('target_id='+data[i].id+' ');
201                     if (!that.team.targetFiltered(data[i].id)) {
202                         action = 'mkws.limitTarget(\'' + teamName + '\', this.getAttribute(\'target_id\'),this.firstChild.nodeValue)';
203                     }
204                 } else {
205                     action = 'mkws.limitQuery(\'' + teamName + '\', \'' + pzIndex + '\', this.firstChild.nodeValue)';
206                 }
207                 acc.push('onclick="' + action + ';return false;">' + data[i].name + '</a>'
208                          + ' <span>' + data[i].freq + '</span>');
209                 acc.push('</div>');
210             }
211             acc.push('</div>');
212         }
213     });
214
215     widget.maybeAutosearch(that);
216 });
217
218
219 mkws.registerWidgetType('Pager', function() {
220     var that = this;
221     var M = mkws.M;
222
223     this.team.queue("pager").subscribe(function(data) {
224         $(that.node).html(drawPager(data))
225
226         function drawPager(data) {
227             var teamName = that.team.name();
228             var s = '<div style="float: right">' + M('Displaying') + ': '
229                 + (data.start + 1) + ' ' + M('to') + ' ' + (data.start + data.num) +
230                 ' ' + M('of') + ' ' + data.merged + ' (' + M('found') + ': '
231                 + data.total + ')</div>';
232
233             //client indexes pages from 1 but pz2 from 0
234             var onsides = 6;
235             var pages = Math.ceil(that.team.totalRecordCount() / that.team.perpage());
236             var currentPage = that.team.currentPage();
237
238             var firstClkbl = (currentPage - onsides > 0)
239                 ? currentPage - onsides
240                 : 1;
241
242             var lastClkbl = firstClkbl + 2*onsides < pages
243                 ? firstClkbl + 2*onsides
244                 : pages;
245
246             var prev = '<span class="mkwsPrev">&#60;&#60; ' + M('Prev') + '</span><b> | </b>';
247             if (currentPage > 1)
248                 prev = '<a href="#" class="mkwsPrev" onclick="mkws.pagerPrev(\'' + teamName + '\');">'
249                 +'&#60;&#60; ' + M('Prev') + '</a><b> | </b>';
250
251             var middle = '';
252             for(var i = firstClkbl; i <= lastClkbl; i++) {
253                 var numLabel = i;
254                 if(i == currentPage)
255                     numLabel = '<b>' + i + '</b>';
256
257                 middle += '<a href="#" onclick="mkws.showPage(\'' + teamName + '\', ' + i + ')"> '
258                     + numLabel + ' </a>';
259             }
260
261             var next = '<b> | </b><span class="mkwsNext">' + M('Next') + ' &#62;&#62;</span>';
262             if (pages - currentPage > 0)
263                 next = '<b> | </b><a href="#" class="mkwsNext" onclick="mkws.pagerNext(\'' + teamName + '\')">'
264                 + M('Next') + ' &#62;&#62;</a>';
265
266             var predots = '';
267             if (firstClkbl > 1)
268                 predots = '...';
269
270             var postdots = '';
271             if (lastClkbl < pages)
272                 postdots = '...';
273
274             s += '<div style="float: clear">'
275                 + prev + predots + middle + postdots + next + '</div>';
276
277             return s;
278         }
279     });
280 });
281
282
283 mkws.registerWidgetType('Records', function() {
284     var that = this;
285     var team = this.team;
286
287     this.team.queue("records").subscribe(function(data) {
288         var html = [];
289         for (var i = 0; i < data.hits.length; i++) {
290             var hit = data.hits[i];
291             var divId = team.recordElementId(hit.recid[0]);
292             html.push('<div class="record mkwsTeam_' + team.name() + ' ' + divId + '">', renderSummary(hit), '</div>');
293             // ### At some point, we may be able to move the
294             // m_currentRecordId and m_currentRecordData members
295             // from the team object into this widget.
296             if (hit.recid == team.currentRecordId()) {
297                 if (team.currentRecordData())
298                     html.push(team.renderDetails(team.currentRecordData()));
299             }
300         }
301         $(that.node).html(html.join(''));
302
303         function renderSummary(hit) {
304             var template = team.loadTemplate("Summary");
305             hit._id = team.recordElementId(hit.recid[0]);
306             hit._onclick = "mkws.showDetails('" + team.name() + "', '" + hit.recid[0] + "');return false;"
307             return template(hit);
308         }
309     });
310
311     widget.maybeAutosearch(that);
312 });
313
314
315 mkws.registerWidgetType('Navi', function() {
316     var that = this;
317     var teamName = this.team.name();
318     var M = mkws.M;
319
320     this.team.queue("navi").subscribe(function() {
321         var filters = that.team.filters();
322         var text = "";
323
324         for (var i in filters) {
325             if (text) {
326                 text += " | ";
327             }
328             var filter = filters[i];
329             if (filter.id) {
330                 text += M('source') + ': <a class="crossout" href="#" onclick="mkws.delimitTarget(\'' + teamName +
331                     "', '" + filter.id + "'" + ');return false;">' + filter.name + '</a>';
332             } else {
333                 text += M(filter.field) + ': <a class="crossout" href="#" onclick="mkws.delimitQuery(\'' + teamName +
334                     "', '" + filter.field + "', '" + filter.value + "'" +
335                     ');return false;">' + filter.value + '</a>';
336             }
337         }
338
339         $(that.node).html(text);
340     });
341 });
342
343
344 // It seems this and the Perpage widget doen't need to subscribe to
345 // anything, since they produce events rather than consuming them.
346 //
347 mkws.registerWidgetType('Sort', function() {
348     var that = this;
349
350     $(this.node).change(function() {
351         that.team.set_sortOrder($(that.node).val());
352         if (that.team.submitted()) {
353             that.team.resetPage();
354             that.team.reShow();
355         }
356         return false;
357     });
358 });
359
360
361 mkws.registerWidgetType('Perpage', function() {
362     var that = this;
363
364     $(this.node).change(function() {
365         that.team.set_perpage($(that.node).val());
366         if (that.team.submitted()) {
367             that.team.resetPage();
368             that.team.reShow();
369         }
370         return false;
371     });
372 });