2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2018 Jo-Philipp Wich <jo@mein.io>
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
11 http://www.apache.org/licenses/LICENSE-2.0
15 var cbi_strings
= { path
: {}, label
: {} };
17 function s8(bytes
, off
) {
19 return (n
> 0x7F) ? (n
- 256) >>> 0 : n
;
22 function u16(bytes
, off
) {
23 return ((bytes
[off
+ 1] << 8) + bytes
[off
]) >>> 0;
27 if (s
=== null || s
.length
=== 0)
32 for (var i
= 0; i
< s
.length
; i
++) {
33 var ch
= s
.charCodeAt(i
);
38 bytes
.push(((ch
>>> 6) & 0x1F) | 0xC0,
40 else if (ch
<= 0xFFFF)
41 bytes
.push(((ch
>>> 12) & 0x0F) | 0xE0,
42 ((ch
>>> 6) & 0x3F) | 0x80,
44 else if (code
<= 0x10FFFF)
45 bytes
.push(((ch
>>> 18) & 0x07) | 0xF0,
46 ((ch
>>> 12) & 0x3F) | 0x80,
47 ((ch
>> 6) & 0x3F) | 0x80,
54 var hash
= (bytes
.length
>>> 0),
55 len
= (bytes
.length
>>> 2),
59 hash
+= u16(bytes
, off
);
60 tmp
= ((u16(bytes
, off
+ 2) << 11) ^ hash
) >>> 0;
61 hash
= ((hash
<< 16) ^ tmp
) >>> 0;
66 switch ((bytes
.length
& 3) >>> 0) {
68 hash
+= u16(bytes
, off
);
69 hash
= (hash
^ (hash
<< 16)) >>> 0;
70 hash
= (hash
^ (s8(bytes
, off
+ 2) << 18)) >>> 0;
75 hash
+= u16(bytes
, off
);
76 hash
= (hash
^ (hash
<< 11)) >>> 0;
81 hash
+= s8(bytes
, off
);
82 hash
= (hash
^ (hash
<< 10)) >>> 0;
87 hash
= (hash
^ (hash
<< 3)) >>> 0;
89 hash
= (hash
^ (hash
<< 4)) >>> 0;
91 hash
= (hash
^ (hash
<< 25)) >>> 0;
94 return (0x100000000 + hash
).toString(16).substr(1);
98 return (window
.TR
&& TR
[sfh(s
)]) || s
;
102 return (/^-?\d+$/.test(x
) ? +x
: NaN
);
106 return (/^-?\d+(?:\.\d+)?$/.test(x
) ? +x
: NaN
);
110 if (!x
.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
113 if (RegExp
.$1 > 255 || RegExp
.$2 > 255 || RegExp
.$3 > 255 || RegExp
.$4 > 255)
116 return [ +RegExp
.$1, +RegExp
.$2, +RegExp
.$3, +RegExp
.$4 ];
120 if (x
.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
121 var v6
= RegExp
.$1, v4
= IPv4(RegExp
.$2);
126 x
= v6
+ ':' + (v4
[0] * 256 + v4
[1]).toString(16)
127 + ':' + (v4
[2] * 256 + v4
[3]).toString(16);
130 if (!x
.match(/^[a-fA-F0-9:]+$/))
133 var prefix_suffix
= x
.split(/::/);
135 if (prefix_suffix
.length
> 2)
138 var prefix
= (prefix_suffix
[0] || '0').split(/:/);
139 var suffix
= prefix_suffix
.length
> 1 ? (prefix_suffix
[1] || '0').split(/:/) : [];
141 if (suffix
.length
? (prefix
.length
+ suffix
.length
> 7)
142 : ((prefix_suffix
.length
< 2 && prefix
.length
< 8) || prefix
.length
> 8))
148 for (i
= 0, word
= parseInt(prefix
[0], 16); i
< prefix
.length
; word
= parseInt(prefix
[++i
], 16))
149 if (prefix
[i
].length
<= 4 && !isNaN(word
) && word
<= 0xFFFF)
154 for (i
= 0; i
< (8 - prefix
.length
- suffix
.length
); i
++)
157 for (i
= 0, word
= parseInt(suffix
[0], 16); i
< suffix
.length
; word
= parseInt(suffix
[++i
], 16))
158 if (suffix
[i
].length
<= 4 && !isNaN(word
) && word
<= 0xFFFF)
166 var CBIValidatorPrototype
= {
167 apply: function(name
, value
, args
) {
170 if (typeof(name
) === 'function')
172 else if (typeof(this.types
[name
]) === 'function')
173 func
= this.types
[name
];
177 if (value
!== undefined && value
!== null)
180 return func
.apply(this, args
);
183 assert: function(condition
, message
) {
185 this.field
.classList
.add('cbi-input-invalid');
186 this.error
= message
;
190 this.field
.classList
.remove('cbi-input-invalid');
195 compile: function(code
) {
203 for (var i
= 0; i
< code
.length
; i
++) {
209 switch (code
.charCodeAt(i
))
219 var label
= code
.substring(pos
, i
);
220 label
= label
.replace(/\\(.)/g, '$1');
221 label
= label
.replace(/^[ \t]+/g, '');
222 label
= label
.replace(/[ \t]+$/g, '');
224 if (label
&& !isNaN(label
)) {
225 stack
.push(parseFloat(label
));
227 else if (label
.match(/^(['"]).*\1$/)) {
228 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
230 else if (typeof this.types
[label
] == 'function') {
231 stack
.push(this.types
[label
]);
235 throw "Syntax error, unhandled token '"+label
+"'";
242 depth
+= (code
.charCodeAt(i
) == 40);
247 if (typeof stack
[stack
.length
-2] != 'function')
248 throw "Syntax error, argument list follows non-function";
250 stack
[stack
.length
-1] = this.compile(code
.substring(pos
, i
));
261 validate: function() {
262 /* element is detached */
263 if (!findParent(this.field
, 'body'))
266 this.field
.classList
.remove('cbi-input-invalid');
267 this.value
= matchesElem(this.field
, 'select') ? this.field
.options
[this.field
.selectedIndex
].value
: this.field
.value
;
272 if (this.value
.length
=== 0)
273 valid
= this.assert(this.optional
, _('non-empty value'));
275 valid
= this.vstack
[0].apply(this, this.vstack
[1]);
278 this.field
.setAttribute('data-tooltip', _('Expecting %s').format(this.error
));
279 this.field
.setAttribute('data-tooltip-style', 'error');
280 this.field
.dispatchEvent(new CustomEvent('validation-failure', { bubbles
: true }));
283 this.field
.removeAttribute('data-tooltip');
284 this.field
.removeAttribute('data-tooltip-style');
285 this.field
.dispatchEvent(new CustomEvent('validation-success', { bubbles
: true }));
292 integer: function() {
293 return this.assert(Int(this.value
) !== NaN
, _('valid integer value'));
296 uinteger: function() {
297 return this.assert(Int(this.value
) >= 0, _('positive integer value'));
301 return this.assert(Dec(this.value
) !== NaN
, _('valid decimal value'));
305 return this.assert(Dec(this.value
) >= 0, _('positive decimal value'));
308 ipaddr: function(nomask
) {
309 return this.assert(this.apply('ip4addr', null, [nomask
]) || this.apply('ip6addr', null, [nomask
]),
310 nomask
? _('valid IP address') : _('valid IP address or prefix'));
313 ip4addr: function(nomask
) {
314 var re
= nomask
? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
315 m
= this.value
.match(re
);
317 return this.assert(m
&& IPv4(m
[1]) && (m
[2] ? IPv4(m
[2]) : (m
[3] ? this.apply('ip4prefix', m
[3]) : true)),
318 nomask
? _('valid IPv4 address') : _('valid IPv4 address or network'));
321 ip6addr: function(nomask
) {
322 var re
= nomask
? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
323 m
= this.value
.match(re
);
325 return this.assert(m
&& IPv6(m
[1]) && (m
[2] ? this.apply('ip6prefix', m
[2]) : true),
326 nomask
? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
329 ip4prefix: function() {
330 return this.assert(!isNaN(this.value
) && this.value
>= 0 && this.value
<= 32,
331 _('valid IPv4 prefix value (0-32)'));
334 ip6prefix: function() {
335 return this.assert(!isNaN(this.value
) && this.value
>= 0 && this.value
<= 128,
336 _('valid IPv6 prefix value (0-128)'));
340 return this.assert(this.apply('cidr4') || this.apply('cidr6'), _('valid IPv4 or IPv6 CIDR'));
344 var m
= this.value
.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
345 return this.assert(m
&& IPv4(m
[1]) && this.apply('ip4prefix', m
[2]), _('valid IPv4 CIDR'));
349 var m
= this.value
.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
350 return this.assert(m
&& IPv6(m
[1]) && this.apply('ip6prefix', m
[2]), _('valid IPv6 CIDR'));
354 var m
= this.value
.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
355 return this.assert(m
&& IPv4(m
[1]) && IPv4(m
[2]), _('IPv4 network in address/netmask notation'));
359 var m
= this.value
.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
360 return this.assert(m
&& IPv6(m
[1]) && IPv6(m
[2]), _('IPv6 network in address/netmask notation'));
363 ip6hostid: function() {
364 if (this.value
== "eui64" || this.value
== "random")
367 var v6
= IPv6(this.value
);
368 return this.assert(!(!v6
|| v6
[0] || v6
[1] || v6
[2] || v6
[3]), _('valid IPv6 host id'));
372 return this.assert(this.apply('ipmask4') || this.apply('ipmask6'),
373 _('valid network in address/netmask notation'));
376 ipmask4: function() {
377 return this.assert(this.apply('cidr4') || this.apply('ipnet4') || this.apply('ip4addr'),
378 _('valid IPv4 network'));
381 ipmask6: function() {
382 return this.assert(this.apply('cidr6') || this.apply('ipnet6') || this.apply('ip6addr'),
383 _('valid IPv6 network'));
387 var p
= Int(this.value
);
388 return this.assert(p
>= 0 && p
<= 65535, _('valid port value'));
391 portrange: function() {
392 if (this.value
.match(/^(\d+)-(\d+)$/)) {
395 return this.assert(p1
<= p2
&& p2
<= 65535,
396 _('valid port or port range (port1-port2)'));
399 return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
402 macaddr: function() {
403 return this.assert(this.value
.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null,
404 _('valid MAC address'));
407 host: function(ipv4only
) {
408 return this.assert(this.apply('hostname') || this.apply(ipv4only
== 1 ? 'ip4addr' : 'ipaddr'),
409 _('valid hostname or IP address'));
412 hostname: function(strict
) {
413 if (this.value
.length
<= 253)
415 (this.value
.match(/^[a-zA-Z0-9_]+$/) != null ||
416 (this.value
.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
417 this.value
.match(/[^0-9.]/))) &&
418 (!strict
|| !this.value
.match(/^_/)),
419 _('valid hostname'));
421 return this.assert(false, _('valid hostname'));
424 network: function() {
425 return this.assert(this.apply('uciname') || this.apply('host'),
426 _('valid UCI identifier, hostname or IP address'));
429 hostport: function(ipv4only
) {
430 var hp
= this.value
.split(/:/);
431 return this.assert(hp
.length
== 2 && this.apply('host', hp
[0], [ipv4only
]) && this.apply('port', hp
[1]),
432 _('valid host:port'));
435 ip4addrport: function() {
436 var hp
= this.value
.split(/:/);
437 return this.assert(hp
.length
== 2 && this.apply('ip4addr', hp
[0], [true]) && this.apply('port', hp
[1]),
438 _('valid IPv4 address:port'));
441 ipaddrport: function(bracket
) {
442 var m4
= this.value
.match(/^([^\[\]:]+):(\d+)$/),
443 m6
= this.value
.match((bracket
== 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
446 return this.assert(this.apply('ip4addr', m4
[1], [true]) && this.apply('port', m4
[2]),
447 _('valid address:port'));
449 return this.assert(m6
&& this.apply('ip6addr', m6
[1], [true]) && this.apply('port', m6
[2]),
450 _('valid address:port'));
457 return this.assert(v
.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
459 return this.assert((v
.length
>= 8) && (v
.length
<= 63), _('key between 8 and 63 characters'));
465 if (v
.substr(0, 2) === 's:')
468 if ((v
.length
== 10) || (v
.length
== 26))
469 return this.assert(v
.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
471 return this.assert((v
.length
=== 5) || (v
.length
=== 13), _('key with either 5 or 13 characters'));
474 uciname: function() {
475 return this.assert(this.value
.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
478 range: function(min
, max
) {
479 var val
= Dec(this.value
);
480 return this.assert(val
>= +min
&& val
<= +max
, _('value between %f and %f').format(min
, max
));
484 return this.assert(Dec(this.value
) >= +min
, _('value greater or equal to %f').format(min
));
488 return this.assert(Dec(this.value
) <= +max
, _('value smaller or equal to %f').format(max
));
491 rangelength: function(min
, max
) {
492 var val
= '' + this.value
;
493 return this.assert((val
.length
>= +min
) && (val
.length
<= +max
),
494 _('value between %d and %d characters').format(min
, max
));
497 minlength: function(min
) {
498 return this.assert((''+this.value
).length
>= +min
,
499 _('value with at least %d characters').format(min
));
502 maxlength: function(max
) {
503 return this.assert((''+this.value
).length
<= +max
,
504 _('value with at most %d characters').format(max
));
510 for (var i
= 0; i
< arguments
.length
; i
+= 2) {
511 if (typeof arguments
[i
] != 'function') {
512 if (arguments
[i
] == this.value
)
513 return this.assert(true);
514 errors
.push('"%s"'.format(arguments
[i
]));
517 else if (arguments
[i
].apply(this, arguments
[i
+1])) {
518 return this.assert(true);
521 errors
.push(this.error
);
525 return this.assert(false, _('one of:\n - %s'.format(errors
.join('\n - '))));
529 for (var i
= 0; i
< arguments
.length
; i
+= 2) {
530 if (typeof arguments
[i
] != 'function') {
531 if (arguments
[i
] != this.value
)
532 return this.assert(false, '"%s"'.format(arguments
[i
]));
535 else if (!arguments
[i
].apply(this, arguments
[i
+1])) {
536 return this.assert(false, this.error
);
540 return this.assert(true);
544 return this.apply('or', this.value
.replace(/^[ \t]*![ \t]*/, ''), arguments
);
547 list: function(subvalidator
, subargs
) {
548 this.field
.setAttribute('data-is-list', 'true');
550 var tokens
= this.value
.match(/[^ \t]+/g);
551 for (var i
= 0; i
< tokens
.length
; i
++)
552 if (!this.apply(subvalidator
, tokens
[i
], subargs
))
553 return this.assert(false, this.error
);
555 return this.assert(true);
558 phonedigit: function() {
559 return this.assert(this.value
.match(/^[0-9\*#!\.]+$/),
560 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
563 timehhmmss: function() {
564 return this.assert(this.value
.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
565 _('valid time (HH:MM:SS)'));
568 dateyyyymmdd: function() {
569 if (this.value
.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
570 var year
= +RegExp
.$1,
573 days_in_month
= [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
575 function is_leap_year(year
) {
576 return ((!(year
% 4) && (year
% 100)) || !(year
% 400));
579 function get_days_in_month(month
, year
) {
580 return (month
=== 2 && is_leap_year(year
)) ? 29 : days_in_month
[month
- 1];
583 /* Firewall rules in the past don't make sense */
584 return this.assert(year
>= 2015 && month
&& month
<= 12 && day
&& day
<= get_days_in_month(month
, year
),
585 _('valid date (YYYY-MM-DD)'));
589 return this.assert(false, _('valid date (YYYY-MM-DD)'));
592 unique: function(subvalidator
, subargs
) {
594 option
= findParent(ctx
.field
, '[data-type][data-name]'),
595 section
= findParent(option
, '.cbi-section'),
596 query
= '[data-type="%s"][data-name="%s"]'.format(option
.getAttribute('data-type'), option
.getAttribute('data-name')),
599 section
.querySelectorAll(query
).forEach(function(sibling
) {
600 if (sibling
=== option
)
603 var input
= sibling
.querySelector('[data-type]'),
604 values
= input
? (input
.getAttribute('data-is-list') ? input
.value
.match(/[^ \t]+/g) : [ input
.value
]) : null;
606 if (values
!== null && values
.indexOf(ctx
.value
) !== -1)
611 return this.assert(false, _('unique value'));
613 if (typeof(subvalidator
) === 'function')
614 return this.apply(subvalidator
, undefined, subargs
);
616 return this.assert(true);
619 hexstring: function() {
620 return this.assert(this.value
.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
621 _('hexadecimal encoded value'));
626 function CBIValidator(field
, type
, optional
)
629 this.optional
= optional
;
630 this.vstack
= this.compile(type
);
633 CBIValidator
.prototype = CBIValidatorPrototype
;
636 function cbi_d_add(field
, dep
, index
) {
637 var obj
= (typeof(field
) === 'string') ? document
.getElementById(field
) : field
;
640 for (var i
=0; i
<cbi_d
.length
; i
++) {
641 if (cbi_d
[i
].id
== obj
.id
) {
650 "parent": obj
.parentNode
.id
,
654 cbi_d
.unshift(entry
);
660 function cbi_d_checkvalue(target
, ref
) {
662 query
= 'input[id="'+target
+'"], input[name="'+target
+'"], ' +
663 'select[id="'+target
+'"], select[name="'+target
+'"]';
665 document
.querySelectorAll(query
).forEach(function(i
) {
666 if (value
=== null && ((i
.type
!== 'radio' && i
.type
!== 'checkbox') || i
.checked
=== true))
670 return (((value
!== null) ? value
: "") == ref
);
673 function cbi_d_check(deps
) {
676 for (var i
=0; i
<deps
.length
; i
++) {
679 for (var j
in deps
[i
]) {
680 if (j
== "!reverse") {
682 } else if (j
== "!default") {
686 istat
= (istat
&& cbi_d_checkvalue(j
, deps
[i
][j
]))
690 if (istat
^ reverse
) {
697 function cbi_d_update() {
699 for (var i
=0; i
<cbi_d
.length
; i
++) {
700 var entry
= cbi_d
[i
];
701 var node
= document
.getElementById(entry
.id
);
702 var parent
= document
.getElementById(entry
.parent
);
704 if (node
&& node
.parentNode
&& !cbi_d_check(entry
.deps
)) {
705 node
.parentNode
.removeChild(node
);
708 else if (parent
&& (!node
|| !node
.parentNode
) && cbi_d_check(entry
.deps
)) {
709 var next
= undefined;
711 for (next
= parent
.firstChild
; next
; next
= next
.nextSibling
) {
712 if (next
.getAttribute
&& parseInt(next
.getAttribute('data-index'), 10) > entry
.index
)
717 parent
.appendChild(entry
.node
);
719 parent
.insertBefore(entry
.node
, next
);
724 // hide optionals widget if no choices remaining
725 if (parent
&& parent
.parentNode
&& parent
.getAttribute('data-optionals'))
726 parent
.parentNode
.style
.display
= (parent
.options
.length
<= 1) ? 'none' : '';
729 if (entry
&& entry
.parent
)
730 cbi_tag_last(parent
);
735 parent
.dispatchEvent(new CustomEvent('dependency-update', { bubbles
: true }));
738 function cbi_init() {
741 document
.querySelectorAll('.cbi-dropdown').forEach(function(node
) {
742 cbi_dropdown_init(node
);
743 node
.addEventListener('cbi-dropdown-change', cbi_d_update
);
746 nodes
= document
.querySelectorAll('[data-strings]');
748 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
749 var str
= JSON
.parse(node
.getAttribute('data-strings'));
750 for (var key
in str
) {
751 for (var key2
in str
[key
]) {
752 var dst
= cbi_strings
[key
] || (cbi_strings
[key
] = { });
753 dst
[key2
] = str
[key
][key2
];
758 nodes
= document
.querySelectorAll('[data-depends]');
760 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
761 var index
= parseInt(node
.getAttribute('data-index'), 10);
762 var depends
= JSON
.parse(node
.getAttribute('data-depends'));
763 if (!isNaN(index
) && depends
.length
> 0) {
764 for (var alt
= 0; alt
< depends
.length
; alt
++)
765 cbi_d_add(node
, depends
[alt
], index
);
769 nodes
= document
.querySelectorAll('[data-update]');
771 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
772 var events
= node
.getAttribute('data-update').split(' ');
773 for (var j
= 0, event
; (event
= events
[j
]) !== undefined; j
++)
774 node
.addEventListener(event
, cbi_d_update
);
777 nodes
= document
.querySelectorAll('[data-choices]');
779 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
780 var choices
= JSON
.parse(node
.getAttribute('data-choices')),
783 for (var j
= 0; j
< choices
[0].length
; j
++)
784 options
[choices
[0][j
]] = choices
[1][j
];
786 var def
= (node
.getAttribute('data-optional') === 'true')
787 ? node
.placeholder
|| '' : null;
789 var cb
= new L
.ui
.Combobox(node
.value
, options
, {
790 name
: node
.getAttribute('name'),
792 select_placeholder
: def
|| _('-- Please choose --'),
793 custom_placeholder
: node
.getAttribute('data-manual') || _('-- custom --')
797 n
.addEventListener('cbi-dropdown-change', cbi_d_update
);
798 node
.parentNode
.replaceChild(n
, node
);
801 nodes
= document
.querySelectorAll('[data-dynlist]');
803 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
804 var choices
= JSON
.parse(node
.getAttribute('data-dynlist')),
805 values
= JSON
.parse(node
.getAttribute('data-values') || '[]'),
808 if (choices
[0] && choices
[0].length
) {
811 for (var j
= 0; j
< choices
[0].length
; j
++)
812 options
[choices
[0][j
]] = choices
[1][j
];
815 var dl
= new L
.ui
.DynamicList(values
, options
, {
816 name
: node
.getAttribute('data-prefix'),
818 datatype
: choices
[2],
819 optional
: choices
[3],
820 placeholder
: node
.getAttribute('data-placeholder')
824 n
.addEventListener('cbi-dynlist-change', cbi_d_update
);
825 node
.parentNode
.replaceChild(n
, node
);
828 nodes
= document
.querySelectorAll('[data-type]');
830 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
831 cbi_validate_field(node
, node
.getAttribute('data-optional') === 'true',
832 node
.getAttribute('data-type'));
835 document
.querySelectorAll('[data-browser]').forEach(cbi_browser_init
);
837 document
.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s
) {
838 s
.parentNode
.classList
.add('cbi-tooltip-container');
841 document
.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i
) {
842 var handler = function(ev
) {
843 var bits
= this.name
.split(/\./),
844 section
= document
.getElementById('cbi-' + bits
[2] + '-' + bits
[3]);
846 section
.style
.opacity
= (ev
.type
=== 'mouseover') ? 0.5 : '';
849 i
.addEventListener('mouseover', handler
);
850 i
.addEventListener('mouseout', handler
);
856 function cbi_filebrowser(id
, defpath
) {
857 var field
= L
.dom
.elem(id
) ? id
: document
.getElementById(id
);
858 var browser
= window
.open(
859 cbi_strings
.path
.browser
+ (field
.value
|| defpath
|| '') + '?field=' + field
.id
,
860 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
866 function cbi_browser_init(field
)
868 field
.parentNode
.insertBefore(
870 'src': L
.resource('cbi/folder.gif'),
871 'class': 'cbi-image-button',
872 'click': function(ev
) {
873 cbi_filebrowser(field
, field
.getAttribute('data-browser'));
876 }), field
.nextSibling
);
879 function cbi_validate_form(form
, errmsg
)
881 /* if triggered by a section removal or addition, don't validate */
882 if (form
.cbi_state
== 'add-section' || form
.cbi_state
== 'del-section')
885 if (form
.cbi_validators
) {
886 for (var i
= 0; i
< form
.cbi_validators
.length
; i
++) {
887 var validator
= form
.cbi_validators
[i
];
889 if (!validator() && errmsg
) {
899 function cbi_validate_reset(form
)
902 function() { cbi_validate_form(form
, null) }, 100
908 function cbi_validate_field(cbid
, optional
, type
)
910 var field
= isElem(cbid
) ? cbid
: document
.getElementById(cbid
);
914 var cbiValidator
= new CBIValidator(field
, type
, optional
);
915 validatorFn
= cbiValidator
.validate
.bind(cbiValidator
);
921 if (validatorFn
!== null) {
922 var form
= findParent(field
, 'form');
924 if (!form
.cbi_validators
)
925 form
.cbi_validators
= [ ];
927 form
.cbi_validators
.push(validatorFn
);
929 field
.addEventListener("blur", validatorFn
);
930 field
.addEventListener("keyup", validatorFn
);
931 field
.addEventListener("cbi-dropdown-change", validatorFn
);
933 if (matchesElem(field
, 'select')) {
934 field
.addEventListener("change", validatorFn
);
935 field
.addEventListener("click", validatorFn
);
942 function cbi_row_swap(elem
, up
, store
)
944 var tr
= findParent(elem
.parentNode
, '.cbi-section-table-row');
949 tr
.classList
.remove('flash');
952 var prev
= tr
.previousElementSibling
;
954 if (prev
&& prev
.classList
.contains('cbi-section-table-row'))
955 tr
.parentNode
.insertBefore(tr
, prev
);
960 var next
= tr
.nextElementSibling
? tr
.nextElementSibling
.nextElementSibling
: null;
962 if (next
&& next
.classList
.contains('cbi-section-table-row'))
963 tr
.parentNode
.insertBefore(tr
, next
);
965 tr
.parentNode
.appendChild(tr
);
972 for (var i
= 0, n
= 0; i
< tr
.parentNode
.childNodes
.length
; i
++) {
973 var node
= tr
.parentNode
.childNodes
[i
];
974 if (node
.classList
&& node
.classList
.contains('cbi-section-table-row')) {
975 node
.classList
.remove('cbi-rowstyle-1');
976 node
.classList
.remove('cbi-rowstyle-2');
977 node
.classList
.add((n
++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
979 if (/-([^\-]+)$/.test(node
.id
))
984 var input
= document
.getElementById(store
);
986 input
.value
= ids
.join(' ');
988 window
.scrollTo(0, tr
.offsetTop
);
990 tr
.classList
.add('flash');
995 function cbi_tag_last(container
)
999 for (var i
= 0; i
< container
.childNodes
.length
; i
++) {
1000 var c
= container
.childNodes
[i
];
1001 if (matchesElem(c
, 'div')) {
1002 c
.classList
.remove('cbi-value-last');
1008 last
.classList
.add('cbi-value-last');
1011 function cbi_submit(elem
, name
, value
, action
)
1013 var form
= elem
.form
|| findParent(elem
, 'form');
1019 form
.action
= action
;
1022 var hidden
= form
.querySelector('input[type="hidden"][name="%s"]'.format(name
)) ||
1023 E('input', { type
: 'hidden', name
: name
});
1025 hidden
.value
= value
|| '1';
1026 form
.appendChild(hidden
);
1033 String
.prototype.format = function()
1038 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1039 var quot_esc = [/"/g
, '"', /'/g, '''];
1041 function esc(s, r) {
1042 if (typeof(s) !== 'string
' && !(s instanceof String))
1045 for (var i = 0; i < r.length; i += 2)
1046 s = s.replace(r[i], r[i+1]);
1053 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
1054 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
1056 while (a
= re
.exec(str
)) {
1058 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
1059 var pPrecision
= a
[6], pType
= a
[7];
1067 if (numSubstitutions
< arguments
.length
) {
1068 var param
= arguments
[numSubstitutions
++];
1071 if (pPad
&& pPad
.substr(0,1) == "'")
1072 pad
= leftpart
.substr(1,1);
1078 var justifyRight
= true;
1079 if (pJustify
&& pJustify
=== "-")
1080 justifyRight
= false;
1084 minLength
= +pMinLength
;
1087 if (pPrecision
&& pType
== 'f')
1088 precision
= +pPrecision
.substring(1);
1094 subst
= (+param
|| 0).toString(2);
1098 subst
= String
.fromCharCode(+param
|| 0);
1102 subst
= ~~(+param
|| 0);
1106 subst
= ~~Math
.abs(+param
|| 0);
1110 subst
= (precision
> -1)
1111 ? ((+param
|| 0.0)).toFixed(precision
)
1116 subst
= (+param
|| 0).toString(8);
1124 subst
= ('' + (+param
|| 0).toString(16)).toLowerCase();
1128 subst
= ('' + (+param
|| 0).toString(16)).toUpperCase();
1132 subst
= esc(param
, html_esc
);
1136 subst
= esc(param
, quot_esc
);
1143 var ts
= (param
|| 0);
1146 tm
= Math
.floor(ts
/ 60);
1151 th
= Math
.floor(tm
/ 60);
1156 td
= Math
.floor(th
/ 24);
1161 ? String
.format('%dd %dh %dm %ds', td
, th
, tm
, ts
)
1162 : String
.format('%dh %dm %ds', th
, tm
, ts
);
1167 var mf
= pMinLength
? +pMinLength
: 1000;
1168 var pr
= pPrecision
? ~~(10 * +('0' + pPrecision
)) : 2;
1171 var val
= (+param
|| 0);
1172 var units
= [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1174 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
1177 subst
= (i
? val
.toFixed(pr
) : val
) + units
[i
];
1185 subst
= subst
.toString();
1186 for (var i
= subst
.length
; i
< pMinLength
; i
++)
1187 if (pJustify
== '-')
1188 subst
= subst
+ ' ';
1190 subst
= pad
+ subst
;
1193 out
+= leftpart
+ subst
;
1194 str
= str
.substr(m
.length
);
1200 String
.prototype.nobr = function()
1202 return this.replace(/[\s\n]+/g, ' ');
1205 String
.format = function()
1209 for (var i
= 1; i
< arguments
.length
; i
++)
1210 a
.push(arguments
[i
]);
1212 return ''.format
.apply(arguments
[0], a
);
1215 String
.nobr = function()
1219 for (var i
= 1; i
< arguments
.length
; i
++)
1220 a
.push(arguments
[i
]);
1222 return ''.nobr
.apply(arguments
[0], a
);
1225 if (window
.NodeList
&& !NodeList
.prototype.forEach
) {
1226 NodeList
.prototype.forEach = function (callback
, thisArg
) {
1227 thisArg
= thisArg
|| window
;
1228 for (var i
= 0; i
< this.length
; i
++) {
1229 callback
.call(thisArg
, this[i
], i
, this);
1234 if (!window
.requestAnimationFrame
) {
1235 window
.requestAnimationFrame = function(f
) {
1236 window
.setTimeout(function() {
1237 f(new Date().getTime())
1243 function isElem(e
) { return L
.dom
.elem(e
) }
1244 function toElem(s
) { return L
.dom
.parse(s
) }
1245 function matchesElem(node
, selector
) { return L
.dom
.matches(node
, selector
) }
1246 function findParent(node
, selector
) { return L
.dom
.parent(node
, selector
) }
1247 function E() { return L
.dom
.create
.apply(L
.dom
, arguments
) }
1249 if (typeof(window
.CustomEvent
) !== 'function') {
1250 function CustomEvent(event
, params
) {
1251 params
= params
|| { bubbles
: false, cancelable
: false, detail
: undefined };
1252 var evt
= document
.createEvent('CustomEvent');
1253 evt
.initCustomEvent( event
, params
.bubbles
, params
.cancelable
, params
.detail
);
1257 CustomEvent
.prototype = window
.Event
.prototype;
1258 window
.CustomEvent
= CustomEvent
;
1261 function cbi_dropdown_init(sb
) {
1262 var dl
= new L
.ui
.Dropdown(sb
, null, { name
: sb
.getAttribute('name') });
1266 function cbi_update_table(table
, data
, placeholder
) {
1267 var target
= isElem(table
) ? table
: document
.querySelector(table
);
1269 if (!isElem(target
))
1272 target
.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead
) {
1275 thead
.querySelectorAll('.th').forEach(function(th
) {
1279 if (Array
.isArray(data
)) {
1280 var n
= 0, rows
= target
.querySelectorAll('.tr');
1282 data
.forEach(function(row
) {
1283 var trow
= E('div', { 'class': 'tr' });
1285 for (var i
= 0; i
< titles
.length
; i
++) {
1286 var text
= (titles
[i
].innerText
|| '').trim();
1287 var td
= trow
.appendChild(E('div', {
1288 'class': titles
[i
].className
,
1289 'data-title': (text
!== '') ? text
: null
1292 td
.classList
.remove('th');
1293 td
.classList
.add('td');
1296 trow
.classList
.add('cbi-rowstyle-%d'.format((n
++ % 2) ? 2 : 1));
1299 target
.replaceChild(trow
, rows
[n
]);
1301 target
.appendChild(trow
);
1305 target
.removeChild(rows
[n
]);
1307 if (placeholder
&& target
.firstElementChild
=== target
.lastElementChild
) {
1308 var trow
= target
.appendChild(E('div', { 'class': 'tr placeholder' }));
1309 var td
= trow
.appendChild(E('div', { 'class': titles
[0].className
}, placeholder
));
1311 td
.classList
.remove('th');
1312 td
.classList
.add('td');
1316 thead
.parentNode
.style
.display
= 'none';
1318 thead
.parentNode
.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow
) {
1319 if (trow
!== thead
) {
1321 trow
.querySelectorAll('.th, .td').forEach(function(td
) {
1322 if (n
< titles
.length
) {
1323 var text
= (titles
[n
++].innerText
|| '').trim();
1325 td
.setAttribute('data-title', text
);
1331 thead
.parentNode
.style
.display
= '';
1336 function showModal(title
, children
)
1338 return L
.showModal(title
, children
);
1341 function hideModal()
1343 return L
.hideModal();
1347 document
.addEventListener('DOMContentLoaded', function() {
1348 document
.addEventListener('validation-failure', function(ev
) {
1349 if (ev
.target
=== document
.activeElement
)
1353 document
.addEventListener('validation-success', function(ev
) {
1354 if (ev
.target
=== document
.activeElement
)
1358 document
.querySelectorAll('.table').forEach(cbi_update_table
);