Add widget.value function
[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: mkws.objectInheritingFrom(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     that.value = function() {
26         return node.value;
27     }
28
29     for (var i = 0; i < node.attributes.length; i++) {
30         var a = node.attributes[i];
31         if (a.name === 'data-mkws-config') {
32             // Treat as a JSON fragment configuring just this widget
33             log(node + ": parsing config fragment '" + a.value + "'");
34             var data;
35             try {
36                 data = $.parseJSON(a.value);
37                 for (var key in data) {
38                     log(node + ": adding config element " + key + "='" + data[key] + "'");
39                     that.config[key] = data[key];
40                 }
41             } catch (err) {
42                 alert("Can't parse " + node + " data-mkws-config as JSON: " + a.value);
43             }
44         } else if (a.name.match (/^data-mkws-/)) {
45             var name = a.name.replace(/^data-mkws-/, '')
46             that.config[name] = a.value;
47             log(node + ": set data-mkws attribute " + name + "='" + a.value + "'");
48         } else if (!ignoreAttrs[a.name]) {
49             that.config[a.name] = a.value;
50             log(node + ": set regular attribute " + a.name + "='" + a.value + "'");
51         }
52     }
53
54     var fn = mkws.promotionFunction(type);
55     if (fn) {
56         fn.call(that);
57         log("made " + type + " widget(node=" + node + ")");
58     } else {
59         log("made UNPROMOTED widget(type=" + type + ", node=" + node + ")");
60     }
61
62     return that;
63 }
64
65
66 // Utility function for use by all widgets that can invoke autosearch.
67 widget.autosearch = function(widget) {
68     widget.team.queue("ready").subscribe(function() {
69         var query = widget.config.autosearch;
70         if (query) {
71             if (query.match(/^!param!/)) {
72                 var param = query.replace(/^!param!/, '');
73                 query = mkws.getParameterByName(param);
74                 widget.log("obtained query '" + query + "' from param '" + param + "'");
75                 if (!query) {
76                     alert("This page has a MasterKey widget that needs a query specified by the '" + param + "' parameter");
77                 }
78             } else if (query.match(/^!path!/)) {
79                 var index = query.replace(/^!path!/, '');
80                 var path = window.location.pathname.split('/');
81                 query = path[path.length - index];
82                 widget.log("obtained query '" + query + "' from path-component '" + index + "'");
83                 if (!query) {
84                     alert("This page has a MasterKey widget that needs a query specified by the path-component " + index);
85                 }
86             }
87
88             var sortOrder = widget.config.sort;
89             var maxrecs = widget.config.maxrecs;
90             var perpage = widget.config.perpage;
91             var limit = widget.config.limit;
92             var targets = widget.config.targets;
93             var targetfilter = widget.config.targetfilter;
94             var target = widget.config.target;
95             if (target) targetfilter = 'udb=="' + target + '"';
96
97             var s = "running auto search: '" + query + "'";
98             if (sortOrder) s += " sorted by '" + sortOrder + "'";
99             if (maxrecs) s += " restricted to " + maxrecs + " records";
100             if (perpage) s += " with " + perpage + " per page";
101             if (limit) s += " limited by '" + limit + "'";
102             if (targets) s += " in targets '" + targets + "'";
103             if (targetfilter) s += " constrained by targetfilter '" + targetfilter + "'";
104             widget.log(s);
105
106             widget.team.newSearch(query, sortOrder, maxrecs, perpage, limit, targets, targetfilter);
107         }
108     });
109 };
110
111
112 // Functions follow for promoting the regular widget object into
113 // widgets of specific types. These could be moved into their own
114 // source files.
115
116
117 mkws.registerWidgetType('Targets', function() {
118     var that = this;
119     var M = mkws.M;
120
121     this.team.queue("targets").subscribe(function(data) {
122         var table ='<table><thead><tr>' +
123             '<td>' + M('Target ID') + '</td>' +
124             '<td>' + M('Hits') + '</td>' +
125             '<td>' + M('Diags') + '</td>' +
126             '<td>' + M('Records') + '</td>' +
127             '<td>' + M('State') + '</td>' +
128             '</tr></thead><tbody>';
129
130         for (var i = 0; i < data.length; i++) {
131             table += "<tr><td>" + data[i].id +
132                 "</td><td>" + data[i].hits +
133                 "</td><td>" + data[i].diagnostic +
134                 "</td><td>" + data[i].records +
135                 "</td><td>" + data[i].state + "</td></tr>";
136         }
137
138         table += '</tbody></table>';
139         var subnode = $(that.node).children('.mkwsBytarget');
140         subnode.html(table);
141     });
142 });
143
144
145 mkws.registerWidgetType('Stat', function() {
146     var that = this;
147     var M = mkws.M;
148
149     this.team.queue("stat").subscribe(function(data) {
150         if (that.node.length === 0)  alert("huh?!");
151
152         $(that.node).html('<span class="head">' + M('Status info') + '</span>' +
153             ' -- ' +
154             '<span class="clients">' + M('Active clients') + ': ' + data.activeclients + '/' + data.clients + '</span>' +
155             ' -- ' +
156             '<span class="records">' + M('Retrieved records') + ': ' + data.records + '/' + data.hits + '</span>');
157     });
158 });
159
160
161 mkws.registerWidgetType('Pager', function() {
162     var that = this;
163     var M = mkws.M;
164
165     this.team.queue("pager").subscribe(function(data) {
166         $(that.node).html(drawPager(data))
167
168         function drawPager(data) {
169             var teamName = that.team.name();
170             var s = '<div style="float: right">' + M('Displaying') + ': '
171                 + (data.start + 1) + ' ' + M('to') + ' ' + (data.start + data.num) +
172                 ' ' + M('of') + ' ' + data.merged + ' (' + M('found') + ': '
173                 + data.total + ')</div>';
174
175             //client indexes pages from 1 but pz2 from 0
176             var onsides = 6;
177             var pages = Math.ceil(that.team.totalRecordCount() / that.team.perpage());
178             var currentPage = that.team.currentPage();
179
180             var firstClkbl = (currentPage - onsides > 0)
181                 ? currentPage - onsides
182                 : 1;
183
184             var lastClkbl = firstClkbl + 2*onsides < pages
185                 ? firstClkbl + 2*onsides
186                 : pages;
187
188             var prev = '<span class="mkwsPrev">&#60;&#60; ' + M('Prev') + '</span> | ';
189             if (currentPage > 1)
190                 prev = '<a href="#" class="mkwsPrev" onclick="mkws.pagerPrev(\'' + teamName + '\');">'
191                 +'&#60;&#60; ' + M('Prev') + '</a> | ';
192
193             var middle = '';
194             for(var i = firstClkbl; i <= lastClkbl; i++) {
195                 var numLabel = i;
196                 if(i == currentPage)
197                     numLabel = '<span class="mkwsSelected">' + i + '</span>';
198
199                 middle += '<a href="#" onclick="mkws.showPage(\'' + teamName + '\', ' + i + ')"> '
200                     + numLabel + ' </a>';
201             }
202
203             var next = ' | <span class="mkwsNext">' + M('Next') + ' &#62;&#62;</span>';
204             if (pages - currentPage > 0)
205                 next = ' | <a href="#" class="mkwsNext" onclick="mkws.pagerNext(\'' + teamName + '\')">'
206                 + M('Next') + ' &#62;&#62;</a>';
207
208             var predots = '';
209             if (firstClkbl > 1)
210                 predots = '...';
211
212             var postdots = '';
213             if (lastClkbl < pages)
214                 postdots = '...';
215
216             s += '<div style="float: clear">'
217                 + prev + predots + middle + postdots + next + '</div>';
218
219             return s;
220         }
221     });
222 });
223
224
225 mkws.registerWidgetType('Records', function() {
226     var that = this;
227     var team = this.team;
228
229     this.team.queue("records").subscribe(function(data) {
230         var html = [];
231         for (var i = 0; i < data.hits.length; i++) {
232             var hit = data.hits[i];
233             var divId = team.recordElementId(hit.recid[0]);
234             html.push('<div class="record mkwsTeam_' + team.name() + ' ' + divId + '">', renderSummary(hit), '</div>');
235             // ### At some point, we may be able to move the
236             // m_currentRecordId and m_currentRecordData members
237             // from the team object into this widget.
238             if (hit.recid == team.currentRecordId()) {
239                 if (team.currentRecordData())
240                     html.push(team.renderDetails(team.currentRecordData()));
241             }
242         }
243         $(that.node).html(html.join(''));
244
245         function renderSummary(hit) {
246             var template = team.loadTemplate(that.config.template || "Summary");
247             hit._id = team.recordElementId(hit.recid[0]);
248             hit._onclick = "mkws.showDetails('" + team.name() + "', '" + hit.recid[0] + "');return false;"
249             return template(hit);
250         }
251     });
252
253     widget.autosearch(that);
254 });
255
256
257 mkws.registerWidgetType('Navi', function() {
258     var that = this;
259     var teamName = this.team.name();
260     var M = mkws.M;
261
262     this.team.queue("navi").subscribe(function() {
263         var filters = that.team.filters();
264         var text = "";
265
266         for (var i in filters) {
267             if (text) {
268                 text += " | ";
269             }
270             var filter = filters[i];
271             if (filter.id) {
272                 text += M('source') + ': <a class="crossout" href="#" onclick="mkws.delimitTarget(\'' + teamName +
273                     "', '" + filter.id + "'" + ');return false;">' + filter.name + '</a>';
274             } else {
275                 text += M(filter.field) + ': <a class="crossout" href="#" onclick="mkws.delimitQuery(\'' + teamName +
276                     "', '" + filter.field + "', '" + filter.value + "'" +
277                     ');return false;">' + filter.value + '</a>';
278             }
279         }
280
281         $(that.node).html(text);
282     });
283 });
284
285
286 // It seems this and the Perpage widget doen't need to subscribe to
287 // anything, since they produce events rather than consuming them.
288 //
289 mkws.registerWidgetType('Sort', function() {
290     var that = this;
291
292     $(this.node).change(function() {
293         that.team.set_sortOrder($(that.node).val());
294         if (that.team.submitted()) {
295             that.team.reShow();
296         }
297         return false;
298     });
299 });
300
301
302 mkws.registerWidgetType('Perpage', function() {
303     var that = this;
304
305     $(this.node).change(function() {
306         that.team.set_perpage($(that.node).val());
307         if (that.team.submitted()) {
308             that.team.reShow();
309         }
310         return false;
311     });
312 });
313
314
315 mkws.registerWidgetType('Done', function() {
316     var that = this;
317
318     this.team.queue("complete").subscribe(function(n) {
319         $(that.node).html("Search complete: found " + n + " records");
320     });
321 });