7c5dd4ef464bf112efd822c9cdd6ba15959ad953
[project/luci.git] / libs / web / htdocs / luci-static / resources / cbi.js
1 /*
2         LuCI - Lua Configuration Interface
3
4         Copyright 2008 Steven Barth <steven@midlink.org>
5         Copyright 2008-2010 Jo-Philipp Wich <xm@subsignal.org>
6
7         Licensed under the Apache License, Version 2.0 (the "License");
8         you may not use this file except in compliance with the License.
9         You may obtain a copy of the License at
10
11         http://www.apache.org/licenses/LICENSE-2.0
12 */
13
14 var cbi_d = [];
15 var cbi_t = [];
16 var cbi_c = [];
17
18 var cbi_validators = {
19
20         'integer': function(v)
21         {
22                 return (v.match(/^-?[0-9]+$/) != null);
23         },
24
25         'uinteger': function(v)
26         {
27                 return (cbi_validators.integer(v) && (v >= 0));
28         },
29
30         'ipaddr': function(v)
31         {
32                 return cbi_validators.ip4addr(v) || cbi_validators.ip6addr(v);
33         },
34
35         'ip4addr': function(v)
36         {
37                 if( v.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)(\/(\d+))?$/) )
38                 {
39                         return (RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
40                                (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
41                                (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
42                                (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
43                                (!RegExp.$5 || ((RegExp.$6 >= 0) && (RegExp.$6 <= 32)))
44                         ;
45                 }
46
47                 return false;
48         },
49
50         'ip6addr': function(v)
51         {
52                 if( v.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/) )
53                 {
54                         if( !RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)) )
55                         {
56                                 var addr = RegExp.$1;
57
58                                 if( addr == '::' )
59                                 {
60                                         return true;
61                                 }
62
63                                 if( addr.indexOf('.') > 0 )
64                                 {
65                                         var off = addr.lastIndexOf(':');
66
67                                         if( !(off && cbi_validators.ip4addr(addr.substr(off+1))) )
68                                                 return false;
69
70                                         addr = addr.substr(0, off) + ':0:0';
71                                 }
72
73                                 if( addr.indexOf('::') < 0 )
74                                 {
75                                         return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
76                                 }
77
78                                 var fields = 0;
79
80                                 for( var i = 0, last = 0, comp = false; i <= addr.length; i++ )
81                                 {
82                                         if( (addr.charAt(i) == ':') || (i == addr.length) )
83                                         {
84                                                 if( (i == last) && !comp )
85                                                 {
86                                                         comp = true;
87                                                 }
88                                                 else
89                                                 {
90                                                         var f = addr.substring(last, i);
91                                                         if( !(f && f.match(/^[a-fA-F0-9]{1,4}$/)) )
92                                                                 return false;
93                                                 }
94
95                                                 fields++;
96                                                 last = i + 1;
97                                         }
98                                 }
99
100                                 return (fields == 8);
101                         }
102                 }
103
104                 return false;
105         },
106
107         'port': function(v)
108         {
109                 return cbi_validators.integer(v) && (v >= 0) && (v <= 65535);
110         },
111
112         'portrange': function(v)
113         {
114                 if( v.match(/^(\d+)-(\d+)$/) )
115                 {
116                         var p1 = RegExp.$1;
117                         var p2 = RegExp.$2;
118
119                         return cbi_validators.port(p1) &&
120                                cbi_validators.port(p2) &&
121                                (parseInt(p1) <= parseInt(p2))
122                         ;
123                 }
124                 else
125                 {
126                         return cbi_validators.port(v);
127                 }
128         },
129
130         'macaddr': function(v)
131         {
132                 return (v.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
133         },
134
135         'host': function(v)
136         {
137                 return cbi_validators.hostname(v) || cbi_validators.ipaddr(v);
138         },
139
140         'hostname': function(v)
141         {
142                 return (v.match(/^[a-zA-Z_][a-zA-Z0-9_\-.]*$/) != null);
143         },
144
145         'wpakey': function(v)
146         {
147                 if( v.length == 64 )
148                         return (v.match(/^[a-fA-F0-9]{64}$/) != null);
149                 else
150                         return (v.length >= 8) && (v.length <= 63);
151         },
152
153         'wepkey': function(v)
154         {
155                 if( v.substr(0,2) == 's:' )
156                         v = v.substr(2);
157
158                 if( (v.length == 10) || (v.length == 26) )
159                         return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
160                 else
161                         return (v.length == 5) || (v.length == 13);
162         },
163
164 };
165
166
167 function cbi_d_add(field, dep, next) {
168         var obj = document.getElementById(field);
169         if (obj) {
170                 var entry
171                 for (var i=0; i<cbi_d.length; i++) {
172                         if (cbi_d[i].id == field) {
173                                 entry = cbi_d[i];
174                                 break;
175                         }
176                 }
177                 if (!entry) {
178                         entry = {
179                                 "node": obj,
180                                 "id": field,
181                                 "parent": obj.parentNode.id,
182                                 "next": next,
183                                 "deps": []
184                         };
185                         cbi_d.unshift(entry);
186                 }
187                 entry.deps.push(dep)
188         }
189 }
190
191 function cbi_d_checkvalue(target, ref) {
192         var t = document.getElementById(target);
193         var value;
194
195         if (!t) {
196                 var tl = document.getElementsByName(target);
197
198                 if( tl.length > 0 && tl[0].type == 'radio' )
199                         for( var i = 0; i < tl.length; i++ )
200                                 if( tl[i].checked ) {
201                                         value = tl[i].value;
202                                         break;
203                                 }
204
205                 value = value ? value : "";
206         } else if (!t.value) {
207                 value = "";
208         } else {
209                 value = t.value;
210
211                 if (t.type == "checkbox") {
212                         value = t.checked ? value : "";
213                 }
214         }
215
216         return (value == ref)
217 }
218
219 function cbi_d_check(deps) {
220         var reverse;
221         var def = false;
222         for (var i=0; i<deps.length; i++) {
223                 var istat = true;
224                 reverse = false;
225                 for (var j in deps[i]) {
226                         if (j == "!reverse") {
227                                 reverse = true;
228                         } else if (j == "!default") {
229                                 def = true;
230                                 istat = false;
231                         } else {
232                                 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
233                         }
234                 }
235                 if (istat) {
236                         return !reverse;
237                 }
238         }
239         return def;
240 }
241
242 function cbi_d_update() {
243         var state = false;
244         for (var i=0; i<cbi_d.length; i++) {
245                 var entry = cbi_d[i];
246                 var next  = document.getElementById(entry.next)
247                 var node  = document.getElementById(entry.id)
248                 var parent = document.getElementById(entry.parent)
249
250                 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
251                         node.parentNode.removeChild(node);
252                         state = true;
253                         if( entry.parent )
254                                 cbi_c[entry.parent]--;
255                 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
256                         if (!next) {
257                                 parent.appendChild(entry.node);
258                         } else {
259                                 next.parentNode.insertBefore(entry.node, next);
260                         }
261                         state = true;
262                         if( entry.parent )
263                                 cbi_c[entry.parent]++;
264                 }
265         }
266
267         if (entry && entry.parent) {
268                 cbi_t_update();
269         }
270
271         if (state) {
272                 cbi_d_update();
273         }
274 }
275
276 function cbi_bind(obj, type, callback, mode) {
277         if (typeof mode == "undefined") {
278                 mode = false;
279         }
280         if (!obj.addEventListener) {
281                 ieCallback = function(){
282                         var e = window.event;
283                         if (!e.target && e.srcElement) {
284                                 e.target = e.srcElement;
285                         };
286                         e.target['_eCB' + type + callback] = callback;
287                         e.target['_eCB' + type + callback](e);
288                         e.target['_eCB' + type + callback] = null;
289                 };
290                 obj.attachEvent('on' + type, ieCallback);
291         } else {
292                 obj.addEventListener(type, callback, mode);
293         }
294         return obj;
295 }
296
297 function cbi_combobox(id, values, def, man) {
298         var selid = "cbi.combobox." + id;
299         if (document.getElementById(selid)) {
300                 return
301         }
302
303         var obj = document.getElementById(id)
304         var sel = document.createElement("select");
305         sel.id = selid;
306         sel.className = 'cbi-input-select';
307         if (obj.className && obj.className.match(/cbi-input-invalid/)) {
308                 sel.className += ' cbi-input-invalid';
309         }
310         if (obj.nextSibling) {
311                 obj.parentNode.insertBefore(sel, obj.nextSibling);
312         } else {
313                 obj.parentNode.appendChild(sel);
314         }
315
316         if (!values[obj.value]) {
317                 if (obj.value == "") {
318                         var optdef = document.createElement("option");
319                         optdef.value = "";
320                         optdef.appendChild(document.createTextNode(def));
321                         sel.appendChild(optdef);
322                 } else {
323                         var opt = document.createElement("option");
324                         opt.value = obj.value;
325                         opt.selected = "selected";
326                         opt.appendChild(document.createTextNode(obj.value));
327                         sel.appendChild(opt);
328                 }
329         }
330
331         for (var i in values) {
332                 var opt = document.createElement("option");
333                 opt.value = i;
334
335                 if (obj.value == i) {
336                         opt.selected = "selected";
337                 }
338
339                 opt.appendChild(document.createTextNode(values[i]));
340                 sel.appendChild(opt);
341         }
342
343         var optman = document.createElement("option");
344         optman.value = "";
345         optman.appendChild(document.createTextNode(man));
346         sel.appendChild(optman);
347
348         obj.style.display = "none";
349
350         cbi_bind(sel, "change", function() {
351                 if (sel.selectedIndex == sel.options.length - 1) {
352                         obj.style.display = "inline";
353                         sel.parentNode.removeChild(sel);
354                         obj.focus();
355                 } else {
356                         obj.value = sel.options[sel.selectedIndex].value;
357                         sel.className = (!obj.validate || obj.validate())
358                                 ? 'cbi-input-select' : 'cbi-input-select cbi-input-invalid';
359                 }
360
361                 try {
362                         cbi_d_update();
363                 } catch (e) {
364                         //Do nothing
365                 }
366         })
367 }
368
369 function cbi_combobox_init(id, values, def, man) {
370         var obj = document.getElementById(id);
371         cbi_bind(obj, "blur", function() {
372                 cbi_combobox(id, values, def, man)
373         });
374         cbi_combobox(id, values, def, man);
375 }
376
377 function cbi_filebrowser(id, url, defpath) {
378         var field   = document.getElementById(id);
379         var browser = window.open(
380                 url + ( field.value || defpath || '' ) + '?field=' + id,
381                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
382         );
383
384         browser.focus();
385 }
386
387 //Hijacks the CBI form to send via XHR (requires Prototype)
388 function cbi_hijack_forms(layer, win, fail, load) {
389         var forms = layer.getElementsByTagName('form');
390         for (var i=0; i<forms.length; i++) {
391                 $(forms[i]).observe('submit', function(event) {
392                         // Prevent the form from also submitting the regular way
393                         event.stop();
394
395                         // Submit via XHR
396                         event.element().request({
397                                 onSuccess: win,
398                                 onFailure: fail
399                         });
400
401                         if (load) {
402                                 load();
403                         }
404                 });
405         }
406 }
407
408
409 function cbi_t_add(section, tab) {
410         var t = document.getElementById('tab.' + section + '.' + tab);
411         var c = document.getElementById('container.' + section + '.' + tab);
412
413         if( t && c ) {
414                 cbi_t[section] = (cbi_t[section] || [ ]);
415                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
416         }
417 }
418
419 function cbi_t_switch(section, tab) {
420         if( cbi_t[section] && cbi_t[section][tab] ) {
421                 var o = cbi_t[section][tab];
422                 var h = document.getElementById('tab.' + section);
423                 for( var tid in cbi_t[section] ) {
424                         var o2 = cbi_t[section][tid];
425                         if( o.tab.id != o2.tab.id ) {
426                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
427                                 o2.container.style.display = 'none';
428                         }
429                         else {
430                                 if(h) h.value = tab;
431                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
432                                 o2.container.style.display = 'block';
433                         }
434                 }
435         }
436         return false
437 }
438
439 function cbi_t_update() {
440         var hl_tabs = [ ];
441
442         for( var sid in cbi_t )
443                 for( var tid in cbi_t[sid] )
444                         if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
445                                 cbi_t[sid][tid].tab.style.display = 'none';
446                         }
447                         else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
448                                 cbi_t[sid][tid].tab.style.display = '';
449
450                                 var t = cbi_t[sid][tid].tab;
451                                 t.className += ' cbi-tab-highlighted';
452                                 hl_tabs.push(t);
453                         }
454
455         if( hl_tabs.length > 0 )
456                 window.setTimeout(function() {
457                         for( var i = 0; i < hl_tabs.length; i++ )
458                                 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
459                 }, 750);
460 }
461
462
463 function cbi_validate_form(form, errmsg)
464 {
465         if( form.cbi_validators )
466         {
467                 for( var i = 0; i < form.cbi_validators.length; i++ )
468                 {
469                         var validator = form.cbi_validators[i];
470                         if( !validator() && errmsg )
471                         {
472                                 alert(errmsg);
473                                 return false;
474                         }
475                 }
476         }
477
478         return true;
479 }
480
481 function cbi_validate_reset(form)
482 {
483         window.setTimeout(
484                 function() { cbi_validate_form(form, null) }, 100
485         );
486
487         return true;
488 }
489
490 function cbi_validate_field(cbid, optional, type)
491 {
492         var field = document.getElementById(cbid);
493         var vldcb = cbi_validators[type];
494
495         if( field && vldcb )
496         {
497                 var validator = function(reset)
498                 {
499                         // is not detached
500                         if( field.form )
501                         {
502                                 field.className = field.className.replace(/ cbi-input-invalid/g, '');
503
504                                 // validate value
505                                 var value = (field.options) ? field.options[field.options.selectedIndex].value : field.value;
506                                 if( !(((value.length == 0) && optional) || vldcb(value)) )
507                                 {
508                                         // invalid
509                                         field.className += ' cbi-input-invalid';
510                                         return false;
511                                 }
512                         }
513
514                         return true;
515                 };
516
517                 if( ! field.form.cbi_validators )
518                         field.form.cbi_validators = [ ];
519
520                 field.form.cbi_validators.push(validator);
521                 field.onblur = field.onkeyup = field.validate = validator;
522
523                 validator();
524         }
525 }
526
527 if( ! String.serialize )
528         String.serialize = function(o)
529         {
530                 switch(typeof(o))
531                 {
532                         case 'object':
533                                 // null
534                                 if( o == null )
535                                 {
536                                         return 'null';
537                                 }
538
539                                 // array
540                                 else if( o.length )
541                                 {
542                                         var i, s = '';
543
544                                         for( var i = 0; i < o.length; i++ )
545                                                 s += (s ? ', ' : '') + String.serialize(o[i]);
546
547                                         return '[ ' + s + ' ]';
548                                 }
549
550                                 // object
551                                 else
552                                 {
553                                         var k, s = '';
554
555                                         for( k in o )
556                                                 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
557
558                                         return '{ ' + s + ' }';
559                                 }
560
561                                 break;
562
563                         case 'string':
564                                 // complex string
565                                 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
566                                         return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
567
568                                 // simple string
569                                 else
570                                         return '"' + o + '"';
571
572                                 break;
573
574                         default:
575                                 return o.toString();
576                 }
577         }
578
579
580 if( ! String.format )
581         String.format = function()
582         {
583                 if (!arguments || arguments.length < 1 || !RegExp)
584                         return;
585
586                 var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
587                 var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
588
589                 function esc(s, r) {
590                         for( var i = 0; i < r.length; i += 2 )
591                                 s = s.replace(r[i], r[i+1]);
592                         return s;
593                 }
594
595                 var str = arguments[0];
596                 var out = '';
597                 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j))/;
598                 var a = b = [], numSubstitutions = 0, numMatches = 0;
599
600                 while( a = re.exec(str) )
601                 {
602                         var m = a[1];
603                         var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
604                         var pPrecision = a[6], pType = a[7];
605
606                         numMatches++;
607
608                         if (pType == '%')
609                         {
610                                 subst = '%';
611                         }
612                         else
613                         {
614                                 if (numSubstitutions++ < arguments.length)
615                                 {
616                                         var param = arguments[numSubstitutions];
617
618                                         var pad = '';
619                                         if (pPad && pPad.substr(0,1) == "'")
620                                                 pad = leftpart.substr(1,1);
621                                         else if (pPad)
622                                                 pad = pPad;
623
624                                         var justifyRight = true;
625                                         if (pJustify && pJustify === "-")
626                                                 justifyRight = false;
627
628                                         var minLength = -1;
629                                         if (pMinLength)
630                                                 minLength = parseInt(pMinLength);
631
632                                         var precision = -1;
633                                         if (pPrecision && pType == 'f')
634                                                 precision = parseInt(pPrecision.substring(1));
635
636                                         var subst = param;
637
638                                         switch(pType)
639                                         {
640                                                 case 'b':
641                                                         subst = (parseInt(param) || 0).toString(2);
642                                                         break;
643
644                                                 case 'c':
645                                                         subst = String.fromCharCode(parseInt(param) || 0);
646                                                         break;
647
648                                                 case 'd':
649                                                         subst = (parseInt(param) || 0);
650                                                         break;
651
652                                                 case 'u':
653                                                         subst = Math.abs(parseInt(param) || 0);
654                                                         break;
655
656                                                 case 'f':
657                                                         subst = (precision > -1)
658                                                                 ? Math.round((parseFloat(param) || 0.0) * Math.pow(10, precision)) / Math.pow(10, precision)
659                                                                 : (parseFloat(param) || 0.0);
660                                                         break;
661
662                                                 case 'o':
663                                                         subst = (parseInt(param) || 0).toString(8);
664                                                         break;
665
666                                                 case 's':
667                                                         subst = param;
668                                                         break;
669
670                                                 case 'x':
671                                                         subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
672                                                         break;
673
674                                                 case 'X':
675                                                         subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
676                                                         break;
677
678                                                 case 'h':
679                                                         subst = esc(param, html_esc);
680                                                         break;
681
682                                                 case 'q':
683                                                         subst = esc(param, quot_esc);
684                                                         break;
685
686                                                 case 'j':
687                                                         subst = String.serialize(param);
688                                                         break;
689                                         }
690                                 }
691                         }
692
693                         out += leftpart + subst;
694                         str = str.substr(m.length);
695                 }
696
697                 return out + str;
698         }