2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2018 Jo-Philipp Wich <jo@mein.io>
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
11 http://www.apache.org/licenses/LICENSE-2.0
16 var cbi_strings = { path: {}, label: {} };
18 function s8(bytes, off) {
20 return (n > 0x7F) ? (n - 256) >>> 0 : n;
23 function u16(bytes, off) {
24 return ((bytes[off + 1] << 8) + bytes[off]) >>> 0;
28 if (s === null || s.length === 0)
33 for (var i = 0; i < s.length; i++) {
34 var ch = s.charCodeAt(i);
39 bytes.push(((ch >>> 6) & 0x1F) | 0xC0,
41 else if (ch <= 0xFFFF)
42 bytes.push(((ch >>> 12) & 0x0F) | 0xE0,
43 ((ch >>> 6) & 0x3F) | 0x80,
45 else if (code <= 0x10FFFF)
46 bytes.push(((ch >>> 18) & 0x07) | 0xF0,
47 ((ch >>> 12) & 0x3F) | 0x80,
48 ((ch >> 6) & 0x3F) | 0x80,
55 var hash = (bytes.length >>> 0),
56 len = (bytes.length >>> 2),
60 hash += u16(bytes, off);
61 tmp = ((u16(bytes, off + 2) << 11) ^ hash) >>> 0;
62 hash = ((hash << 16) ^ tmp) >>> 0;
67 switch ((bytes.length & 3) >>> 0) {
69 hash += u16(bytes, off);
70 hash = (hash ^ (hash << 16)) >>> 0;
71 hash = (hash ^ (s8(bytes, off + 2) << 18)) >>> 0;
76 hash += u16(bytes, off);
77 hash = (hash ^ (hash << 11)) >>> 0;
82 hash += s8(bytes, off);
83 hash = (hash ^ (hash << 10)) >>> 0;
88 hash = (hash ^ (hash << 3)) >>> 0;
90 hash = (hash ^ (hash << 4)) >>> 0;
92 hash = (hash ^ (hash << 25)) >>> 0;
95 return (0x100000000 + hash).toString(16).substr(1);
99 return (window.TR && TR[sfh(s)]) || s;
103 return (/^-?\d+$/.test(x) ? +x : NaN);
107 return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
111 if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
114 if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
117 return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
121 if (x.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
122 var v6 = RegExp.$1, v4 = IPv4(RegExp.$2);
127 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
128 + ':' + (v4[2] * 256 + v4[3]).toString(16);
131 if (!x.match(/^[a-fA-F0-9:]+$/))
134 var prefix_suffix = x.split(/::/);
136 if (prefix_suffix.length > 2)
139 var prefix = (prefix_suffix[0] || '0').split(/:/);
140 var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
142 if (suffix.length ? (prefix.length + suffix.length > 7)
143 : ((prefix_suffix.length < 2 && prefix.length < 8) || prefix.length > 8))
149 for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
150 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
155 for (i = 0; i < (8 - prefix.length - suffix.length); i++)
158 for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
159 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
167 var CBIValidatorPrototype = {
168 apply: function(name, value, args) {
171 if (typeof(name) === 'function')
173 else if (typeof(this.types[name]) === 'function')
174 func = this.types[name];
178 if (value !== undefined && value !== null)
181 return func.apply(this, args);
184 assert: function(condition, message) {
186 this.field.classList.add('cbi-input-invalid');
187 this.error = message;
191 this.field.classList.remove('cbi-input-invalid');
196 compile: function(code) {
204 for (var i = 0; i < code.length; i++) {
210 switch (code.charCodeAt(i))
220 var label = code.substring(pos, i);
221 label = label.replace(/\\(.)/g, '$1');
222 label = label.replace(/^[ \t]+/g, '');
223 label = label.replace(/[ \t]+$/g, '');
225 if (label && !isNaN(label)) {
226 stack.push(parseFloat(label));
228 else if (label.match(/^(['"]).*\1$/)) {
229 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
231 else if (typeof this.types[label] == 'function') {
232 stack.push(this.types[label]);
236 throw "Syntax error, unhandled token '"+label+"'";
243 depth += (code.charCodeAt(i) == 40);
248 if (typeof stack[stack.length-2] != 'function')
249 throw "Syntax error, argument list follows non-function";
251 stack[stack.length-1] = this.compile(code.substring(pos, i));
262 validate: function() {
263 /* element is detached */
264 if (!findParent(this.field, 'form'))
267 this.field.classList.remove('cbi-input-invalid');
268 this.value = matchesElem(this.field, 'select') ? this.field.options[this.field.selectedIndex].value : this.field.value;
273 if (this.value.length === 0)
274 valid = this.assert(this.optional, _('non-empty value'));
276 valid = this.vstack[0].apply(this, this.vstack[1]);
279 this.field.setAttribute('data-tooltip', _('Expecting %s').format(this.error));
280 this.field.setAttribute('data-tooltip-style', 'error');
281 this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
284 this.field.removeAttribute('data-tooltip');
285 this.field.removeAttribute('data-tooltip-style');
286 this.field.dispatchEvent(new CustomEvent('validation-success', { bubbles: true }));
293 integer: function() {
294 return this.assert(Int(this.value) !== NaN, _('valid integer value'));
297 uinteger: function() {
298 return this.assert(Int(this.value) >= 0, _('positive integer value'));
302 return this.assert(Dec(this.value) !== NaN, _('valid decimal value'));
306 return this.assert(Dec(this.value) >= 0, _('positive decimal value'));
309 ipaddr: function(nomask) {
310 return this.assert(this.apply('ip4addr', null, [nomask]) || this.apply('ip6addr', null, [nomask]),
311 nomask ? _('valid IP address') : _('valid IP address or prefix'));
314 ip4addr: function(nomask) {
315 var re = nomask ? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
316 m = this.value.match(re);
318 return this.assert(m && IPv4(m[1]) && (m[2] ? IPv4(m[2]) : (m[3] ? this.apply('ip4prefix', m[3]) : true)),
319 nomask ? _('valid IPv4 address') : _('valid IPv4 address or network'));
322 ip6addr: function(nomask) {
323 var re = nomask ? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
324 m = this.value.match(re);
326 return this.assert(m && IPv6(m[1]) && (m[2] ? this.apply('ip6prefix', m[2]) : true),
327 nomask ? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
330 ip4prefix: function() {
331 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 32,
332 _('valid IPv4 prefix value (0-32)'));
335 ip6prefix: function() {
336 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 128,
337 _('valid IPv6 prefix value (0-128)'));
341 return this.assert(this.apply('cidr4') || this.apply('cidr6'), _('valid IPv4 or IPv6 CIDR'));
345 var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
346 return this.assert(m && IPv4(m[1]) && this.apply('ip4prefix', m[2]), _('valid IPv4 CIDR'));
350 var m = this.value.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
351 return this.assert(m && IPv6(m[1]) && this.apply('ip6prefix', m[2]), _('valid IPv6 CIDR'));
355 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})$/);
356 return this.assert(m && IPv4(m[1]) && IPv4(m[2]), _('IPv4 network in address/netmask notation'));
360 var m = this.value.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
361 return this.assert(m && IPv6(m[1]) && IPv6(m[2]), _('IPv6 network in address/netmask notation'));
364 ip6hostid: function() {
365 if (this.value == "eui64" || this.value == "random")
368 var v6 = IPv6(this.value);
369 return this.assert(!(!v6 || v6[0] || v6[1] || v6[2] || v6[3]), _('valid IPv6 host id'));
373 return this.assert(this.apply('ipmask4') || this.apply('ipmask6'),
374 _('valid network in address/netmask notation'));
377 ipmask4: function() {
378 return this.assert(this.apply('cidr4') || this.apply('ipnet4') || this.apply('ip4addr'),
379 _('valid IPv4 network'));
382 ipmask6: function() {
383 return this.assert(this.apply('cidr6') || this.apply('ipnet6') || this.apply('ip6addr'),
384 _('valid IPv6 network'));
388 var p = Int(this.value);
389 return this.assert(p >= 0 && p <= 65535, _('valid port value'));
392 portrange: function() {
393 if (this.value.match(/^(\d+)-(\d+)$/)) {
396 return this.assert(p1 <= p2 && p2 <= 65535,
397 _('valid port or port range (port1-port2)'));
400 return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
403 macaddr: function() {
404 return this.assert(this.value.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null,
405 _('valid MAC address'));
408 host: function(ipv4only) {
409 return this.assert(this.apply('hostname') || this.apply(ipv4only == 1 ? 'ip4addr' : 'ipaddr'),
410 _('valid hostname or IP address'));
413 hostname: function(strict) {
414 if (this.value.length <= 253)
416 (this.value.match(/^[a-zA-Z0-9_]+$/) != null ||
417 (this.value.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
418 this.value.match(/[^0-9.]/))) &&
419 (!strict || !this.value.match(/^_/)),
420 _('valid hostname'));
422 return this.assert(false, _('valid hostname'));
425 network: function() {
426 return this.assert(this.apply('uciname') || this.apply('host'),
427 _('valid UCI identifier, hostname or IP address'));
430 hostport: function(ipv4only) {
431 var hp = this.value.split(/:/);
432 return this.assert(hp.length == 2 && this.apply('host', hp[0], [ipv4only]) && this.apply('port', hp[1]),
433 _('valid host:port'));
436 ip4addrport: function() {
437 var hp = this.value.split(/:/);
438 return this.assert(hp.length == 2 && this.apply('ip4addr', hp[0], [true]) && this.apply('port', hp[1]),
439 _('valid IPv4 address:port'));
442 ipaddrport: function(bracket) {
443 var m4 = this.value.match(/^([^\[\]:]+):(\d+)$/),
444 m6 = this.value.match((bracket == 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
447 return this.assert(this.apply('ip4addr', m4[0], [true]) && this.apply('port', m4[1]),
448 _('valid address:port'));
450 return this.assert(m6 && this.apply('ip6addr', m6[0], [true]) && this.apply('port', m6[1]),
451 _('valid address:port'));
458 return this.assert(v.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
460 return this.assert((v.length >= 8) && (v.length <= 63), _('key between 8 and 63 characters'));
466 if (v.substr(0, 2) === 's:')
469 if ((v.length == 10) || (v.length == 26))
470 return this.assert(v.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
472 return this.assert((v.length === 5) || (v.length === 13), _('key with either 5 or 13 characters'));
475 uciname: function() {
476 return this.assert(this.value.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
479 range: function(min, max) {
480 var val = Dec(this.value);
481 return this.assert(val >= +min && val <= +max, _('value between %f and %f').format(min, max));
485 return this.assert(Dec(this.value) >= +min, _('value greater or equal to %f').format(min));
489 return this.assert(Dec(this.value) <= +max, _('value smaller or equal to %f').format(max));
492 rangelength: function(min, max) {
493 var val = '' + this.value;
494 return this.assert((val.length >= +min) && (val.length <= +max),
495 _('value between %d and %d characters').format(min, max));
498 minlength: function(min) {
499 return this.assert((''+this.value).length >= +min,
500 _('value with at least %d characters').format(min));
503 maxlength: function(max) {
504 return this.assert((''+this.value).length <= +max,
505 _('value with at most %d characters').format(max));
511 for (var i = 0; i < arguments.length; i += 2) {
512 if (typeof arguments[i] != 'function') {
513 if (arguments[i] == this.value)
514 return this.assert(true);
515 errors.push('"%s"'.format(arguments[i]));
518 else if (arguments[i].apply(this, arguments[i+1])) {
519 return this.assert(true);
522 errors.push(this.error);
526 return this.assert(false, _('one of:\n - %s'.format(errors.join('\n - '))));
530 for (var i = 0; i < arguments.length; i += 2) {
531 if (typeof arguments[i] != 'function') {
532 if (arguments[i] != this.value)
533 return this.assert(false, '"%s"'.format(arguments[i]));
536 else if (!arguments[i].apply(this, arguments[i+1])) {
537 return this.assert(false, this.error);
541 return this.assert(true);
545 return this.apply('or', this.value.replace(/^[ \t]*![ \t]*/, ''), arguments);
548 list: function(subvalidator, subargs) {
549 this.field.setAttribute('data-is-list', 'true');
551 var tokens = this.value.match(/[^ \t]+/g);
552 for (var i = 0; i < tokens.length; i++)
553 if (!this.apply(subvalidator, tokens[i], subargs))
554 return this.assert(false, this.error);
556 return this.assert(true);
559 phonedigit: function() {
560 return this.assert(this.value.match(/^[0-9\*#!\.]+$/),
561 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
564 timehhmmss: function() {
565 return this.assert(this.value.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
566 _('valid time (HH:MM:SS)'));
569 dateyyyymmdd: function() {
570 if (this.value.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
571 var year = +RegExp.$1,
574 days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
576 function is_leap_year(year) {
577 return ((!(year % 4) && (year % 100)) || !(year % 400));
580 function get_days_in_month(month, year) {
581 return (month === 2 && is_leap_year(year)) ? 29 : days_in_month[month - 1];
584 /* Firewall rules in the past don't make sense */
585 return this.assert(year >= 2015 && month && month <= 12 && day && day <= get_days_in_month(month, year),
586 _('valid date (YYYY-MM-DD)'));
590 return this.assert(false, _('valid date (YYYY-MM-DD)'));
593 unique: function(subvalidator, subargs) {
595 option = findParent(ctx.field, '[data-type][data-name]'),
596 section = findParent(option, '.cbi-section'),
597 query = '[data-type="%s"][data-name="%s"]'.format(option.getAttribute('data-type'), option.getAttribute('data-name')),
600 section.querySelectorAll(query).forEach(function(sibling) {
601 if (sibling === option)
604 var input = sibling.querySelector('[data-type]'),
605 values = input ? (input.getAttribute('data-is-list') ? input.value.match(/[^ \t]+/g) : [ input.value ]) : null;
607 if (values !== null && values.indexOf(ctx.value) !== -1)
612 return this.assert(false, _('unique value'));
614 if (typeof(subvalidator) === 'function')
615 return this.apply(subvalidator, undefined, subargs);
617 return this.assert(true);
620 hexstring: function() {
621 return this.assert(this.value.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
622 _('hexadecimal encoded value'));
627 function CBIValidator(field, type, optional)
630 this.optional = optional;
631 this.vstack = this.compile(type);
634 CBIValidator.prototype = CBIValidatorPrototype;
637 function cbi_d_add(field, dep, index) {
638 var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
641 for (var i=0; i<cbi_d.length; i++) {
642 if (cbi_d[i].id == obj.id) {
651 "parent": obj.parentNode.id,
655 cbi_d.unshift(entry);
661 function cbi_d_checkvalue(target, ref) {
663 query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
664 'select[id="'+target+'"], select[name="'+target+'"]';
666 document.querySelectorAll(query).forEach(function(i) {
667 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
671 return (((value !== null) ? value : "") == ref);
674 function cbi_d_check(deps) {
677 for (var i=0; i<deps.length; i++) {
680 for (var j in deps[i]) {
681 if (j == "!reverse") {
683 } else if (j == "!default") {
687 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
691 if (istat ^ reverse) {
698 function cbi_d_update() {
700 for (var i=0; i<cbi_d.length; i++) {
701 var entry = cbi_d[i];
702 var node = document.getElementById(entry.id);
703 var parent = document.getElementById(entry.parent);
705 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
706 node.parentNode.removeChild(node);
709 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
710 var next = undefined;
712 for (next = parent.firstChild; next; next = next.nextSibling) {
713 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
718 parent.appendChild(entry.node);
720 parent.insertBefore(entry.node, next);
725 // hide optionals widget if no choices remaining
726 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
727 parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
730 if (entry && entry.parent) {
732 cbi_tag_last(parent);
739 function cbi_init() {
742 nodes = document.querySelectorAll('[data-strings]');
744 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
745 var str = JSON.parse(node.getAttribute('data-strings'));
746 for (var key in str) {
747 for (var key2 in str[key]) {
748 var dst = cbi_strings[key] || (cbi_strings[key] = { });
749 dst[key2] = str[key][key2];
754 nodes = document.querySelectorAll('[data-depends]');
756 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
757 var index = parseInt(node.getAttribute('data-index'), 10);
758 var depends = JSON.parse(node.getAttribute('data-depends'));
759 if (!isNaN(index) && depends.length > 0) {
760 for (var alt = 0; alt < depends.length; alt++)
761 cbi_d_add(node, depends[alt], index);
765 nodes = document.querySelectorAll('[data-update]');
767 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
768 var events = node.getAttribute('data-update').split(' ');
769 for (var j = 0, event; (event = events[j]) !== undefined; j++)
770 node.addEventListener(event, cbi_d_update);
773 nodes = document.querySelectorAll('[data-choices]');
775 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
776 var choices = JSON.parse(node.getAttribute('data-choices'));
779 for (var j = 0; j < choices[0].length; j++)
780 options[choices[0][j]] = choices[1][j];
782 var def = (node.getAttribute('data-optional') === 'true')
783 ? node.placeholder || '' : null;
785 cbi_combobox_init(node, options, def,
786 node.getAttribute('data-manual'));
789 nodes = document.querySelectorAll('[data-dynlist]');
791 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
792 var choices = JSON.parse(node.getAttribute('data-dynlist'));
795 if (choices[0] && choices[0].length) {
798 for (var j = 0; j < choices[0].length; j++)
799 options[choices[0][j]] = choices[1][j];
802 cbi_dynlist_init(node, choices[2], choices[3], options);
805 nodes = document.querySelectorAll('[data-type]');
807 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
808 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
809 node.getAttribute('data-type'));
812 document.querySelectorAll('.cbi-dropdown').forEach(function(s) {
813 cbi_dropdown_init(s);
816 document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
817 s.parentNode.classList.add('cbi-tooltip-container');
820 document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
821 var handler = function(ev) {
822 var bits = this.name.split(/\./),
823 section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
825 section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
828 i.addEventListener('mouseover', handler);
829 i.addEventListener('mouseout', handler);
835 function cbi_combobox_init(id, values, def, man) {
836 var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
839 'class': 'cbi-dropdown',
841 'optional': obj.getAttribute('data-optional'),
842 'placeholder': _('-- Please choose --'),
843 'data-type': obj.getAttribute('data-type'),
844 'data-optional': obj.getAttribute('data-optional')
847 if (!(obj.value in values) && obj.value.length) {
848 sb.lastElementChild.appendChild(E('li', {
849 'data-value': obj.value,
851 }, obj.value.length ? obj.value : (def || _('-- Please choose --'))));
854 for (var i in values) {
855 sb.lastElementChild.appendChild(E('li', {
857 'selected': (i == obj.value) ? '' : null
861 sb.lastElementChild.appendChild(E('li', { 'data-value': '-' }, [
864 'class': 'create-item-input',
865 'data-type': obj.getAttribute('data-type'),
866 'data-optional': true,
867 'placeholder': (man || _('-- custom --'))
871 sb.value = obj.value;
872 obj.parentNode.replaceChild(sb, obj);
875 function cbi_filebrowser(id, defpath) {
876 var field = document.getElementById(id);
877 var browser = window.open(
878 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
879 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
885 function cbi_browser_init(id, resource, defpath)
887 function cbi_browser_btnclick(e) {
888 cbi_filebrowser(id, defpath);
892 var field = document.getElementById(id);
894 var btn = document.createElement('img');
895 btn.className = 'cbi-image-button';
896 btn.src = (resource || cbi_strings.path.resource) + '/cbi/folder.gif';
897 field.parentNode.insertBefore(btn, field.nextSibling);
899 btn.addEventListener('click', cbi_browser_btnclick);
903 addItem: function(dl, value, text, flash) {
905 new_item = E('div', { 'class': flash ? 'item flash' : 'item', 'tabindex': 0 }, [
906 E('span', {}, text || value),
909 'name': dl.getAttribute('data-prefix'),
912 dl.querySelectorAll('.item, .add-item').forEach(function(item) {
916 var hidden = item.querySelector('input[type="hidden"]');
918 if (hidden && hidden.value === value)
920 else if (!hidden || hidden.value >= value)
921 exists = !!item.parentNode.insertBefore(new_item, item);
925 removeItem: function(dl, item) {
926 var sb = dl.querySelector('.cbi-dropdown');
928 var value = item.querySelector('input[type="hidden"]').value;
930 sb.querySelectorAll('ul > li').forEach(function(li) {
931 if (li.getAttribute('data-value') === value)
932 li.removeAttribute('unselectable');
936 item.parentNode.removeChild(item);
939 handleClick: function(ev) {
940 var dl = ev.currentTarget,
941 item = findParent(ev.target, '.item');
944 this.removeItem(dl, item);
946 else if (matchesElem(ev.target, '.cbi-button-add')) {
947 var input = ev.target.previousElementSibling;
948 if (input.value.length && !input.classList.contains('cbi-input-invalid')) {
949 this.addItem(dl, input.value, null, true);
955 handleDropdownChange: function(ev) {
956 var dl = ev.currentTarget,
957 sbIn = ev.detail.instance,
958 sbEl = ev.detail.element,
959 sbVal = ev.detail.value;
964 sbIn.setValues(sbEl, null);
965 sbVal.element.setAttribute('unselectable', '');
967 this.addItem(dl, sbVal.value, sbVal.text, true);
970 handleKeydown: function(ev) {
971 var dl = ev.currentTarget,
972 item = findParent(ev.target, '.item');
975 switch (ev.keyCode) {
976 case 8: /* backspace */
977 if (item.previousElementSibling)
978 item.previousElementSibling.focus();
980 this.removeItem(dl, item);
983 case 46: /* delete */
984 if (item.nextElementSibling) {
985 if (item.nextElementSibling.classList.contains('item'))
986 item.nextElementSibling.focus();
988 item.nextElementSibling.firstElementChild.focus();
991 this.removeItem(dl, item);
995 else if (matchesElem(ev.target, '.cbi-input-text')) {
996 switch (ev.keyCode) {
998 if (ev.target.value.length && !ev.target.classList.contains('cbi-input-invalid')) {
999 this.addItem(dl, ev.target.value, null, true);
1000 ev.target.value = '';
1005 ev.preventDefault();
1012 function cbi_dynlist_init(dl, datatype, optional, choices)
1014 if (!(this instanceof cbi_dynlist_init))
1015 return new cbi_dynlist_init(dl, datatype, optional, choices);
1017 dl.classList.add('cbi-dynlist');
1018 dl.appendChild(E('div', { 'class': 'add-item' }, E('input', {
1020 'name': 'cbi.dynlist.' + dl.getAttribute('data-prefix'),
1021 'class': 'cbi-input-text',
1022 'data-type': datatype,
1023 'data-optional': true
1027 cbi_combobox_init(dl.lastElementChild.lastElementChild, choices, '', _('-- custom --'));
1029 dl.lastElementChild.appendChild(E('div', { 'class': 'cbi-button cbi-button-add' }, '+'));
1031 dl.addEventListener('click', this.handleClick.bind(this));
1032 dl.addEventListener('keydown', this.handleKeydown.bind(this));
1033 dl.addEventListener('cbi-dropdown-change', this.handleDropdownChange.bind(this));
1036 var values = JSON.parse(dl.getAttribute('data-values') || '[]');
1038 if (typeof(values) === 'object' && Array.isArray(values))
1039 for (var i = 0; i < values.length; i++)
1040 this.addItem(dl, values[i], choices ? choices[values[i]] : null);
1045 cbi_dynlist_init.prototype = CBIDynamicList;
1048 function cbi_t_add(section, tab) {
1049 var t = document.getElementById('tab.' + section + '.' + tab);
1050 var c = document.getElementById('container.' + section + '.' + tab);
1053 cbi_t[section] = (cbi_t[section] || [ ]);
1054 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
1058 function cbi_t_switch(section, tab) {
1059 if (cbi_t[section] && cbi_t[section][tab]) {
1060 var o = cbi_t[section][tab];
1061 var h = document.getElementById('tab.' + section);
1063 for (var tid in cbi_t[section]) {
1064 var o2 = cbi_t[section][tid];
1066 if (o.tab.id != o2.tab.id) {
1067 o2.tab.classList.remove('cbi-tab');
1068 o2.tab.classList.add('cbi-tab-disabled');
1069 o2.container.style.display = 'none';
1075 o2.tab.classList.remove('cbi-tab-disabled');
1076 o2.tab.classList.add('cbi-tab');
1077 o2.container.style.display = 'block';
1085 function cbi_t_update() {
1087 var updated = false;
1089 for (var sid in cbi_t)
1090 for (var tid in cbi_t[sid]) {
1091 var t = cbi_t[sid][tid].tab;
1092 var c = cbi_t[sid][tid].container;
1094 if (!c.firstElementChild) {
1095 t.style.display = 'none';
1097 else if (t.style.display == 'none') {
1098 t.style.display = '';
1099 t.classList.add('cbi-tab-highlighted');
1107 if (hl_tabs.length > 0)
1108 window.setTimeout(function() {
1109 for (var i = 0; i < hl_tabs.length; i++)
1110 hl_tabs[i].classList.remove('cbi-tab-highlighted');
1117 function cbi_validate_form(form, errmsg)
1119 /* if triggered by a section removal or addition, don't validate */
1120 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
1123 if (form.cbi_validators) {
1124 for (var i = 0; i < form.cbi_validators.length; i++) {
1125 var validator = form.cbi_validators[i];
1127 if (!validator() && errmsg) {
1137 function cbi_validate_reset(form)
1140 function() { cbi_validate_form(form, null) }, 100
1146 function cbi_validate_field(cbid, optional, type)
1148 var field = isElem(cbid) ? cbid : document.getElementById(cbid);
1152 var cbiValidator = new CBIValidator(field, type, optional);
1153 validatorFn = cbiValidator.validate.bind(cbiValidator);
1159 if (validatorFn !== null) {
1160 var form = findParent(field, 'form');
1162 if (!form.cbi_validators)
1163 form.cbi_validators = [ ];
1165 form.cbi_validators.push(validatorFn);
1167 field.addEventListener("blur", validatorFn);
1168 field.addEventListener("keyup", validatorFn);
1169 field.addEventListener("cbi-dropdown-change", validatorFn);
1171 if (matchesElem(field, 'select')) {
1172 field.addEventListener("change", validatorFn);
1173 field.addEventListener("click", validatorFn);
1180 function cbi_row_swap(elem, up, store)
1182 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
1187 tr.classList.remove('flash');
1190 var prev = tr.previousElementSibling;
1192 if (prev && prev.classList.contains('cbi-section-table-row'))
1193 tr.parentNode.insertBefore(tr, prev);
1198 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1200 if (next && next.classList.contains('cbi-section-table-row'))
1201 tr.parentNode.insertBefore(tr, next);
1203 tr.parentNode.appendChild(tr);
1210 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1211 var node = tr.parentNode.childNodes[i];
1212 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1213 node.classList.remove('cbi-rowstyle-1');
1214 node.classList.remove('cbi-rowstyle-2');
1215 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1217 if (/-([^\-]+)$/.test(node.id))
1218 ids.push(RegExp.$1);
1222 var input = document.getElementById(store);
1224 input.value = ids.join(' ');
1226 window.scrollTo(0, tr.offsetTop);
1227 void tr.offsetWidth;
1228 tr.classList.add('flash');
1233 function cbi_tag_last(container)
1237 for (var i = 0; i < container.childNodes.length; i++) {
1238 var c = container.childNodes[i];
1239 if (matchesElem(c, 'div')) {
1240 c.classList.remove('cbi-value-last');
1246 last.classList.add('cbi-value-last');
1249 function cbi_submit(elem, name, value, action)
1251 var form = elem.form || findParent(elem, 'form');
1257 form.action = action;
1260 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1261 E('input', { type: 'hidden', name: name });
1263 hidden.value = value || '1';
1264 form.appendChild(hidden);
1271 String.prototype.format = function()
1276 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1277 var quot_esc = [/"/g, '"', /'/g, '''];
1279 function esc(s, r) {
1280 if (typeof(s) !== 'string' && !(s instanceof String))
1283 for (var i = 0; i < r.length; i += 2)
1284 s = s.replace(r[i], r[i+1]);
1291 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1292 var a = b = [], numSubstitutions = 0, numMatches = 0;
1294 while (a = re.exec(str)) {
1296 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1297 var pPrecision = a[6], pType = a[7];
1305 if (numSubstitutions < arguments.length) {
1306 var param = arguments[numSubstitutions++];
1309 if (pPad && pPad.substr(0,1) == "'")
1310 pad = leftpart.substr(1,1);
1316 var justifyRight = true;
1317 if (pJustify && pJustify === "-")
1318 justifyRight = false;
1322 minLength = +pMinLength;
1325 if (pPrecision && pType == 'f')
1326 precision = +pPrecision.substring(1);
1332 subst = (+param || 0).toString(2);
1336 subst = String.fromCharCode(+param || 0);
1340 subst = ~~(+param || 0);
1344 subst = ~~Math.abs(+param || 0);
1348 subst = (precision > -1)
1349 ? ((+param || 0.0)).toFixed(precision)
1354 subst = (+param || 0).toString(8);
1362 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1366 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1370 subst = esc(param, html_esc);
1374 subst = esc(param, quot_esc);
1381 var ts = (param || 0);
1384 tm = Math.floor(ts / 60);
1389 th = Math.floor(tm / 60);
1394 td = Math.floor(th / 24);
1399 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1400 : String.format('%dh %dm %ds', th, tm, ts);
1405 var mf = pMinLength ? +pMinLength : 1000;
1406 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1409 var val = (+param || 0);
1410 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1412 for (i = 0; (i < units.length) && (val > mf); i++)
1415 subst = (i ? val.toFixed(pr) : val) + units[i];
1423 subst = subst.toString();
1424 for (var i = subst.length; i < pMinLength; i++)
1425 if (pJustify == '-')
1426 subst = subst + ' ';
1428 subst = pad + subst;
1431 out += leftpart + subst;
1432 str = str.substr(m.length);
1438 String.prototype.nobr = function()
1440 return this.replace(/[\s\n]+/g, ' ');
1443 String.format = function()
1447 for (var i = 1; i < arguments.length; i++)
1448 a.push(arguments[i]);
1450 return ''.format.apply(arguments[0], a);
1453 String.nobr = function()
1457 for (var i = 1; i < arguments.length; i++)
1458 a.push(arguments[i]);
1460 return ''.nobr.apply(arguments[0], a);
1463 if (window.NodeList && !NodeList.prototype.forEach) {
1464 NodeList.prototype.forEach = function (callback, thisArg) {
1465 thisArg = thisArg || window;
1466 for (var i = 0; i < this.length; i++) {
1467 callback.call(thisArg, this[i], i, this);
1472 if (!window.requestAnimationFrame) {
1473 window.requestAnimationFrame = function(f) {
1474 window.setTimeout(function() {
1475 f(new Date().getTime())
1481 var dummyElem, domParser;
1485 return (typeof(e) === 'object' && e !== null && 'nodeType' in e);
1493 domParser = domParser || new DOMParser();
1494 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1500 dummyElem = dummyElem || document.createElement('div');
1501 dummyElem.innerHTML = s;
1502 elem = dummyElem.firstChild;
1507 return elem || null;
1510 function matchesElem(node, selector)
1512 return ((node.matches && node.matches(selector)) ||
1513 (node.msMatchesSelector && node.msMatchesSelector(selector)));
1516 function findParent(node, selector)
1519 return node.closest(selector);
1522 if (matchesElem(node, selector))
1525 node = node.parentNode;
1532 var html = arguments[0],
1533 attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null,
1534 data = attr ? arguments[2] : arguments[1],
1539 else if (html.charCodeAt(0) === 60)
1540 elem = toElem(html);
1542 elem = document.createElement(html);
1548 for (var key in attr)
1549 if (attr.hasOwnProperty(key) && attr[key] !== null && attr[key] !== undefined)
1550 switch (typeof(attr[key])) {
1552 elem.addEventListener(key, attr[key]);
1556 elem.setAttribute(key, JSON.stringify(attr[key]));
1560 elem.setAttribute(key, attr[key]);
1563 if (typeof(data) === 'function')
1567 elem.appendChild(data);
1569 else if (Array.isArray(data)) {
1570 for (var i = 0; i < data.length; i++)
1571 if (isElem(data[i]))
1572 elem.appendChild(data[i]);
1574 elem.appendChild(document.createTextNode('' + data[i]));
1576 else if (data !== null && data !== undefined) {
1577 elem.innerHTML = '' + data;
1583 if (typeof(window.CustomEvent) !== 'function') {
1584 function CustomEvent(event, params) {
1585 params = params || { bubbles: false, cancelable: false, detail: undefined };
1586 var evt = document.createEvent('CustomEvent');
1587 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1591 CustomEvent.prototype = window.Event.prototype;
1592 window.CustomEvent = CustomEvent;
1596 openDropdown: function(sb) {
1597 var st = window.getComputedStyle(sb, null),
1598 ul = sb.querySelector('ul'),
1599 li = ul.querySelectorAll('li'),
1600 fl = findParent(sb, '.cbi-value-field'),
1601 sel = ul.querySelector('[selected]'),
1602 rect = sb.getBoundingClientRect(),
1603 items = Math.min(this.dropdown_items, li.length);
1605 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1606 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1609 sb.setAttribute('open', '');
1611 var pv = ul.cloneNode(true);
1612 pv.classList.add('preview');
1615 fl.classList.add('cbi-dropdown-open');
1617 if ('ontouchstart' in window) {
1618 var vpWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
1619 vpHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
1620 scrollFrom = window.pageYOffset,
1621 scrollTo = scrollFrom + rect.top - vpHeight * 0.5,
1624 ul.style.top = sb.offsetHeight + 'px';
1625 ul.style.left = -rect.left + 'px';
1626 ul.style.right = (rect.right - vpWidth) + 'px';
1627 ul.style.maxHeight = (vpHeight * 0.5) + 'px';
1628 ul.style.WebkitOverflowScrolling = 'touch';
1630 var scrollStep = function(timestamp) {
1633 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1636 var duration = Math.max(timestamp - start, 1);
1637 if (duration < 100) {
1638 document.body.scrollTop = scrollFrom + (scrollTo - scrollFrom) * (duration / 100);
1639 window.requestAnimationFrame(scrollStep);
1642 document.body.scrollTop = scrollTo;
1646 window.requestAnimationFrame(scrollStep);
1649 ul.style.maxHeight = '1px';
1650 ul.style.top = ul.style.bottom = '';
1652 window.requestAnimationFrame(function() {
1653 var height = items * li[Math.max(0, li.length - 2)].offsetHeight;
1655 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1656 ul.style[((rect.top + rect.height + height) > window.innerHeight) ? 'bottom' : 'top'] = rect.height + 'px';
1657 ul.style.maxHeight = height + 'px';
1661 ul.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c) {
1665 ul.classList.add('dropdown');
1667 sb.insertBefore(pv, ul.nextElementSibling);
1669 li.forEach(function(l) {
1670 l.setAttribute('tabindex', 0);
1673 sb.lastElementChild.setAttribute('tabindex', 0);
1675 this.setFocus(sb, sel || li[0], true);
1678 closeDropdown: function(sb, no_focus) {
1679 if (!sb.hasAttribute('open'))
1682 var pv = sb.querySelector('ul.preview'),
1683 ul = sb.querySelector('ul.dropdown'),
1684 li = ul.querySelectorAll('li'),
1685 fl = findParent(sb, '.cbi-value-field');
1687 li.forEach(function(l) { l.removeAttribute('tabindex'); });
1688 sb.lastElementChild.removeAttribute('tabindex');
1691 sb.removeAttribute('open');
1692 sb.style.width = sb.style.height = '';
1694 ul.classList.remove('dropdown');
1695 ul.style.top = ul.style.bottom = ul.style.maxHeight = '';
1698 fl.classList.remove('cbi-dropdown-open');
1701 this.setFocus(sb, sb);
1703 this.saveValues(sb, ul);
1706 toggleItem: function(sb, li, force_state) {
1707 if (li.hasAttribute('unselectable'))
1711 var cbox = li.querySelector('input[type="checkbox"]'),
1712 items = li.parentNode.querySelectorAll('li'),
1713 label = sb.querySelector('ul.preview'),
1714 sel = li.parentNode.querySelectorAll('[selected]').length,
1715 more = sb.querySelector('.more'),
1716 ndisplay = this.display_items,
1719 if (li.hasAttribute('selected')) {
1720 if (force_state !== true) {
1721 if (sel > 1 || this.optional) {
1722 li.removeAttribute('selected');
1723 cbox.checked = cbox.disabled = false;
1727 cbox.disabled = true;
1732 if (force_state !== false) {
1733 li.setAttribute('selected', '');
1734 cbox.checked = true;
1735 cbox.disabled = false;
1740 while (label.firstElementChild)
1741 label.removeChild(label.firstElementChild);
1743 for (var i = 0; i < items.length; i++) {
1744 items[i].removeAttribute('display');
1745 if (items[i].hasAttribute('selected')) {
1746 if (ndisplay-- > 0) {
1747 items[i].setAttribute('display', n++);
1748 label.appendChild(items[i].cloneNode(true));
1750 var c = items[i].querySelector('input[type="checkbox"]');
1752 c.disabled = (sel == 1 && !this.optional);
1757 sb.setAttribute('more', '');
1759 sb.removeAttribute('more');
1761 if (ndisplay === this.display_items)
1762 sb.setAttribute('empty', '');
1764 sb.removeAttribute('empty');
1766 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1769 var sel = li.parentNode.querySelector('[selected]');
1771 sel.removeAttribute('display');
1772 sel.removeAttribute('selected');
1775 li.setAttribute('display', 0);
1776 li.setAttribute('selected', '');
1778 this.closeDropdown(sb, true);
1781 this.saveValues(sb, li.parentNode);
1784 transformItem: function(sb, li) {
1785 var cbox = E('form', {}, E('input', { type: 'checkbox', tabindex: -1, onclick: 'event.preventDefault()' })),
1788 while (li.firstChild)
1789 label.appendChild(li.firstChild);
1791 li.appendChild(cbox);
1792 li.appendChild(label);
1795 saveValues: function(sb, ul) {
1796 var sel = ul.querySelectorAll('li[selected]'),
1797 div = sb.lastElementChild,
1801 while (div.lastElementChild)
1802 div.removeChild(div.lastElementChild);
1804 sel.forEach(function (s) {
1805 if (s.hasAttribute('placeholder'))
1810 value: s.hasAttribute('data-value') ? s.getAttribute('data-value') : s.innerText,
1814 div.appendChild(E('input', {
1816 name: s.hasAttribute('name') ? s.getAttribute('name') : (sb.getAttribute('name') || ''),
1822 strval += strval.length ? ' ' + v.value : v.value;
1831 detail.values = values;
1833 detail.value = values.length ? values[0] : null;
1837 sb.dispatchEvent(new CustomEvent('cbi-dropdown-change', {
1845 setValues: function(sb, values) {
1846 var ul = sb.querySelector('ul');
1849 ul.querySelectorAll('li[data-value]').forEach(function(li) {
1850 if (values === null || !(li.getAttribute('data-value') in values))
1851 this.toggleItem(sb, li, false);
1853 this.toggleItem(sb, li, true);
1857 var ph = ul.querySelector('li[placeholder]');
1859 this.toggleItem(sb, ph);
1861 ul.querySelectorAll('li[data-value]').forEach(function(li) {
1862 if (values !== null && (li.getAttribute('data-value') in values))
1863 this.toggleItem(sb, li);
1868 setFocus: function(sb, elem, scroll) {
1869 if (sb && sb.hasAttribute && sb.hasAttribute('locked-in'))
1872 if (sb.target && findParent(sb.target, 'ul.dropdown'))
1875 document.querySelectorAll('.focus').forEach(function(e) {
1876 if (!matchesElem(e, 'input')) {
1877 e.classList.remove('focus');
1884 elem.classList.add('focus');
1887 elem.parentNode.scrollTop = elem.offsetTop - elem.parentNode.offsetTop;
1891 createItems: function(sb, value) {
1893 val = (value || '').trim(),
1894 ul = sb.querySelector('ul');
1897 val = val.length ? [ val ] : [];
1899 val = val.length ? val.split(/\s+/) : [];
1901 val.forEach(function(item) {
1902 var new_item = null;
1904 ul.childNodes.forEach(function(li) {
1905 if (li.getAttribute && li.getAttribute('data-value') === item)
1911 tpl = sb.querySelector(sbox.template);
1914 markup = (tpl.textContent || tpl.innerHTML || tpl.firstChild.data).replace(/^<!--|-->$/, '').trim();
1916 markup = '<li data-value="{{value}}">{{value}}</li>';
1918 new_item = E(markup.replace(/{{value}}/g, item));
1921 sbox.transformItem(sb, new_item);
1924 var old = ul.querySelector('li[created]');
1926 ul.removeChild(old);
1928 new_item.setAttribute('created', '');
1931 new_item = ul.insertBefore(new_item, ul.lastElementChild);
1934 sbox.toggleItem(sb, new_item, true);
1935 sbox.setFocus(sb, new_item, true);
1939 closeAllDropdowns: function() {
1940 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1941 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1945 handleClick: function(ev) {
1946 var sb = ev.currentTarget;
1948 if (!sb.hasAttribute('open')) {
1949 if (!matchesElem(ev.target, 'input'))
1950 this.openDropdown(sb);
1953 var li = findParent(ev.target, 'li');
1954 if (li && li.parentNode.classList.contains('dropdown'))
1955 this.toggleItem(sb, li);
1956 else if (li && li.parentNode.classList.contains('preview'))
1957 this.closeDropdown(sb);
1960 ev.preventDefault();
1961 ev.stopPropagation();
1964 handleKeydown: function(ev) {
1965 var sb = ev.currentTarget;
1967 if (matchesElem(ev.target, 'input'))
1970 if (!sb.hasAttribute('open')) {
1971 switch (ev.keyCode) {
1976 this.openDropdown(sb);
1977 ev.preventDefault();
1981 var active = findParent(document.activeElement, 'li');
1983 switch (ev.keyCode) {
1985 this.closeDropdown(sb);
1990 if (!active.hasAttribute('selected'))
1991 this.toggleItem(sb, active);
1992 this.closeDropdown(sb);
1993 ev.preventDefault();
1999 this.toggleItem(sb, active);
2000 ev.preventDefault();
2005 if (active && active.previousElementSibling) {
2006 this.setFocus(sb, active.previousElementSibling);
2007 ev.preventDefault();
2012 if (active && active.nextElementSibling) {
2013 this.setFocus(sb, active.nextElementSibling);
2014 ev.preventDefault();
2021 handleDropdownClose: function(ev) {
2022 var sb = ev.currentTarget;
2024 this.closeDropdown(sb, true);
2027 handleDropdownSelect: function(ev) {
2028 var sb = ev.currentTarget,
2029 li = findParent(ev.target, 'li');
2034 this.toggleItem(sb, li);
2035 this.closeDropdown(sb, true);
2038 handleMouseover: function(ev) {
2039 var sb = ev.currentTarget;
2041 if (!sb.hasAttribute('open'))
2044 var li = findParent(ev.target, 'li');
2046 if (li && li.parentNode.classList.contains('dropdown'))
2047 this.setFocus(sb, li);
2050 handleFocus: function(ev) {
2051 var sb = ev.currentTarget;
2053 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
2054 if (s !== sb || sb.hasAttribute('open'))
2055 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
2059 handleCanaryFocus: function(ev) {
2060 this.closeDropdown(ev.currentTarget.parentNode);
2063 handleCreateKeydown: function(ev) {
2064 var input = ev.currentTarget,
2065 sb = findParent(input, '.cbi-dropdown');
2067 switch (ev.keyCode) {
2069 ev.preventDefault();
2071 if (input.classList.contains('cbi-input-invalid'))
2074 this.createItems(sb, input.value);
2081 handleCreateFocus: function(ev) {
2082 var input = ev.currentTarget,
2083 cbox = findParent(input, 'li').querySelector('input[type="checkbox"]'),
2084 sb = findParent(input, '.cbi-dropdown');
2087 cbox.checked = true;
2089 sb.setAttribute('locked-in', '');
2092 handleCreateBlur: function(ev) {
2093 var input = ev.currentTarget,
2094 cbox = findParent(input, 'li').querySelector('input[type="checkbox"]'),
2095 sb = findParent(input, '.cbi-dropdown');
2098 cbox.checked = false;
2100 sb.removeAttribute('locked-in');
2103 handleCreateClick: function(ev) {
2104 ev.currentTarget.querySelector(this.create).focus();
2108 function cbi_dropdown_init(sb) {
2109 if (!(this instanceof cbi_dropdown_init))
2110 return new cbi_dropdown_init(sb);
2112 this.multi = sb.hasAttribute('multiple');
2113 this.optional = sb.hasAttribute('optional');
2114 this.placeholder = sb.getAttribute('placeholder') || '---';
2115 this.display_items = parseInt(sb.getAttribute('display-items') || 3);
2116 this.dropdown_items = parseInt(sb.getAttribute('dropdown-items') || 5);
2117 this.create = sb.getAttribute('item-create') || '.create-item-input';
2118 this.template = sb.getAttribute('item-template') || 'script[type="item-template"]';
2120 var ul = sb.querySelector('ul'),
2121 more = sb.appendChild(E('span', { class: 'more', tabindex: -1 }, '···')),
2122 open = sb.appendChild(E('span', { class: 'open', tabindex: -1 }, '▾')),
2123 canary = sb.appendChild(E('div')),
2124 create = sb.querySelector(this.create),
2125 ndisplay = this.display_items,
2129 var items = ul.querySelectorAll('li');
2131 for (var i = 0; i < items.length; i++) {
2132 this.transformItem(sb, items[i]);
2134 if (items[i].hasAttribute('selected') && ndisplay-- > 0)
2135 items[i].setAttribute('display', n++);
2139 if (this.optional && !ul.querySelector('li[data-value=""]')) {
2140 var placeholder = E('li', { placeholder: '' }, this.placeholder);
2141 ul.firstChild ? ul.insertBefore(placeholder, ul.firstChild) : ul.appendChild(placeholder);
2144 var items = ul.querySelectorAll('li'),
2145 sel = sb.querySelectorAll('[selected]');
2147 sel.forEach(function(s) {
2148 s.removeAttribute('selected');
2151 var s = sel[0] || items[0];
2153 s.setAttribute('selected', '');
2154 s.setAttribute('display', n++);
2160 this.saveValues(sb, ul);
2162 ul.setAttribute('tabindex', -1);
2163 sb.setAttribute('tabindex', 0);
2166 sb.setAttribute('more', '')
2168 sb.removeAttribute('more');
2170 if (ndisplay === this.display_items)
2171 sb.setAttribute('empty', '')
2173 sb.removeAttribute('empty');
2175 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
2178 sb.addEventListener('click', this.handleClick.bind(this));
2179 sb.addEventListener('keydown', this.handleKeydown.bind(this));
2180 sb.addEventListener('cbi-dropdown-close', this.handleDropdownClose.bind(this));
2181 sb.addEventListener('cbi-dropdown-select', this.handleDropdownSelect.bind(this));
2183 if ('ontouchstart' in window) {
2184 sb.addEventListener('touchstart', function(ev) { ev.stopPropagation(); });
2185 window.addEventListener('touchstart', this.closeAllDropdowns);
2188 sb.addEventListener('mouseover', this.handleMouseover.bind(this));
2189 sb.addEventListener('focus', this.handleFocus.bind(this));
2191 canary.addEventListener('focus', this.handleCanaryFocus.bind(this));
2193 window.addEventListener('mouseover', this.setFocus);
2194 window.addEventListener('click', this.closeAllDropdowns);
2198 create.addEventListener('keydown', this.handleCreateKeydown.bind(this));
2199 create.addEventListener('focus', this.handleCreateFocus.bind(this));
2200 create.addEventListener('blur', this.handleCreateBlur.bind(this));
2202 var li = findParent(create, 'li');
2204 li.setAttribute('unselectable', '');
2205 li.addEventListener('click', this.handleCreateClick.bind(this));
2209 cbi_dropdown_init.prototype = CBIDropdown;
2211 function cbi_update_table(table, data, placeholder) {
2212 var target = isElem(table) ? table : document.querySelector(table);
2214 if (!isElem(target))
2217 target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
2220 thead.querySelectorAll('.th').forEach(function(th) {
2224 if (Array.isArray(data)) {
2225 var n = 0, rows = target.querySelectorAll('.tr');
2227 data.forEach(function(row) {
2228 var trow = E('div', { 'class': 'tr' });
2230 for (var i = 0; i < titles.length; i++) {
2231 var text = (titles[i].innerText || '').trim();
2232 var td = trow.appendChild(E('div', {
2233 'class': titles[i].className,
2234 'data-title': (text !== '') ? text : null
2237 td.classList.remove('th');
2238 td.classList.add('td');
2241 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
2244 target.replaceChild(trow, rows[n]);
2246 target.appendChild(trow);
2250 target.removeChild(rows[n]);
2252 if (placeholder && target.firstElementChild === target.lastElementChild) {
2253 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
2254 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
2256 td.classList.remove('th');
2257 td.classList.add('td');
2261 thead.parentNode.style.display = 'none';
2263 thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
2264 if (trow !== thead) {
2266 trow.querySelectorAll('.th, .td').forEach(function(td) {
2267 if (n < titles.length) {
2268 var text = (titles[n++].innerText || '').trim();
2270 td.setAttribute('data-title', text);
2276 thead.parentNode.style.display = '';
2281 function showModal(title, children)
2283 return L.showModal(title, children);
2286 function hideModal()
2288 return L.hideModal();
2292 document.addEventListener('DOMContentLoaded', function() {
2293 document.addEventListener('validation-failure', function(ev) {
2294 if (ev.target === document.activeElement)
2298 document.addEventListener('validation-success', function(ev) {
2299 if (ev.target === document.activeElement)
2303 document.querySelectorAll('.table').forEach(cbi_update_table);