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