8b4340074a29614aebf877a8adaff76b1c0d13ad
[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     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('Pager', function() {
158     var that = this;
159     var M = mkws.M;
160
161     this.team.queue("pager").subscribe(function(data) {
162         $(that.node).html(drawPager(data))
163
164         function drawPager(data) {
165             var teamName = that.team.name();
166             var s = '<div style="float: right">' + M('Displaying') + ': '
167                 + (data.start + 1) + ' ' + M('to') + ' ' + (data.start + data.num) +
168                 ' ' + M('of') + ' ' + data.merged + ' (' + M('found') + ': '
169                 + data.total + ')</div>';
170
171             //client indexes pages from 1 but pz2 from 0
172             var onsides = 6;
173             var pages = Math.ceil(that.team.totalRecordCount() / that.team.perpage());
174             var currentPage = that.team.currentPage();
175
176             var firstClkbl = (currentPage - onsides > 0)
177                 ? currentPage - onsides
178                 : 1;
179
180             var lastClkbl = firstClkbl + 2*onsides < pages
181                 ? firstClkbl + 2*onsides
182                 : pages;
183
184             var prev = '<span class="mkwsPrev">&#60;&#60; ' + M('Prev') + '</span><b> | </b>';
185             if (currentPage > 1)
186                 prev = '<a href="#" class="mkwsPrev" onclick="mkws.pagerPrev(\'' + teamName + '\');">'
187                 +'&#60;&#60; ' + M('Prev') + '</a><b> | </b>';
188
189             var middle = '';
190             for(var i = firstClkbl; i <= lastClkbl; i++) {
191                 var numLabel = i;
192                 if(i == currentPage)
193                     numLabel = '<b>' + i + '</b>';
194
195                 middle += '<a href="#" onclick="mkws.showPage(\'' + teamName + '\', ' + i + ')"> '
196                     + numLabel + ' </a>';
197             }
198
199             var next = '<b> | </b><span class="mkwsNext">' + M('Next') + ' &#62;&#62;</span>';
200             if (pages - currentPage > 0)
201                 next = '<b> | </b><a href="#" class="mkwsNext" onclick="mkws.pagerNext(\'' + teamName + '\')">'
202                 + M('Next') + ' &#62;&#62;</a>';
203
204             var predots = '';
205             if (firstClkbl > 1)
206                 predots = '...';
207
208             var postdots = '';
209             if (lastClkbl < pages)
210                 postdots = '...';
211
212             s += '<div style="float: clear">'
213                 + prev + predots + middle + postdots + next + '</div>';
214
215             return s;
216         }
217     });
218 });
219
220
221 mkws.registerWidgetType('Records', function() {
222     var that = this;
223     var team = this.team;
224
225     this.team.queue("records").subscribe(function(data) {
226         var html = [];
227         for (var i = 0; i < data.hits.length; i++) {
228             var hit = data.hits[i];
229             var divId = team.recordElementId(hit.recid[0]);
230             html.push('<div class="record mkwsTeam_' + team.name() + ' ' + divId + '">', renderSummary(hit), '</div>');
231             // ### At some point, we may be able to move the
232             // m_currentRecordId and m_currentRecordData members
233             // from the team object into this widget.
234             if (hit.recid == team.currentRecordId()) {
235                 if (team.currentRecordData())
236                     html.push(team.renderDetails(team.currentRecordData()));
237             }
238         }
239         $(that.node).html(html.join(''));
240
241         function renderSummary(hit) {
242             var template = team.loadTemplate(that.config.template || "Summary");
243             hit._id = team.recordElementId(hit.recid[0]);
244             hit._onclick = "mkws.showDetails('" + team.name() + "', '" + hit.recid[0] + "');return false;"
245             return template(hit);
246         }
247     });
248
249     widget.autosearch(that);
250 });
251
252
253 mkws.registerWidgetType('Navi', function() {
254     var that = this;
255     var teamName = this.team.name();
256     var M = mkws.M;
257
258     this.team.queue("navi").subscribe(function() {
259         var filters = that.team.filters();
260         var text = "";
261
262         for (var i in filters) {
263             if (text) {
264                 text += " | ";
265             }
266             var filter = filters[i];
267             if (filter.id) {
268                 text += M('source') + ': <a class="crossout" href="#" onclick="mkws.delimitTarget(\'' + teamName +
269                     "', '" + filter.id + "'" + ');return false;">' + filter.name + '</a>';
270             } else {
271                 text += M(filter.field) + ': <a class="crossout" href="#" onclick="mkws.delimitQuery(\'' + teamName +
272                     "', '" + filter.field + "', '" + filter.value + "'" +
273                     ');return false;">' + filter.value + '</a>';
274             }
275         }
276
277         $(that.node).html(text);
278     });
279 });
280
281
282 // It seems this and the Perpage widget doen't need to subscribe to
283 // anything, since they produce events rather than consuming them.
284 //
285 mkws.registerWidgetType('Sort', function() {
286     var that = this;
287
288     $(this.node).change(function() {
289         that.team.set_sortOrder($(that.node).val());
290         if (that.team.submitted()) {
291             that.team.resetPage();
292             that.team.reShow();
293         }
294         return false;
295     });
296 });
297
298
299 mkws.registerWidgetType('Perpage', function() {
300     var that = this;
301
302     $(this.node).change(function() {
303         that.team.set_perpage($(that.node).val());
304         if (that.team.submitted()) {
305             that.team.resetPage();
306             that.team.reShow();
307         }
308         return false;
309     });
310 });
311
312
313 mkws.registerWidgetType('Done', function() {
314     var that = this;
315
316     this.team.queue("complete").subscribe(function(n) {
317         $(that.node).html("Search complete: found " + n + " records");
318     });
319 });