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