Reorder.
[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 // This is a utility function that can be used by all widgets that can
63 // invoke an autosearch. It properly belongs to the widget superclass,
64 // but since there are no classes in JavaScript there's no scope for
65 // it to live in, hence its being put into the mkws object.
66
67 mkws.maybeAutosearch = function(widget) {
68     var query = widget.config.autosearch;
69     if (query) {
70         if (query.match(/^!param!/)) {
71             var param = query.replace(/^!param!/, '');
72             query = mkws.getParameterByName(param);
73             widget.log("obtained query '" + query + "' from param '" + param + "'");
74             if (!query) {
75                 alert("This page has a MasterKey widget that needs a query specified by the '" + param + "' parameter");
76             }
77         } else if (query.match(/^!path!/)) {
78             var index = query.replace(/^!path!/, '');
79             var path = window.location.pathname.split('/');
80             query = path[path.length - index];
81             widget.log("obtained query '" + query + "' from path-component '" + index + "'");
82             if (!query) {
83                 alert("This page has a MasterKey widget that needs a query specified by the path-component " + index);
84             }
85         }
86
87         widget.team.queue("ready").subscribe(function() {
88             var sortOrder = widget.config.sort;
89             var perpage = widget.config.perpage;
90             var limit = widget.config.limit;
91             var targets = widget.config.targets;
92             var targetfilter = widget.config.targetfilter;
93             var s = "running auto search: '" + query + "'";
94             if (sortOrder) s += " sorted by '" + sortOrder + "'";
95             if (perpage) s += " with " + perpage + " per page";
96             if (limit) s += " limited by '" + limit + "'";
97             if (targets) s += " in targets '" + targets + "'";
98             if (targetfilter) s += " constrained by targetfilter '" + targetfilter + "'";
99             widget.log(s);
100
101             widget.team.newSearch(query, sortOrder, perpage, limit, targets, targetfilter);
102         });
103     }
104 };
105
106
107 // Functions follow for promoting the regular widget object into
108 // widgets of specific types. These could be moved into their own
109 // source files.
110
111
112 mkws.registerWidgetType('Targets', function() {
113     var that = this;
114     var M = mkws.M;
115
116     this.team.queue("targets").subscribe(function(data) {
117         var table ='<table><thead><tr>' +
118             '<td>' + M('Target ID') + '</td>' +
119             '<td>' + M('Hits') + '</td>' +
120             '<td>' + M('Diags') + '</td>' +
121             '<td>' + M('Records') + '</td>' +
122             '<td>' + M('State') + '</td>' +
123             '</tr></thead><tbody>';
124
125         for (var i = 0; i < data.length; i++) {
126             table += "<tr><td>" + data[i].id +
127                 "</td><td>" + data[i].hits +
128                 "</td><td>" + data[i].diagnostic +
129                 "</td><td>" + data[i].records +
130                 "</td><td>" + data[i].state + "</td></tr>";
131         }
132
133         table += '</tbody></table>';
134         var subnode = $(that.node).children('.mkwsBytarget');
135         subnode.html(table);
136     });
137 });
138
139
140 mkws.registerWidgetType('Stat', function() {
141     var that = this;
142     var M = mkws.M;
143
144     this.team.queue("stat").subscribe(function(data) {
145         if (that.node.length === 0)  alert("huh?!");
146
147         $(that.node).html('<span class="head">' + M('Status info') + '</span>' +
148             ' -- ' +
149             '<span class="clients">' + M('Active clients') + ': ' + data.activeclients + '/' + data.clients + '</span>' +
150             ' -- ' +
151             '<span class="records">' + M('Retrieved records') + ': ' + data.records + '/' + data.hits + '</span>');
152     });
153 });
154
155
156 mkws.registerWidgetType('Termlists', function() {
157     var that = this;
158     var M = mkws.M;
159
160     this.team.queue("termlists").subscribe(function(data) {
161         if (!that.node) {
162             alert("termlists event when there are no termlists");
163             return;
164         }
165
166         // no facets: this should never happen
167         var facets = that.config.facets;
168         if (!facets || facets.length == 0) {
169             alert("onTerm called even though we have no facets: " + $.toJSON(data));
170             $(that.node).hide();
171             return;
172         }
173
174         // display if we first got results
175         $(that.node).show();
176
177         var acc = [];
178         acc.push('<div class="title">' + M('Termlists') + '</div>');
179
180         for (var i = 0; i < facets.length; i++) {
181             if (facets[i] == "xtargets") {
182                 addSingleFacet(acc, "Sources",  data.xtargets, 16, null);
183             } else if (facets[i] == "subject") {
184                 addSingleFacet(acc, "Subjects", data.subject,  10, "subject");
185             } else if (facets[i] == "author") {
186                 addSingleFacet(acc, "Authors",  data.author,   10, "author");
187             } else {
188                 alert("bad facet configuration: '" + facets[i] + "'");
189             }
190         }
191
192         $(that.node).html(acc.join(''));
193
194         function addSingleFacet(acc, caption, data, max, pzIndex) {
195             var teamName = that.team.name();
196             acc.push('<div class="facet mkwsFacet' + caption + ' mkwsTeam_' + teamName + '">');
197             acc.push('<div class="termtitle">' + M(caption) + '</div>');
198             for (var i = 0; i < data.length && i < max; i++) {
199                 acc.push('<div class="term">');
200                 acc.push('<a href="#" ');
201                 var action = '';
202                 if (!pzIndex) {
203                     // Special case: target selection
204                     acc.push('target_id='+data[i].id+' ');
205                     if (!that.team.targetFiltered(data[i].id)) {
206                         action = 'mkws.limitTarget(\'' + teamName + '\', this.getAttribute(\'target_id\'),this.firstChild.nodeValue)';
207                     }
208                 } else {
209                     action = 'mkws.limitQuery(\'' + teamName + '\', \'' + pzIndex + '\', this.firstChild.nodeValue)';
210                 }
211                 acc.push('onclick="' + action + ';return false;">' + data[i].name + '</a>'
212                          + ' <span>' + data[i].freq + '</span>');
213                 acc.push('</div>');
214             }
215             acc.push('</div>');
216         }
217     });
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     mkws.maybeAutosearch(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 });