2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2012 Jo-Philipp Wich <jow@openwrt.org>
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
16 var cbi_strings
= { path
: {}, label
: {} };
19 if (s
=== null || s
.length
=== 0)
22 var hash
= (s
.length
>>> 0),
23 len
= (s
.length
>>> 2),
27 hash
+= ((s
.charCodeAt(off
+ 1) << 8) + s
.charCodeAt(off
)) >>> 0;
28 tmp
= ((((s
.charCodeAt(off
+ 3) << 8) + s
.charCodeAt(off
+ 2)) << 11) ^ hash
) >>> 0;
29 hash
= ((hash
<< 16) ^ tmp
) >>> 0;
34 switch ((s
.length
& 3) >>> 0) {
36 hash
+= ((s
.charCodeAt(off
+ 1) << 8) + s
.charCodeAt(off
)) >>> 0;
37 hash
= (hash
^ (hash
<< 16)) >>> 0;
38 hash
= (hash
^ (s
.charCodeAt(off
+ 2) << 18)) >>> 0;
43 hash
+= ((s
.charCodeAt(off
+ 1) << 8) + s
.charCodeAt(off
)) >>> 0;
44 hash
= (hash
^ (hash
<< 11)) >>> 0;
49 hash
+= s
.charCodeAt(off
);
50 hash
= (hash
^ (hash
<< 10)) >>> 0;
55 hash
= (hash
^ (hash
<< 3)) >>> 0;
57 hash
= (hash
^ (hash
<< 4)) >>> 0;
59 hash
= (hash
^ (hash
<< 25)) >>> 0;
62 return (0x100000000 + hash
).toString(16).substr(1);
66 return (window
.TR
&& TR
[sfh(s
)]) || s
;
70 return (/^-?\d+$/.test(x
) ? +x
: NaN
);
74 return (/^-?\d+(?:\.\d+)?$/.test(x
) ? +x
: NaN
);
78 if (!x
.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
81 if (RegExp
.$1 > 255 || RegExp
.$2 > 255 || RegExp
.$3 > 255 || RegExp
.$4 > 255)
84 return [ +RegExp
.$1, +RegExp
.$2, +RegExp
.$3, +RegExp
.$4 ];
88 if (x
.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
89 var v6
= RegExp
.$1, v4
= IPv4(RegExp
.$2);
94 x
= v6
+ ':' + (v4
[0] * 256 + v4
[1]).toString(16)
95 + ':' + (v4
[2] * 256 + v4
[3]).toString(16);
98 if (!x
.match(/^[a-fA-F0-9:]+$/))
101 var prefix_suffix
= x
.split(/::/);
103 if (prefix_suffix
.length
> 2)
106 var prefix
= (prefix_suffix
[0] || '0').split(/:/);
107 var suffix
= prefix_suffix
.length
> 1 ? (prefix_suffix
[1] || '0').split(/:/) : [];
109 if (suffix
.length
? (prefix
.length
+ suffix
.length
> 7) : (prefix
.length
> 8))
115 for (i
= 0, word
= parseInt(prefix
[0], 16); i
< prefix
.length
; word
= parseInt(prefix
[++i
], 16))
116 if (prefix
[i
].length
<= 4 && !isNaN(word
) && word
<= 0xFFFF)
121 for (i
= 0; i
< (8 - prefix
.length
- suffix
.length
); i
++)
124 for (i
= 0, word
= parseInt(suffix
[0], 16); i
< suffix
.length
; word
= parseInt(suffix
[++i
], 16))
125 if (suffix
[i
].length
<= 4 && !isNaN(word
) && word
<= 0xFFFF)
133 var cbi_validators
= {
135 'integer': function()
140 'uinteger': function()
142 return (Int(this) >= 0);
152 return (Dec(this) >= 0);
157 return cbi_validators
.ip4addr
.apply(this) ||
158 cbi_validators
.ip6addr
.apply(this);
161 'ip4addr': function()
163 var m
= this.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})|\/(\d{1,2}))?$/);
164 return !!(m
&& IPv4(m
[1]) && (m
[2] ? IPv4(m
[2]) : (m
[3] ? cbi_validators
.ip4prefix
.apply(m
[3]) : true)));
167 'ip6addr': function()
169 var m
= this.match(/^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/);
170 return !!(m
&& IPv6(m
[1]) && (m
[2] ? cbi_validators
.ip6prefix
.apply(m
[2]) : true));
173 'ip4prefix': function()
175 return !isNaN(this) && this >= 0 && this <= 32;
178 'ip6prefix': function()
180 return !isNaN(this) && this >= 0 && this <= 128;
185 return cbi_validators
.cidr4
.apply(this) ||
186 cbi_validators
.cidr6
.apply(this);
191 var m
= this.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
192 return !!(m
&& IPv4(m
[1]) && cbi_validators
.ip4prefix
.apply(m
[2]));
197 var m
= this.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
198 return !!(m
&& IPv6(m
[1]) && cbi_validators
.ip6prefix
.apply(m
[2]));
203 var m
= this.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})$/);
204 return !!(m
&& IPv4(m
[1]) && IPv4(m
[2]));
209 var m
= this.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
210 return !!(m
&& IPv6(m
[1]) && IPv6(m
[2]));
213 'ip6hostid': function()
215 if (this == "eui64" || this == "random")
219 return !(!v6
|| v6
[0] || v6
[1] || v6
[2] || v6
[3]);
224 return cbi_validators
.ipmask4
.apply(this) ||
225 cbi_validators
.ipmask6
.apply(this);
228 'ipmask4': function()
230 return cbi_validators
.cidr4
.apply(this) ||
231 cbi_validators
.ipnet4
.apply(this) ||
232 cbi_validators
.ip4addr
.apply(this);
235 'ipmask6': function()
237 return cbi_validators
.cidr6
.apply(this) ||
238 cbi_validators
.ipnet6
.apply(this) ||
239 cbi_validators
.ip6addr
.apply(this);
245 return (p
>= 0 && p
<= 65535);
248 'portrange': function()
250 if (this.match(/^(\d+)-(\d+)$/))
254 return (p1
<= p2
&& p2
<= 65535);
257 return cbi_validators
.port
.apply(this);
260 'macaddr': function()
262 return (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
265 'host': function(ipv4only
)
267 return cbi_validators
.hostname
.apply(this) ||
268 ((ipv4only
!= 1) && cbi_validators
.ipaddr
.apply(this)) ||
269 ((ipv4only
== 1) && cbi_validators
.ip4addr
.apply(this));
272 'hostname': function(strict
)
274 if (this.length
<= 253)
275 return (this.match(/^[a-zA-Z0-9_]+$/) != null ||
276 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
277 this.match(/[^0-9.]/))) &&
278 (!strict
|| !this.match(/^_/));
283 'network': function()
285 return cbi_validators
.uciname
.apply(this) ||
286 cbi_validators
.host
.apply(this);
289 'hostport': function(ipv4only
)
291 var hp
= this.split(/:/);
294 return (cbi_validators
.host
.apply(hp
[0], ipv4only
) &&
295 cbi_validators
.port
.apply(hp
[1]));
300 'ip4addrport': function()
302 var hp
= this.split(/:/);
305 return (cbi_validators
.ipaddr
.apply(hp
[0]) &&
306 cbi_validators
.port
.apply(hp
[1]));
310 'ipaddrport': function(bracket
)
312 if (this.match(/^([^\[\]:]+):([^:]+)$/)) {
315 return (cbi_validators
.ip4addr
.apply(addr
) &&
316 cbi_validators
.port
.apply(port
));
317 } else if ((bracket
== 1) && (this.match(/^\[(.+)\]:([^:]+)$/))) {
320 return (cbi_validators
.ip6addr
.apply(addr
) &&
321 cbi_validators
.port
.apply(port
));
322 } else if ((bracket
!= 1) && (this.match(/^([^\[\]]+):([^:]+)$/))) {
325 return (cbi_validators
.ip6addr
.apply(addr
) &&
326 cbi_validators
.port
.apply(port
));
337 return (v
.match(/^[a-fA-F0-9]{64}$/) != null);
339 return (v
.length
>= 8) && (v
.length
<= 63);
346 if ( v
.substr(0,2) == 's:' )
349 if( (v
.length
== 10) || (v
.length
== 26) )
350 return (v
.match(/^[a-fA-F0-9]{10,26}$/) != null);
352 return (v
.length
== 5) || (v
.length
== 13);
355 'uciname': function()
357 return (this.match(/^[a-zA-Z0-9_]+$/) != null);
360 'range': function(min
, max
)
363 return (val
>= +min
&& val
<= +max
);
368 return (Dec(this) >= +min
);
373 return (Dec(this) <= +max
);
376 'rangelength': function(min
, max
)
379 return ((val
.length
>= +min
) && (val
.length
<= +max
));
382 'minlength': function(min
)
384 return ((''+this).length
>= +min
);
387 'maxlength': function(max
)
389 return ((''+this).length
<= +max
);
394 for (var i
= 0; i
< arguments
.length
; i
+= 2)
396 if (typeof arguments
[i
] != 'function')
398 if (arguments
[i
] == this)
402 else if (arguments
[i
].apply(this, arguments
[i
+1]))
412 for (var i
= 0; i
< arguments
.length
; i
+= 2)
414 if (typeof arguments
[i
] != 'function')
416 if (arguments
[i
] != this)
420 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
430 return cbi_validators
.or
.apply(
431 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
434 'list': function(subvalidator
, subargs
)
436 if (typeof subvalidator
!= 'function')
439 var tokens
= this.match(/[^ \t]+/g);
440 for (var i
= 0; i
< tokens
.length
; i
++)
441 if (!subvalidator
.apply(tokens
[i
], subargs
))
446 'phonedigit': function()
448 return (this.match(/^[0-9\*#!\.]+$/) != null);
450 'timehhmmss': function()
452 return (this.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/) != null);
454 'dateyyyymmdd': function()
459 if (this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
460 var year
= RegExp
.$1;
461 var month
= RegExp
.$2;
464 var days_in_month
= [ 31, 28, 31, 30, 31, 30, 31, 31, 30 , 31, 30, 31 ];
465 function is_leap_year(year
) {
466 return ((year
% 4) == 0) && ((year
% 100) != 0) || ((year
% 400) == 0);
468 function get_days_in_month(month
, year
) {
469 if ((month
== 2) && is_leap_year(year
)) {
472 return days_in_month
[month
];
475 /* Firewall rules in the past don't make sense */
479 if ((month
<= 0) || (month
> 12)) {
482 if ((day
<= 0) || (day
> get_days_in_month(month
, year
))) {
494 function cbi_d_add(field
, dep
, index
) {
495 var obj
= (typeof(field
) === 'string') ? document
.getElementById(field
) : field
;
498 for (var i
=0; i
<cbi_d
.length
; i
++) {
499 if (cbi_d
[i
].id
== obj
.id
) {
508 "parent": obj
.parentNode
.id
,
512 cbi_d
.unshift(entry
);
518 function cbi_d_checkvalue(target
, ref
) {
520 query
= 'input[id="'+target
+'"], input[name="'+target
+'"], ' +
521 'select[id="'+target
+'"], select[name="'+target
+'"]';
523 document
.querySelectorAll(query
).forEach(function(i
) {
524 if (value
=== null && ((i
.type
!== 'radio' && i
.type
!== 'checkbox') || i
.checked
=== true))
528 return (((value
!== null) ? value
: "") == ref
);
531 function cbi_d_check(deps
) {
534 for (var i
=0; i
<deps
.length
; i
++) {
537 for (var j
in deps
[i
]) {
538 if (j
== "!reverse") {
540 } else if (j
== "!default") {
544 istat
= (istat
&& cbi_d_checkvalue(j
, deps
[i
][j
]))
548 if (istat
^ reverse
) {
555 function cbi_d_update() {
557 for (var i
=0; i
<cbi_d
.length
; i
++) {
558 var entry
= cbi_d
[i
];
559 var node
= document
.getElementById(entry
.id
);
560 var parent
= document
.getElementById(entry
.parent
);
562 if (node
&& node
.parentNode
&& !cbi_d_check(entry
.deps
)) {
563 node
.parentNode
.removeChild(node
);
566 else if (parent
&& (!node
|| !node
.parentNode
) && cbi_d_check(entry
.deps
)) {
567 var next
= undefined;
569 for (next
= parent
.firstChild
; next
; next
= next
.nextSibling
) {
570 if (next
.getAttribute
&& parseInt(next
.getAttribute('data-index'), 10) > entry
.index
)
575 parent
.appendChild(entry
.node
);
577 parent
.insertBefore(entry
.node
, next
);
582 // hide optionals widget if no choices remaining
583 if (parent
&& parent
.parentNode
&& parent
.getAttribute('data-optionals'))
584 parent
.parentNode
.style
.display
= (parent
.options
.length
<= 1) ? 'none' : '';
587 if (entry
&& entry
.parent
) {
589 cbi_tag_last(parent
);
596 function cbi_init() {
599 nodes
= document
.querySelectorAll('[data-strings]');
601 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
602 var str
= JSON
.parse(node
.getAttribute('data-strings'));
603 for (var key
in str
) {
604 for (var key2
in str
[key
]) {
605 var dst
= cbi_strings
[key
] || (cbi_strings
[key
] = { });
606 dst
[key2
] = str
[key
][key2
];
611 nodes
= document
.querySelectorAll('[data-depends]');
613 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
614 var index
= parseInt(node
.getAttribute('data-index'), 10);
615 var depends
= JSON
.parse(node
.getAttribute('data-depends'));
616 if (!isNaN(index
) && depends
.length
> 0) {
617 for (var alt
= 0; alt
< depends
.length
; alt
++)
618 cbi_d_add(node
, depends
[alt
], index
);
622 nodes
= document
.querySelectorAll('[data-update]');
624 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
625 var events
= node
.getAttribute('data-update').split(' ');
626 for (var j
= 0, event
; (event
= events
[j
]) !== undefined; j
++)
627 cbi_bind(node
, event
, cbi_d_update
);
630 nodes
= document
.querySelectorAll('[data-choices]');
632 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
633 var choices
= JSON
.parse(node
.getAttribute('data-choices'));
636 for (var j
= 0; j
< choices
[0].length
; j
++)
637 options
[choices
[0][j
]] = choices
[1][j
];
639 var def
= (node
.getAttribute('data-optional') === 'true')
640 ? node
.placeholder
|| '' : null;
642 cbi_combobox_init(node
, options
, def
,
643 node
.getAttribute('data-manual'));
646 nodes
= document
.querySelectorAll('[data-dynlist]');
648 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
649 var choices
= JSON
.parse(node
.getAttribute('data-dynlist'));
652 if (choices
[0] && choices
[0].length
) {
655 for (var j
= 0; j
< choices
[0].length
; j
++)
656 options
[choices
[0][j
]] = choices
[1][j
];
659 cbi_dynlist_init(node
, choices
[2], choices
[3], options
);
662 nodes
= document
.querySelectorAll('[data-type]');
664 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
665 cbi_validate_field(node
, node
.getAttribute('data-optional') === 'true',
666 node
.getAttribute('data-type'));
669 document
.querySelectorAll('.cbi-dropdown').forEach(function(s
) {
670 cbi_dropdown_init(s
);
673 document
.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s
) {
674 s
.parentNode
.classList
.add('cbi-tooltip-container');
677 document
.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i
) {
678 var handler = function(ev
) {
679 var bits
= this.name
.split(/\./),
680 section
= document
.getElementById('cbi-' + bits
[2] + '-' + bits
[3]);
682 section
.style
.opacity
= (ev
.type
=== 'mouseover') ? 0.5 : '';
685 i
.addEventListener('mouseover', handler
);
686 i
.addEventListener('mouseout', handler
);
692 function cbi_bind(obj
, type
, callback
, mode
) {
693 if (!obj
.addEventListener
) {
694 obj
.attachEvent('on' + type
,
696 var e
= window
.event
;
698 if (!e
.target
&& e
.srcElement
)
699 e
.target
= e
.srcElement
;
701 return !!callback(e
);
705 obj
.addEventListener(type
, callback
, !!mode
);
710 function cbi_combobox(id
, values
, def
, man
, focus
) {
711 var selid
= "cbi.combobox." + id
;
712 if (document
.getElementById(selid
)) {
716 var obj
= document
.getElementById(id
)
717 var sel
= document
.createElement("select");
719 sel
.index
= obj
.index
;
720 sel
.classList
.remove('cbi-input-text');
721 sel
.classList
.add('cbi-input-select');
724 obj
.parentNode
.insertBefore(sel
, obj
.nextSibling
);
726 obj
.parentNode
.appendChild(sel
);
728 var dt
= obj
.getAttribute('cbi_datatype');
729 var op
= obj
.getAttribute('cbi_optional');
731 if (!values
[obj
.value
]) {
732 if (obj
.value
== "") {
733 var optdef
= document
.createElement("option");
735 optdef
.appendChild(document
.createTextNode(typeof(def
) === 'string' ? def
: _('-- Please choose --')));
736 sel
.appendChild(optdef
);
739 var opt
= document
.createElement("option");
740 opt
.value
= obj
.value
;
741 opt
.selected
= "selected";
742 opt
.appendChild(document
.createTextNode(obj
.value
));
743 sel
.appendChild(opt
);
747 for (var i
in values
) {
748 var opt
= document
.createElement("option");
752 opt
.selected
= "selected";
754 opt
.appendChild(document
.createTextNode(values
[i
]));
755 sel
.appendChild(opt
);
758 var optman
= document
.createElement("option");
760 optman
.appendChild(document
.createTextNode(typeof(man
) === 'string' ? man
: _('-- custom --')));
761 sel
.appendChild(optman
);
763 obj
.style
.display
= "none";
766 cbi_validate_field(sel
, op
== 'true', dt
);
768 cbi_bind(sel
, "change", function() {
769 if (sel
.selectedIndex
== sel
.options
.length
- 1) {
770 obj
.style
.display
= "inline";
772 sel
.parentNode
.removeChild(sel
);
776 obj
.value
= sel
.options
[sel
.selectedIndex
].value
;
786 // Retrigger validation in select
793 function cbi_combobox_init(id
, values
, def
, man
) {
794 var obj
= (typeof(id
) === 'string') ? document
.getElementById(id
) : id
;
795 cbi_bind(obj
, "blur", function() {
796 cbi_combobox(obj
.id
, values
, def
, man
, true);
798 cbi_combobox(obj
.id
, values
, def
, man
, false);
801 function cbi_filebrowser(id
, defpath
) {
802 var field
= document
.getElementById(id
);
803 var browser
= window
.open(
804 cbi_strings
.path
.browser
+ ( field
.value
|| defpath
|| '' ) + '?field=' + id
,
805 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
811 function cbi_browser_init(id
, resource
, defpath
)
813 function cbi_browser_btnclick(e
) {
814 cbi_filebrowser(id
, defpath
);
818 var field
= document
.getElementById(id
);
820 var btn
= document
.createElement('img');
821 btn
.className
= 'cbi-image-button';
822 btn
.src
= (resource
|| cbi_strings
.path
.resource
) + '/cbi/folder.gif';
823 field
.parentNode
.insertBefore(btn
, field
.nextSibling
);
825 cbi_bind(btn
, 'click', cbi_browser_btnclick
);
828 function cbi_dynlist_init(parent
, datatype
, optional
, choices
)
830 var prefix
= parent
.getAttribute('data-prefix');
831 var holder
= parent
.getAttribute('data-placeholder');
835 function cbi_dynlist_redraw(focus
, add
, del
)
839 while (parent
.firstChild
) {
840 var n
= parent
.firstChild
;
844 if (matchesElem(n
, 'input'))
845 values
.push(n
.value
|| '');
846 else if (matchesElem(n
, 'select'))
847 values
[values
.length
-1] = n
.options
[n
.selectedIndex
].value
;
850 parent
.removeChild(n
);
855 values
.splice(focus
, 0, '');
857 else if (values
.length
== 0) {
862 for (var i
= 0; i
< values
.length
; i
++) {
863 var t
= document
.createElement('input');
864 t
.id
= prefix
+ '.' + (i
+1);
869 t
.className
= 'cbi-input-text';
871 if (i
== 0 && holder
)
872 t
.placeholder
= holder
;
875 class: 'cbi-button cbi-button-' + ((i
+1) < values
.length
? 'remove' : 'add')
876 }, (i
+1) < values
.length
? '×' : '+');
878 parent
.appendChild(t
);
879 parent
.appendChild(b
);
881 if (datatype
== 'file')
882 cbi_browser_init(t
.id
, null, parent
.getAttribute('data-browser-path'));
884 parent
.appendChild(document
.createElement('br'));
887 cbi_validate_field(t
.id
, ((i
+1) == values
.length
) || optional
, datatype
);
890 cbi_combobox_init(t
.id
, choices
, '', _('-- custom --'));
893 cbi_bind(b
, 'keydown', cbi_dynlist_keydown
);
894 cbi_bind(b
, 'keypress', cbi_dynlist_keypress
);
896 if (i
== focus
|| -i
== focus
)
900 cbi_bind(t
, 'keydown', cbi_dynlist_keydown
);
901 cbi_bind(t
, 'keypress', cbi_dynlist_keypress
);
906 else if (-i
== focus
) {
909 /* force cursor to end */
916 cbi_bind(b
, 'click', cbi_dynlist_btnclick
);
920 function cbi_dynlist_keypress(ev
)
922 ev
= ev
? ev
: window
.event
;
924 var se
= ev
.target
? ev
.target
: ev
.srcElement
;
926 if (se
.nodeType
== 3)
929 switch (ev
.keyCode
) {
930 /* backspace, delete */
933 if (se
.value
.length
== 0) {
934 if (ev
.preventDefault
)
942 /* enter, arrow up, arrow down */
946 if (ev
.preventDefault
)
955 function cbi_dynlist_keydown(ev
)
957 ev
= ev
? ev
: window
.event
;
959 var se
= ev
.target
? ev
.target
: ev
.srcElement
;
961 if (se
.nodeType
== 3)
964 var prev
= se
.previousSibling
;
965 while (prev
&& prev
.name
!= prefix
)
966 prev
= prev
.previousSibling
;
968 var next
= se
.nextSibling
;
969 while (next
&& next
.name
!= prefix
)
970 next
= next
.nextSibling
;
972 /* advance one further in combobox case */
973 if (next
&& next
.nextSibling
.name
== prefix
)
974 next
= next
.nextSibling
;
976 switch (ev
.keyCode
) {
977 /* backspace, delete */
980 var del
= (matchesElem(se
, 'select'))
981 ? true : (se
.value
.length
== 0);
984 if (ev
.preventDefault
)
987 var focus
= se
.index
;
991 cbi_dynlist_redraw(focus
, -1, se
.index
);
1000 cbi_dynlist_redraw(-1, se
.index
, -1);
1021 function cbi_dynlist_btnclick(ev
)
1023 ev
= ev
? ev
: window
.event
;
1025 var se
= ev
.target
? ev
.target
: ev
.srcElement
;
1026 var input
= se
.previousSibling
;
1027 while (input
&& input
.name
!= prefix
)
1028 input
= input
.previousSibling
;
1030 if (se
.classList
.contains('cbi-button-remove')) {
1033 cbi_dynlist_keydown({
1039 cbi_dynlist_keydown({
1048 cbi_dynlist_redraw(NaN
, -1, -1);
1052 function cbi_t_add(section
, tab
) {
1053 var t
= document
.getElementById('tab.' + section
+ '.' + tab
);
1054 var c
= document
.getElementById('container.' + section
+ '.' + tab
);
1057 cbi_t
[section
] = (cbi_t
[section
] || [ ]);
1058 cbi_t
[section
][tab
] = { 'tab': t
, 'container': c
, 'cid': c
.id
};
1062 function cbi_t_switch(section
, tab
) {
1063 if (cbi_t
[section
] && cbi_t
[section
][tab
]) {
1064 var o
= cbi_t
[section
][tab
];
1065 var h
= document
.getElementById('tab.' + section
);
1067 for (var tid
in cbi_t
[section
]) {
1068 var o2
= cbi_t
[section
][tid
];
1070 if (o
.tab
.id
!= o2
.tab
.id
) {
1071 o2
.tab
.classList
.remove('cbi-tab');
1072 o2
.tab
.classList
.add('cbi-tab-disabled');
1073 o2
.container
.style
.display
= 'none';
1079 o2
.tab
.classList
.remove('cbi-tab-disabled');
1080 o2
.tab
.classList
.add('cbi-tab');
1081 o2
.container
.style
.display
= 'block';
1089 function cbi_t_update() {
1091 var updated
= false;
1093 for (var sid
in cbi_t
)
1094 for (var tid
in cbi_t
[sid
]) {
1095 var t
= cbi_t
[sid
][tid
].tab
;
1096 var c
= cbi_t
[sid
][tid
].container
;
1098 if (!c
.firstElementChild
) {
1099 t
.style
.display
= 'none';
1101 else if (t
.style
.display
== 'none') {
1102 t
.style
.display
= '';
1103 t
.classList
.add('cbi-tab-highlighted');
1111 if (hl_tabs
.length
> 0)
1112 window
.setTimeout(function() {
1113 for (var i
= 0; i
< hl_tabs
.length
; i
++)
1114 hl_tabs
[i
].classList
.remove('cbi-tab-highlighted');
1121 function cbi_validate_form(form
, errmsg
)
1123 /* if triggered by a section removal or addition, don't validate */
1124 if (form
.cbi_state
== 'add-section' || form
.cbi_state
== 'del-section')
1127 if (form
.cbi_validators
) {
1128 for (var i
= 0; i
< form
.cbi_validators
.length
; i
++) {
1129 var validator
= form
.cbi_validators
[i
];
1131 if (!validator() && errmsg
) {
1141 function cbi_validate_reset(form
)
1144 function() { cbi_validate_form(form
, null) }, 100
1150 function cbi_validate_compile(code
)
1159 for (var i
= 0; i
< code
.length
; i
++) {
1165 switch (code
.charCodeAt(i
))
1175 var label
= code
.substring(pos
, i
);
1176 label
= label
.replace(/\\(.)/g, '$1');
1177 label
= label
.replace(/^[ \t]+/g, '');
1178 label
= label
.replace(/[ \t]+$/g, '');
1180 if (label
&& !isNaN(label
)) {
1181 stack
.push(parseFloat(label
));
1183 else if (label
.match(/^(['"]).*\1$/)) {
1184 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
1186 else if (typeof cbi_validators
[label
] == 'function') {
1187 stack
.push(cbi_validators
[label
]);
1191 throw "Syntax error, unhandled token '"+label
+"'";
1198 depth
+= (code
.charCodeAt(i
) == 40);
1203 if (typeof stack
[stack
.length
-2] != 'function')
1204 throw "Syntax error, argument list follows non-function";
1206 stack
[stack
.length
-1] =
1207 arguments
.callee(code
.substring(pos
, i
));
1219 function cbi_validate_field(cbid
, optional
, type
)
1221 var field
= (typeof cbid
== "string") ? document
.getElementById(cbid
) : cbid
;
1222 var vstack
; try { vstack
= cbi_validate_compile(type
); } catch(e
) { };
1224 if (field
&& vstack
&& typeof vstack
[0] == "function") {
1225 var validator = function()
1229 field
.classList
.remove('cbi-input-invalid');
1232 var value
= (field
.options
&& field
.options
.selectedIndex
> -1)
1233 ? field
.options
[field
.options
.selectedIndex
].value
: field
.value
;
1235 if (!(((value
.length
== 0) && optional
) || vstack
[0].apply(value
, vstack
[1]))) {
1237 field
.classList
.add('cbi-input-invalid');
1245 if (!field
.form
.cbi_validators
)
1246 field
.form
.cbi_validators
= [ ];
1248 field
.form
.cbi_validators
.push(validator
);
1250 cbi_bind(field
, "blur", validator
);
1251 cbi_bind(field
, "keyup", validator
);
1253 if (matchesElem(field
, 'select')) {
1254 cbi_bind(field
, "change", validator
);
1255 cbi_bind(field
, "click", validator
);
1258 field
.setAttribute("cbi_validate", validator
);
1259 field
.setAttribute("cbi_datatype", type
);
1260 field
.setAttribute("cbi_optional", (!!optional
).toString());
1264 var fcbox
= document
.getElementById('cbi.combobox.' + field
.id
);
1266 cbi_validate_field(fcbox
, optional
, type
);
1270 function cbi_row_swap(elem
, up
, store
)
1272 var tr
= findParent(elem
.parentNode
, '.cbi-section-table-row');
1277 tr
.classList
.remove('flash');
1280 var prev
= tr
.previousElementSibling
;
1282 if (prev
&& prev
.classList
.contains('cbi-section-table-row'))
1283 tr
.parentNode
.insertBefore(tr
, prev
);
1288 var next
= tr
.nextElementSibling
? tr
.nextElementSibling
.nextElementSibling
: null;
1290 if (next
&& next
.classList
.contains('cbi-section-table-row'))
1291 tr
.parentNode
.insertBefore(tr
, next
);
1293 tr
.parentNode
.appendChild(tr
);
1300 for (var i
= 0, n
= 0; i
< tr
.parentNode
.childNodes
.length
; i
++) {
1301 var node
= tr
.parentNode
.childNodes
[i
];
1302 if (node
.classList
&& node
.classList
.contains('cbi-section-table-row')) {
1303 node
.classList
.remove('cbi-rowstyle-1');
1304 node
.classList
.remove('cbi-rowstyle-2');
1305 node
.classList
.add((n
++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1307 if (/-([^\-]+)$/.test(node
.id
))
1308 ids
.push(RegExp
.$1);
1312 var input
= document
.getElementById(store
);
1314 input
.value
= ids
.join(' ');
1316 window
.scrollTo(0, tr
.offsetTop
);
1317 void tr
.offsetWidth
;
1318 tr
.classList
.add('flash');
1323 function cbi_tag_last(container
)
1327 for (var i
= 0; i
< container
.childNodes
.length
; i
++) {
1328 var c
= container
.childNodes
[i
];
1329 if (matchesElem(c
, 'div')) {
1330 c
.classList
.remove('cbi-value-last');
1336 last
.classList
.add('cbi-value-last');
1339 function cbi_submit(elem
, name
, value
, action
)
1341 var form
= elem
.form
|| findParent(elem
, 'form');
1347 form
.action
= action
;
1350 var hidden
= form
.querySelector('input[type="hidden"][name="%s"]'.format(name
)) ||
1351 E('input', { type
: 'hidden', name
: name
});
1353 hidden
.value
= value
|| '1';
1354 form
.appendChild(hidden
);
1361 String
.prototype.format = function()
1366 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1367 var quot_esc = [/"/g
, '"', /'/g, '''];
1369 function esc(s, r) {
1370 if (typeof(s) !== 'string
' && !(s instanceof String))
1373 for (var i = 0; i < r.length; i += 2)
1374 s = s.replace(r[i], r[i+1]);
1381 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
1382 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
1384 while (a
= re
.exec(str
)) {
1386 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
1387 var pPrecision
= a
[6], pType
= a
[7];
1395 if (numSubstitutions
< arguments
.length
) {
1396 var param
= arguments
[numSubstitutions
++];
1399 if (pPad
&& pPad
.substr(0,1) == "'")
1400 pad
= leftpart
.substr(1,1);
1406 var justifyRight
= true;
1407 if (pJustify
&& pJustify
=== "-")
1408 justifyRight
= false;
1412 minLength
= +pMinLength
;
1415 if (pPrecision
&& pType
== 'f')
1416 precision
= +pPrecision
.substring(1);
1422 subst
= (+param
|| 0).toString(2);
1426 subst
= String
.fromCharCode(+param
|| 0);
1430 subst
= ~~(+param
|| 0);
1434 subst
= ~~Math
.abs(+param
|| 0);
1438 subst
= (precision
> -1)
1439 ? ((+param
|| 0.0)).toFixed(precision
)
1444 subst
= (+param
|| 0).toString(8);
1452 subst
= ('' + (+param
|| 0).toString(16)).toLowerCase();
1456 subst
= ('' + (+param
|| 0).toString(16)).toUpperCase();
1460 subst
= esc(param
, html_esc
);
1464 subst
= esc(param
, quot_esc
);
1471 var ts
= (param
|| 0);
1474 tm
= Math
.floor(ts
/ 60);
1479 th
= Math
.floor(tm
/ 60);
1484 td
= Math
.floor(th
/ 24);
1489 ? String
.format('%dd %dh %dm %ds', td
, th
, tm
, ts
)
1490 : String
.format('%dh %dm %ds', th
, tm
, ts
);
1495 var mf
= pMinLength
? +pMinLength
: 1000;
1496 var pr
= pPrecision
? ~~(10 * +('0' + pPrecision
)) : 2;
1499 var val
= (+param
|| 0);
1500 var units
= [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1502 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
1505 subst
= (i
? val
.toFixed(pr
) : val
) + units
[i
];
1513 subst
= subst
.toString();
1514 for (var i
= subst
.length
; i
< pMinLength
; i
++)
1515 if (pJustify
== '-')
1516 subst
= subst
+ ' ';
1518 subst
= pad
+ subst
;
1521 out
+= leftpart
+ subst
;
1522 str
= str
.substr(m
.length
);
1528 String
.prototype.nobr = function()
1530 return this.replace(/[\s\n]+/g, ' ');
1533 String
.format = function()
1537 for (var i
= 1; i
< arguments
.length
; i
++)
1538 a
.push(arguments
[i
]);
1540 return ''.format
.apply(arguments
[0], a
);
1543 String
.nobr = function()
1547 for (var i
= 1; i
< arguments
.length
; i
++)
1548 a
.push(arguments
[i
]);
1550 return ''.nobr
.apply(arguments
[0], a
);
1553 if (window
.NodeList
&& !NodeList
.prototype.forEach
) {
1554 NodeList
.prototype.forEach = function (callback
, thisArg
) {
1555 thisArg
= thisArg
|| window
;
1556 for (var i
= 0; i
< this.length
; i
++) {
1557 callback
.call(thisArg
, this[i
], i
, this);
1563 var dummyElem
, domParser
;
1567 return (typeof(e
) === 'object' && e
!== null && 'nodeType' in e
);
1575 domParser
= domParser
|| new DOMParser();
1576 elem
= domParser
.parseFromString(s
, 'text/html').body
.firstChild
;
1582 dummyElem
= dummyElem
|| document
.createElement('div');
1583 dummyElem
.innerHTML
= s
;
1584 elem
= dummyElem
.firstChild
;
1589 return elem
|| null;
1592 function matchesElem(node
, selector
)
1594 return ((node
.matches
&& node
.matches(selector
)) ||
1595 (node
.msMatchesSelector
&& node
.msMatchesSelector(selector
)));
1598 function findParent(node
, selector
)
1601 if (matchesElem(node
, selector
))
1604 node
= node
.parentNode
;
1611 var html
= arguments
[0],
1612 attr
= (arguments
[1] instanceof Object
&& !Array
.isArray(arguments
[1])) ? arguments
[1] : null,
1613 data
= attr
? arguments
[2] : arguments
[1],
1618 else if (html
.charCodeAt(0) === 60)
1619 elem
= toElem(html
);
1621 elem
= document
.createElement(html
);
1627 for (var key
in attr
)
1628 if (attr
.hasOwnProperty(key
) && attr
[key
] !== null && attr
[key
] !== undefined)
1629 elem
.setAttribute(key
, attr
[key
]);
1631 if (typeof(data
) === 'function')
1635 elem
.appendChild(data
);
1637 else if (Array
.isArray(data
)) {
1638 for (var i
= 0; i
< data
.length
; i
++)
1639 if (isElem(data
[i
]))
1640 elem
.appendChild(data
[i
]);
1642 elem
.appendChild(document
.createTextNode('' + data
[i
]));
1644 else if (data
!== null && data
!== undefined) {
1645 elem
.innerHTML
= '' + data
;
1651 if (typeof(window
.CustomEvent
) !== 'function') {
1652 function CustomEvent(event
, params
) {
1653 params
= params
|| { bubbles
: false, cancelable
: false, detail
: undefined };
1654 var evt
= document
.createEvent('CustomEvent');
1655 evt
.initCustomEvent( event
, params
.bubbles
, params
.cancelable
, params
.detail
);
1659 CustomEvent
.prototype = window
.Event
.prototype;
1660 window
.CustomEvent
= CustomEvent
;
1664 openDropdown: function(sb
) {
1665 var st
= window
.getComputedStyle(sb
, null),
1666 ul
= sb
.querySelector('ul'),
1667 li
= ul
.querySelectorAll('li'),
1668 sel
= ul
.querySelector('[selected]'),
1669 rect
= sb
.getBoundingClientRect(),
1670 h
= sb
.clientHeight
- parseFloat(st
.paddingTop
) - parseFloat(st
.paddingBottom
),
1671 mh
= this.dropdown_items
* h
,
1672 eh
= Math
.min(mh
, li
.length
* h
);
1674 document
.querySelectorAll('.cbi-dropdown[open]').forEach(function(s
) {
1675 s
.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1678 ul
.style
.maxHeight
= mh
+ 'px';
1679 sb
.setAttribute('open', '');
1681 ul
.scrollTop
= sel
? Math
.max(sel
.offsetTop
- sel
.offsetHeight
, 0) : 0;
1682 ul
.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c
) {
1686 ul
.style
.top
= ul
.style
.bottom
= '';
1687 ul
.style
[((sb
.getBoundingClientRect().top
+ eh
) > window
.innerHeight
) ? 'bottom' : 'top'] = rect
.height
+ 'px';
1688 ul
.classList
.add('dropdown');
1690 var pv
= ul
.cloneNode(true);
1691 pv
.classList
.remove('dropdown');
1692 pv
.classList
.add('preview');
1694 sb
.insertBefore(pv
, ul
.nextElementSibling
);
1696 li
.forEach(function(l
) {
1697 l
.setAttribute('tabindex', 0);
1700 sb
.lastElementChild
.setAttribute('tabindex', 0);
1702 this.setFocus(sb
, sel
|| li
[0], true);
1705 closeDropdown: function(sb
, no_focus
) {
1706 if (!sb
.hasAttribute('open'))
1709 var pv
= sb
.querySelector('ul.preview'),
1710 ul
= sb
.querySelector('ul.dropdown'),
1711 li
= ul
.querySelectorAll('li');
1713 li
.forEach(function(l
) { l
.removeAttribute('tabindex'); });
1714 sb
.lastElementChild
.removeAttribute('tabindex');
1717 sb
.removeAttribute('open');
1718 sb
.style
.width
= sb
.style
.height
= '';
1720 ul
.classList
.remove('dropdown');
1723 this.setFocus(sb
, sb
);
1725 this.saveValues(sb
, ul
);
1728 toggleItem: function(sb
, li
, force_state
) {
1729 if (li
.hasAttribute('unselectable'))
1733 var cbox
= li
.querySelector('input[type="checkbox"]'),
1734 items
= li
.parentNode
.querySelectorAll('li'),
1735 label
= sb
.querySelector('ul.preview'),
1736 sel
= li
.parentNode
.querySelectorAll('[selected]').length
,
1737 more
= sb
.querySelector('.more'),
1738 ndisplay
= this.display_items
,
1741 if (li
.hasAttribute('selected')) {
1742 if (force_state
!== true) {
1743 if (sel
> 1 || this.optional
) {
1744 li
.removeAttribute('selected');
1745 cbox
.checked
= cbox
.disabled
= false;
1749 cbox
.disabled
= true;
1754 if (force_state
!== false) {
1755 li
.setAttribute('selected', '');
1756 cbox
.checked
= true;
1757 cbox
.disabled
= false;
1762 while (label
.firstElementChild
)
1763 label
.removeChild(label
.firstElementChild
);
1765 for (var i
= 0; i
< items
.length
; i
++) {
1766 items
[i
].removeAttribute('display');
1767 if (items
[i
].hasAttribute('selected')) {
1768 if (ndisplay
-- > 0) {
1769 items
[i
].setAttribute('display', n
++);
1770 label
.appendChild(items
[i
].cloneNode(true));
1772 var c
= items
[i
].querySelector('input[type="checkbox"]');
1774 c
.disabled
= (sel
== 1 && !this.optional
);
1779 sb
.setAttribute('more', '');
1781 sb
.removeAttribute('more');
1783 if (ndisplay
=== this.display_items
)
1784 sb
.setAttribute('empty', '');
1786 sb
.removeAttribute('empty');
1788 more
.innerHTML
= (ndisplay
=== this.display_items
) ? this.placeholder
: '···';
1791 var sel
= li
.parentNode
.querySelector('[selected]');
1793 sel
.removeAttribute('display');
1794 sel
.removeAttribute('selected');
1797 li
.setAttribute('display', 0);
1798 li
.setAttribute('selected', '');
1800 this.closeDropdown(sb
, true);
1803 this.saveValues(sb
, li
.parentNode
);
1806 transformItem: function(sb
, li
) {
1807 var cbox
= E('form', {}, E('input', { type
: 'checkbox', tabindex
: -1, onclick
: 'event.preventDefault()' })),
1810 while (li
.firstChild
)
1811 label
.appendChild(li
.firstChild
);
1813 li
.appendChild(cbox
);
1814 li
.appendChild(label
);
1817 saveValues: function(sb
, ul
) {
1818 var sel
= ul
.querySelectorAll('[selected]'),
1819 div
= sb
.lastElementChild
;
1821 while (div
.lastElementChild
)
1822 div
.removeChild(div
.lastElementChild
);
1824 sel
.forEach(function (s
) {
1825 div
.appendChild(E('input', {
1827 name
: s
.hasAttribute('name') ? s
.getAttribute('name') : (sb
.getAttribute('name') || ''),
1828 value
: s
.hasAttribute('data-value') ? s
.getAttribute('data-value') : s
.innerText
1835 setFocus: function(sb
, elem
, scroll
) {
1836 if (sb
&& sb
.hasAttribute
&& sb
.hasAttribute('locked-in'))
1839 document
.querySelectorAll('.focus').forEach(function(e
) {
1840 if (!matchesElem(e
, 'input')) {
1841 e
.classList
.remove('focus');
1848 elem
.classList
.add('focus');
1851 elem
.parentNode
.scrollTop
= elem
.offsetTop
- elem
.parentNode
.offsetTop
;
1855 createItems: function(sb
, value
) {
1857 val
= (value
|| '').trim().split(/\s+/),
1858 ul
= sb
.querySelector('ul');
1861 val
.length
= Math
.min(val
.length
, 1);
1863 val
.forEach(function(item
) {
1864 var new_item
= null;
1866 ul
.childNodes
.forEach(function(li
) {
1867 if (li
.getAttribute
&& li
.getAttribute('data-value') === item
)
1873 tpl
= sb
.querySelector(sbox
.template
);
1876 markup
= (tpl
.textContent
|| tpl
.innerHTML
|| tpl
.firstChild
.data
).replace(/^<!--|-->$/, '').trim();
1878 markup
= '<li data-value="{{value}}">{{value}}</li>';
1880 new_item
= E(markup
.replace(/{{value}}/g, item
));
1883 sbox
.transformItem(sb
, new_item
);
1886 var old
= ul
.querySelector('li[created]');
1888 ul
.removeChild(old
);
1890 new_item
.setAttribute('created', '');
1893 new_item
= ul
.insertBefore(new_item
, ul
.lastElementChild
);
1896 sbox
.toggleItem(sb
, new_item
, true);
1897 sbox
.setFocus(sb
, new_item
, true);
1901 closeAllDropdowns: function() {
1902 document
.querySelectorAll('.cbi-dropdown[open]').forEach(function(s
) {
1903 s
.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1908 function cbi_dropdown_init(sb
) {
1909 if (!(this instanceof cbi_dropdown_init
))
1910 return new cbi_dropdown_init(sb
);
1912 this.multi
= sb
.hasAttribute('multiple');
1913 this.optional
= sb
.hasAttribute('optional');
1914 this.placeholder
= sb
.getAttribute('placeholder') || '---';
1915 this.display_items
= parseInt(sb
.getAttribute('display-items') || 3);
1916 this.dropdown_items
= parseInt(sb
.getAttribute('dropdown-items') || 5);
1917 this.create
= sb
.getAttribute('item-create') || '.create-item-input';
1918 this.template
= sb
.getAttribute('item-template') || 'script[type="item-template"]';
1921 ul
= sb
.querySelector('ul'),
1922 items
= ul
.querySelectorAll('li'),
1923 more
= sb
.appendChild(E('span', { class: 'more', tabindex
: -1 }, '···')),
1924 open
= sb
.appendChild(E('span', { class: 'open', tabindex
: -1 }, '▾')),
1925 canary
= sb
.appendChild(E('div')),
1926 create
= sb
.querySelector(this.create
),
1927 ndisplay
= this.display_items
,
1931 for (var i
= 0; i
< items
.length
; i
++) {
1932 sbox
.transformItem(sb
, items
[i
]);
1934 if (items
[i
].hasAttribute('selected') && ndisplay
-- > 0)
1935 items
[i
].setAttribute('display', n
++);
1939 var sel
= sb
.querySelectorAll('[selected]');
1941 sel
.forEach(function(s
) {
1942 s
.removeAttribute('selected');
1945 var s
= sel
[0] || items
[0];
1947 s
.setAttribute('selected', '');
1948 s
.setAttribute('display', n
++);
1953 if (this.optional
&& !ul
.querySelector('li[data-value=""]')) {
1954 var placeholder
= E('li', { placeholder
: '' }, this.placeholder
);
1955 ul
.firstChild
? ul
.insertBefore(placeholder
, ul
.firstChild
) : ul
.appendChild(placeholder
);
1959 sbox
.saveValues(sb
, ul
);
1961 ul
.setAttribute('tabindex', -1);
1962 sb
.setAttribute('tabindex', 0);
1965 sb
.setAttribute('more', '')
1967 sb
.removeAttribute('more');
1969 if (ndisplay
=== this.display_items
)
1970 sb
.setAttribute('empty', '')
1972 sb
.removeAttribute('empty');
1974 more
.innerHTML
= (ndisplay
=== this.display_items
) ? this.placeholder
: '···';
1977 sb
.addEventListener('click', function(ev
) {
1978 if (!this.hasAttribute('open')) {
1979 if (!matchesElem(ev
.target
, 'input'))
1980 sbox
.openDropdown(this);
1983 var li
= findParent(ev
.target
, 'li');
1984 if (li
&& li
.parentNode
.classList
.contains('dropdown'))
1985 sbox
.toggleItem(this, li
);
1988 ev
.preventDefault();
1989 ev
.stopPropagation();
1992 sb
.addEventListener('keydown', function(ev
) {
1993 if (matchesElem(ev
.target
, 'input'))
1996 if (!this.hasAttribute('open')) {
1997 switch (ev
.keyCode
) {
2002 sbox
.openDropdown(this);
2003 ev
.preventDefault();
2008 var active
= findParent(document
.activeElement
, 'li');
2010 switch (ev
.keyCode
) {
2012 sbox
.closeDropdown(this);
2017 if (!active
.hasAttribute('selected'))
2018 sbox
.toggleItem(this, active
);
2019 sbox
.closeDropdown(this);
2020 ev
.preventDefault();
2026 sbox
.toggleItem(this, active
);
2027 ev
.preventDefault();
2032 if (active
&& active
.previousElementSibling
) {
2033 sbox
.setFocus(this, active
.previousElementSibling
);
2034 ev
.preventDefault();
2039 if (active
&& active
.nextElementSibling
) {
2040 sbox
.setFocus(this, active
.nextElementSibling
);
2041 ev
.preventDefault();
2048 sb
.addEventListener('cbi-dropdown-close', function(ev
) {
2049 sbox
.closeDropdown(this, true);
2052 if ('ontouchstart' in window
) {
2053 sb
.addEventListener('touchstart', function(ev
) { ev
.stopPropagation(); });
2054 window
.addEventListener('touchstart', sbox
.closeAllDropdowns
);
2057 sb
.addEventListener('mouseover', function(ev
) {
2058 if (!this.hasAttribute('open'))
2061 var li
= findParent(ev
.target
, 'li');
2063 if (li
.parentNode
.classList
.contains('dropdown'))
2064 sbox
.setFocus(this, li
);
2066 ev
.stopPropagation();
2070 sb
.addEventListener('focus', function(ev
) {
2071 document
.querySelectorAll('.cbi-dropdown[open]').forEach(function(s
) {
2072 if (s
!== this || this.hasAttribute('open'))
2073 s
.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
2077 canary
.addEventListener('focus', function(ev
) {
2078 sbox
.closeDropdown(this.parentNode
);
2081 window
.addEventListener('mouseover', sbox
.setFocus
);
2082 window
.addEventListener('click', sbox
.closeAllDropdowns
);
2086 create
.addEventListener('keydown', function(ev
) {
2087 switch (ev
.keyCode
) {
2089 ev
.preventDefault();
2091 if (this.classList
.contains('cbi-input-invalid'))
2094 sbox
.createItems(sb
, this.value
);
2101 create
.addEventListener('focus', function(ev
) {
2102 var cbox
= findParent(this, 'li').querySelector('input[type="checkbox"]');
2103 if (cbox
) cbox
.checked
= true;
2104 sb
.setAttribute('locked-in', '');
2107 create
.addEventListener('blur', function(ev
) {
2108 var cbox
= findParent(this, 'li').querySelector('input[type="checkbox"]');
2109 if (cbox
) cbox
.checked
= false;
2110 sb
.removeAttribute('locked-in');
2113 var li
= findParent(create
, 'li');
2115 li
.setAttribute('unselectable', '');
2116 li
.addEventListener('click', function(ev
) {
2117 this.querySelector(sbox
.create
).focus();
2122 cbi_dropdown_init
.prototype = CBIDropdown
;
2124 function cbi_update_table(table
, data
, placeholder
) {
2125 var target
= isElem(table
) ? table
: document
.querySelector(table
);
2127 if (!isElem(target
))
2130 target
.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead
) {
2133 thead
.querySelectorAll('.th').forEach(function(th
) {
2137 if (Array
.isArray(data
)) {
2138 var n
= 0, rows
= target
.querySelectorAll('.tr');
2140 data
.forEach(function(row
) {
2141 var trow
= E('div', { 'class': 'tr' });
2143 for (var i
= 0; i
< titles
.length
; i
++) {
2144 var text
= (titles
[i
].innerText
|| '').trim();
2145 var td
= trow
.appendChild(E('div', {
2146 'class': titles
[i
].className
,
2147 'data-title': (text
!== '') ? text
: null
2150 td
.classList
.remove('th');
2151 td
.classList
.add('td');
2154 trow
.classList
.add('cbi-rowstyle-%d'.format((n
++ % 2) ? 2 : 1));
2157 target
.replaceChild(trow
, rows
[n
]);
2159 target
.appendChild(trow
);
2163 target
.removeChild(rows
[n
]);
2165 if (placeholder
&& target
.firstElementChild
=== target
.lastElementChild
) {
2166 var trow
= target
.appendChild(E('div', { 'class': 'tr placeholder' }));
2167 var td
= trow
.appendChild(E('div', { 'class': titles
[0].className
}, placeholder
));
2169 td
.classList
.remove('th');
2170 td
.classList
.add('td');
2174 thead
.parentNode
.style
.display
= 'none';
2176 thead
.parentNode
.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow
) {
2177 if (trow
!== thead
) {
2179 trow
.querySelectorAll('.th, .td').forEach(function(td
) {
2180 if (n
< titles
.length
) {
2181 var text
= (titles
[n
++].innerText
|| '').trim();
2183 td
.setAttribute('data-title', text
);
2189 thead
.parentNode
.style
.display
= '';
2194 var tooltipDiv
= null, tooltipTimeout
= null;
2196 function showTooltip(ev
) {
2197 if (!matchesElem(ev
.target
, '[data-tooltip]'))
2200 if (tooltipTimeout
!== null) {
2201 window
.clearTimeout(tooltipTimeout
);
2202 tooltipTimeout
= null;
2205 var rect
= ev
.target
.getBoundingClientRect(),
2206 x
= rect
.left
+ window
.pageXOffset
,
2207 y
= rect
.top
+ rect
.height
+ window
.pageYOffset
;
2209 tooltipDiv
.className
= 'cbi-tooltip';
2210 tooltipDiv
.innerHTML
= '▲ ';
2211 tooltipDiv
.firstChild
.data
+= ev
.target
.getAttribute('data-tooltip');
2213 if (ev
.target
.hasAttribute('data-tooltip-style'))
2214 tooltipDiv
.classList
.add(ev
.target
.getAttribute('data-tooltip-style'));
2216 if ((y
+ tooltipDiv
.offsetHeight
) > (window
.innerHeight
+ window
.pageYOffset
)) {
2217 y
-= (tooltipDiv
.offsetHeight
+ ev
.target
.offsetHeight
);
2218 tooltipDiv
.firstChild
.data
= '▼ ' + tooltipDiv
.firstChild
.data
.substr(2);
2221 tooltipDiv
.style
.top
= y
+ 'px';
2222 tooltipDiv
.style
.left
= x
+ 'px';
2223 tooltipDiv
.style
.opacity
= 1;
2226 function hideTooltip(ev
) {
2227 if (ev
.target
=== tooltipDiv
|| ev
.relatedTarget
=== tooltipDiv
)
2230 if (tooltipTimeout
!== null) {
2231 window
.clearTimeout(tooltipTimeout
);
2232 tooltipTimeout
= null;
2235 tooltipDiv
.style
.opacity
= 0;
2236 tooltipTimeout
= window
.setTimeout(function() { tooltipDiv
.removeAttribute('style'); }, 250);
2239 document
.addEventListener('DOMContentLoaded', function() {
2240 tooltipDiv
= document
.body
.appendChild(E('div', { 'class': 'cbi-tooltip' }));
2242 document
.addEventListener('mouseover', showTooltip
, true);
2243 document
.addEventListener('mouseout', hideTooltip
, true);
2244 document
.addEventListener('focus', showTooltip
, true);
2245 document
.addEventListener('blur', hideTooltip
, true);
2247 document
.querySelectorAll('.table').forEach(cbi_update_table
);