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
, 'form'))
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
[0], [true]) && this.apply('port', m4
[1]),
447 _('valid address:port'));
449 return this.assert(m6
&& this.apply('ip6addr', m6
[0], [true]) && this.apply('port', m6
[1]),
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 nodes
= document
.querySelectorAll('[data-strings]');
743 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
744 var str
= JSON
.parse(node
.getAttribute('data-strings'));
745 for (var key
in str
) {
746 for (var key2
in str
[key
]) {
747 var dst
= cbi_strings
[key
] || (cbi_strings
[key
] = { });
748 dst
[key2
] = str
[key
][key2
];
753 nodes
= document
.querySelectorAll('[data-depends]');
755 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
756 var index
= parseInt(node
.getAttribute('data-index'), 10);
757 var depends
= JSON
.parse(node
.getAttribute('data-depends'));
758 if (!isNaN(index
) && depends
.length
> 0) {
759 for (var alt
= 0; alt
< depends
.length
; alt
++)
760 cbi_d_add(node
, depends
[alt
], index
);
764 nodes
= document
.querySelectorAll('[data-update]');
766 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
767 var events
= node
.getAttribute('data-update').split(' ');
768 for (var j
= 0, event
; (event
= events
[j
]) !== undefined; j
++)
769 node
.addEventListener(event
, cbi_d_update
);
772 nodes
= document
.querySelectorAll('[data-choices]');
774 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
775 var choices
= JSON
.parse(node
.getAttribute('data-choices'));
778 for (var j
= 0; j
< choices
[0].length
; j
++)
779 options
[choices
[0][j
]] = choices
[1][j
];
781 var def
= (node
.getAttribute('data-optional') === 'true')
782 ? node
.placeholder
|| '' : null;
784 cbi_combobox_init(node
, options
, def
,
785 node
.getAttribute('data-manual'));
788 nodes
= document
.querySelectorAll('[data-dynlist]');
790 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
791 var choices
= JSON
.parse(node
.getAttribute('data-dynlist'));
794 if (choices
[0] && choices
[0].length
) {
797 for (var j
= 0; j
< choices
[0].length
; j
++)
798 options
[choices
[0][j
]] = choices
[1][j
];
801 cbi_dynlist_init(node
, choices
[2], choices
[3], options
);
804 nodes
= document
.querySelectorAll('[data-type]');
806 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
807 cbi_validate_field(node
, node
.getAttribute('data-optional') === 'true',
808 node
.getAttribute('data-type'));
811 document
.querySelectorAll('.cbi-dropdown').forEach(cbi_dropdown_init
);
812 document
.querySelectorAll('[data-browser]').forEach(cbi_browser_init
);
814 document
.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s
) {
815 s
.parentNode
.classList
.add('cbi-tooltip-container');
818 document
.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i
) {
819 var handler = function(ev
) {
820 var bits
= this.name
.split(/\./),
821 section
= document
.getElementById('cbi-' + bits
[2] + '-' + bits
[3]);
823 section
.style
.opacity
= (ev
.type
=== 'mouseover') ? 0.5 : '';
826 i
.addEventListener('mouseover', handler
);
827 i
.addEventListener('mouseout', handler
);
833 function cbi_combobox_init(id
, values
, def
, man
) {
834 var obj
= (typeof(id
) === 'string') ? document
.getElementById(id
) : id
;
837 'class': 'cbi-dropdown',
839 'optional': obj
.getAttribute('data-optional'),
840 'placeholder': _('-- Please choose --'),
841 'data-type': obj
.getAttribute('data-type'),
842 'data-optional': obj
.getAttribute('data-optional')
845 if (!(obj
.value
in values
) && obj
.value
.length
) {
846 sb
.lastElementChild
.appendChild(E('li', {
847 'data-value': obj
.value
,
849 }, obj
.value
.length
? obj
.value
: (def
|| _('-- Please choose --'))));
852 for (var i
in values
) {
853 sb
.lastElementChild
.appendChild(E('li', {
855 'selected': (i
== obj
.value
) ? '' : null
859 sb
.lastElementChild
.appendChild(E('li', { 'data-value': '-' }, [
862 'class': 'create-item-input',
863 'data-type': obj
.getAttribute('data-type'),
864 'data-optional': true,
865 'placeholder': (man
|| _('-- custom --'))
869 sb
.value
= obj
.value
;
870 obj
.parentNode
.replaceChild(sb
, obj
);
873 function cbi_filebrowser(id
, defpath
) {
874 var field
= L
.dom
.elem(id
) ? id
: document
.getElementById(id
);
875 var browser
= window
.open(
876 cbi_strings
.path
.browser
+ (field
.value
|| defpath
|| '') + '?field=' + field
.id
,
877 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
883 function cbi_browser_init(field
)
885 field
.parentNode
.insertBefore(
887 'src': L
.resource('cbi/folder.gif'),
888 'class': 'cbi-image-button',
889 'click': function(ev
) {
890 cbi_filebrowser(field
, field
.getAttribute('data-browser'));
893 }), field
.nextSibling
);
897 addItem: function(dl
, value
, text
, flash
) {
899 new_item
= E('div', { 'class': flash
? 'item flash' : 'item', 'tabindex': 0 }, [
900 E('span', {}, text
|| value
),
903 'name': dl
.getAttribute('data-prefix'),
906 dl
.querySelectorAll('.item, .add-item').forEach(function(item
) {
910 var hidden
= item
.querySelector('input[type="hidden"]');
912 if (hidden
&& hidden
.value
=== value
)
914 else if (!hidden
|| hidden
.value
>= value
)
915 exists
= !!item
.parentNode
.insertBefore(new_item
, item
);
921 removeItem: function(dl
, item
) {
922 var sb
= dl
.querySelector('.cbi-dropdown');
924 var value
= item
.querySelector('input[type="hidden"]').value
;
926 sb
.querySelectorAll('ul > li').forEach(function(li
) {
927 if (li
.getAttribute('data-value') === value
)
928 li
.removeAttribute('unselectable');
932 item
.parentNode
.removeChild(item
);
936 handleClick: function(ev
) {
937 var dl
= ev
.currentTarget
,
938 item
= findParent(ev
.target
, '.item');
941 this.removeItem(dl
, item
);
943 else if (matchesElem(ev
.target
, '.cbi-button-add')) {
944 var input
= ev
.target
.previousElementSibling
;
945 if (input
.value
.length
&& !input
.classList
.contains('cbi-input-invalid')) {
946 this.addItem(dl
, input
.value
, null, true);
952 handleDropdownChange: function(ev
) {
953 var dl
= ev
.currentTarget
,
954 sbIn
= ev
.detail
.instance
,
955 sbEl
= ev
.detail
.element
,
956 sbVal
= ev
.detail
.value
;
961 sbIn
.setValues(sbEl
, null);
962 sbVal
.element
.setAttribute('unselectable', '');
964 this.addItem(dl
, sbVal
.value
, sbVal
.text
, true);
967 handleKeydown: function(ev
) {
968 var dl
= ev
.currentTarget
,
969 item
= findParent(ev
.target
, '.item');
972 switch (ev
.keyCode
) {
973 case 8: /* backspace */
974 if (item
.previousElementSibling
)
975 item
.previousElementSibling
.focus();
977 this.removeItem(dl
, item
);
980 case 46: /* delete */
981 if (item
.nextElementSibling
) {
982 if (item
.nextElementSibling
.classList
.contains('item'))
983 item
.nextElementSibling
.focus();
985 item
.nextElementSibling
.firstElementChild
.focus();
988 this.removeItem(dl
, item
);
992 else if (matchesElem(ev
.target
, '.cbi-input-text')) {
993 switch (ev
.keyCode
) {
995 if (ev
.target
.value
.length
&& !ev
.target
.classList
.contains('cbi-input-invalid')) {
996 this.addItem(dl
, ev
.target
.value
, null, true);
997 ev
.target
.value
= '';
1002 ev
.preventDefault();
1009 function cbi_dynlist_init(dl
, datatype
, optional
, choices
)
1011 if (!(this instanceof cbi_dynlist_init
))
1012 return new cbi_dynlist_init(dl
, datatype
, optional
, choices
);
1014 dl
.classList
.add('cbi-dynlist');
1015 dl
.appendChild(E('div', { 'class': 'add-item' }, E('input', {
1017 'name': 'cbi.dynlist.' + dl
.getAttribute('data-prefix'),
1018 'class': 'cbi-input-text',
1019 'placeholder': dl
.getAttribute('data-placeholder'),
1020 'data-type': datatype
,
1021 'data-optional': true
1025 cbi_combobox_init(dl
.lastElementChild
.lastElementChild
, choices
, '', _('-- custom --'));
1027 dl
.lastElementChild
.appendChild(E('div', { 'class': 'cbi-button cbi-button-add' }, '+'));
1029 dl
.addEventListener('click', this.handleClick
.bind(this));
1030 dl
.addEventListener('keydown', this.handleKeydown
.bind(this));
1031 dl
.addEventListener('cbi-dropdown-change', this.handleDropdownChange
.bind(this));
1034 var values
= JSON
.parse(dl
.getAttribute('data-values') || '[]');
1036 if (typeof(values
) === 'object' && Array
.isArray(values
))
1037 for (var i
= 0; i
< values
.length
; i
++)
1038 this.addItem(dl
, values
[i
], choices
? choices
[values
[i
]] : null);
1043 cbi_dynlist_init
.prototype = CBIDynamicList
;
1046 function cbi_validate_form(form
, errmsg
)
1048 /* if triggered by a section removal or addition, don't validate */
1049 if (form
.cbi_state
== 'add-section' || form
.cbi_state
== 'del-section')
1052 if (form
.cbi_validators
) {
1053 for (var i
= 0; i
< form
.cbi_validators
.length
; i
++) {
1054 var validator
= form
.cbi_validators
[i
];
1056 if (!validator() && errmsg
) {
1066 function cbi_validate_reset(form
)
1069 function() { cbi_validate_form(form
, null) }, 100
1075 function cbi_validate_field(cbid
, optional
, type
)
1077 var field
= isElem(cbid
) ? cbid
: document
.getElementById(cbid
);
1081 var cbiValidator
= new CBIValidator(field
, type
, optional
);
1082 validatorFn
= cbiValidator
.validate
.bind(cbiValidator
);
1088 if (validatorFn
!== null) {
1089 var form
= findParent(field
, 'form');
1091 if (!form
.cbi_validators
)
1092 form
.cbi_validators
= [ ];
1094 form
.cbi_validators
.push(validatorFn
);
1096 field
.addEventListener("blur", validatorFn
);
1097 field
.addEventListener("keyup", validatorFn
);
1098 field
.addEventListener("cbi-dropdown-change", validatorFn
);
1100 if (matchesElem(field
, 'select')) {
1101 field
.addEventListener("change", validatorFn
);
1102 field
.addEventListener("click", validatorFn
);
1109 function cbi_row_swap(elem
, up
, store
)
1111 var tr
= findParent(elem
.parentNode
, '.cbi-section-table-row');
1116 tr
.classList
.remove('flash');
1119 var prev
= tr
.previousElementSibling
;
1121 if (prev
&& prev
.classList
.contains('cbi-section-table-row'))
1122 tr
.parentNode
.insertBefore(tr
, prev
);
1127 var next
= tr
.nextElementSibling
? tr
.nextElementSibling
.nextElementSibling
: null;
1129 if (next
&& next
.classList
.contains('cbi-section-table-row'))
1130 tr
.parentNode
.insertBefore(tr
, next
);
1132 tr
.parentNode
.appendChild(tr
);
1139 for (var i
= 0, n
= 0; i
< tr
.parentNode
.childNodes
.length
; i
++) {
1140 var node
= tr
.parentNode
.childNodes
[i
];
1141 if (node
.classList
&& node
.classList
.contains('cbi-section-table-row')) {
1142 node
.classList
.remove('cbi-rowstyle-1');
1143 node
.classList
.remove('cbi-rowstyle-2');
1144 node
.classList
.add((n
++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1146 if (/-([^\-]+)$/.test(node
.id
))
1147 ids
.push(RegExp
.$1);
1151 var input
= document
.getElementById(store
);
1153 input
.value
= ids
.join(' ');
1155 window
.scrollTo(0, tr
.offsetTop
);
1156 void tr
.offsetWidth
;
1157 tr
.classList
.add('flash');
1162 function cbi_tag_last(container
)
1166 for (var i
= 0; i
< container
.childNodes
.length
; i
++) {
1167 var c
= container
.childNodes
[i
];
1168 if (matchesElem(c
, 'div')) {
1169 c
.classList
.remove('cbi-value-last');
1175 last
.classList
.add('cbi-value-last');
1178 function cbi_submit(elem
, name
, value
, action
)
1180 var form
= elem
.form
|| findParent(elem
, 'form');
1186 form
.action
= action
;
1189 var hidden
= form
.querySelector('input[type="hidden"][name="%s"]'.format(name
)) ||
1190 E('input', { type
: 'hidden', name
: name
});
1192 hidden
.value
= value
|| '1';
1193 form
.appendChild(hidden
);
1200 String
.prototype.format = function()
1205 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1206 var quot_esc = [/"/g
, '"', /'/g, '''];
1208 function esc(s, r) {
1209 if (typeof(s) !== 'string
' && !(s instanceof String))
1212 for (var i = 0; i < r.length; i += 2)
1213 s = s.replace(r[i], r[i+1]);
1220 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
1221 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
1223 while (a
= re
.exec(str
)) {
1225 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
1226 var pPrecision
= a
[6], pType
= a
[7];
1234 if (numSubstitutions
< arguments
.length
) {
1235 var param
= arguments
[numSubstitutions
++];
1238 if (pPad
&& pPad
.substr(0,1) == "'")
1239 pad
= leftpart
.substr(1,1);
1245 var justifyRight
= true;
1246 if (pJustify
&& pJustify
=== "-")
1247 justifyRight
= false;
1251 minLength
= +pMinLength
;
1254 if (pPrecision
&& pType
== 'f')
1255 precision
= +pPrecision
.substring(1);
1261 subst
= (+param
|| 0).toString(2);
1265 subst
= String
.fromCharCode(+param
|| 0);
1269 subst
= ~~(+param
|| 0);
1273 subst
= ~~Math
.abs(+param
|| 0);
1277 subst
= (precision
> -1)
1278 ? ((+param
|| 0.0)).toFixed(precision
)
1283 subst
= (+param
|| 0).toString(8);
1291 subst
= ('' + (+param
|| 0).toString(16)).toLowerCase();
1295 subst
= ('' + (+param
|| 0).toString(16)).toUpperCase();
1299 subst
= esc(param
, html_esc
);
1303 subst
= esc(param
, quot_esc
);
1310 var ts
= (param
|| 0);
1313 tm
= Math
.floor(ts
/ 60);
1318 th
= Math
.floor(tm
/ 60);
1323 td
= Math
.floor(th
/ 24);
1328 ? String
.format('%dd %dh %dm %ds', td
, th
, tm
, ts
)
1329 : String
.format('%dh %dm %ds', th
, tm
, ts
);
1334 var mf
= pMinLength
? +pMinLength
: 1000;
1335 var pr
= pPrecision
? ~~(10 * +('0' + pPrecision
)) : 2;
1338 var val
= (+param
|| 0);
1339 var units
= [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1341 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
1344 subst
= (i
? val
.toFixed(pr
) : val
) + units
[i
];
1352 subst
= subst
.toString();
1353 for (var i
= subst
.length
; i
< pMinLength
; i
++)
1354 if (pJustify
== '-')
1355 subst
= subst
+ ' ';
1357 subst
= pad
+ subst
;
1360 out
+= leftpart
+ subst
;
1361 str
= str
.substr(m
.length
);
1367 String
.prototype.nobr = function()
1369 return this.replace(/[\s\n]+/g, ' ');
1372 String
.format = function()
1376 for (var i
= 1; i
< arguments
.length
; i
++)
1377 a
.push(arguments
[i
]);
1379 return ''.format
.apply(arguments
[0], a
);
1382 String
.nobr = function()
1386 for (var i
= 1; i
< arguments
.length
; i
++)
1387 a
.push(arguments
[i
]);
1389 return ''.nobr
.apply(arguments
[0], a
);
1392 if (window
.NodeList
&& !NodeList
.prototype.forEach
) {
1393 NodeList
.prototype.forEach = function (callback
, thisArg
) {
1394 thisArg
= thisArg
|| window
;
1395 for (var i
= 0; i
< this.length
; i
++) {
1396 callback
.call(thisArg
, this[i
], i
, this);
1401 if (!window
.requestAnimationFrame
) {
1402 window
.requestAnimationFrame = function(f
) {
1403 window
.setTimeout(function() {
1404 f(new Date().getTime())
1410 function isElem(e
) { return L
.dom
.elem(e
) }
1411 function toElem(s
) { return L
.dom
.parse(s
) }
1412 function matchesElem(node
, selector
) { return L
.dom
.matches(node
, selector
) }
1413 function findParent(node
, selector
) { return L
.dom
.parent(node
, selector
) }
1414 function E() { return L
.dom
.create
.apply(L
.dom
, arguments
) }
1416 if (typeof(window
.CustomEvent
) !== 'function') {
1417 function CustomEvent(event
, params
) {
1418 params
= params
|| { bubbles
: false, cancelable
: false, detail
: undefined };
1419 var evt
= document
.createEvent('CustomEvent');
1420 evt
.initCustomEvent( event
, params
.bubbles
, params
.cancelable
, params
.detail
);
1424 CustomEvent
.prototype = window
.Event
.prototype;
1425 window
.CustomEvent
= CustomEvent
;
1429 openDropdown: function(sb
) {
1430 var st
= window
.getComputedStyle(sb
, null),
1431 ul
= sb
.querySelector('ul'),
1432 li
= ul
.querySelectorAll('li'),
1433 fl
= findParent(sb
, '.cbi-value-field'),
1434 sel
= ul
.querySelector('[selected]'),
1435 rect
= sb
.getBoundingClientRect(),
1436 items
= Math
.min(this.dropdown_items
, li
.length
);
1438 document
.querySelectorAll('.cbi-dropdown[open]').forEach(function(s
) {
1439 s
.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1442 sb
.setAttribute('open', '');
1444 var pv
= ul
.cloneNode(true);
1445 pv
.classList
.add('preview');
1448 fl
.classList
.add('cbi-dropdown-open');
1450 if ('ontouchstart' in window
) {
1451 var vpWidth
= Math
.max(document
.documentElement
.clientWidth
, window
.innerWidth
|| 0),
1452 vpHeight
= Math
.max(document
.documentElement
.clientHeight
, window
.innerHeight
|| 0),
1453 scrollFrom
= window
.pageYOffset
,
1454 scrollTo
= scrollFrom
+ rect
.top
- vpHeight
* 0.5,
1457 ul
.style
.top
= sb
.offsetHeight
+ 'px';
1458 ul
.style
.left
= -rect
.left
+ 'px';
1459 ul
.style
.right
= (rect
.right
- vpWidth
) + 'px';
1460 ul
.style
.maxHeight
= (vpHeight
* 0.5) + 'px';
1461 ul
.style
.WebkitOverflowScrolling
= 'touch';
1463 var scrollStep = function(timestamp
) {
1466 ul
.scrollTop
= sel
? Math
.max(sel
.offsetTop
- sel
.offsetHeight
, 0) : 0;
1469 var duration
= Math
.max(timestamp
- start
, 1);
1470 if (duration
< 100) {
1471 document
.body
.scrollTop
= scrollFrom
+ (scrollTo
- scrollFrom
) * (duration
/ 100);
1472 window
.requestAnimationFrame(scrollStep
);
1475 document
.body
.scrollTop
= scrollTo
;
1479 window
.requestAnimationFrame(scrollStep
);
1482 ul
.style
.maxHeight
= '1px';
1483 ul
.style
.top
= ul
.style
.bottom
= '';
1485 window
.requestAnimationFrame(function() {
1486 var height
= items
* li
[Math
.max(0, li
.length
- 2)].offsetHeight
;
1488 ul
.scrollTop
= sel
? Math
.max(sel
.offsetTop
- sel
.offsetHeight
, 0) : 0;
1489 ul
.style
[((rect
.top
+ rect
.height
+ height
) > window
.innerHeight
) ? 'bottom' : 'top'] = rect
.height
+ 'px';
1490 ul
.style
.maxHeight
= height
+ 'px';
1494 ul
.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c
) {
1498 ul
.classList
.add('dropdown');
1500 sb
.insertBefore(pv
, ul
.nextElementSibling
);
1502 li
.forEach(function(l
) {
1503 l
.setAttribute('tabindex', 0);
1506 sb
.lastElementChild
.setAttribute('tabindex', 0);
1508 this.setFocus(sb
, sel
|| li
[0], true);
1511 closeDropdown: function(sb
, no_focus
) {
1512 if (!sb
.hasAttribute('open'))
1515 var pv
= sb
.querySelector('ul.preview'),
1516 ul
= sb
.querySelector('ul.dropdown'),
1517 li
= ul
.querySelectorAll('li'),
1518 fl
= findParent(sb
, '.cbi-value-field');
1520 li
.forEach(function(l
) { l
.removeAttribute('tabindex'); });
1521 sb
.lastElementChild
.removeAttribute('tabindex');
1524 sb
.removeAttribute('open');
1525 sb
.style
.width
= sb
.style
.height
= '';
1527 ul
.classList
.remove('dropdown');
1528 ul
.style
.top
= ul
.style
.bottom
= ul
.style
.maxHeight
= '';
1531 fl
.classList
.remove('cbi-dropdown-open');
1534 this.setFocus(sb
, sb
);
1536 this.saveValues(sb
, ul
);
1539 toggleItem: function(sb
, li
, force_state
) {
1540 if (li
.hasAttribute('unselectable'))
1544 var cbox
= li
.querySelector('input[type="checkbox"]'),
1545 items
= li
.parentNode
.querySelectorAll('li'),
1546 label
= sb
.querySelector('ul.preview'),
1547 sel
= li
.parentNode
.querySelectorAll('[selected]').length
,
1548 more
= sb
.querySelector('.more'),
1549 ndisplay
= this.display_items
,
1552 if (li
.hasAttribute('selected')) {
1553 if (force_state
!== true) {
1554 if (sel
> 1 || this.optional
) {
1555 li
.removeAttribute('selected');
1556 cbox
.checked
= cbox
.disabled
= false;
1560 cbox
.disabled
= true;
1565 if (force_state
!== false) {
1566 li
.setAttribute('selected', '');
1567 cbox
.checked
= true;
1568 cbox
.disabled
= false;
1573 while (label
.firstElementChild
)
1574 label
.removeChild(label
.firstElementChild
);
1576 for (var i
= 0; i
< items
.length
; i
++) {
1577 items
[i
].removeAttribute('display');
1578 if (items
[i
].hasAttribute('selected')) {
1579 if (ndisplay
-- > 0) {
1580 items
[i
].setAttribute('display', n
++);
1581 label
.appendChild(items
[i
].cloneNode(true));
1583 var c
= items
[i
].querySelector('input[type="checkbox"]');
1585 c
.disabled
= (sel
== 1 && !this.optional
);
1590 sb
.setAttribute('more', '');
1592 sb
.removeAttribute('more');
1594 if (ndisplay
=== this.display_items
)
1595 sb
.setAttribute('empty', '');
1597 sb
.removeAttribute('empty');
1599 more
.innerHTML
= (ndisplay
=== this.display_items
) ? this.placeholder
: 'ยทยทยท';
1602 var sel
= li
.parentNode
.querySelector('[selected]');
1604 sel
.removeAttribute('display');
1605 sel
.removeAttribute('selected');
1608 li
.setAttribute('display', 0);
1609 li
.setAttribute('selected', '');
1611 this.closeDropdown(sb
, true);
1614 this.saveValues(sb
, li
.parentNode
);
1617 transformItem: function(sb
, li
) {
1618 var cbox
= E('form', {}, E('input', { type
: 'checkbox', tabindex
: -1, onclick
: 'event.preventDefault()' })),
1621 while (li
.firstChild
)
1622 label
.appendChild(li
.firstChild
);
1624 li
.appendChild(cbox
);
1625 li
.appendChild(label
);
1628 saveValues: function(sb
, ul
) {
1629 var sel
= ul
.querySelectorAll('li[selected]'),
1630 div
= sb
.lastElementChild
,
1634 while (div
.lastElementChild
)
1635 div
.removeChild(div
.lastElementChild
);
1637 sel
.forEach(function (s
) {
1638 if (s
.hasAttribute('placeholder'))
1643 value
: s
.hasAttribute('data-value') ? s
.getAttribute('data-value') : s
.innerText
,
1647 div
.appendChild(E('input', {
1649 name
: s
.hasAttribute('name') ? s
.getAttribute('name') : (sb
.getAttribute('name') || ''),
1655 strval
+= strval
.length
? ' ' + v
.value
: v
.value
;
1664 detail
.values
= values
;
1666 detail
.value
= values
.length
? values
[0] : null;
1670 sb
.dispatchEvent(new CustomEvent('cbi-dropdown-change', {
1678 setValues: function(sb
, values
) {
1679 var ul
= sb
.querySelector('ul');
1682 ul
.querySelectorAll('li[data-value]').forEach(function(li
) {
1683 if (values
=== null || !(li
.getAttribute('data-value') in values
))
1684 this.toggleItem(sb
, li
, false);
1686 this.toggleItem(sb
, li
, true);
1690 var ph
= ul
.querySelector('li[placeholder]');
1692 this.toggleItem(sb
, ph
);
1694 ul
.querySelectorAll('li[data-value]').forEach(function(li
) {
1695 if (values
!== null && (li
.getAttribute('data-value') in values
))
1696 this.toggleItem(sb
, li
);
1701 setFocus: function(sb
, elem
, scroll
) {
1702 if (sb
&& sb
.hasAttribute
&& sb
.hasAttribute('locked-in'))
1705 if (sb
.target
&& findParent(sb
.target
, 'ul.dropdown'))
1708 document
.querySelectorAll('.focus').forEach(function(e
) {
1709 if (!matchesElem(e
, 'input')) {
1710 e
.classList
.remove('focus');
1717 elem
.classList
.add('focus');
1720 elem
.parentNode
.scrollTop
= elem
.offsetTop
- elem
.parentNode
.offsetTop
;
1724 createItems: function(sb
, value
) {
1726 val
= (value
|| '').trim(),
1727 ul
= sb
.querySelector('ul');
1730 val
= val
.length
? [ val
] : [];
1732 val
= val
.length
? val
.split(/\s+/) : [];
1734 val
.forEach(function(item
) {
1735 var new_item
= null;
1737 ul
.childNodes
.forEach(function(li
) {
1738 if (li
.getAttribute
&& li
.getAttribute('data-value') === item
)
1744 tpl
= sb
.querySelector(sbox
.template
);
1747 markup
= (tpl
.textContent
|| tpl
.innerHTML
|| tpl
.firstChild
.data
).replace(/^<!--|-->$/, '').trim();
1749 markup
= '<li data-value="{{value}}">{{value}}</li>';
1751 new_item
= E(markup
.replace(/{{value}}/g, item
));
1754 sbox
.transformItem(sb
, new_item
);
1757 var old
= ul
.querySelector('li[created]');
1759 ul
.removeChild(old
);
1761 new_item
.setAttribute('created', '');
1764 new_item
= ul
.insertBefore(new_item
, ul
.lastElementChild
);
1767 sbox
.toggleItem(sb
, new_item
, true);
1768 sbox
.setFocus(sb
, new_item
, true);
1772 closeAllDropdowns: function() {
1773 document
.querySelectorAll('.cbi-dropdown[open]').forEach(function(s
) {
1774 s
.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1778 handleClick: function(ev
) {
1779 var sb
= ev
.currentTarget
;
1781 if (!sb
.hasAttribute('open')) {
1782 if (!matchesElem(ev
.target
, 'input'))
1783 this.openDropdown(sb
);
1786 var li
= findParent(ev
.target
, 'li');
1787 if (li
&& li
.parentNode
.classList
.contains('dropdown'))
1788 this.toggleItem(sb
, li
);
1789 else if (li
&& li
.parentNode
.classList
.contains('preview'))
1790 this.closeDropdown(sb
);
1793 ev
.preventDefault();
1794 ev
.stopPropagation();
1797 handleKeydown: function(ev
) {
1798 var sb
= ev
.currentTarget
;
1800 if (matchesElem(ev
.target
, 'input'))
1803 if (!sb
.hasAttribute('open')) {
1804 switch (ev
.keyCode
) {
1809 this.openDropdown(sb
);
1810 ev
.preventDefault();
1814 var active
= findParent(document
.activeElement
, 'li');
1816 switch (ev
.keyCode
) {
1818 this.closeDropdown(sb
);
1823 if (!active
.hasAttribute('selected'))
1824 this.toggleItem(sb
, active
);
1825 this.closeDropdown(sb
);
1826 ev
.preventDefault();
1832 this.toggleItem(sb
, active
);
1833 ev
.preventDefault();
1838 if (active
&& active
.previousElementSibling
) {
1839 this.setFocus(sb
, active
.previousElementSibling
);
1840 ev
.preventDefault();
1845 if (active
&& active
.nextElementSibling
) {
1846 this.setFocus(sb
, active
.nextElementSibling
);
1847 ev
.preventDefault();
1854 handleDropdownClose: function(ev
) {
1855 var sb
= ev
.currentTarget
;
1857 this.closeDropdown(sb
, true);
1860 handleDropdownSelect: function(ev
) {
1861 var sb
= ev
.currentTarget
,
1862 li
= findParent(ev
.target
, 'li');
1867 this.toggleItem(sb
, li
);
1868 this.closeDropdown(sb
, true);
1871 handleMouseover: function(ev
) {
1872 var sb
= ev
.currentTarget
;
1874 if (!sb
.hasAttribute('open'))
1877 var li
= findParent(ev
.target
, 'li');
1879 if (li
&& li
.parentNode
.classList
.contains('dropdown'))
1880 this.setFocus(sb
, li
);
1883 handleFocus: function(ev
) {
1884 var sb
= ev
.currentTarget
;
1886 document
.querySelectorAll('.cbi-dropdown[open]').forEach(function(s
) {
1887 if (s
!== sb
|| sb
.hasAttribute('open'))
1888 s
.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1892 handleCanaryFocus: function(ev
) {
1893 this.closeDropdown(ev
.currentTarget
.parentNode
);
1896 handleCreateKeydown: function(ev
) {
1897 var input
= ev
.currentTarget
,
1898 sb
= findParent(input
, '.cbi-dropdown');
1900 switch (ev
.keyCode
) {
1902 ev
.preventDefault();
1904 if (input
.classList
.contains('cbi-input-invalid'))
1907 this.createItems(sb
, input
.value
);
1914 handleCreateFocus: function(ev
) {
1915 var input
= ev
.currentTarget
,
1916 cbox
= findParent(input
, 'li').querySelector('input[type="checkbox"]'),
1917 sb
= findParent(input
, '.cbi-dropdown');
1920 cbox
.checked
= true;
1922 sb
.setAttribute('locked-in', '');
1925 handleCreateBlur: function(ev
) {
1926 var input
= ev
.currentTarget
,
1927 cbox
= findParent(input
, 'li').querySelector('input[type="checkbox"]'),
1928 sb
= findParent(input
, '.cbi-dropdown');
1931 cbox
.checked
= false;
1933 sb
.removeAttribute('locked-in');
1936 handleCreateClick: function(ev
) {
1937 ev
.currentTarget
.querySelector(this.create
).focus();
1941 function cbi_dropdown_init(sb
) {
1942 if (!(this instanceof cbi_dropdown_init
))
1943 return new cbi_dropdown_init(sb
);
1945 this.multi
= sb
.hasAttribute('multiple');
1946 this.optional
= sb
.hasAttribute('optional');
1947 this.placeholder
= sb
.getAttribute('placeholder') || '---';
1948 this.display_items
= parseInt(sb
.getAttribute('display-items') || 3);
1949 this.dropdown_items
= parseInt(sb
.getAttribute('dropdown-items') || 5);
1950 this.create
= sb
.getAttribute('item-create') || '.create-item-input';
1951 this.template
= sb
.getAttribute('item-template') || 'script[type="item-template"]';
1953 var ul
= sb
.querySelector('ul'),
1954 more
= sb
.appendChild(E('span', { class: 'more', tabindex
: -1 }, 'ยทยทยท')),
1955 open
= sb
.appendChild(E('span', { class: 'open', tabindex
: -1 }, 'โพ')),
1956 canary
= sb
.appendChild(E('div')),
1957 create
= sb
.querySelector(this.create
),
1958 ndisplay
= this.display_items
,
1962 var items
= ul
.querySelectorAll('li');
1964 for (var i
= 0; i
< items
.length
; i
++) {
1965 this.transformItem(sb
, items
[i
]);
1967 if (items
[i
].hasAttribute('selected') && ndisplay
-- > 0)
1968 items
[i
].setAttribute('display', n
++);
1972 if (this.optional
&& !ul
.querySelector('li[data-value=""]')) {
1973 var placeholder
= E('li', { placeholder
: '' }, this.placeholder
);
1974 ul
.firstChild
? ul
.insertBefore(placeholder
, ul
.firstChild
) : ul
.appendChild(placeholder
);
1977 var items
= ul
.querySelectorAll('li'),
1978 sel
= sb
.querySelectorAll('[selected]');
1980 sel
.forEach(function(s
) {
1981 s
.removeAttribute('selected');
1984 var s
= sel
[0] || items
[0];
1986 s
.setAttribute('selected', '');
1987 s
.setAttribute('display', n
++);
1993 this.saveValues(sb
, ul
);
1995 ul
.setAttribute('tabindex', -1);
1996 sb
.setAttribute('tabindex', 0);
1999 sb
.setAttribute('more', '')
2001 sb
.removeAttribute('more');
2003 if (ndisplay
=== this.display_items
)
2004 sb
.setAttribute('empty', '')
2006 sb
.removeAttribute('empty');
2008 more
.innerHTML
= (ndisplay
=== this.display_items
) ? this.placeholder
: 'ยทยทยท';
2011 sb
.addEventListener('click', this.handleClick
.bind(this));
2012 sb
.addEventListener('keydown', this.handleKeydown
.bind(this));
2013 sb
.addEventListener('cbi-dropdown-close', this.handleDropdownClose
.bind(this));
2014 sb
.addEventListener('cbi-dropdown-select', this.handleDropdownSelect
.bind(this));
2016 if ('ontouchstart' in window
) {
2017 sb
.addEventListener('touchstart', function(ev
) { ev
.stopPropagation(); });
2018 window
.addEventListener('touchstart', this.closeAllDropdowns
);
2021 sb
.addEventListener('mouseover', this.handleMouseover
.bind(this));
2022 sb
.addEventListener('focus', this.handleFocus
.bind(this));
2024 canary
.addEventListener('focus', this.handleCanaryFocus
.bind(this));
2026 window
.addEventListener('mouseover', this.setFocus
);
2027 window
.addEventListener('click', this.closeAllDropdowns
);
2031 create
.addEventListener('keydown', this.handleCreateKeydown
.bind(this));
2032 create
.addEventListener('focus', this.handleCreateFocus
.bind(this));
2033 create
.addEventListener('blur', this.handleCreateBlur
.bind(this));
2035 var li
= findParent(create
, 'li');
2037 li
.setAttribute('unselectable', '');
2038 li
.addEventListener('click', this.handleCreateClick
.bind(this));
2042 cbi_dropdown_init
.prototype = CBIDropdown
;
2044 function cbi_update_table(table
, data
, placeholder
) {
2045 var target
= isElem(table
) ? table
: document
.querySelector(table
);
2047 if (!isElem(target
))
2050 target
.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead
) {
2053 thead
.querySelectorAll('.th').forEach(function(th
) {
2057 if (Array
.isArray(data
)) {
2058 var n
= 0, rows
= target
.querySelectorAll('.tr');
2060 data
.forEach(function(row
) {
2061 var trow
= E('div', { 'class': 'tr' });
2063 for (var i
= 0; i
< titles
.length
; i
++) {
2064 var text
= (titles
[i
].innerText
|| '').trim();
2065 var td
= trow
.appendChild(E('div', {
2066 'class': titles
[i
].className
,
2067 'data-title': (text
!== '') ? text
: null
2070 td
.classList
.remove('th');
2071 td
.classList
.add('td');
2074 trow
.classList
.add('cbi-rowstyle-%d'.format((n
++ % 2) ? 2 : 1));
2077 target
.replaceChild(trow
, rows
[n
]);
2079 target
.appendChild(trow
);
2083 target
.removeChild(rows
[n
]);
2085 if (placeholder
&& target
.firstElementChild
=== target
.lastElementChild
) {
2086 var trow
= target
.appendChild(E('div', { 'class': 'tr placeholder' }));
2087 var td
= trow
.appendChild(E('div', { 'class': titles
[0].className
}, placeholder
));
2089 td
.classList
.remove('th');
2090 td
.classList
.add('td');
2094 thead
.parentNode
.style
.display
= 'none';
2096 thead
.parentNode
.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow
) {
2097 if (trow
!== thead
) {
2099 trow
.querySelectorAll('.th, .td').forEach(function(td
) {
2100 if (n
< titles
.length
) {
2101 var text
= (titles
[n
++].innerText
|| '').trim();
2103 td
.setAttribute('data-title', text
);
2109 thead
.parentNode
.style
.display
= '';
2114 function showModal(title
, children
)
2116 return L
.showModal(title
, children
);
2119 function hideModal()
2121 return L
.hideModal();
2125 document
.addEventListener('DOMContentLoaded', function() {
2126 document
.addEventListener('validation-failure', function(ev
) {
2127 if (ev
.target
=== document
.activeElement
)
2131 document
.addEventListener('validation-success', function(ev
) {
2132 if (ev
.target
=== document
.activeElement
)
2136 document
.querySelectorAll('.table').forEach(cbi_update_table
);