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