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)
110 : ((prefix_suffix.length < 2 && prefix.length < 8) || prefix.length > 8))
116 for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
117 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
122 for (i = 0; i < (8 - prefix.length - suffix.length); i++)
125 for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
126 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
134 var CBIValidatorPrototype = {
135 apply: function(name, value, args) {
138 if (typeof(name) === 'function')
140 else if (typeof(this.types[name]) === 'function')
141 func = this.types[name];
145 if (value !== undefined && value !== null)
148 return func.apply(this, args);
151 assert: function(condition, message) {
153 this.field.classList.add('cbi-input-invalid');
154 this.error = message;
158 this.field.classList.remove('cbi-input-invalid');
163 compile: function(code) {
171 for (var i = 0; i < code.length; i++) {
177 switch (code.charCodeAt(i))
187 var label = code.substring(pos, i);
188 label = label.replace(/\\(.)/g, '$1');
189 label = label.replace(/^[ \t]+/g, '');
190 label = label.replace(/[ \t]+$/g, '');
192 if (label && !isNaN(label)) {
193 stack.push(parseFloat(label));
195 else if (label.match(/^(['"]).*\1$/)) {
196 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
198 else if (typeof this.types[label] == 'function') {
199 stack.push(this.types[label]);
203 throw "Syntax error, unhandled token '"+label+"'";
210 depth += (code.charCodeAt(i) == 40);
215 if (typeof stack[stack.length-2] != 'function')
216 throw "Syntax error, argument list follows non-function";
218 stack[stack.length-1] = this.compile(code.substring(pos, i));
229 validate: function() {
230 /* element is detached */
231 if (!this.field.form)
234 this.field.classList.remove('cbi-input-invalid');
235 this.value = matchesElem(this.field, 'select') ? this.field.options[this.field.selectedIndex].value : this.field.value;
240 if (this.value.length === 0)
241 valid = this.assert(this.optional, _('non-empty value'));
243 valid = this.vstack[0].apply(this, this.vstack[1]);
246 this.field.setAttribute('data-tooltip', 'Expecting ' + this.error);
247 this.field.setAttribute('data-tooltip-style', 'error');
248 this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
251 this.field.removeAttribute('data-tooltip');
252 this.field.removeAttribute('data-tooltip-style');
253 this.field.dispatchEvent(new CustomEvent('validation-success', { bubbles: true }));
260 integer: function() {
261 return this.assert(Int(this.value) !== NaN, _('valid integer value'));
264 uinteger: function() {
265 return this.assert(Int(this.value) >= 0, _('positive integer value'));
269 return this.assert(Dec(this.value) !== NaN, _('valid decimal value'));
273 return this.assert(Dec(this.value) >= 0, _('positive decimal value'));
276 ipaddr: function(nomask) {
277 return this.assert(this.apply('ip4addr', null, [nomask]) || this.apply('ip6addr', null, [nomask]),
278 nomask ? _('valid IP address') : _('valid IP address or prefix'));
281 ip4addr: function(nomask) {
282 var re = nomask ? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
283 m = this.value.match(re);
285 return this.assert(m && IPv4(m[1]) && (m[2] ? IPv4(m[2]) : (m[3] ? this.apply('ip4prefix', m[3]) : true)),
286 nomask ? _('valid IPv4 address') : _('valid IPv4 address or network'));
289 ip6addr: function(nomask) {
290 var re = nomask ? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
291 m = this.value.match(re);
293 return this.assert(m && IPv6(m[1]) && (m[2] ? this.apply('ip6prefix', m[2]) : true),
294 nomask ? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
297 ip4prefix: function() {
298 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 32,
299 _('valid IPv4 prefix value (0-32)'));
302 ip6prefix: function() {
303 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 128,
304 _('valid IPv6 prefix value (0-128)'));
308 return this.assert(this.apply('cidr4') || this.apply('cidr6'), _('valid IPv4 or IPv6 CIDR'));
312 var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
313 return this.assert(m && IPv4(m[1]) && this.apply('ip4prefix', m[2]), _('valid IPv4 CIDR'));
317 var m = this.value.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
318 return this.assert(m && IPv6(m[1]) && this.apply('ip6prefix', m[2]), _('valid IPv6 CIDR'));
322 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})$/);
323 return this.assert(m && IPv4(m[1]) && IPv4(m[2]), _('IPv4 network in address/netmask notation'));
327 var m = this.value.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
328 return this.assert(m && IPv6(m[1]) && IPv6(m[2]), _('IPv6 network in address/netmask notation'));
331 ip6hostid: function() {
332 if (this.value == "eui64" || this.value == "random")
335 var v6 = IPv6(this.value);
336 return this.assert(!(!v6 || v6[0] || v6[1] || v6[2] || v6[3]), _('valid IPv6 host id'));
340 return this.assert(this.apply('ipmask4') || this.apply('ipmask6'),
341 _('valid network in address/netmask notation'));
344 ipmask4: function() {
345 return this.assert(this.apply('cidr4') || this.apply('ipnet4') || this.apply('ip4addr'),
346 _('valid IPv4 network'));
349 ipmask6: function() {
350 return this.assert(this.apply('cidr6') || this.apply('ipnet6') || this.apply('ip6addr'),
351 _('valid IPv6 network'));
355 var p = Int(this.value);
356 return this.assert(p >= 0 && p <= 65535, _('valid port value'));
359 portrange: function() {
360 if (this.value.match(/^(\d+)-(\d+)$/)) {
363 return this.assert(p1 <= p2 && p2 <= 65535,
364 _('valid port or port range (port1-port2)'));
367 return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
370 macaddr: function() {
371 return this.assert(this.value.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null,
372 _('valid MAC address'));
375 host: function(ipv4only) {
376 return this.assert(this.apply('hostname') || this.apply(ipv4only == 1 ? 'ip4addr' : 'ipaddr'),
377 _('valid hostname or IP address'));
380 hostname: function(strict) {
381 if (this.value.length <= 253)
383 (this.value.match(/^[a-zA-Z0-9_]+$/) != null ||
384 (this.value.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
385 this.value.match(/[^0-9.]/))) &&
386 (!strict || !this.value.match(/^_/)),
387 _('valid hostname'));
389 return this.assert(false, _('valid hostname'));
392 network: function() {
393 return this.assert(this.apply('uciname') || this.apply('host'),
394 _('valid UCI identifier, hostname or IP address'));
397 hostport: function(ipv4only) {
398 var hp = this.value.split(/:/);
399 return this.assert(hp.length == 2 && this.apply('host', hp[0], [ipv4only]) && this.apply('port', hp[1]),
400 _('valid host:port'));
403 ip4addrport: function() {
404 var hp = this.value.split(/:/);
405 return this.assert(hp.length == 2 && this.apply('ip4addr', hp[0], [true]) && this.apply('port', hp[1]),
406 _('valid IPv4 address:port'));
409 ipaddrport: function(bracket) {
410 var m4 = this.value.match(/^([^\[\]:]+):(\d+)$/),
411 m6 = this.value.match((bracket == 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
414 return this.assert(this.apply('ip4addr', m4[0], [true]) && this.apply('port', m4[1]),
415 _('valid address:port'));
417 return this.assert(m6 && this.apply('ip6addr', m6[0], [true]) && this.apply('port', m6[1]),
418 _('valid address:port'));
425 return this.assert(v.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
427 return this.assert((v.length >= 8) && (v.length <= 63), _('key between 8 and 63 characters'));
433 if (v.substr(0, 2) === 's:')
436 if ((v.length == 10) || (v.length == 26))
437 return this.assert(v.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
439 return this.assert((v.length === 5) || (v.length === 13), _('key with either 5 or 13 characters'));
442 uciname: function() {
443 return this.assert(this.value.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
446 range: function(min, max) {
447 var val = Dec(this.value);
448 return this.assert(val >= +min && val <= +max, _('value between %f and %f').format(min, max));
452 return this.assert(Dec(this.value) >= +min, _('value greater or equal to %f').format(min));
456 return this.assert(Dec(this.value) <= +max, _('value smaller or equal to %f').format(max));
459 rangelength: function(min, max) {
460 var val = '' + this.value;
461 return this.assert((val.length >= +min) && (val.length <= +max),
462 _('value between %d and %d characters').format(min, max));
465 minlength: function(min) {
466 return this.assert((''+this.value).length >= +min,
467 _('value with at least %d characters').format(min));
470 maxlength: function(max) {
471 return this.assert((''+this.value).length <= +max,
472 _('value with at most %d characters').format(max));
478 for (var i = 0; i < arguments.length; i += 2) {
479 if (typeof arguments[i] != 'function') {
480 if (arguments[i] == this.value)
481 return this.assert(true);
482 errors.push('"%s"'.format(arguments[i]));
485 else if (arguments[i].apply(this, arguments[i+1])) {
486 return this.assert(true);
489 errors.push(this.error);
493 return this.assert(false, _('one of:\n - %s'.format(errors.join('\n - '))));
497 for (var i = 0; i < arguments.length; i += 2) {
498 if (typeof arguments[i] != 'function') {
499 if (arguments[i] != this.value)
500 return this.assert(false, '"%s"'.format(arguments[i]));
503 else if (!arguments[i].apply(this, arguments[i+1])) {
504 return this.assert(false, this.error);
508 return this.assert(true);
512 return this.apply('or', this.value.replace(/^[ \t]*![ \t]*/, ''), arguments);
515 list: function(subvalidator, subargs) {
516 this.field.setAttribute('data-is-list', 'true');
518 var tokens = this.value.match(/[^ \t]+/g);
519 for (var i = 0; i < tokens.length; i++)
520 if (!this.apply(subvalidator, tokens[i], subargs))
521 return this.assert(false, this.error);
523 return this.assert(true);
526 phonedigit: function() {
527 return this.assert(this.value.match(/^[0-9\*#!\.]+$/),
528 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
531 timehhmmss: function() {
532 return this.assert(this.value.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
533 _('valid time (HH:MM:SS'));
536 dateyyyymmdd: function() {
537 if (this.value.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
538 var year = +RegExp.$1,
541 days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
543 function is_leap_year(year) {
544 return ((!(year % 4) && (year % 100)) || !(year % 400));
547 function get_days_in_month(month, year) {
548 return (month === 2 && is_leap_year(year)) ? 29 : days_in_month[month - 1];
551 /* Firewall rules in the past don't make sense */
552 return this.assert(year >= 2015 && month && month <= 12 && day && day <= get_days_in_month(month, year),
553 _('valid date (YYYY-MM-DD)'));
557 return this.assert(false, _('valid date (YYYY-MM-DD)'));
560 unique: function(subvalidator, subargs) {
562 option = findParent(ctx.field, '[data-type][data-name]'),
563 section = findParent(option, '.cbi-section'),
564 query = '[data-type="%s"][data-name="%s"]'.format(option.getAttribute('data-type'), option.getAttribute('data-name')),
567 section.querySelectorAll(query).forEach(function(sibling) {
568 if (sibling === option)
571 var input = sibling.querySelector('[data-type]'),
572 values = input.getAttribute('data-is-list') ? input.value.match(/[^ \t]+/g) : [ input.value ];
574 if (values !== null && values.indexOf(ctx.value) !== -1)
579 return this.assert(false, _('unique value'));
581 if (typeof(subvalidator) === 'function')
582 return this.apply(subvalidator, undefined, subargs);
584 return this.assert(true);
589 function CBIValidator(field, type, optional)
592 this.optional = optional;
593 this.vstack = this.compile(type);
596 CBIValidator.prototype = CBIValidatorPrototype;
599 function cbi_d_add(field, dep, index) {
600 var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
603 for (var i=0; i<cbi_d.length; i++) {
604 if (cbi_d[i].id == obj.id) {
613 "parent": obj.parentNode.id,
617 cbi_d.unshift(entry);
623 function cbi_d_checkvalue(target, ref) {
625 query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
626 'select[id="'+target+'"], select[name="'+target+'"]';
628 document.querySelectorAll(query).forEach(function(i) {
629 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
633 return (((value !== null) ? value : "") == ref);
636 function cbi_d_check(deps) {
639 for (var i=0; i<deps.length; i++) {
642 for (var j in deps[i]) {
643 if (j == "!reverse") {
645 } else if (j == "!default") {
649 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
653 if (istat ^ reverse) {
660 function cbi_d_update() {
662 for (var i=0; i<cbi_d.length; i++) {
663 var entry = cbi_d[i];
664 var node = document.getElementById(entry.id);
665 var parent = document.getElementById(entry.parent);
667 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
668 node.parentNode.removeChild(node);
671 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
672 var next = undefined;
674 for (next = parent.firstChild; next; next = next.nextSibling) {
675 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
680 parent.appendChild(entry.node);
682 parent.insertBefore(entry.node, next);
687 // hide optionals widget if no choices remaining
688 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
689 parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
692 if (entry && entry.parent) {
694 cbi_tag_last(parent);
701 function cbi_init() {
704 nodes = document.querySelectorAll('[data-strings]');
706 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
707 var str = JSON.parse(node.getAttribute('data-strings'));
708 for (var key in str) {
709 for (var key2 in str[key]) {
710 var dst = cbi_strings[key] || (cbi_strings[key] = { });
711 dst[key2] = str[key][key2];
716 nodes = document.querySelectorAll('[data-depends]');
718 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
719 var index = parseInt(node.getAttribute('data-index'), 10);
720 var depends = JSON.parse(node.getAttribute('data-depends'));
721 if (!isNaN(index) && depends.length > 0) {
722 for (var alt = 0; alt < depends.length; alt++)
723 cbi_d_add(node, depends[alt], index);
727 nodes = document.querySelectorAll('[data-update]');
729 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
730 var events = node.getAttribute('data-update').split(' ');
731 for (var j = 0, event; (event = events[j]) !== undefined; j++)
732 cbi_bind(node, event, cbi_d_update);
735 nodes = document.querySelectorAll('[data-choices]');
737 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
738 var choices = JSON.parse(node.getAttribute('data-choices'));
741 for (var j = 0; j < choices[0].length; j++)
742 options[choices[0][j]] = choices[1][j];
744 var def = (node.getAttribute('data-optional') === 'true')
745 ? node.placeholder || '' : null;
747 cbi_combobox_init(node, options, def,
748 node.getAttribute('data-manual'));
751 nodes = document.querySelectorAll('[data-dynlist]');
753 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
754 var choices = JSON.parse(node.getAttribute('data-dynlist'));
757 if (choices[0] && choices[0].length) {
760 for (var j = 0; j < choices[0].length; j++)
761 options[choices[0][j]] = choices[1][j];
764 cbi_dynlist_init(node, choices[2], choices[3], options);
767 nodes = document.querySelectorAll('[data-type]');
769 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
770 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
771 node.getAttribute('data-type'));
774 document.querySelectorAll('.cbi-dropdown').forEach(function(s) {
775 cbi_dropdown_init(s);
778 document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
779 s.parentNode.classList.add('cbi-tooltip-container');
782 document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
783 var handler = function(ev) {
784 var bits = this.name.split(/\./),
785 section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
787 section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
790 i.addEventListener('mouseover', handler);
791 i.addEventListener('mouseout', handler);
797 function cbi_bind(obj, type, callback, mode) {
798 if (!obj.addEventListener) {
799 obj.attachEvent('on' + type,
801 var e = window.event;
803 if (!e.target && e.srcElement)
804 e.target = e.srcElement;
806 return !!callback(e);
810 obj.addEventListener(type, callback, !!mode);
815 function cbi_combobox(id, values, def, man, focus) {
816 var selid = "cbi.combobox." + id;
817 if (document.getElementById(selid)) {
821 var obj = document.getElementById(id)
822 var sel = document.createElement("select");
824 sel.index = obj.index;
825 sel.classList.remove('cbi-input-text');
826 sel.classList.add('cbi-input-select');
829 obj.parentNode.insertBefore(sel, obj.nextSibling);
831 obj.parentNode.appendChild(sel);
833 var dt = obj.getAttribute('cbi_datatype');
834 var op = obj.getAttribute('cbi_optional');
836 if (!values[obj.value]) {
837 if (obj.value == "") {
838 var optdef = document.createElement("option");
840 optdef.appendChild(document.createTextNode(typeof(def) === 'string' ? def : _('-- Please choose --')));
841 sel.appendChild(optdef);
844 var opt = document.createElement("option");
845 opt.value = obj.value;
846 opt.selected = "selected";
847 opt.appendChild(document.createTextNode(obj.value));
848 sel.appendChild(opt);
852 for (var i in values) {
853 var opt = document.createElement("option");
857 opt.selected = "selected";
859 opt.appendChild(document.createTextNode(values[i]));
860 sel.appendChild(opt);
863 var optman = document.createElement("option");
865 optman.appendChild(document.createTextNode(typeof(man) === 'string' ? man : _('-- custom --')));
866 sel.appendChild(optman);
868 obj.style.display = "none";
871 cbi_validate_field(sel, op == 'true', dt);
873 cbi_bind(sel, "change", function() {
874 if (sel.selectedIndex == sel.options.length - 1) {
875 obj.style.display = "inline";
877 sel.parentNode.removeChild(sel);
881 obj.value = sel.options[sel.selectedIndex].value;
891 // Retrigger validation in select
898 function cbi_combobox_init(id, values, def, man) {
899 var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
900 cbi_bind(obj, "blur", function() {
901 cbi_combobox(obj.id, values, def, man, true);
903 cbi_combobox(obj.id, values, def, man, false);
906 function cbi_filebrowser(id, defpath) {
907 var field = document.getElementById(id);
908 var browser = window.open(
909 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
910 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
916 function cbi_browser_init(id, resource, defpath)
918 function cbi_browser_btnclick(e) {
919 cbi_filebrowser(id, defpath);
923 var field = document.getElementById(id);
925 var btn = document.createElement('img');
926 btn.className = 'cbi-image-button';
927 btn.src = (resource || cbi_strings.path.resource) + '/cbi/folder.gif';
928 field.parentNode.insertBefore(btn, field.nextSibling);
930 cbi_bind(btn, 'click', cbi_browser_btnclick);
933 function cbi_dynlist_init(parent, datatype, optional, choices)
935 var prefix = parent.getAttribute('data-prefix');
936 var holder = parent.getAttribute('data-placeholder');
940 function cbi_dynlist_redraw(focus, add, del)
944 while (parent.firstChild) {
945 var n = parent.firstChild;
949 if (matchesElem(n, 'input'))
950 values.push(n.value || '');
951 else if (matchesElem(n, 'select'))
952 values[values.length-1] = n.options[n.selectedIndex].value;
955 parent.removeChild(n);
960 values.splice(focus, 0, '');
962 else if (values.length == 0) {
967 for (var i = 0; i < values.length; i++) {
968 var t = document.createElement('input');
969 t.id = prefix + '.' + (i+1);
974 t.className = 'cbi-input-text';
976 if (i == 0 && holder)
977 t.placeholder = holder;
980 class: 'cbi-button cbi-button-' + ((i+1) < values.length ? 'remove' : 'add')
981 }, (i+1) < values.length ? '×' : '+');
983 parent.appendChild(t);
984 parent.appendChild(b);
986 if (datatype == 'file')
987 cbi_browser_init(t.id, null, parent.getAttribute('data-browser-path'));
989 parent.appendChild(document.createElement('br'));
992 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
995 cbi_combobox_init(t.id, choices, '', _('-- custom --'));
998 cbi_bind(b, 'keydown', cbi_dynlist_keydown);
999 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
1001 if (i == focus || -i == focus)
1005 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
1006 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
1011 else if (-i == focus) {
1014 /* force cursor to end */
1021 cbi_bind(b, 'click', cbi_dynlist_btnclick);
1025 function cbi_dynlist_keypress(ev)
1027 ev = ev ? ev : window.event;
1029 var se = ev.target ? ev.target : ev.srcElement;
1031 if (se.nodeType == 3)
1034 switch (ev.keyCode) {
1035 /* backspace, delete */
1038 if (se.value.length == 0) {
1039 if (ev.preventDefault)
1040 ev.preventDefault();
1047 /* enter, arrow up, arrow down */
1051 if (ev.preventDefault)
1052 ev.preventDefault();
1060 function cbi_dynlist_keydown(ev)
1062 ev = ev ? ev : window.event;
1064 var se = ev.target ? ev.target : ev.srcElement;
1066 if (se.nodeType == 3)
1069 var prev = se.previousSibling;
1070 while (prev && prev.name != prefix)
1071 prev = prev.previousSibling;
1073 var next = se.nextSibling;
1074 while (next && next.name != prefix)
1075 next = next.nextSibling;
1077 /* advance one further in combobox case */
1078 if (next && next.nextSibling.name == prefix)
1079 next = next.nextSibling;
1081 switch (ev.keyCode) {
1082 /* backspace, delete */
1085 var del = (matchesElem(se, 'select'))
1086 ? true : (se.value.length == 0);
1089 if (ev.preventDefault)
1090 ev.preventDefault();
1092 var focus = se.index;
1093 if (ev.keyCode == 8)
1096 cbi_dynlist_redraw(focus, -1, se.index);
1105 cbi_dynlist_redraw(-1, se.index, -1);
1126 function cbi_dynlist_btnclick(ev)
1128 ev = ev ? ev : window.event;
1130 var se = ev.target ? ev.target : ev.srcElement;
1131 var input = se.previousSibling;
1132 while (input && input.name != prefix)
1133 input = input.previousSibling;
1135 if (se.classList.contains('cbi-button-remove')) {
1138 cbi_dynlist_keydown({
1144 cbi_dynlist_keydown({
1153 cbi_dynlist_redraw(NaN, -1, -1);
1157 function cbi_t_add(section, tab) {
1158 var t = document.getElementById('tab.' + section + '.' + tab);
1159 var c = document.getElementById('container.' + section + '.' + tab);
1162 cbi_t[section] = (cbi_t[section] || [ ]);
1163 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
1167 function cbi_t_switch(section, tab) {
1168 if (cbi_t[section] && cbi_t[section][tab]) {
1169 var o = cbi_t[section][tab];
1170 var h = document.getElementById('tab.' + section);
1172 for (var tid in cbi_t[section]) {
1173 var o2 = cbi_t[section][tid];
1175 if (o.tab.id != o2.tab.id) {
1176 o2.tab.classList.remove('cbi-tab');
1177 o2.tab.classList.add('cbi-tab-disabled');
1178 o2.container.style.display = 'none';
1184 o2.tab.classList.remove('cbi-tab-disabled');
1185 o2.tab.classList.add('cbi-tab');
1186 o2.container.style.display = 'block';
1194 function cbi_t_update() {
1196 var updated = false;
1198 for (var sid in cbi_t)
1199 for (var tid in cbi_t[sid]) {
1200 var t = cbi_t[sid][tid].tab;
1201 var c = cbi_t[sid][tid].container;
1203 if (!c.firstElementChild) {
1204 t.style.display = 'none';
1206 else if (t.style.display == 'none') {
1207 t.style.display = '';
1208 t.classList.add('cbi-tab-highlighted');
1216 if (hl_tabs.length > 0)
1217 window.setTimeout(function() {
1218 for (var i = 0; i < hl_tabs.length; i++)
1219 hl_tabs[i].classList.remove('cbi-tab-highlighted');
1226 function cbi_validate_form(form, errmsg)
1228 /* if triggered by a section removal or addition, don't validate */
1229 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
1232 if (form.cbi_validators) {
1233 for (var i = 0; i < form.cbi_validators.length; i++) {
1234 var validator = form.cbi_validators[i];
1236 if (!validator() && errmsg) {
1246 function cbi_validate_reset(form)
1249 function() { cbi_validate_form(form, null) }, 100
1255 function cbi_validate_field(cbid, optional, type)
1257 var field = isElem(cbid) ? cbid : document.getElementById(cbid);
1261 var cbiValidator = new CBIValidator(field, type, optional);
1263 validatorFn = function() {
1264 return cbiValidator.validate();
1271 if (validatorFn !== null) {
1272 if (!field.form.cbi_validators)
1273 field.form.cbi_validators = [ ];
1275 field.form.cbi_validators.push(validatorFn);
1277 cbi_bind(field, "blur", validatorFn);
1278 cbi_bind(field, "keyup", validatorFn);
1280 if (matchesElem(field, 'select')) {
1281 cbi_bind(field, "change", validatorFn);
1282 cbi_bind(field, "click", validatorFn);
1285 field.setAttribute("cbi_validate", validatorFn);
1286 field.setAttribute("cbi_datatype", type);
1287 field.setAttribute("cbi_optional", (!!optional).toString());
1291 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1293 cbi_validate_field(fcbox, optional, type);
1297 function cbi_row_swap(elem, up, store)
1299 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
1304 tr.classList.remove('flash');
1307 var prev = tr.previousElementSibling;
1309 if (prev && prev.classList.contains('cbi-section-table-row'))
1310 tr.parentNode.insertBefore(tr, prev);
1315 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1317 if (next && next.classList.contains('cbi-section-table-row'))
1318 tr.parentNode.insertBefore(tr, next);
1320 tr.parentNode.appendChild(tr);
1327 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1328 var node = tr.parentNode.childNodes[i];
1329 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1330 node.classList.remove('cbi-rowstyle-1');
1331 node.classList.remove('cbi-rowstyle-2');
1332 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1334 if (/-([^\-]+)$/.test(node.id))
1335 ids.push(RegExp.$1);
1339 var input = document.getElementById(store);
1341 input.value = ids.join(' ');
1343 window.scrollTo(0, tr.offsetTop);
1344 void tr.offsetWidth;
1345 tr.classList.add('flash');
1350 function cbi_tag_last(container)
1354 for (var i = 0; i < container.childNodes.length; i++) {
1355 var c = container.childNodes[i];
1356 if (matchesElem(c, 'div')) {
1357 c.classList.remove('cbi-value-last');
1363 last.classList.add('cbi-value-last');
1366 function cbi_submit(elem, name, value, action)
1368 var form = elem.form || findParent(elem, 'form');
1374 form.action = action;
1377 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1378 E('input', { type: 'hidden', name: name });
1380 hidden.value = value || '1';
1381 form.appendChild(hidden);
1388 String.prototype.format = function()
1393 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1394 var quot_esc = [/"/g, '"', /'/g, '''];
1396 function esc(s, r) {
1397 if (typeof(s) !== 'string' && !(s instanceof String))
1400 for (var i = 0; i < r.length; i += 2)
1401 s = s.replace(r[i], r[i+1]);
1408 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1409 var a = b = [], numSubstitutions = 0, numMatches = 0;
1411 while (a = re.exec(str)) {
1413 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1414 var pPrecision = a[6], pType = a[7];
1422 if (numSubstitutions < arguments.length) {
1423 var param = arguments[numSubstitutions++];
1426 if (pPad && pPad.substr(0,1) == "'")
1427 pad = leftpart.substr(1,1);
1433 var justifyRight = true;
1434 if (pJustify && pJustify === "-")
1435 justifyRight = false;
1439 minLength = +pMinLength;
1442 if (pPrecision && pType == 'f')
1443 precision = +pPrecision.substring(1);
1449 subst = (+param || 0).toString(2);
1453 subst = String.fromCharCode(+param || 0);
1457 subst = ~~(+param || 0);
1461 subst = ~~Math.abs(+param || 0);
1465 subst = (precision > -1)
1466 ? ((+param || 0.0)).toFixed(precision)
1471 subst = (+param || 0).toString(8);
1479 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1483 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1487 subst = esc(param, html_esc);
1491 subst = esc(param, quot_esc);
1498 var ts = (param || 0);
1501 tm = Math.floor(ts / 60);
1506 th = Math.floor(tm / 60);
1511 td = Math.floor(th / 24);
1516 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1517 : String.format('%dh %dm %ds', th, tm, ts);
1522 var mf = pMinLength ? +pMinLength : 1000;
1523 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1526 var val = (+param || 0);
1527 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1529 for (i = 0; (i < units.length) && (val > mf); i++)
1532 subst = (i ? val.toFixed(pr) : val) + units[i];
1540 subst = subst.toString();
1541 for (var i = subst.length; i < pMinLength; i++)
1542 if (pJustify == '-')
1543 subst = subst + ' ';
1545 subst = pad + subst;
1548 out += leftpart + subst;
1549 str = str.substr(m.length);
1555 String.prototype.nobr = function()
1557 return this.replace(/[\s\n]+/g, ' ');
1560 String.format = function()
1564 for (var i = 1; i < arguments.length; i++)
1565 a.push(arguments[i]);
1567 return ''.format.apply(arguments[0], a);
1570 String.nobr = function()
1574 for (var i = 1; i < arguments.length; i++)
1575 a.push(arguments[i]);
1577 return ''.nobr.apply(arguments[0], a);
1580 if (window.NodeList && !NodeList.prototype.forEach) {
1581 NodeList.prototype.forEach = function (callback, thisArg) {
1582 thisArg = thisArg || window;
1583 for (var i = 0; i < this.length; i++) {
1584 callback.call(thisArg, this[i], i, this);
1590 var dummyElem, domParser;
1594 return (typeof(e) === 'object' && e !== null && 'nodeType' in e);
1602 domParser = domParser || new DOMParser();
1603 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1609 dummyElem = dummyElem || document.createElement('div');
1610 dummyElem.innerHTML = s;
1611 elem = dummyElem.firstChild;
1616 return elem || null;
1619 function matchesElem(node, selector)
1621 return ((node.matches && node.matches(selector)) ||
1622 (node.msMatchesSelector && node.msMatchesSelector(selector)));
1625 function findParent(node, selector)
1628 if (matchesElem(node, selector))
1631 node = node.parentNode;
1638 var html = arguments[0],
1639 attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null,
1640 data = attr ? arguments[2] : arguments[1],
1645 else if (html.charCodeAt(0) === 60)
1646 elem = toElem(html);
1648 elem = document.createElement(html);
1654 for (var key in attr)
1655 if (attr.hasOwnProperty(key) && attr[key] !== null && attr[key] !== undefined)
1656 elem.setAttribute(key, attr[key]);
1658 if (typeof(data) === 'function')
1662 elem.appendChild(data);
1664 else if (Array.isArray(data)) {
1665 for (var i = 0; i < data.length; i++)
1666 if (isElem(data[i]))
1667 elem.appendChild(data[i]);
1669 elem.appendChild(document.createTextNode('' + data[i]));
1671 else if (data !== null && data !== undefined) {
1672 elem.innerHTML = '' + data;
1678 if (typeof(window.CustomEvent) !== 'function') {
1679 function CustomEvent(event, params) {
1680 params = params || { bubbles: false, cancelable: false, detail: undefined };
1681 var evt = document.createEvent('CustomEvent');
1682 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1686 CustomEvent.prototype = window.Event.prototype;
1687 window.CustomEvent = CustomEvent;
1691 openDropdown: function(sb) {
1692 var st = window.getComputedStyle(sb, null),
1693 ul = sb.querySelector('ul'),
1694 li = ul.querySelectorAll('li'),
1695 sel = ul.querySelector('[selected]'),
1696 rect = sb.getBoundingClientRect(),
1697 h = sb.clientHeight - parseFloat(st.paddingTop) - parseFloat(st.paddingBottom),
1698 mh = this.dropdown_items * h,
1699 eh = Math.min(mh, li.length * h);
1701 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1702 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1705 ul.style.maxHeight = mh + 'px';
1706 sb.setAttribute('open', '');
1708 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1709 ul.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c) {
1713 ul.style.top = ul.style.bottom = '';
1714 ul.style[((sb.getBoundingClientRect().top + eh) > window.innerHeight) ? 'bottom' : 'top'] = rect.height + 'px';
1715 ul.classList.add('dropdown');
1717 var pv = ul.cloneNode(true);
1718 pv.classList.remove('dropdown');
1719 pv.classList.add('preview');
1721 sb.insertBefore(pv, ul.nextElementSibling);
1723 li.forEach(function(l) {
1724 l.setAttribute('tabindex', 0);
1727 sb.lastElementChild.setAttribute('tabindex', 0);
1729 this.setFocus(sb, sel || li[0], true);
1732 closeDropdown: function(sb, no_focus) {
1733 if (!sb.hasAttribute('open'))
1736 var pv = sb.querySelector('ul.preview'),
1737 ul = sb.querySelector('ul.dropdown'),
1738 li = ul.querySelectorAll('li');
1740 li.forEach(function(l) { l.removeAttribute('tabindex'); });
1741 sb.lastElementChild.removeAttribute('tabindex');
1744 sb.removeAttribute('open');
1745 sb.style.width = sb.style.height = '';
1747 ul.classList.remove('dropdown');
1750 this.setFocus(sb, sb);
1752 this.saveValues(sb, ul);
1755 toggleItem: function(sb, li, force_state) {
1756 if (li.hasAttribute('unselectable'))
1760 var cbox = li.querySelector('input[type="checkbox"]'),
1761 items = li.parentNode.querySelectorAll('li'),
1762 label = sb.querySelector('ul.preview'),
1763 sel = li.parentNode.querySelectorAll('[selected]').length,
1764 more = sb.querySelector('.more'),
1765 ndisplay = this.display_items,
1768 if (li.hasAttribute('selected')) {
1769 if (force_state !== true) {
1770 if (sel > 1 || this.optional) {
1771 li.removeAttribute('selected');
1772 cbox.checked = cbox.disabled = false;
1776 cbox.disabled = true;
1781 if (force_state !== false) {
1782 li.setAttribute('selected', '');
1783 cbox.checked = true;
1784 cbox.disabled = false;
1789 while (label.firstElementChild)
1790 label.removeChild(label.firstElementChild);
1792 for (var i = 0; i < items.length; i++) {
1793 items[i].removeAttribute('display');
1794 if (items[i].hasAttribute('selected')) {
1795 if (ndisplay-- > 0) {
1796 items[i].setAttribute('display', n++);
1797 label.appendChild(items[i].cloneNode(true));
1799 var c = items[i].querySelector('input[type="checkbox"]');
1801 c.disabled = (sel == 1 && !this.optional);
1806 sb.setAttribute('more', '');
1808 sb.removeAttribute('more');
1810 if (ndisplay === this.display_items)
1811 sb.setAttribute('empty', '');
1813 sb.removeAttribute('empty');
1815 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1818 var sel = li.parentNode.querySelector('[selected]');
1820 sel.removeAttribute('display');
1821 sel.removeAttribute('selected');
1824 li.setAttribute('display', 0);
1825 li.setAttribute('selected', '');
1827 this.closeDropdown(sb, true);
1830 this.saveValues(sb, li.parentNode);
1833 transformItem: function(sb, li) {
1834 var cbox = E('form', {}, E('input', { type: 'checkbox', tabindex: -1, onclick: 'event.preventDefault()' })),
1837 while (li.firstChild)
1838 label.appendChild(li.firstChild);
1840 li.appendChild(cbox);
1841 li.appendChild(label);
1844 saveValues: function(sb, ul) {
1845 var sel = ul.querySelectorAll('[selected]'),
1846 div = sb.lastElementChild;
1848 while (div.lastElementChild)
1849 div.removeChild(div.lastElementChild);
1851 sel.forEach(function (s) {
1852 div.appendChild(E('input', {
1854 name: s.hasAttribute('name') ? s.getAttribute('name') : (sb.getAttribute('name') || ''),
1855 value: s.hasAttribute('data-value') ? s.getAttribute('data-value') : s.innerText
1862 setFocus: function(sb, elem, scroll) {
1863 if (sb && sb.hasAttribute && sb.hasAttribute('locked-in'))
1866 document.querySelectorAll('.focus').forEach(function(e) {
1867 if (!matchesElem(e, 'input')) {
1868 e.classList.remove('focus');
1875 elem.classList.add('focus');
1878 elem.parentNode.scrollTop = elem.offsetTop - elem.parentNode.offsetTop;
1882 createItems: function(sb, value) {
1884 val = (value || '').trim().split(/\s+/),
1885 ul = sb.querySelector('ul');
1888 val.length = Math.min(val.length, 1);
1890 val.forEach(function(item) {
1891 var new_item = null;
1893 ul.childNodes.forEach(function(li) {
1894 if (li.getAttribute && li.getAttribute('data-value') === item)
1900 tpl = sb.querySelector(sbox.template);
1903 markup = (tpl.textContent || tpl.innerHTML || tpl.firstChild.data).replace(/^<!--|-->$/, '').trim();
1905 markup = '<li data-value="{{value}}">{{value}}</li>';
1907 new_item = E(markup.replace(/{{value}}/g, item));
1910 sbox.transformItem(sb, new_item);
1913 var old = ul.querySelector('li[created]');
1915 ul.removeChild(old);
1917 new_item.setAttribute('created', '');
1920 new_item = ul.insertBefore(new_item, ul.lastElementChild);
1923 sbox.toggleItem(sb, new_item, true);
1924 sbox.setFocus(sb, new_item, true);
1928 closeAllDropdowns: function() {
1929 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1930 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1935 function cbi_dropdown_init(sb) {
1936 if (!(this instanceof cbi_dropdown_init))
1937 return new cbi_dropdown_init(sb);
1939 this.multi = sb.hasAttribute('multiple');
1940 this.optional = sb.hasAttribute('optional');
1941 this.placeholder = sb.getAttribute('placeholder') || '---';
1942 this.display_items = parseInt(sb.getAttribute('display-items') || 3);
1943 this.dropdown_items = parseInt(sb.getAttribute('dropdown-items') || 5);
1944 this.create = sb.getAttribute('item-create') || '.create-item-input';
1945 this.template = sb.getAttribute('item-template') || 'script[type="item-template"]';
1948 ul = sb.querySelector('ul'),
1949 items = ul.querySelectorAll('li'),
1950 more = sb.appendChild(E('span', { class: 'more', tabindex: -1 }, '···')),
1951 open = sb.appendChild(E('span', { class: 'open', tabindex: -1 }, '▾')),
1952 canary = sb.appendChild(E('div')),
1953 create = sb.querySelector(this.create),
1954 ndisplay = this.display_items,
1958 for (var i = 0; i < items.length; i++) {
1959 sbox.transformItem(sb, items[i]);
1961 if (items[i].hasAttribute('selected') && ndisplay-- > 0)
1962 items[i].setAttribute('display', n++);
1966 var sel = sb.querySelectorAll('[selected]');
1968 sel.forEach(function(s) {
1969 s.removeAttribute('selected');
1972 var s = sel[0] || items[0];
1974 s.setAttribute('selected', '');
1975 s.setAttribute('display', n++);
1980 if (this.optional && !ul.querySelector('li[data-value=""]')) {
1981 var placeholder = E('li', { placeholder: '' }, this.placeholder);
1982 ul.firstChild ? ul.insertBefore(placeholder, ul.firstChild) : ul.appendChild(placeholder);
1986 sbox.saveValues(sb, ul);
1988 ul.setAttribute('tabindex', -1);
1989 sb.setAttribute('tabindex', 0);
1992 sb.setAttribute('more', '')
1994 sb.removeAttribute('more');
1996 if (ndisplay === this.display_items)
1997 sb.setAttribute('empty', '')
1999 sb.removeAttribute('empty');
2001 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
2004 sb.addEventListener('click', function(ev) {
2005 if (!this.hasAttribute('open')) {
2006 if (!matchesElem(ev.target, 'input'))
2007 sbox.openDropdown(this);
2010 var li = findParent(ev.target, 'li');
2011 if (li && li.parentNode.classList.contains('dropdown'))
2012 sbox.toggleItem(this, li);
2015 ev.preventDefault();
2016 ev.stopPropagation();
2019 sb.addEventListener('keydown', function(ev) {
2020 if (matchesElem(ev.target, 'input'))
2023 if (!this.hasAttribute('open')) {
2024 switch (ev.keyCode) {
2029 sbox.openDropdown(this);
2030 ev.preventDefault();
2035 var active = findParent(document.activeElement, 'li');
2037 switch (ev.keyCode) {
2039 sbox.closeDropdown(this);
2044 if (!active.hasAttribute('selected'))
2045 sbox.toggleItem(this, active);
2046 sbox.closeDropdown(this);
2047 ev.preventDefault();
2053 sbox.toggleItem(this, active);
2054 ev.preventDefault();
2059 if (active && active.previousElementSibling) {
2060 sbox.setFocus(this, active.previousElementSibling);
2061 ev.preventDefault();
2066 if (active && active.nextElementSibling) {
2067 sbox.setFocus(this, active.nextElementSibling);
2068 ev.preventDefault();
2075 sb.addEventListener('cbi-dropdown-close', function(ev) {
2076 sbox.closeDropdown(this, true);
2079 if ('ontouchstart' in window) {
2080 sb.addEventListener('touchstart', function(ev) { ev.stopPropagation(); });
2081 window.addEventListener('touchstart', sbox.closeAllDropdowns);
2084 sb.addEventListener('mouseover', function(ev) {
2085 if (!this.hasAttribute('open'))
2088 var li = findParent(ev.target, 'li');
2090 if (li.parentNode.classList.contains('dropdown'))
2091 sbox.setFocus(this, li);
2093 ev.stopPropagation();
2097 sb.addEventListener('focus', function(ev) {
2098 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
2099 if (s !== this || this.hasAttribute('open'))
2100 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
2104 canary.addEventListener('focus', function(ev) {
2105 sbox.closeDropdown(this.parentNode);
2108 window.addEventListener('mouseover', sbox.setFocus);
2109 window.addEventListener('click', sbox.closeAllDropdowns);
2113 create.addEventListener('keydown', function(ev) {
2114 switch (ev.keyCode) {
2116 ev.preventDefault();
2118 if (this.classList.contains('cbi-input-invalid'))
2121 sbox.createItems(sb, this.value);
2128 create.addEventListener('focus', function(ev) {
2129 var cbox = findParent(this, 'li').querySelector('input[type="checkbox"]');
2130 if (cbox) cbox.checked = true;
2131 sb.setAttribute('locked-in', '');
2134 create.addEventListener('blur', function(ev) {
2135 var cbox = findParent(this, 'li').querySelector('input[type="checkbox"]');
2136 if (cbox) cbox.checked = false;
2137 sb.removeAttribute('locked-in');
2140 var li = findParent(create, 'li');
2142 li.setAttribute('unselectable', '');
2143 li.addEventListener('click', function(ev) {
2144 this.querySelector(sbox.create).focus();
2149 cbi_dropdown_init.prototype = CBIDropdown;
2151 function cbi_update_table(table, data, placeholder) {
2152 var target = isElem(table) ? table : document.querySelector(table);
2154 if (!isElem(target))
2157 target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
2160 thead.querySelectorAll('.th').forEach(function(th) {
2164 if (Array.isArray(data)) {
2165 var n = 0, rows = target.querySelectorAll('.tr');
2167 data.forEach(function(row) {
2168 var trow = E('div', { 'class': 'tr' });
2170 for (var i = 0; i < titles.length; i++) {
2171 var text = (titles[i].innerText || '').trim();
2172 var td = trow.appendChild(E('div', {
2173 'class': titles[i].className,
2174 'data-title': (text !== '') ? text : null
2177 td.classList.remove('th');
2178 td.classList.add('td');
2181 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
2184 target.replaceChild(trow, rows[n]);
2186 target.appendChild(trow);
2190 target.removeChild(rows[n]);
2192 if (placeholder && target.firstElementChild === target.lastElementChild) {
2193 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
2194 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
2196 td.classList.remove('th');
2197 td.classList.add('td');
2201 thead.parentNode.style.display = 'none';
2203 thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
2204 if (trow !== thead) {
2206 trow.querySelectorAll('.th, .td').forEach(function(td) {
2207 if (n < titles.length) {
2208 var text = (titles[n++].innerText || '').trim();
2210 td.setAttribute('data-title', text);
2216 thead.parentNode.style.display = '';
2221 var tooltipDiv = null, tooltipTimeout = null;
2223 function showTooltip(ev) {
2224 if (!matchesElem(ev.target, '[data-tooltip]'))
2227 if (tooltipTimeout !== null) {
2228 window.clearTimeout(tooltipTimeout);
2229 tooltipTimeout = null;
2232 var rect = ev.target.getBoundingClientRect(),
2233 x = rect.left + window.pageXOffset,
2234 y = rect.top + rect.height + window.pageYOffset;
2236 tooltipDiv.className = 'cbi-tooltip';
2237 tooltipDiv.innerHTML = '▲ ';
2238 tooltipDiv.firstChild.data += ev.target.getAttribute('data-tooltip');
2240 if (ev.target.hasAttribute('data-tooltip-style'))
2241 tooltipDiv.classList.add(ev.target.getAttribute('data-tooltip-style'));
2243 if ((y + tooltipDiv.offsetHeight) > (window.innerHeight + window.pageYOffset)) {
2244 y -= (tooltipDiv.offsetHeight + ev.target.offsetHeight);
2245 tooltipDiv.firstChild.data = '▼ ' + tooltipDiv.firstChild.data.substr(2);
2248 tooltipDiv.style.top = y + 'px';
2249 tooltipDiv.style.left = x + 'px';
2250 tooltipDiv.style.opacity = 1;
2253 function hideTooltip(ev) {
2254 if (ev.target === tooltipDiv || ev.relatedTarget === tooltipDiv)
2257 if (tooltipTimeout !== null) {
2258 window.clearTimeout(tooltipTimeout);
2259 tooltipTimeout = null;
2262 tooltipDiv.style.opacity = 0;
2263 tooltipTimeout = window.setTimeout(function() { tooltipDiv.removeAttribute('style'); }, 250);
2266 document.addEventListener('DOMContentLoaded', function() {
2267 tooltipDiv = document.body.appendChild(E('div', { 'class': 'cbi-tooltip' }));
2269 document.addEventListener('mouseover', showTooltip, true);
2270 document.addEventListener('mouseout', hideTooltip, true);
2271 document.addEventListener('focus', showTooltip, true);
2272 document.addEventListener('blur', hideTooltip, true);
2274 document.addEventListener('validation-failure', function(ev) {
2275 if (ev.target === document.activeElement)
2279 document.addEventListener('validation-success', function(ev) {
2280 if (ev.target === document.activeElement)
2284 document.querySelectorAll('.table').forEach(cbi_update_table);