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 (!findParent(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 %s').format(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 ? (input.getAttribute('data-is-list') ? input.value.match(/[^ \t]+/g) : [ input.value ]) : null;
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);
587 hexstring: function() {
588 return this.assert(this.value.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
589 _('hexadecimal encoded value'));
594 function CBIValidator(field, type, optional)
597 this.optional = optional;
598 this.vstack = this.compile(type);
601 CBIValidator.prototype = CBIValidatorPrototype;
604 function cbi_d_add(field, dep, index) {
605 var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
608 for (var i=0; i<cbi_d.length; i++) {
609 if (cbi_d[i].id == obj.id) {
618 "parent": obj.parentNode.id,
622 cbi_d.unshift(entry);
628 function cbi_d_checkvalue(target, ref) {
630 query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
631 'select[id="'+target+'"], select[name="'+target+'"]';
633 document.querySelectorAll(query).forEach(function(i) {
634 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
638 return (((value !== null) ? value : "") == ref);
641 function cbi_d_check(deps) {
644 for (var i=0; i<deps.length; i++) {
647 for (var j in deps[i]) {
648 if (j == "!reverse") {
650 } else if (j == "!default") {
654 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
658 if (istat ^ reverse) {
665 function cbi_d_update() {
667 for (var i=0; i<cbi_d.length; i++) {
668 var entry = cbi_d[i];
669 var node = document.getElementById(entry.id);
670 var parent = document.getElementById(entry.parent);
672 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
673 node.parentNode.removeChild(node);
676 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
677 var next = undefined;
679 for (next = parent.firstChild; next; next = next.nextSibling) {
680 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
685 parent.appendChild(entry.node);
687 parent.insertBefore(entry.node, next);
692 // hide optionals widget if no choices remaining
693 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
694 parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
697 if (entry && entry.parent) {
699 cbi_tag_last(parent);
706 function cbi_init() {
709 nodes = document.querySelectorAll('[data-strings]');
711 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
712 var str = JSON.parse(node.getAttribute('data-strings'));
713 for (var key in str) {
714 for (var key2 in str[key]) {
715 var dst = cbi_strings[key] || (cbi_strings[key] = { });
716 dst[key2] = str[key][key2];
721 nodes = document.querySelectorAll('[data-depends]');
723 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
724 var index = parseInt(node.getAttribute('data-index'), 10);
725 var depends = JSON.parse(node.getAttribute('data-depends'));
726 if (!isNaN(index) && depends.length > 0) {
727 for (var alt = 0; alt < depends.length; alt++)
728 cbi_d_add(node, depends[alt], index);
732 nodes = document.querySelectorAll('[data-update]');
734 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
735 var events = node.getAttribute('data-update').split(' ');
736 for (var j = 0, event; (event = events[j]) !== undefined; j++)
737 node.addEventListener(event, cbi_d_update);
740 nodes = document.querySelectorAll('[data-choices]');
742 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
743 var choices = JSON.parse(node.getAttribute('data-choices'));
746 for (var j = 0; j < choices[0].length; j++)
747 options[choices[0][j]] = choices[1][j];
749 var def = (node.getAttribute('data-optional') === 'true')
750 ? node.placeholder || '' : null;
752 cbi_combobox_init(node, options, def,
753 node.getAttribute('data-manual'));
756 nodes = document.querySelectorAll('[data-dynlist]');
758 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
759 var choices = JSON.parse(node.getAttribute('data-dynlist'));
762 if (choices[0] && choices[0].length) {
765 for (var j = 0; j < choices[0].length; j++)
766 options[choices[0][j]] = choices[1][j];
769 cbi_dynlist_init(node, choices[2], choices[3], options);
772 nodes = document.querySelectorAll('[data-type]');
774 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
775 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
776 node.getAttribute('data-type'));
779 document.querySelectorAll('.cbi-dropdown').forEach(function(s) {
780 cbi_dropdown_init(s);
783 document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
784 s.parentNode.classList.add('cbi-tooltip-container');
787 document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
788 var handler = function(ev) {
789 var bits = this.name.split(/\./),
790 section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
792 section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
795 i.addEventListener('mouseover', handler);
796 i.addEventListener('mouseout', handler);
802 function cbi_combobox_init(id, values, def, man) {
803 var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
806 'class': 'cbi-dropdown',
808 'optional': obj.getAttribute('data-optional'),
809 'placeholder': _('-- Please choose --'),
810 'data-type': obj.getAttribute('data-type'),
811 'data-optional': obj.getAttribute('data-optional')
814 if (!(obj.value in values) && obj.value.length) {
815 sb.lastElementChild.appendChild(E('li', {
816 'data-value': obj.value,
818 }, obj.value.length ? obj.value : (def || _('-- Please choose --'))));
821 for (var i in values) {
822 sb.lastElementChild.appendChild(E('li', {
824 'selected': (i == obj.value) ? '' : null
828 sb.lastElementChild.appendChild(E('li', { 'data-value': '-' }, [
831 'class': 'create-item-input',
832 'data-type': obj.getAttribute('data-type'),
833 'data-optional': true,
834 'placeholder': (man || _('-- custom --'))
838 sb.value = obj.value;
839 obj.parentNode.replaceChild(sb, obj);
842 function cbi_filebrowser(id, defpath) {
843 var field = document.getElementById(id);
844 var browser = window.open(
845 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
846 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
852 function cbi_browser_init(id, resource, defpath)
854 function cbi_browser_btnclick(e) {
855 cbi_filebrowser(id, defpath);
859 var field = document.getElementById(id);
861 var btn = document.createElement('img');
862 btn.className = 'cbi-image-button';
863 btn.src = (resource || cbi_strings.path.resource) + '/cbi/folder.gif';
864 field.parentNode.insertBefore(btn, field.nextSibling);
866 btn.addEventListener('click', cbi_browser_btnclick);
870 addItem: function(dl, value, text, flash) {
872 new_item = E('div', { 'class': flash ? 'item flash' : 'item', 'tabindex': 0 }, [
873 E('span', {}, text || value),
876 'name': dl.getAttribute('data-prefix'),
879 dl.querySelectorAll('.item, .add-item').forEach(function(item) {
883 var hidden = item.querySelector('input[type="hidden"]');
885 if (hidden && hidden.value === value)
887 else if (!hidden || hidden.value >= value)
888 exists = !!item.parentNode.insertBefore(new_item, item);
892 removeItem: function(dl, item) {
893 var sb = dl.querySelector('.cbi-dropdown');
895 var value = item.querySelector('input[type="hidden"]').value;
897 sb.querySelectorAll('ul > li').forEach(function(li) {
898 if (li.getAttribute('data-value') === value)
899 li.removeAttribute('unselectable');
903 item.parentNode.removeChild(item);
906 handleClick: function(ev) {
907 var dl = ev.currentTarget,
908 item = findParent(ev.target, '.item');
911 this.removeItem(dl, item);
913 else if (matchesElem(ev.target, '.cbi-button-add')) {
914 var input = ev.target.previousElementSibling;
915 if (input.value.length && !input.classList.contains('cbi-input-invalid')) {
916 this.addItem(dl, input.value, null, true);
922 handleDropdownChange: function(ev) {
923 var dl = ev.currentTarget,
924 sbIn = ev.detail.instance,
925 sbEl = ev.detail.element,
926 sbVal = ev.detail.value;
931 sbIn.setValues(sbEl, null);
932 sbVal.element.setAttribute('unselectable', '');
934 this.addItem(dl, sbVal.value, sbVal.text, true);
937 handleKeydown: function(ev) {
938 var dl = ev.currentTarget,
939 item = findParent(ev.target, '.item');
942 switch (ev.keyCode) {
943 case 8: /* backspace */
944 if (item.previousElementSibling)
945 item.previousElementSibling.focus();
947 this.removeItem(dl, item);
950 case 46: /* delete */
951 if (item.nextElementSibling) {
952 if (item.nextElementSibling.classList.contains('item'))
953 item.nextElementSibling.focus();
955 item.nextElementSibling.firstElementChild.focus();
958 this.removeItem(dl, item);
962 else if (matchesElem(ev.target, '.cbi-input-text')) {
963 switch (ev.keyCode) {
965 if (ev.target.value.length && !ev.target.classList.contains('cbi-input-invalid')) {
966 this.addItem(dl, ev.target.value, null, true);
967 ev.target.value = '';
979 function cbi_dynlist_init(dl, datatype, optional, choices)
981 if (!(this instanceof cbi_dynlist_init))
982 return new cbi_dynlist_init(dl, datatype, optional, choices);
984 dl.classList.add('cbi-dynlist');
985 dl.appendChild(E('div', { 'class': 'add-item' }, E('input', {
987 'name': 'cbi.dynlist.' + dl.getAttribute('data-prefix'),
988 'class': 'cbi-input-text',
989 'data-type': datatype,
990 'data-optional': true
994 cbi_combobox_init(dl.lastElementChild.lastElementChild, choices, '', _('-- custom --'));
996 dl.lastElementChild.appendChild(E('div', { 'class': 'cbi-button cbi-button-add' }, '+'));
998 dl.addEventListener('click', this.handleClick.bind(this));
999 dl.addEventListener('keydown', this.handleKeydown.bind(this));
1000 dl.addEventListener('cbi-dropdown-change', this.handleDropdownChange.bind(this));
1003 var values = JSON.parse(dl.getAttribute('data-values') || '[]');
1005 if (typeof(values) === 'object' && Array.isArray(values))
1006 for (var i = 0; i < values.length; i++)
1007 this.addItem(dl, values[i], choices ? choices[values[i]] : null);
1012 cbi_dynlist_init.prototype = CBIDynamicList;
1015 function cbi_t_add(section, tab) {
1016 var t = document.getElementById('tab.' + section + '.' + tab);
1017 var c = document.getElementById('container.' + section + '.' + tab);
1020 cbi_t[section] = (cbi_t[section] || [ ]);
1021 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
1025 function cbi_t_switch(section, tab) {
1026 if (cbi_t[section] && cbi_t[section][tab]) {
1027 var o = cbi_t[section][tab];
1028 var h = document.getElementById('tab.' + section);
1030 for (var tid in cbi_t[section]) {
1031 var o2 = cbi_t[section][tid];
1033 if (o.tab.id != o2.tab.id) {
1034 o2.tab.classList.remove('cbi-tab');
1035 o2.tab.classList.add('cbi-tab-disabled');
1036 o2.container.style.display = 'none';
1042 o2.tab.classList.remove('cbi-tab-disabled');
1043 o2.tab.classList.add('cbi-tab');
1044 o2.container.style.display = 'block';
1052 function cbi_t_update() {
1054 var updated = false;
1056 for (var sid in cbi_t)
1057 for (var tid in cbi_t[sid]) {
1058 var t = cbi_t[sid][tid].tab;
1059 var c = cbi_t[sid][tid].container;
1061 if (!c.firstElementChild) {
1062 t.style.display = 'none';
1064 else if (t.style.display == 'none') {
1065 t.style.display = '';
1066 t.classList.add('cbi-tab-highlighted');
1074 if (hl_tabs.length > 0)
1075 window.setTimeout(function() {
1076 for (var i = 0; i < hl_tabs.length; i++)
1077 hl_tabs[i].classList.remove('cbi-tab-highlighted');
1084 function cbi_validate_form(form, errmsg)
1086 /* if triggered by a section removal or addition, don't validate */
1087 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
1090 if (form.cbi_validators) {
1091 for (var i = 0; i < form.cbi_validators.length; i++) {
1092 var validator = form.cbi_validators[i];
1094 if (!validator() && errmsg) {
1104 function cbi_validate_reset(form)
1107 function() { cbi_validate_form(form, null) }, 100
1113 function cbi_validate_field(cbid, optional, type)
1115 var field = isElem(cbid) ? cbid : document.getElementById(cbid);
1119 var cbiValidator = new CBIValidator(field, type, optional);
1120 validatorFn = cbiValidator.validate.bind(cbiValidator);
1126 if (validatorFn !== null) {
1127 var form = findParent(field, 'form');
1129 if (!form.cbi_validators)
1130 form.cbi_validators = [ ];
1132 form.cbi_validators.push(validatorFn);
1134 field.addEventListener("blur", validatorFn);
1135 field.addEventListener("keyup", validatorFn);
1136 field.addEventListener("cbi-dropdown-change", validatorFn);
1138 if (matchesElem(field, 'select')) {
1139 field.addEventListener("change", validatorFn);
1140 field.addEventListener("click", validatorFn);
1147 function cbi_row_swap(elem, up, store)
1149 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
1154 tr.classList.remove('flash');
1157 var prev = tr.previousElementSibling;
1159 if (prev && prev.classList.contains('cbi-section-table-row'))
1160 tr.parentNode.insertBefore(tr, prev);
1165 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1167 if (next && next.classList.contains('cbi-section-table-row'))
1168 tr.parentNode.insertBefore(tr, next);
1170 tr.parentNode.appendChild(tr);
1177 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1178 var node = tr.parentNode.childNodes[i];
1179 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1180 node.classList.remove('cbi-rowstyle-1');
1181 node.classList.remove('cbi-rowstyle-2');
1182 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1184 if (/-([^\-]+)$/.test(node.id))
1185 ids.push(RegExp.$1);
1189 var input = document.getElementById(store);
1191 input.value = ids.join(' ');
1193 window.scrollTo(0, tr.offsetTop);
1194 void tr.offsetWidth;
1195 tr.classList.add('flash');
1200 function cbi_tag_last(container)
1204 for (var i = 0; i < container.childNodes.length; i++) {
1205 var c = container.childNodes[i];
1206 if (matchesElem(c, 'div')) {
1207 c.classList.remove('cbi-value-last');
1213 last.classList.add('cbi-value-last');
1216 function cbi_submit(elem, name, value, action)
1218 var form = elem.form || findParent(elem, 'form');
1224 form.action = action;
1227 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1228 E('input', { type: 'hidden', name: name });
1230 hidden.value = value || '1';
1231 form.appendChild(hidden);
1238 String.prototype.format = function()
1243 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1244 var quot_esc = [/"/g, '"', /'/g, '''];
1246 function esc(s, r) {
1247 if (typeof(s) !== 'string' && !(s instanceof String))
1250 for (var i = 0; i < r.length; i += 2)
1251 s = s.replace(r[i], r[i+1]);
1258 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1259 var a = b = [], numSubstitutions = 0, numMatches = 0;
1261 while (a = re.exec(str)) {
1263 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1264 var pPrecision = a[6], pType = a[7];
1272 if (numSubstitutions < arguments.length) {
1273 var param = arguments[numSubstitutions++];
1276 if (pPad && pPad.substr(0,1) == "'")
1277 pad = leftpart.substr(1,1);
1283 var justifyRight = true;
1284 if (pJustify && pJustify === "-")
1285 justifyRight = false;
1289 minLength = +pMinLength;
1292 if (pPrecision && pType == 'f')
1293 precision = +pPrecision.substring(1);
1299 subst = (+param || 0).toString(2);
1303 subst = String.fromCharCode(+param || 0);
1307 subst = ~~(+param || 0);
1311 subst = ~~Math.abs(+param || 0);
1315 subst = (precision > -1)
1316 ? ((+param || 0.0)).toFixed(precision)
1321 subst = (+param || 0).toString(8);
1329 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1333 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1337 subst = esc(param, html_esc);
1341 subst = esc(param, quot_esc);
1348 var ts = (param || 0);
1351 tm = Math.floor(ts / 60);
1356 th = Math.floor(tm / 60);
1361 td = Math.floor(th / 24);
1366 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1367 : String.format('%dh %dm %ds', th, tm, ts);
1372 var mf = pMinLength ? +pMinLength : 1000;
1373 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1376 var val = (+param || 0);
1377 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1379 for (i = 0; (i < units.length) && (val > mf); i++)
1382 subst = (i ? val.toFixed(pr) : val) + units[i];
1390 subst = subst.toString();
1391 for (var i = subst.length; i < pMinLength; i++)
1392 if (pJustify == '-')
1393 subst = subst + ' ';
1395 subst = pad + subst;
1398 out += leftpart + subst;
1399 str = str.substr(m.length);
1405 String.prototype.nobr = function()
1407 return this.replace(/[\s\n]+/g, ' ');
1410 String.format = function()
1414 for (var i = 1; i < arguments.length; i++)
1415 a.push(arguments[i]);
1417 return ''.format.apply(arguments[0], a);
1420 String.nobr = function()
1424 for (var i = 1; i < arguments.length; i++)
1425 a.push(arguments[i]);
1427 return ''.nobr.apply(arguments[0], a);
1430 if (window.NodeList && !NodeList.prototype.forEach) {
1431 NodeList.prototype.forEach = function (callback, thisArg) {
1432 thisArg = thisArg || window;
1433 for (var i = 0; i < this.length; i++) {
1434 callback.call(thisArg, this[i], i, this);
1440 var dummyElem, domParser;
1444 return (typeof(e) === 'object' && e !== null && 'nodeType' in e);
1452 domParser = domParser || new DOMParser();
1453 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1459 dummyElem = dummyElem || document.createElement('div');
1460 dummyElem.innerHTML = s;
1461 elem = dummyElem.firstChild;
1466 return elem || null;
1469 function matchesElem(node, selector)
1471 return ((node.matches && node.matches(selector)) ||
1472 (node.msMatchesSelector && node.msMatchesSelector(selector)));
1475 function findParent(node, selector)
1478 return node.closest(selector);
1481 if (matchesElem(node, selector))
1484 node = node.parentNode;
1491 var html = arguments[0],
1492 attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null,
1493 data = attr ? arguments[2] : arguments[1],
1498 else if (html.charCodeAt(0) === 60)
1499 elem = toElem(html);
1501 elem = document.createElement(html);
1507 for (var key in attr)
1508 if (attr.hasOwnProperty(key) && attr[key] !== null && attr[key] !== undefined)
1509 switch (typeof(attr[key])) {
1511 elem.addEventListener(key, attr[key]);
1515 elem.setAttribute(key, JSON.stringify(attr[key]));
1519 elem.setAttribute(key, attr[key]);
1522 if (typeof(data) === 'function')
1526 elem.appendChild(data);
1528 else if (Array.isArray(data)) {
1529 for (var i = 0; i < data.length; i++)
1530 if (isElem(data[i]))
1531 elem.appendChild(data[i]);
1533 elem.appendChild(document.createTextNode('' + data[i]));
1535 else if (data !== null && data !== undefined) {
1536 elem.innerHTML = '' + data;
1542 if (typeof(window.CustomEvent) !== 'function') {
1543 function CustomEvent(event, params) {
1544 params = params || { bubbles: false, cancelable: false, detail: undefined };
1545 var evt = document.createEvent('CustomEvent');
1546 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1550 CustomEvent.prototype = window.Event.prototype;
1551 window.CustomEvent = CustomEvent;
1555 openDropdown: function(sb) {
1556 var st = window.getComputedStyle(sb, null),
1557 ul = sb.querySelector('ul'),
1558 li = ul.querySelectorAll('li'),
1559 sel = ul.querySelector('[selected]'),
1560 rect = sb.getBoundingClientRect(),
1561 h = sb.clientHeight - parseFloat(st.paddingTop) - parseFloat(st.paddingBottom),
1562 mh = this.dropdown_items * h,
1563 eh = Math.min(mh, li.length * h);
1565 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1566 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1569 sb.setAttribute('open', '');
1571 if ('ontouchstart' in window) {
1572 var scroll = document.documentElement.scrollTop,
1573 vpWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
1574 vpHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
1576 ul.style.top = h + 'px';
1577 ul.style.left = -rect.left + 'px';
1578 ul.style.right = (rect.right - vpWidth) + 'px';
1580 window.scrollTo(0, (scroll + rect.top - vpHeight * 0.6));
1583 ul.style.maxHeight = mh + 'px';
1584 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1585 ul.style.top = ul.style.bottom = '';
1586 ul.style[((rect.top + rect.height + eh) > window.innerHeight) ? 'bottom' : 'top'] = rect.height + 'px';
1589 ul.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c) {
1593 ul.classList.add('dropdown');
1595 var pv = ul.cloneNode(true);
1596 pv.classList.remove('dropdown');
1597 pv.classList.add('preview');
1599 sb.insertBefore(pv, ul.nextElementSibling);
1601 li.forEach(function(l) {
1602 l.setAttribute('tabindex', 0);
1605 sb.lastElementChild.setAttribute('tabindex', 0);
1607 this.setFocus(sb, sel || li[0], true);
1610 closeDropdown: function(sb, no_focus) {
1611 if (!sb.hasAttribute('open'))
1614 var pv = sb.querySelector('ul.preview'),
1615 ul = sb.querySelector('ul.dropdown'),
1616 li = ul.querySelectorAll('li');
1618 li.forEach(function(l) { l.removeAttribute('tabindex'); });
1619 sb.lastElementChild.removeAttribute('tabindex');
1622 sb.removeAttribute('open');
1623 sb.style.width = sb.style.height = '';
1625 ul.classList.remove('dropdown');
1628 this.setFocus(sb, sb);
1630 this.saveValues(sb, ul);
1633 toggleItem: function(sb, li, force_state) {
1634 if (li.hasAttribute('unselectable'))
1638 var cbox = li.querySelector('input[type="checkbox"]'),
1639 items = li.parentNode.querySelectorAll('li'),
1640 label = sb.querySelector('ul.preview'),
1641 sel = li.parentNode.querySelectorAll('[selected]').length,
1642 more = sb.querySelector('.more'),
1643 ndisplay = this.display_items,
1646 if (li.hasAttribute('selected')) {
1647 if (force_state !== true) {
1648 if (sel > 1 || this.optional) {
1649 li.removeAttribute('selected');
1650 cbox.checked = cbox.disabled = false;
1654 cbox.disabled = true;
1659 if (force_state !== false) {
1660 li.setAttribute('selected', '');
1661 cbox.checked = true;
1662 cbox.disabled = false;
1667 while (label.firstElementChild)
1668 label.removeChild(label.firstElementChild);
1670 for (var i = 0; i < items.length; i++) {
1671 items[i].removeAttribute('display');
1672 if (items[i].hasAttribute('selected')) {
1673 if (ndisplay-- > 0) {
1674 items[i].setAttribute('display', n++);
1675 label.appendChild(items[i].cloneNode(true));
1677 var c = items[i].querySelector('input[type="checkbox"]');
1679 c.disabled = (sel == 1 && !this.optional);
1684 sb.setAttribute('more', '');
1686 sb.removeAttribute('more');
1688 if (ndisplay === this.display_items)
1689 sb.setAttribute('empty', '');
1691 sb.removeAttribute('empty');
1693 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1696 var sel = li.parentNode.querySelector('[selected]');
1698 sel.removeAttribute('display');
1699 sel.removeAttribute('selected');
1702 li.setAttribute('display', 0);
1703 li.setAttribute('selected', '');
1705 this.closeDropdown(sb, true);
1708 this.saveValues(sb, li.parentNode);
1711 transformItem: function(sb, li) {
1712 var cbox = E('form', {}, E('input', { type: 'checkbox', tabindex: -1, onclick: 'event.preventDefault()' })),
1715 while (li.firstChild)
1716 label.appendChild(li.firstChild);
1718 li.appendChild(cbox);
1719 li.appendChild(label);
1722 saveValues: function(sb, ul) {
1723 var sel = ul.querySelectorAll('li[selected]'),
1724 div = sb.lastElementChild,
1728 while (div.lastElementChild)
1729 div.removeChild(div.lastElementChild);
1731 sel.forEach(function (s) {
1732 if (s.hasAttribute('placeholder'))
1737 value: s.hasAttribute('data-value') ? s.getAttribute('data-value') : s.innerText,
1741 div.appendChild(E('input', {
1743 name: s.hasAttribute('name') ? s.getAttribute('name') : (sb.getAttribute('name') || ''),
1749 strval += strval.length ? ' ' + v.value : v.value;
1758 detail.values = values;
1760 detail.value = values.length ? values[0] : null;
1764 sb.dispatchEvent(new CustomEvent('cbi-dropdown-change', {
1772 setValues: function(sb, values) {
1773 var ul = sb.querySelector('ul');
1776 ul.querySelectorAll('li[data-value]').forEach(function(li) {
1777 if (values === null || !(li.getAttribute('data-value') in values))
1778 this.toggleItem(sb, li, false);
1780 this.toggleItem(sb, li, true);
1784 var ph = ul.querySelector('li[placeholder]');
1786 this.toggleItem(sb, ph);
1788 ul.querySelectorAll('li[data-value]').forEach(function(li) {
1789 if (values !== null && (li.getAttribute('data-value') in values))
1790 this.toggleItem(sb, li);
1795 setFocus: function(sb, elem, scroll) {
1796 if (sb && sb.hasAttribute && sb.hasAttribute('locked-in'))
1799 if (sb.target && findParent(sb.target, 'ul.dropdown'))
1802 document.querySelectorAll('.focus').forEach(function(e) {
1803 if (!matchesElem(e, 'input')) {
1804 e.classList.remove('focus');
1811 elem.classList.add('focus');
1814 elem.parentNode.scrollTop = elem.offsetTop - elem.parentNode.offsetTop;
1818 createItems: function(sb, value) {
1820 val = (value || '').trim().split(/\s+/),
1821 ul = sb.querySelector('ul');
1824 val.length = Math.min(val.length, 1);
1826 if (val.length === 1 && val[0].length === 0)
1829 val.forEach(function(item) {
1830 var new_item = null;
1832 ul.childNodes.forEach(function(li) {
1833 if (li.getAttribute && li.getAttribute('data-value') === item)
1839 tpl = sb.querySelector(sbox.template);
1842 markup = (tpl.textContent || tpl.innerHTML || tpl.firstChild.data).replace(/^<!--|-->$/, '').trim();
1844 markup = '<li data-value="{{value}}">{{value}}</li>';
1846 new_item = E(markup.replace(/{{value}}/g, item));
1849 sbox.transformItem(sb, new_item);
1852 var old = ul.querySelector('li[created]');
1854 ul.removeChild(old);
1856 new_item.setAttribute('created', '');
1859 new_item = ul.insertBefore(new_item, ul.lastElementChild);
1862 sbox.toggleItem(sb, new_item, true);
1863 sbox.setFocus(sb, new_item, true);
1867 closeAllDropdowns: function() {
1868 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1869 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1873 handleClick: function(ev) {
1874 var sb = ev.currentTarget;
1876 if (!sb.hasAttribute('open')) {
1877 if (!matchesElem(ev.target, 'input'))
1878 this.openDropdown(sb);
1881 var li = findParent(ev.target, 'li');
1882 if (li && li.parentNode.classList.contains('dropdown'))
1883 this.toggleItem(sb, li);
1886 ev.preventDefault();
1887 ev.stopPropagation();
1890 handleKeydown: function(ev) {
1891 var sb = ev.currentTarget;
1893 if (matchesElem(ev.target, 'input'))
1896 if (!sb.hasAttribute('open')) {
1897 switch (ev.keyCode) {
1902 this.openDropdown(sb);
1903 ev.preventDefault();
1907 var active = findParent(document.activeElement, 'li');
1909 switch (ev.keyCode) {
1911 this.closeDropdown(sb);
1916 if (!active.hasAttribute('selected'))
1917 this.toggleItem(sb, active);
1918 this.closeDropdown(sb);
1919 ev.preventDefault();
1925 this.toggleItem(sb, active);
1926 ev.preventDefault();
1931 if (active && active.previousElementSibling) {
1932 this.setFocus(sb, active.previousElementSibling);
1933 ev.preventDefault();
1938 if (active && active.nextElementSibling) {
1939 this.setFocus(sb, active.nextElementSibling);
1940 ev.preventDefault();
1947 handleDropdownClose: function(ev) {
1948 var sb = ev.currentTarget;
1950 this.closeDropdown(sb, true);
1953 handleDropdownSelect: function(ev) {
1954 var sb = ev.currentTarget,
1955 li = findParent(ev.target, 'li');
1960 this.toggleItem(sb, li);
1961 this.closeDropdown(sb, true);
1964 handleMouseover: function(ev) {
1965 var sb = ev.currentTarget;
1967 if (!sb.hasAttribute('open'))
1970 var li = findParent(ev.target, 'li');
1972 if (li && li.parentNode.classList.contains('dropdown'))
1973 this.setFocus(sb, li);
1976 handleFocus: function(ev) {
1977 var sb = ev.currentTarget;
1979 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1980 if (s !== sb || sb.hasAttribute('open'))
1981 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1985 handleCanaryFocus: function(ev) {
1986 this.closeDropdown(ev.currentTarget.parentNode);
1989 handleCreateKeydown: function(ev) {
1990 var input = ev.currentTarget,
1991 sb = findParent(input, '.cbi-dropdown');
1993 switch (ev.keyCode) {
1995 ev.preventDefault();
1997 if (input.classList.contains('cbi-input-invalid'))
2000 this.createItems(sb, input.value);
2007 handleCreateFocus: function(ev) {
2008 var input = ev.currentTarget,
2009 cbox = findParent(input, 'li').querySelector('input[type="checkbox"]'),
2010 sb = findParent(input, '.cbi-dropdown');
2013 cbox.checked = true;
2015 sb.setAttribute('locked-in', '');
2018 handleCreateBlur: function(ev) {
2019 var input = ev.currentTarget,
2020 cbox = findParent(input, 'li').querySelector('input[type="checkbox"]'),
2021 sb = findParent(input, '.cbi-dropdown');
2024 cbox.checked = false;
2026 sb.removeAttribute('locked-in');
2029 handleCreateClick: function(ev) {
2030 ev.currentTarget.querySelector(this.create).focus();
2034 function cbi_dropdown_init(sb) {
2035 if (!(this instanceof cbi_dropdown_init))
2036 return new cbi_dropdown_init(sb);
2038 this.multi = sb.hasAttribute('multiple');
2039 this.optional = sb.hasAttribute('optional');
2040 this.placeholder = sb.getAttribute('placeholder') || '---';
2041 this.display_items = parseInt(sb.getAttribute('display-items') || 3);
2042 this.dropdown_items = parseInt(sb.getAttribute('dropdown-items') || 5);
2043 this.create = sb.getAttribute('item-create') || '.create-item-input';
2044 this.template = sb.getAttribute('item-template') || 'script[type="item-template"]';
2046 var ul = sb.querySelector('ul'),
2047 more = sb.appendChild(E('span', { class: 'more', tabindex: -1 }, '···')),
2048 open = sb.appendChild(E('span', { class: 'open', tabindex: -1 }, '▾')),
2049 canary = sb.appendChild(E('div')),
2050 create = sb.querySelector(this.create),
2051 ndisplay = this.display_items,
2055 var items = ul.querySelectorAll('li');
2057 for (var i = 0; i < items.length; i++) {
2058 this.transformItem(sb, items[i]);
2060 if (items[i].hasAttribute('selected') && ndisplay-- > 0)
2061 items[i].setAttribute('display', n++);
2065 if (this.optional && !ul.querySelector('li[data-value=""]')) {
2066 var placeholder = E('li', { placeholder: '' }, this.placeholder);
2067 ul.firstChild ? ul.insertBefore(placeholder, ul.firstChild) : ul.appendChild(placeholder);
2070 var items = ul.querySelectorAll('li'),
2071 sel = sb.querySelectorAll('[selected]');
2073 sel.forEach(function(s) {
2074 s.removeAttribute('selected');
2077 var s = sel[0] || items[0];
2079 s.setAttribute('selected', '');
2080 s.setAttribute('display', n++);
2086 this.saveValues(sb, ul);
2088 ul.setAttribute('tabindex', -1);
2089 sb.setAttribute('tabindex', 0);
2092 sb.setAttribute('more', '')
2094 sb.removeAttribute('more');
2096 if (ndisplay === this.display_items)
2097 sb.setAttribute('empty', '')
2099 sb.removeAttribute('empty');
2101 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
2104 sb.addEventListener('click', this.handleClick.bind(this));
2105 sb.addEventListener('keydown', this.handleKeydown.bind(this));
2106 sb.addEventListener('cbi-dropdown-close', this.handleDropdownClose.bind(this));
2107 sb.addEventListener('cbi-dropdown-select', this.handleDropdownSelect.bind(this));
2109 if ('ontouchstart' in window) {
2110 sb.addEventListener('touchstart', function(ev) { ev.stopPropagation(); });
2111 window.addEventListener('touchstart', this.closeAllDropdowns);
2114 sb.addEventListener('mouseover', this.handleMouseover.bind(this));
2115 sb.addEventListener('focus', this.handleFocus.bind(this));
2117 canary.addEventListener('focus', this.handleCanaryFocus.bind(this));
2119 window.addEventListener('mouseover', this.setFocus);
2120 window.addEventListener('click', this.closeAllDropdowns);
2124 create.addEventListener('keydown', this.handleCreateKeydown.bind(this));
2125 create.addEventListener('focus', this.handleCreateFocus.bind(this));
2126 create.addEventListener('blur', this.handleCreateBlur.bind(this));
2128 var li = findParent(create, 'li');
2130 li.setAttribute('unselectable', '');
2131 li.addEventListener('click', this.handleCreateClick.bind(this));
2135 cbi_dropdown_init.prototype = CBIDropdown;
2137 function cbi_update_table(table, data, placeholder) {
2138 var target = isElem(table) ? table : document.querySelector(table);
2140 if (!isElem(target))
2143 target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
2146 thead.querySelectorAll('.th').forEach(function(th) {
2150 if (Array.isArray(data)) {
2151 var n = 0, rows = target.querySelectorAll('.tr');
2153 data.forEach(function(row) {
2154 var trow = E('div', { 'class': 'tr' });
2156 for (var i = 0; i < titles.length; i++) {
2157 var text = (titles[i].innerText || '').trim();
2158 var td = trow.appendChild(E('div', {
2159 'class': titles[i].className,
2160 'data-title': (text !== '') ? text : null
2163 td.classList.remove('th');
2164 td.classList.add('td');
2167 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
2170 target.replaceChild(trow, rows[n]);
2172 target.appendChild(trow);
2176 target.removeChild(rows[n]);
2178 if (placeholder && target.firstElementChild === target.lastElementChild) {
2179 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
2180 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
2182 td.classList.remove('th');
2183 td.classList.add('td');
2187 thead.parentNode.style.display = 'none';
2189 thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
2190 if (trow !== thead) {
2192 trow.querySelectorAll('.th, .td').forEach(function(td) {
2193 if (n < titles.length) {
2194 var text = (titles[n++].innerText || '').trim();
2196 td.setAttribute('data-title', text);
2202 thead.parentNode.style.display = '';
2207 var tooltipDiv = null, tooltipTimeout = null;
2209 function showTooltip(ev) {
2210 var target = findParent(ev.target, '[data-tooltip]');
2215 if (tooltipTimeout !== null) {
2216 window.clearTimeout(tooltipTimeout);
2217 tooltipTimeout = null;
2220 var rect = target.getBoundingClientRect(),
2221 x = rect.left + window.pageXOffset,
2222 y = rect.top + rect.height + window.pageYOffset;
2224 tooltipDiv.className = 'cbi-tooltip';
2225 tooltipDiv.innerHTML = '▲ ';
2226 tooltipDiv.firstChild.data += target.getAttribute('data-tooltip');
2228 if (target.hasAttribute('data-tooltip-style'))
2229 tooltipDiv.classList.add(target.getAttribute('data-tooltip-style'));
2231 if ((y + tooltipDiv.offsetHeight) > (window.innerHeight + window.pageYOffset)) {
2232 y -= (tooltipDiv.offsetHeight + target.offsetHeight);
2233 tooltipDiv.firstChild.data = '▼ ' + tooltipDiv.firstChild.data.substr(2);
2236 tooltipDiv.style.top = y + 'px';
2237 tooltipDiv.style.left = x + 'px';
2238 tooltipDiv.style.opacity = 1;
2241 function hideTooltip(ev) {
2242 if (ev.target === tooltipDiv || ev.relatedTarget === tooltipDiv)
2245 if (tooltipTimeout !== null) {
2246 window.clearTimeout(tooltipTimeout);
2247 tooltipTimeout = null;
2250 tooltipDiv.style.opacity = 0;
2251 tooltipTimeout = window.setTimeout(function() { tooltipDiv.removeAttribute('style'); }, 250);
2254 document.addEventListener('DOMContentLoaded', function() {
2255 tooltipDiv = document.body.appendChild(E('div', { 'class': 'cbi-tooltip' }));
2257 document.addEventListener('mouseover', showTooltip, true);
2258 document.addEventListener('mouseout', hideTooltip, true);
2259 document.addEventListener('focus', showTooltip, true);
2260 document.addEventListener('blur', hideTooltip, true);
2262 document.addEventListener('validation-failure', function(ev) {
2263 if (ev.target === document.activeElement)
2267 document.addEventListener('validation-success', function(ev) {
2268 if (ev.target === document.activeElement)
2272 document.querySelectorAll('.table').forEach(cbi_update_table);