libs/web: rework DynamicList widget
[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 var colons = 0;
76 var fill = '0';
77
78 for( var i = 0; i < addr.length; i++ )
79 if( addr.charAt(i) == ':' )
80 colons++;
81
82 if( colons > 7 )
83 return false;
84
85 for( var i = 0; i < (7 - colons); i++ )
86 fill += ':0';
87
88 addr = addr.replace(/::/, ':' + fill + ':');
89 }
90
91 return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
92 }
93 }
94
95 return false;
96 },
97
98 'port': function(v)
99 {
100 return cbi_validators.integer(v) && (v >= 0) && (v <= 65535);
101 },
102
103 'portrange': function(v)
104 {
105 if( v.match(/^(\d+)-(\d+)$/) )
106 {
107 var p1 = RegExp.$1;
108 var p2 = RegExp.$2;
109
110 return cbi_validators.port(p1) &&
111 cbi_validators.port(p2) &&
112 (parseInt(p1) <= parseInt(p2))
113 ;
114 }
115 else
116 {
117 return cbi_validators.port(v);
118 }
119 },
120
121 'macaddr': function(v)
122 {
123 return (v.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
124 },
125
126 'host': function(v)
127 {
128 return cbi_validators.hostname(v) || cbi_validators.ipaddr(v);
129 },
130
131 'hostname': function(v)
132 {
133 return (v.match(/^[a-zA-Z_][a-zA-Z0-9_\-.]*$/) != null);
134 },
135
136 'wpakey': function(v)
137 {
138 if( v.length == 64 )
139 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
140 else
141 return (v.length >= 8) && (v.length <= 63);
142 },
143
144 'wepkey': function(v)
145 {
146 if( v.substr(0,2) == 's:' )
147 v = v.substr(2);
148
149 if( (v.length == 10) || (v.length == 26) )
150 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
151 else
152 return (v.length == 5) || (v.length == 13);
153 },
154
155 };
156
157
158 function cbi_d_add(field, dep, next) {
159 var obj = document.getElementById(field);
160 if (obj) {
161 var entry
162 for (var i=0; i<cbi_d.length; i++) {
163 if (cbi_d[i].id == field) {
164 entry = cbi_d[i];
165 break;
166 }
167 }
168 if (!entry) {
169 entry = {
170 "node": obj,
171 "id": field,
172 "parent": obj.parentNode.id,
173 "next": next,
174 "deps": []
175 };
176 cbi_d.unshift(entry);
177 }
178 entry.deps.push(dep)
179 }
180 }
181
182 function cbi_d_checkvalue(target, ref) {
183 var t = document.getElementById(target);
184 var value;
185
186 if (!t) {
187 var tl = document.getElementsByName(target);
188
189 if( tl.length > 0 && tl[0].type == 'radio' )
190 for( var i = 0; i < tl.length; i++ )
191 if( tl[i].checked ) {
192 value = tl[i].value;
193 break;
194 }
195
196 value = value ? value : "";
197 } else if (!t.value) {
198 value = "";
199 } else {
200 value = t.value;
201
202 if (t.type == "checkbox") {
203 value = t.checked ? value : "";
204 }
205 }
206
207 return (value == ref)
208 }
209
210 function cbi_d_check(deps) {
211 var reverse;
212 var def = false;
213 for (var i=0; i<deps.length; i++) {
214 var istat = true;
215 reverse = false;
216 for (var j in deps[i]) {
217 if (j == "!reverse") {
218 reverse = true;
219 } else if (j == "!default") {
220 def = true;
221 istat = false;
222 } else {
223 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
224 }
225 }
226 if (istat) {
227 return !reverse;
228 }
229 }
230 return def;
231 }
232
233 function cbi_d_update() {
234 var state = false;
235 for (var i=0; i<cbi_d.length; i++) {
236 var entry = cbi_d[i];
237 var next = document.getElementById(entry.next)
238 var node = document.getElementById(entry.id)
239 var parent = document.getElementById(entry.parent)
240
241 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
242 node.parentNode.removeChild(node);
243 state = true;
244 if( entry.parent )
245 cbi_c[entry.parent]--;
246 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
247 if (!next) {
248 parent.appendChild(entry.node);
249 } else {
250 next.parentNode.insertBefore(entry.node, next);
251 }
252 state = true;
253 if( entry.parent )
254 cbi_c[entry.parent]++;
255 }
256 }
257
258 if (entry && entry.parent) {
259 cbi_t_update();
260 }
261
262 if (state) {
263 cbi_d_update();
264 }
265 }
266
267 function cbi_bind(obj, type, callback, mode) {
268 if (!obj.addEventListener) {
269 obj.attachEvent('on' + type,
270 function(){
271 var e = window.event;
272
273 if (!e.target && e.srcElement)
274 e.target = e.srcElement;
275
276 return !!callback(e);
277 }
278 );
279 } else {
280 obj.addEventListener(type, callback, !!mode);
281 }
282 return obj;
283 }
284
285 function cbi_combobox(id, values, def, man) {
286 var selid = "cbi.combobox." + id;
287 if (document.getElementById(selid)) {
288 return
289 }
290
291 var obj = document.getElementById(id)
292 var sel = document.createElement("select");
293 sel.id = selid;
294 sel.className = 'cbi-input-select';
295 if (obj.className && obj.className.match(/cbi-input-invalid/)) {
296 sel.className += ' cbi-input-invalid';
297 }
298 if (obj.nextSibling) {
299 obj.parentNode.insertBefore(sel, obj.nextSibling);
300 } else {
301 obj.parentNode.appendChild(sel);
302 }
303
304 if (!values[obj.value]) {
305 if (obj.value == "") {
306 var optdef = document.createElement("option");
307 optdef.value = "";
308 optdef.appendChild(document.createTextNode(def));
309 sel.appendChild(optdef);
310 } else {
311 var opt = document.createElement("option");
312 opt.value = obj.value;
313 opt.selected = "selected";
314 opt.appendChild(document.createTextNode(obj.value));
315 sel.appendChild(opt);
316 }
317 }
318
319 for (var i in values) {
320 var opt = document.createElement("option");
321 opt.value = i;
322
323 if (obj.value == i) {
324 opt.selected = "selected";
325 }
326
327 opt.appendChild(document.createTextNode(values[i]));
328 sel.appendChild(opt);
329 }
330
331 var optman = document.createElement("option");
332 optman.value = "";
333 optman.appendChild(document.createTextNode(man));
334 sel.appendChild(optman);
335
336 obj.style.display = "none";
337
338 cbi_bind(sel, "change", function() {
339 if (sel.selectedIndex == sel.options.length - 1) {
340 obj.style.display = "inline";
341 sel.parentNode.removeChild(sel);
342 obj.focus();
343 } else {
344 obj.value = sel.options[sel.selectedIndex].value;
345
346 var vld = obj.getAttribute("cbi_validate");
347 sel.className = (!vld || vld())
348 ? 'cbi-input-select' : 'cbi-input-select cbi-input-invalid';
349 }
350
351 try {
352 cbi_d_update();
353 } catch (e) {
354 //Do nothing
355 }
356 })
357 }
358
359 function cbi_combobox_init(id, values, def, man) {
360 var obj = document.getElementById(id);
361 cbi_bind(obj, "blur", function() {
362 cbi_combobox(id, values, def, man)
363 });
364 cbi_combobox(id, values, def, man);
365 }
366
367 function cbi_filebrowser(id, url, defpath) {
368 var field = document.getElementById(id);
369 var browser = window.open(
370 url + ( field.value || defpath || '' ) + '?field=' + id,
371 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
372 );
373
374 browser.focus();
375 }
376
377 function cbi_dynlist_init(name)
378 {
379 function cbi_dynlist_renumber(e)
380 {
381 var count = 1;
382 var childs = e.parentNode.childNodes;
383
384 for( var i = 0; i < childs.length; i++ )
385 if( childs[i].name == name )
386 childs[i].id = name + '.' + (count++);
387
388 e.focus();
389 }
390
391 function cbi_dynlist_keypress(ev)
392 {
393 ev = ev ? ev : window.event;
394
395 var se = ev.target ? ev.target : ev.srcElement;
396
397 if (se.nodeType == 3)
398 se = se.parentNode;
399
400 switch (ev.keyCode)
401 {
402 /* backspace, delete */
403 case 8:
404 case 46:
405 if (se.value.length == 0)
406 {
407 if (ev.preventDefault)
408 ev.preventDefault();
409
410 return false;
411 }
412
413 return true;
414
415 /* enter, arrow up, arrow down */
416 case 13:
417 case 38:
418 case 40:
419 if (ev.preventDefault)
420 ev.preventDefault();
421
422 return false;
423 }
424
425 return true;
426 }
427
428 function cbi_dynlist_keydown(ev)
429 {
430 ev = ev ? ev : window.event;
431
432 var se = ev.target ? ev.target : ev.srcElement;
433
434 if (se.nodeType == 3)
435 se = se.parentNode;
436
437 var prev = se.previousSibling;
438 while (prev && prev.name != name)
439 prev = prev.previousSibling;
440
441 var next = se.nextSibling;
442 while (next && next.name != name)
443 next = next.nextSibling;
444
445 switch (ev.keyCode)
446 {
447 /* backspace, delete */
448 case 8:
449 case 46:
450 var jump = (ev.keyCode == 8)
451 ? (prev || next) : (next || prev);
452
453 if (se.value.length == 0 && jump)
454 {
455 se.parentNode.removeChild(se.nextSibling);
456 se.parentNode.removeChild(se);
457
458 cbi_dynlist_renumber(jump);
459
460 if (ev.preventDefault)
461 ev.preventDefault();
462
463 return false;
464 }
465
466 break;
467
468 /* enter */
469 case 13:
470 var n = document.createElement('input');
471 n.name = se.name;
472 n.type = se.type;
473
474 cbi_bind(n, 'keydown', cbi_dynlist_keydown);
475 cbi_bind(n, 'keypress', cbi_dynlist_keypress);
476
477 if (next)
478 {
479 se.parentNode.insertBefore(n, next);
480 se.parentNode.insertBefore(document.createElement('br'), next);
481 }
482 else
483 {
484 se.parentNode.appendChild(n);
485 se.parentNode.appendChild(document.createElement('br'));
486 }
487
488 var dt = se.getAttribute('cbi_datatype');
489 var op = se.getAttribute('cbi_optional') == 'true';
490
491 if (dt)
492 cbi_validate_field(n, op, dt);
493
494 cbi_dynlist_renumber(n);
495 break;
496
497 /* arrow up */
498 case 38:
499 if (prev)
500 prev.focus();
501
502 break;
503
504 /* arrow down */
505 case 40:
506 if (next)
507 next.focus();
508
509 break;
510 }
511
512 return true;
513 }
514
515 var inputs = document.getElementsByName(name);
516 for( var i = 0; i < inputs.length; i++ )
517 {
518 cbi_bind(inputs[i], 'keydown', cbi_dynlist_keydown);
519 cbi_bind(inputs[i], 'keypress', cbi_dynlist_keypress);
520 }
521 }
522
523 //Hijacks the CBI form to send via XHR (requires Prototype)
524 function cbi_hijack_forms(layer, win, fail, load) {
525 var forms = layer.getElementsByTagName('form');
526 for (var i=0; i<forms.length; i++) {
527 $(forms[i]).observe('submit', function(event) {
528 // Prevent the form from also submitting the regular way
529 event.stop();
530
531 // Submit via XHR
532 event.element().request({
533 onSuccess: win,
534 onFailure: fail
535 });
536
537 if (load) {
538 load();
539 }
540 });
541 }
542 }
543
544
545 function cbi_t_add(section, tab) {
546 var t = document.getElementById('tab.' + section + '.' + tab);
547 var c = document.getElementById('container.' + section + '.' + tab);
548
549 if( t && c ) {
550 cbi_t[section] = (cbi_t[section] || [ ]);
551 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
552 }
553 }
554
555 function cbi_t_switch(section, tab) {
556 if( cbi_t[section] && cbi_t[section][tab] ) {
557 var o = cbi_t[section][tab];
558 var h = document.getElementById('tab.' + section);
559 for( var tid in cbi_t[section] ) {
560 var o2 = cbi_t[section][tid];
561 if( o.tab.id != o2.tab.id ) {
562 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
563 o2.container.style.display = 'none';
564 }
565 else {
566 if(h) h.value = tab;
567 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
568 o2.container.style.display = 'block';
569 }
570 }
571 }
572 return false
573 }
574
575 function cbi_t_update() {
576 var hl_tabs = [ ];
577
578 for( var sid in cbi_t )
579 for( var tid in cbi_t[sid] )
580 if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
581 cbi_t[sid][tid].tab.style.display = 'none';
582 }
583 else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
584 cbi_t[sid][tid].tab.style.display = '';
585
586 var t = cbi_t[sid][tid].tab;
587 t.className += ' cbi-tab-highlighted';
588 hl_tabs.push(t);
589 }
590
591 if( hl_tabs.length > 0 )
592 window.setTimeout(function() {
593 for( var i = 0; i < hl_tabs.length; i++ )
594 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
595 }, 750);
596 }
597
598
599 function cbi_validate_form(form, errmsg)
600 {
601 /* if triggered by a section removal or addition, don't validate */
602 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
603 return true;
604
605 if( form.cbi_validators )
606 {
607 for( var i = 0; i < form.cbi_validators.length; i++ )
608 {
609 var validator = form.cbi_validators[i];
610 if( !validator() && errmsg )
611 {
612 alert(errmsg);
613 return false;
614 }
615 }
616 }
617
618 return true;
619 }
620
621 function cbi_validate_reset(form)
622 {
623 window.setTimeout(
624 function() { cbi_validate_form(form, null) }, 100
625 );
626
627 return true;
628 }
629
630 function cbi_validate_field(cbid, optional, type)
631 {
632 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
633 var vldcb = cbi_validators[type];
634
635 if( field && vldcb )
636 {
637 var validator = function()
638 {
639 // is not detached
640 if( field.form )
641 {
642 field.className = field.className.replace(/ cbi-input-invalid/g, '');
643
644 // validate value
645 var value = (field.options) ? field.options[field.options.selectedIndex].value : field.value;
646 if( !(((value.length == 0) && optional) || vldcb(value)) )
647 {
648 // invalid
649 field.className += ' cbi-input-invalid';
650 return false;
651 }
652 }
653
654 return true;
655 };
656
657 if( ! field.form.cbi_validators )
658 field.form.cbi_validators = [ ];
659
660 field.form.cbi_validators.push(validator);
661
662 cbi_bind(field, "blur", validator);
663 cbi_bind(field, "keyup", validator);
664
665 field.setAttribute("cbi_validate", validator);
666 field.setAttribute("cbi_datatype", type);
667 field.setAttribute("cbi_optional", (!!optional).toString());
668
669 validator();
670 }
671 }
672
673 if( ! String.serialize )
674 String.serialize = function(o)
675 {
676 switch(typeof(o))
677 {
678 case 'object':
679 // null
680 if( o == null )
681 {
682 return 'null';
683 }
684
685 // array
686 else if( o.length )
687 {
688 var i, s = '';
689
690 for( var i = 0; i < o.length; i++ )
691 s += (s ? ', ' : '') + String.serialize(o[i]);
692
693 return '[ ' + s + ' ]';
694 }
695
696 // object
697 else
698 {
699 var k, s = '';
700
701 for( k in o )
702 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
703
704 return '{ ' + s + ' }';
705 }
706
707 break;
708
709 case 'string':
710 // complex string
711 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
712 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
713
714 // simple string
715 else
716 return '"' + o + '"';
717
718 break;
719
720 default:
721 return o.toString();
722 }
723 }
724
725
726 if( ! String.format )
727 String.format = function()
728 {
729 if (!arguments || arguments.length < 1 || !RegExp)
730 return;
731
732 var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
733 var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
734
735 function esc(s, r) {
736 for( var i = 0; i < r.length; i += 2 )
737 s = s.replace(r[i], r[i+1]);
738 return s;
739 }
740
741 var str = arguments[0];
742 var out = '';
743 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j))/;
744 var a = b = [], numSubstitutions = 0, numMatches = 0;
745
746 while( a = re.exec(str) )
747 {
748 var m = a[1];
749 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
750 var pPrecision = a[6], pType = a[7];
751
752 numMatches++;
753
754 if (pType == '%')
755 {
756 subst = '%';
757 }
758 else
759 {
760 if (numSubstitutions++ < arguments.length)
761 {
762 var param = arguments[numSubstitutions];
763
764 var pad = '';
765 if (pPad && pPad.substr(0,1) == "'")
766 pad = leftpart.substr(1,1);
767 else if (pPad)
768 pad = pPad;
769
770 var justifyRight = true;
771 if (pJustify && pJustify === "-")
772 justifyRight = false;
773
774 var minLength = -1;
775 if (pMinLength)
776 minLength = parseInt(pMinLength);
777
778 var precision = -1;
779 if (pPrecision && pType == 'f')
780 precision = parseInt(pPrecision.substring(1));
781
782 var subst = param;
783
784 switch(pType)
785 {
786 case 'b':
787 subst = (parseInt(param) || 0).toString(2);
788 break;
789
790 case 'c':
791 subst = String.fromCharCode(parseInt(param) || 0);
792 break;
793
794 case 'd':
795 subst = (parseInt(param) || 0);
796 break;
797
798 case 'u':
799 subst = Math.abs(parseInt(param) || 0);
800 break;
801
802 case 'f':
803 subst = (precision > -1)
804 ? Math.round((parseFloat(param) || 0.0) * Math.pow(10, precision)) / Math.pow(10, precision)
805 : (parseFloat(param) || 0.0);
806 break;
807
808 case 'o':
809 subst = (parseInt(param) || 0).toString(8);
810 break;
811
812 case 's':
813 subst = param;
814 break;
815
816 case 'x':
817 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
818 break;
819
820 case 'X':
821 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
822 break;
823
824 case 'h':
825 subst = esc(param, html_esc);
826 break;
827
828 case 'q':
829 subst = esc(param, quot_esc);
830 break;
831
832 case 'j':
833 subst = String.serialize(param);
834 break;
835 }
836 }
837 }
838
839 out += leftpart + subst;
840 str = str.substr(m.length);
841 }
842
843 return out + str;
844 }