Rename maybeAutosearch function to autosearch.
[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.autosearch = 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 maxrecs = widget.config.maxrecs;
86             var perpage = widget.config.perpage;
87             var limit = widget.config.limit;
88             var targets = widget.config.targets;
89             var targetfilter = widget.config.targetfilter;
90             var s = "running auto search: '" + query + "'";
91             if (sortOrder) s += " sorted by '" + sortOrder + "'";
92             if (maxrecs) s += " restricted to " + maxrecs + " records";
93             if (perpage) s += " with " + perpage + " per page";
94             if (limit) s += " limited by '" + limit + "'";
95             if (targets) s += " in targets '" + targets + "'";
96             if (targetfilter) s += " constrained by targetfilter '" + targetfilter + "'";
97             widget.log(s);
98
99             widget.team.newSearch(query, sortOrder, maxrecs, perpage, limit, targets, targetfilter);
100         });
101     }
102 };
103
104
105 // Functions follow for promoting the regular widget object into
106 // widgets of specific types. These could be moved into their own
107 // source files.
108
109
110 mkws.registerWidgetType('Targets', function() {
111     var that = this;
112     var M = mkws.M;
113
114     this.team.queue("targets").subscribe(function(data) {
115         var table ='<table><thead><tr>' +
116             '<td>' + M('Target ID') + '</td>' +
117             '<td>' + M('Hits') + '</td>' +
118             '<td>' + M('Diags') + '</td>' +
119             '<td>' + M('Records') + '</td>' +
120             '<td>' + M('State') + '</td>' +
121             '</tr></thead><tbody>';
122
123         for (var i = 0; i < data.length; i++) {
124             table += "<tr><td>" + data[i].id +
125                 "</td><td>" + data[i].hits +
126                 "</td><td>" + data[i].diagnostic +
127                 "</td><td>" + data[i].records +
128                 "</td><td>" + data[i].state + "</td></tr>";
129         }
130
131         table += '</tbody></table>';
132         var subnode = $(that.node).children('.mkwsBytarget');
133         subnode.html(table);
134     });
135 });
136
137
138 mkws.registerWidgetType('Stat', function() {
139     var that = this;
140     var M = mkws.M;
141
142     this.team.queue("stat").subscribe(function(data) {
143         if (that.node.length === 0)  alert("huh?!");
144
145         $(that.node).html('<span class="head">' + M('Status info') + '</span>' +
146             ' -- ' +
147             '<span class="clients">' + M('Active clients') + ': ' + data.activeclients + '/' + data.clients + '</span>' +
148             ' -- ' +
149             '<span class="records">' + M('Retrieved records') + ': ' + data.records + '/' + data.hits + '</span>');
150     });
151 });
152
153
154 mkws.registerWidgetType('Termlists', function() {
155     var that = this;
156     var M = mkws.M;
157
158     this.team.queue("termlists").subscribe(function(data) {
159         if (!that.node) {
160             alert("termlists event when there are no termlists");
161             return;
162         }
163
164         // no facets: this should never happen
165         var facets = that.config.facets;
166         if (!facets || facets.length == 0) {
167             alert("onTerm called even though we have no facets: " + $.toJSON(data));
168             $(that.node).hide();
169             return;
170         }
171
172         // display if we first got results
173         $(that.node).show();
174
175         var acc = [];
176         acc.push('<div class="title">' + M('Termlists') + '</div>');
177
178         for (var i = 0; i < facets.length; i++) {
179             if (facets[i] == "xtargets") {
180                 addSingleFacet(acc, "Sources",  data.xtargets, 16, null);
181             } else if (facets[i] == "subject") {
182                 addSingleFacet(acc, "Subjects", data.subject,  10, "subject");
183             } else if (facets[i] == "author") {
184                 addSingleFacet(acc, "Authors",  data.author,   10, "author");
185             } else {
186                 alert("bad facet configuration: '" + facets[i] + "'");
187             }
188         }
189
190         $(that.node).html(acc.join(''));
191
192         function addSingleFacet(acc, caption, data, max, pzIndex) {
193             var teamName = that.team.name();
194             acc.push('<div class="facet mkwsFacet' + caption + ' mkwsTeam_' + teamName + '">');
195             acc.push('<div class="termtitle">' + M(caption) + '</div>');
196             for (var i = 0; i < data.length && i < max; i++) {
197                 acc.push('<div class="term">');
198                 acc.push('<a href="#" ');
199                 var action = '';
200                 if (!pzIndex) {
201                     // Special case: target selection
202                     acc.push('target_id='+data[i].id+' ');
203                     if (!that.team.targetFiltered(data[i].id)) {
204                         action = 'mkws.limitTarget(\'' + teamName + '\', this.getAttribute(\'target_id\'),this.firstChild.nodeValue)';
205                     }
206                 } else {
207                     action = 'mkws.limitQuery(\'' + teamName + '\', \'' + pzIndex + '\', this.firstChild.nodeValue)';
208                 }
209                 acc.push('onclick="' + action + ';return false;">' + data[i].name + '</a>'
210                          + ' <span>' + data[i].freq + '</span>');
211                 acc.push('</div>');
212             }
213             acc.push('</div>');
214         }
215     });
216
217     widget.autosearch(that);
218 });
219
220
221 mkws.registerWidgetType('Pager', function() {
222     var that = this;
223     var M = mkws.M;
224
225     this.team.queue("pager").subscribe(function(data) {
226         $(that.node).html(drawPager(data))
227
228         function drawPager(data) {
229             var teamName = that.team.name();
230             var s = '<div style="float: right">' + M('Displaying') + ': '
231                 + (data.start + 1) + ' ' + M('to') + ' ' + (data.start + data.num) +
232                 ' ' + M('of') + ' ' + data.merged + ' (' + M('found') + ': '
233                 + data.total + ')</div>';
234
235             //client indexes pages from 1 but pz2 from 0
236             var onsides = 6;
237             var pages = Math.ceil(that.team.totalRecordCount() / that.team.perpage());
238             var currentPage = that.team.currentPage();
239
240             var firstClkbl = (currentPage - onsides > 0)
241                 ? currentPage - onsides
242                 : 1;
243
244             var lastClkbl = firstClkbl + 2*onsides < pages
245                 ? firstClkbl + 2*onsides
246                 : pages;
247
248             var prev = '<span class="mkwsPrev">&#60;&#60; ' + M('Prev') + '</span><b> | </b>';
249             if (currentPage > 1)
250                 prev = '<a href="#" class="mkwsPrev" onclick="mkws.pagerPrev(\'' + teamName + '\');">'
251                 +'&#60;&#60; ' + M('Prev') + '</a><b> | </b>';
252
253             var middle = '';
254             for(var i = firstClkbl; i <= lastClkbl; i++) {
255                 var numLabel = i;
256                 if(i == currentPage)
257                     numLabel = '<b>' + i + '</b>';
258
259                 middle += '<a href="#" onclick="mkws.showPage(\'' + teamName + '\', ' + i + ')"> '
260                     + numLabel + ' </a>';
261             }
262
263             var next = '<b> | </b><span class="mkwsNext">' + M('Next') + ' &#62;&#62;</span>';
264             if (pages - currentPage > 0)
265                 next = '<b> | </b><a href="#" class="mkwsNext" onclick="mkws.pagerNext(\'' + teamName + '\')">'
266                 + M('Next') + ' &#62;&#62;</a>';
267
268             var predots = '';
269             if (firstClkbl > 1)
270                 predots = '...';
271
272             var postdots = '';
273             if (lastClkbl < pages)
274                 postdots = '...';
275
276             s += '<div style="float: clear">'
277                 + prev + predots + middle + postdots + next + '</div>';
278
279             return s;
280         }
281     });
282 });
283
284
285 mkws.registerWidgetType('Records', function() {
286     var that = this;
287     var team = this.team;
288
289     this.team.queue("records").subscribe(function(data) {
290         var html = [];
291         for (var i = 0; i < data.hits.length; i++) {
292             var hit = data.hits[i];
293             var divId = team.recordElementId(hit.recid[0]);
294             html.push('<div class="record mkwsTeam_' + team.name() + ' ' + divId + '">', renderSummary(hit), '</div>');
295             // ### At some point, we may be able to move the
296             // m_currentRecordId and m_currentRecordData members
297             // from the team object into this widget.
298             if (hit.recid == team.currentRecordId()) {
299                 if (team.currentRecordData())
300                     html.push(team.renderDetails(team.currentRecordData()));
301             }
302         }
303         $(that.node).html(html.join(''));
304
305         function renderSummary(hit) {
306             var template = team.loadTemplate("Summary");
307             hit._id = team.recordElementId(hit.recid[0]);
308             hit._onclick = "mkws.showDetails('" + team.name() + "', '" + hit.recid[0] + "');return false;"
309             return template(hit);
310         }
311     });
312
313     widget.autosearch(that);
314 });
315
316
317 mkws.registerWidgetType('Navi', function() {
318     var that = this;
319     var teamName = this.team.name();
320     var M = mkws.M;
321
322     this.team.queue("navi").subscribe(function() {
323         var filters = that.team.filters();
324         var text = "";
325
326         for (var i in filters) {
327             if (text) {
328                 text += " | ";
329             }
330             var filter = filters[i];
331             if (filter.id) {
332                 text += M('source') + ': <a class="crossout" href="#" onclick="mkws.delimitTarget(\'' + teamName +
333                     "', '" + filter.id + "'" + ');return false;">' + filter.name + '</a>';
334             } else {
335                 text += M(filter.field) + ': <a class="crossout" href="#" onclick="mkws.delimitQuery(\'' + teamName +
336                     "', '" + filter.field + "', '" + filter.value + "'" +
337                     ');return false;">' + filter.value + '</a>';
338             }
339         }
340
341         $(that.node).html(text);
342     });
343 });
344
345
346 // It seems this and the Perpage widget doen't need to subscribe to
347 // anything, since they produce events rather than consuming them.
348 //
349 mkws.registerWidgetType('Sort', function() {
350     var that = this;
351
352     $(this.node).change(function() {
353         that.team.set_sortOrder($(that.node).val());
354         if (that.team.submitted()) {
355             that.team.resetPage();
356             that.team.reShow();
357         }
358         return false;
359     });
360 });
361
362
363 mkws.registerWidgetType('Perpage', function() {
364     var that = this;
365
366     $(this.node).change(function() {
367         that.team.set_perpage($(that.node).val());
368         if (that.team.submitted()) {
369             that.team.resetPage();
370             that.team.reShow();
371         }
372         return false;
373     });
374 });