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)
24 for (var i = 0; i < s.length; i++) {
25 var ch = s.charCodeAt(i);
30 bytes.push(((ch >>> 6) & 0x1F) | 0xC0,
32 else if (ch <= 0xFFFF)
33 bytes.push(((ch >>> 12) & 0x0F) | 0xE0,
34 ((ch >>> 6) & 0x3F) | 0x80,
36 else if (code <= 0x10FFFF)
37 bytes.push(((ch >>> 18) & 0x07) | 0xF0,
38 ((ch >>> 12) & 0x3F) | 0x80,
39 ((ch >> 6) & 0x3F) | 0x80,
46 var hash = (bytes.length >>> 0),
47 len = (bytes.length >>> 2),
51 hash += ((bytes[off + 1] << 8) + bytes[off]) >>> 0;
52 tmp = ((((bytes[off + 3] << 8) + bytes[off + 2]) << 11) ^ hash) >>> 0;
53 hash = ((hash << 16) ^ tmp) >>> 0;
58 switch ((bytes.length & 3) >>> 0) {
60 hash += ((bytes[off + 1] << 8) + bytes[off]) >>> 0;
61 hash = (hash ^ (hash << 16)) >>> 0;
62 hash = (hash ^ (bytes[off + 2] << 18)) >>> 0;
67 hash += ((bytes[off + 1] << 8) + bytes[off]) >>> 0;
68 hash = (hash ^ (hash << 11)) >>> 0;
74 hash = (hash ^ (hash << 10)) >>> 0;
79 hash = (hash ^ (hash << 3)) >>> 0;
81 hash = (hash ^ (hash << 4)) >>> 0;
83 hash = (hash ^ (hash << 25)) >>> 0;
86 return (0x100000000 + hash).toString(16).substr(1);
90 return (window.TR && TR[sfh(s)]) || s;
94 return (/^-?\d+$/.test(x) ? +x : NaN);
98 return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
102 if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
105 if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
108 return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
112 if (x.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
113 var v6 = RegExp.$1, v4 = IPv4(RegExp.$2);
118 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
119 + ':' + (v4[2] * 256 + v4[3]).toString(16);
122 if (!x.match(/^[a-fA-F0-9:]+$/))
125 var prefix_suffix = x.split(/::/);
127 if (prefix_suffix.length > 2)
130 var prefix = (prefix_suffix[0] || '0').split(/:/);
131 var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
133 if (suffix.length ? (prefix.length + suffix.length > 7)
134 : ((prefix_suffix.length < 2 && prefix.length < 8) || prefix.length > 8))
140 for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
141 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
146 for (i = 0; i < (8 - prefix.length - suffix.length); i++)
149 for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
150 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
158 var CBIValidatorPrototype = {
159 apply: function(name, value, args) {
162 if (typeof(name) === 'function')
164 else if (typeof(this.types[name]) === 'function')
165 func = this.types[name];
169 if (value !== undefined && value !== null)
172 return func.apply(this, args);
175 assert: function(condition, message) {
177 this.field.classList.add('cbi-input-invalid');
178 this.error = message;
182 this.field.classList.remove('cbi-input-invalid');
187 compile: function(code) {
195 for (var i = 0; i < code.length; i++) {
201 switch (code.charCodeAt(i))
211 var label = code.substring(pos, i);
212 label = label.replace(/\\(.)/g, '$1');
213 label = label.replace(/^[ \t]+/g, '');
214 label = label.replace(/[ \t]+$/g, '');
216 if (label && !isNaN(label)) {
217 stack.push(parseFloat(label));
219 else if (label.match(/^(['"]).*\1$/)) {
220 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
222 else if (typeof this.types[label] == 'function') {
223 stack.push(this.types[label]);
227 throw "Syntax error, unhandled token '"+label+"'";
234 depth += (code.charCodeAt(i) == 40);
239 if (typeof stack[stack.length-2] != 'function')
240 throw "Syntax error, argument list follows non-function";
242 stack[stack.length-1] = this.compile(code.substring(pos, i));
253 validate: function() {
254 /* element is detached */
255 if (!findParent(this.field, 'form'))
258 this.field.classList.remove('cbi-input-invalid');
259 this.value = matchesElem(this.field, 'select') ? this.field.options[this.field.selectedIndex].value : this.field.value;
264 if (this.value.length === 0)
265 valid = this.assert(this.optional, _('non-empty value'));
267 valid = this.vstack[0].apply(this, this.vstack[1]);
270 this.field.setAttribute('data-tooltip', _('Expecting %s').format(this.error));
271 this.field.setAttribute('data-tooltip-style', 'error');
272 this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
275 this.field.removeAttribute('data-tooltip');
276 this.field.removeAttribute('data-tooltip-style');
277 this.field.dispatchEvent(new CustomEvent('validation-success', { bubbles: true }));
284 integer: function() {
285 return this.assert(Int(this.value) !== NaN, _('valid integer value'));
288 uinteger: function() {
289 return this.assert(Int(this.value) >= 0, _('positive integer value'));
293 return this.assert(Dec(this.value) !== NaN, _('valid decimal value'));
297 return this.assert(Dec(this.value) >= 0, _('positive decimal value'));
300 ipaddr: function(nomask) {
301 return this.assert(this.apply('ip4addr', null, [nomask]) || this.apply('ip6addr', null, [nomask]),
302 nomask ? _('valid IP address') : _('valid IP address or prefix'));
305 ip4addr: function(nomask) {
306 var re = nomask ? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
307 m = this.value.match(re);
309 return this.assert(m && IPv4(m[1]) && (m[2] ? IPv4(m[2]) : (m[3] ? this.apply('ip4prefix', m[3]) : true)),
310 nomask ? _('valid IPv4 address') : _('valid IPv4 address or network'));
313 ip6addr: function(nomask) {
314 var re = nomask ? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
315 m = this.value.match(re);
317 return this.assert(m && IPv6(m[1]) && (m[2] ? this.apply('ip6prefix', m[2]) : true),
318 nomask ? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
321 ip4prefix: function() {
322 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 32,
323 _('valid IPv4 prefix value (0-32)'));
326 ip6prefix: function() {
327 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 128,
328 _('valid IPv6 prefix value (0-128)'));
332 return this.assert(this.apply('cidr4') || this.apply('cidr6'), _('valid IPv4 or IPv6 CIDR'));
336 var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
337 return this.assert(m && IPv4(m[1]) && this.apply('ip4prefix', m[2]), _('valid IPv4 CIDR'));
341 var m = this.value.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
342 return this.assert(m && IPv6(m[1]) && this.apply('ip6prefix', m[2]), _('valid IPv6 CIDR'));
346 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})$/);
347 return this.assert(m && IPv4(m[1]) && IPv4(m[2]), _('IPv4 network in address/netmask notation'));
351 var m = this.value.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
352 return this.assert(m && IPv6(m[1]) && IPv6(m[2]), _('IPv6 network in address/netmask notation'));
355 ip6hostid: function() {
356 if (this.value == "eui64" || this.value == "random")
359 var v6 = IPv6(this.value);
360 return this.assert(!(!v6 || v6[0] || v6[1] || v6[2] || v6[3]), _('valid IPv6 host id'));
364 return this.assert(this.apply('ipmask4') || this.apply('ipmask6'),
365 _('valid network in address/netmask notation'));
368 ipmask4: function() {
369 return this.assert(this.apply('cidr4') || this.apply('ipnet4') || this.apply('ip4addr'),
370 _('valid IPv4 network'));
373 ipmask6: function() {
374 return this.assert(this.apply('cidr6') || this.apply('ipnet6') || this.apply('ip6addr'),
375 _('valid IPv6 network'));
379 var p = Int(this.value);
380 return this.assert(p >= 0 && p <= 65535, _('valid port value'));
383 portrange: function() {
384 if (this.value.match(/^(\d+)-(\d+)$/)) {
387 return this.assert(p1 <= p2 && p2 <= 65535,
388 _('valid port or port range (port1-port2)'));
391 return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
394 macaddr: function() {
395 return this.assert(this.value.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null,
396 _('valid MAC address'));
399 host: function(ipv4only) {
400 return this.assert(this.apply('hostname') || this.apply(ipv4only == 1 ? 'ip4addr' : 'ipaddr'),
401 _('valid hostname or IP address'));
404 hostname: function(strict) {
405 if (this.value.length <= 253)
407 (this.value.match(/^[a-zA-Z0-9_]+$/) != null ||
408 (this.value.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
409 this.value.match(/[^0-9.]/))) &&
410 (!strict || !this.value.match(/^_/)),
411 _('valid hostname'));
413 return this.assert(false, _('valid hostname'));
416 network: function() {
417 return this.assert(this.apply('uciname') || this.apply('host'),
418 _('valid UCI identifier, hostname or IP address'));
421 hostport: function(ipv4only) {
422 var hp = this.value.split(/:/);
423 return this.assert(hp.length == 2 && this.apply('host', hp[0], [ipv4only]) && this.apply('port', hp[1]),
424 _('valid host:port'));
427 ip4addrport: function() {
428 var hp = this.value.split(/:/);
429 return this.assert(hp.length == 2 && this.apply('ip4addr', hp[0], [true]) && this.apply('port', hp[1]),
430 _('valid IPv4 address:port'));
433 ipaddrport: function(bracket) {
434 var m4 = this.value.match(/^([^\[\]:]+):(\d+)$/),
435 m6 = this.value.match((bracket == 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
438 return this.assert(this.apply('ip4addr', m4[0], [true]) && this.apply('port', m4[1]),
439 _('valid address:port'));
441 return this.assert(m6 && this.apply('ip6addr', m6[0], [true]) && this.apply('port', m6[1]),
442 _('valid address:port'));
449 return this.assert(v.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
451 return this.assert((v.length >= 8) && (v.length <= 63), _('key between 8 and 63 characters'));
457 if (v.substr(0, 2) === 's:')
460 if ((v.length == 10) || (v.length == 26))
461 return this.assert(v.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
463 return this.assert((v.length === 5) || (v.length === 13), _('key with either 5 or 13 characters'));
466 uciname: function() {
467 return this.assert(this.value.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
470 range: function(min, max) {
471 var val = Dec(this.value);
472 return this.assert(val >= +min && val <= +max, _('value between %f and %f').format(min, max));
476 return this.assert(Dec(this.value) >= +min, _('value greater or equal to %f').format(min));
480 return this.assert(Dec(this.value) <= +max, _('value smaller or equal to %f').format(max));
483 rangelength: function(min, max) {
484 var val = '' + this.value;
485 return this.assert((val.length >= +min) && (val.length <= +max),
486 _('value between %d and %d characters').format(min, max));
489 minlength: function(min) {
490 return this.assert((''+this.value).length >= +min,
491 _('value with at least %d characters').format(min));
494 maxlength: function(max) {
495 return this.assert((''+this.value).length <= +max,
496 _('value with at most %d characters').format(max));
502 for (var i = 0; i < arguments.length; i += 2) {
503 if (typeof arguments[i] != 'function') {
504 if (arguments[i] == this.value)
505 return this.assert(true);
506 errors.push('"%s"'.format(arguments[i]));
509 else if (arguments[i].apply(this, arguments[i+1])) {
510 return this.assert(true);
513 errors.push(this.error);
517 return this.assert(false, _('one of:\n - %s'.format(errors.join('\n - '))));
521 for (var i = 0; i < arguments.length; i += 2) {
522 if (typeof arguments[i] != 'function') {
523 if (arguments[i] != this.value)
524 return this.assert(false, '"%s"'.format(arguments[i]));
527 else if (!arguments[i].apply(this, arguments[i+1])) {
528 return this.assert(false, this.error);
532 return this.assert(true);
536 return this.apply('or', this.value.replace(/^[ \t]*![ \t]*/, ''), arguments);
539 list: function(subvalidator, subargs) {
540 this.field.setAttribute('data-is-list', 'true');
542 var tokens = this.value.match(/[^ \t]+/g);
543 for (var i = 0; i < tokens.length; i++)
544 if (!this.apply(subvalidator, tokens[i], subargs))
545 return this.assert(false, this.error);
547 return this.assert(true);
550 phonedigit: function() {
551 return this.assert(this.value.match(/^[0-9\*#!\.]+$/),
552 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
555 timehhmmss: function() {
556 return this.assert(this.value.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
557 _('valid time (HH:MM:SS)'));
560 dateyyyymmdd: function() {
561 if (this.value.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
562 var year = +RegExp.$1,
565 days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
567 function is_leap_year(year) {
568 return ((!(year % 4) && (year % 100)) || !(year % 400));
571 function get_days_in_month(month, year) {
572 return (month === 2 && is_leap_year(year)) ? 29 : days_in_month[month - 1];
575 /* Firewall rules in the past don't make sense */
576 return this.assert(year >= 2015 && month && month <= 12 && day && day <= get_days_in_month(month, year),
577 _('valid date (YYYY-MM-DD)'));
581 return this.assert(false, _('valid date (YYYY-MM-DD)'));
584 unique: function(subvalidator, subargs) {
586 option = findParent(ctx.field, '[data-type][data-name]'),
587 section = findParent(option, '.cbi-section'),
588 query = '[data-type="%s"][data-name="%s"]'.format(option.getAttribute('data-type'), option.getAttribute('data-name')),
591 section.querySelectorAll(query).forEach(function(sibling) {
592 if (sibling === option)
595 var input = sibling.querySelector('[data-type]'),
596 values = input ? (input.getAttribute('data-is-list') ? input.value.match(/[^ \t]+/g) : [ input.value ]) : null;
598 if (values !== null && values.indexOf(ctx.value) !== -1)
603 return this.assert(false, _('unique value'));
605 if (typeof(subvalidator) === 'function')
606 return this.apply(subvalidator, undefined, subargs);
608 return this.assert(true);
611 hexstring: function() {
612 return this.assert(this.value.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
613 _('hexadecimal encoded value'));
618 function CBIValidator(field, type, optional)
621 this.optional = optional;
622 this.vstack = this.compile(type);
625 CBIValidator.prototype = CBIValidatorPrototype;
628 function cbi_d_add(field, dep, index) {
629 var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
632 for (var i=0; i<cbi_d.length; i++) {
633 if (cbi_d[i].id == obj.id) {
642 "parent": obj.parentNode.id,
646 cbi_d.unshift(entry);
652 function cbi_d_checkvalue(target, ref) {
654 query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
655 'select[id="'+target+'"], select[name="'+target+'"]';
657 document.querySelectorAll(query).forEach(function(i) {
658 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
662 return (((value !== null) ? value : "") == ref);
665 function cbi_d_check(deps) {
668 for (var i=0; i<deps.length; i++) {
671 for (var j in deps[i]) {
672 if (j == "!reverse") {
674 } else if (j == "!default") {
678 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
682 if (istat ^ reverse) {
689 function cbi_d_update() {
691 for (var i=0; i<cbi_d.length; i++) {
692 var entry = cbi_d[i];
693 var node = document.getElementById(entry.id);
694 var parent = document.getElementById(entry.parent);
696 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
697 node.parentNode.removeChild(node);
700 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
701 var next = undefined;
703 for (next = parent.firstChild; next; next = next.nextSibling) {
704 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
709 parent.appendChild(entry.node);
711 parent.insertBefore(entry.node, next);
716 // hide optionals widget if no choices remaining
717 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
718 parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
721 if (entry && entry.parent) {
723 cbi_tag_last(parent);
730 function cbi_init() {
733 nodes = document.querySelectorAll('[data-strings]');
735 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
736 var str = JSON.parse(node.getAttribute('data-strings'));
737 for (var key in str) {
738 for (var key2 in str[key]) {
739 var dst = cbi_strings[key] || (cbi_strings[key] = { });
740 dst[key2] = str[key][key2];
745 nodes = document.querySelectorAll('[data-depends]');
747 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
748 var index = parseInt(node.getAttribute('data-index'), 10);
749 var depends = JSON.parse(node.getAttribute('data-depends'));
750 if (!isNaN(index) && depends.length > 0) {
751 for (var alt = 0; alt < depends.length; alt++)
752 cbi_d_add(node, depends[alt], index);
756 nodes = document.querySelectorAll('[data-update]');
758 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
759 var events = node.getAttribute('data-update').split(' ');
760 for (var j = 0, event; (event = events[j]) !== undefined; j++)
761 node.addEventListener(event, cbi_d_update);
764 nodes = document.querySelectorAll('[data-choices]');
766 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
767 var choices = JSON.parse(node.getAttribute('data-choices'));
770 for (var j = 0; j < choices[0].length; j++)
771 options[choices[0][j]] = choices[1][j];
773 var def = (node.getAttribute('data-optional') === 'true')
774 ? node.placeholder || '' : null;
776 cbi_combobox_init(node, options, def,
777 node.getAttribute('data-manual'));
780 nodes = document.querySelectorAll('[data-dynlist]');
782 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
783 var choices = JSON.parse(node.getAttribute('data-dynlist'));
786 if (choices[0] && choices[0].length) {
789 for (var j = 0; j < choices[0].length; j++)
790 options[choices[0][j]] = choices[1][j];
793 cbi_dynlist_init(node, choices[2], choices[3], options);
796 nodes = document.querySelectorAll('[data-type]');
798 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
799 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
800 node.getAttribute('data-type'));
803 document.querySelectorAll('.cbi-dropdown').forEach(function(s) {
804 cbi_dropdown_init(s);
807 document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
808 s.parentNode.classList.add('cbi-tooltip-container');
811 document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
812 var handler = function(ev) {
813 var bits = this.name.split(/\./),
814 section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
816 section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
819 i.addEventListener('mouseover', handler);
820 i.addEventListener('mouseout', handler);
826 function cbi_combobox_init(id, values, def, man) {
827 var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
830 'class': 'cbi-dropdown',
832 'optional': obj.getAttribute('data-optional'),
833 'placeholder': _('-- Please choose --'),
834 'data-type': obj.getAttribute('data-type'),
835 'data-optional': obj.getAttribute('data-optional')
838 if (!(obj.value in values) && obj.value.length) {
839 sb.lastElementChild.appendChild(E('li', {
840 'data-value': obj.value,
842 }, obj.value.length ? obj.value : (def || _('-- Please choose --'))));
845 for (var i in values) {
846 sb.lastElementChild.appendChild(E('li', {
848 'selected': (i == obj.value) ? '' : null
852 sb.lastElementChild.appendChild(E('li', { 'data-value': '-' }, [
855 'class': 'create-item-input',
856 'data-type': obj.getAttribute('data-type'),
857 'data-optional': true,
858 'placeholder': (man || _('-- custom --'))
862 sb.value = obj.value;
863 obj.parentNode.replaceChild(sb, obj);
866 function cbi_filebrowser(id, defpath) {
867 var field = document.getElementById(id);
868 var browser = window.open(
869 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
870 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
876 function cbi_browser_init(id, resource, defpath)
878 function cbi_browser_btnclick(e) {
879 cbi_filebrowser(id, defpath);
883 var field = document.getElementById(id);
885 var btn = document.createElement('img');
886 btn.className = 'cbi-image-button';
887 btn.src = (resource || cbi_strings.path.resource) + '/cbi/folder.gif';
888 field.parentNode.insertBefore(btn, field.nextSibling);
890 btn.addEventListener('click', cbi_browser_btnclick);
894 addItem: function(dl, value, text, flash) {
896 new_item = E('div', { 'class': flash ? 'item flash' : 'item', 'tabindex': 0 }, [
897 E('span', {}, text || value),
900 'name': dl.getAttribute('data-prefix'),
903 dl.querySelectorAll('.item, .add-item').forEach(function(item) {
907 var hidden = item.querySelector('input[type="hidden"]');
909 if (hidden && hidden.value === value)
911 else if (!hidden || hidden.value >= value)
912 exists = !!item.parentNode.insertBefore(new_item, item);
916 removeItem: function(dl, item) {
917 var sb = dl.querySelector('.cbi-dropdown');
919 var value = item.querySelector('input[type="hidden"]').value;
921 sb.querySelectorAll('ul > li').forEach(function(li) {
922 if (li.getAttribute('data-value') === value)
923 li.removeAttribute('unselectable');
927 item.parentNode.removeChild(item);
930 handleClick: function(ev) {
931 var dl = ev.currentTarget,
932 item = findParent(ev.target, '.item');
935 this.removeItem(dl, item);
937 else if (matchesElem(ev.target, '.cbi-button-add')) {
938 var input = ev.target.previousElementSibling;
939 if (input.value.length && !input.classList.contains('cbi-input-invalid')) {
940 this.addItem(dl, input.value, null, true);
946 handleDropdownChange: function(ev) {
947 var dl = ev.currentTarget,
948 sbIn = ev.detail.instance,
949 sbEl = ev.detail.element,
950 sbVal = ev.detail.value;
955 sbIn.setValues(sbEl, null);
956 sbVal.element.setAttribute('unselectable', '');
958 this.addItem(dl, sbVal.value, sbVal.text, true);
961 handleKeydown: function(ev) {
962 var dl = ev.currentTarget,
963 item = findParent(ev.target, '.item');
966 switch (ev.keyCode) {
967 case 8: /* backspace */
968 if (item.previousElementSibling)
969 item.previousElementSibling.focus();
971 this.removeItem(dl, item);
974 case 46: /* delete */
975 if (item.nextElementSibling) {
976 if (item.nextElementSibling.classList.contains('item'))
977 item.nextElementSibling.focus();
979 item.nextElementSibling.firstElementChild.focus();
982 this.removeItem(dl, item);
986 else if (matchesElem(ev.target, '.cbi-input-text')) {
987 switch (ev.keyCode) {
989 if (ev.target.value.length && !ev.target.classList.contains('cbi-input-invalid')) {
990 this.addItem(dl, ev.target.value, null, true);
991 ev.target.value = '';
1003 function cbi_dynlist_init(dl, datatype, optional, choices)
1005 if (!(this instanceof cbi_dynlist_init))
1006 return new cbi_dynlist_init(dl, datatype, optional, choices);
1008 dl.classList.add('cbi-dynlist');
1009 dl.appendChild(E('div', { 'class': 'add-item' }, E('input', {
1011 'name': 'cbi.dynlist.' + dl.getAttribute('data-prefix'),
1012 'class': 'cbi-input-text',
1013 'data-type': datatype,
1014 'data-optional': true
1018 cbi_combobox_init(dl.lastElementChild.lastElementChild, choices, '', _('-- custom --'));
1020 dl.lastElementChild.appendChild(E('div', { 'class': 'cbi-button cbi-button-add' }, '+'));
1022 dl.addEventListener('click', this.handleClick.bind(this));
1023 dl.addEventListener('keydown', this.handleKeydown.bind(this));
1024 dl.addEventListener('cbi-dropdown-change', this.handleDropdownChange.bind(this));
1027 var values = JSON.parse(dl.getAttribute('data-values') || '[]');
1029 if (typeof(values) === 'object' && Array.isArray(values))
1030 for (var i = 0; i < values.length; i++)
1031 this.addItem(dl, values[i], choices ? choices[values[i]] : null);
1036 cbi_dynlist_init.prototype = CBIDynamicList;
1039 function cbi_t_add(section, tab) {
1040 var t = document.getElementById('tab.' + section + '.' + tab);
1041 var c = document.getElementById('container.' + section + '.' + tab);
1044 cbi_t[section] = (cbi_t[section] || [ ]);
1045 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
1049 function cbi_t_switch(section, tab) {
1050 if (cbi_t[section] && cbi_t[section][tab]) {
1051 var o = cbi_t[section][tab];
1052 var h = document.getElementById('tab.' + section);
1054 for (var tid in cbi_t[section]) {
1055 var o2 = cbi_t[section][tid];
1057 if (o.tab.id != o2.tab.id) {
1058 o2.tab.classList.remove('cbi-tab');
1059 o2.tab.classList.add('cbi-tab-disabled');
1060 o2.container.style.display = 'none';
1066 o2.tab.classList.remove('cbi-tab-disabled');
1067 o2.tab.classList.add('cbi-tab');
1068 o2.container.style.display = 'block';
1076 function cbi_t_update() {
1078 var updated = false;
1080 for (var sid in cbi_t)
1081 for (var tid in cbi_t[sid]) {
1082 var t = cbi_t[sid][tid].tab;
1083 var c = cbi_t[sid][tid].container;
1085 if (!c.firstElementChild) {
1086 t.style.display = 'none';
1088 else if (t.style.display == 'none') {
1089 t.style.display = '';
1090 t.classList.add('cbi-tab-highlighted');
1098 if (hl_tabs.length > 0)
1099 window.setTimeout(function() {
1100 for (var i = 0; i < hl_tabs.length; i++)
1101 hl_tabs[i].classList.remove('cbi-tab-highlighted');
1108 function cbi_validate_form(form, errmsg)
1110 /* if triggered by a section removal or addition, don't validate */
1111 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
1114 if (form.cbi_validators) {
1115 for (var i = 0; i < form.cbi_validators.length; i++) {
1116 var validator = form.cbi_validators[i];
1118 if (!validator() && errmsg) {
1128 function cbi_validate_reset(form)
1131 function() { cbi_validate_form(form, null) }, 100
1137 function cbi_validate_field(cbid, optional, type)
1139 var field = isElem(cbid) ? cbid : document.getElementById(cbid);
1143 var cbiValidator = new CBIValidator(field, type, optional);
1144 validatorFn = cbiValidator.validate.bind(cbiValidator);
1150 if (validatorFn !== null) {
1151 var form = findParent(field, 'form');
1153 if (!form.cbi_validators)
1154 form.cbi_validators = [ ];
1156 form.cbi_validators.push(validatorFn);
1158 field.addEventListener("blur", validatorFn);
1159 field.addEventListener("keyup", validatorFn);
1160 field.addEventListener("cbi-dropdown-change", validatorFn);
1162 if (matchesElem(field, 'select')) {
1163 field.addEventListener("change", validatorFn);
1164 field.addEventListener("click", validatorFn);
1171 function cbi_row_swap(elem, up, store)
1173 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
1178 tr.classList.remove('flash');
1181 var prev = tr.previousElementSibling;
1183 if (prev && prev.classList.contains('cbi-section-table-row'))
1184 tr.parentNode.insertBefore(tr, prev);
1189 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1191 if (next && next.classList.contains('cbi-section-table-row'))
1192 tr.parentNode.insertBefore(tr, next);
1194 tr.parentNode.appendChild(tr);
1201 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1202 var node = tr.parentNode.childNodes[i];
1203 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1204 node.classList.remove('cbi-rowstyle-1');
1205 node.classList.remove('cbi-rowstyle-2');
1206 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1208 if (/-([^\-]+)$/.test(node.id))
1209 ids.push(RegExp.$1);
1213 var input = document.getElementById(store);
1215 input.value = ids.join(' ');
1217 window.scrollTo(0, tr.offsetTop);
1218 void tr.offsetWidth;
1219 tr.classList.add('flash');
1224 function cbi_tag_last(container)
1228 for (var i = 0; i < container.childNodes.length; i++) {
1229 var c = container.childNodes[i];
1230 if (matchesElem(c, 'div')) {
1231 c.classList.remove('cbi-value-last');
1237 last.classList.add('cbi-value-last');
1240 function cbi_submit(elem, name, value, action)
1242 var form = elem.form || findParent(elem, 'form');
1248 form.action = action;
1251 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1252 E('input', { type: 'hidden', name: name });
1254 hidden.value = value || '1';
1255 form.appendChild(hidden);
1262 String.prototype.format = function()
1267 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1268 var quot_esc = [/"/g, '"', /'/g, '''];
1270 function esc(s, r) {
1271 if (typeof(s) !== 'string' && !(s instanceof String))
1274 for (var i = 0; i < r.length; i += 2)
1275 s = s.replace(r[i], r[i+1]);
1282 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1283 var a = b = [], numSubstitutions = 0, numMatches = 0;
1285 while (a = re.exec(str)) {
1287 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1288 var pPrecision = a[6], pType = a[7];
1296 if (numSubstitutions < arguments.length) {
1297 var param = arguments[numSubstitutions++];
1300 if (pPad && pPad.substr(0,1) == "'")
1301 pad = leftpart.substr(1,1);
1307 var justifyRight = true;
1308 if (pJustify && pJustify === "-")
1309 justifyRight = false;
1313 minLength = +pMinLength;
1316 if (pPrecision && pType == 'f')
1317 precision = +pPrecision.substring(1);
1323 subst = (+param || 0).toString(2);
1327 subst = String.fromCharCode(+param || 0);
1331 subst = ~~(+param || 0);
1335 subst = ~~Math.abs(+param || 0);
1339 subst = (precision > -1)
1340 ? ((+param || 0.0)).toFixed(precision)
1345 subst = (+param || 0).toString(8);
1353 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1357 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1361 subst = esc(param, html_esc);
1365 subst = esc(param, quot_esc);
1372 var ts = (param || 0);
1375 tm = Math.floor(ts / 60);
1380 th = Math.floor(tm / 60);
1385 td = Math.floor(th / 24);
1390 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1391 : String.format('%dh %dm %ds', th, tm, ts);
1396 var mf = pMinLength ? +pMinLength : 1000;
1397 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1400 var val = (+param || 0);
1401 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1403 for (i = 0; (i < units.length) && (val > mf); i++)
1406 subst = (i ? val.toFixed(pr) : val) + units[i];
1414 subst = subst.toString();
1415 for (var i = subst.length; i < pMinLength; i++)
1416 if (pJustify == '-')
1417 subst = subst + ' ';
1419 subst = pad + subst;
1422 out += leftpart + subst;
1423 str = str.substr(m.length);
1429 String.prototype.nobr = function()
1431 return this.replace(/[\s\n]+/g, ' ');
1434 String.format = function()
1438 for (var i = 1; i < arguments.length; i++)
1439 a.push(arguments[i]);
1441 return ''.format.apply(arguments[0], a);
1444 String.nobr = function()
1448 for (var i = 1; i < arguments.length; i++)
1449 a.push(arguments[i]);
1451 return ''.nobr.apply(arguments[0], a);
1454 if (window.NodeList && !NodeList.prototype.forEach) {
1455 NodeList.prototype.forEach = function (callback, thisArg) {
1456 thisArg = thisArg || window;
1457 for (var i = 0; i < this.length; i++) {
1458 callback.call(thisArg, this[i], i, this);
1463 if (!window.requestAnimationFrame) {
1464 window.requestAnimationFrame = function(f) {
1465 window.setTimeout(function() {
1466 f(new Date().getTime())
1472 var dummyElem, domParser;
1476 return (typeof(e) === 'object' && e !== null && 'nodeType' in e);
1484 domParser = domParser || new DOMParser();
1485 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1491 dummyElem = dummyElem || document.createElement('div');
1492 dummyElem.innerHTML = s;
1493 elem = dummyElem.firstChild;
1498 return elem || null;
1501 function matchesElem(node, selector)
1503 return ((node.matches && node.matches(selector)) ||
1504 (node.msMatchesSelector && node.msMatchesSelector(selector)));
1507 function findParent(node, selector)
1510 return node.closest(selector);
1513 if (matchesElem(node, selector))
1516 node = node.parentNode;
1523 var html = arguments[0],
1524 attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null,
1525 data = attr ? arguments[2] : arguments[1],
1530 else if (html.charCodeAt(0) === 60)
1531 elem = toElem(html);
1533 elem = document.createElement(html);
1539 for (var key in attr)
1540 if (attr.hasOwnProperty(key) && attr[key] !== null && attr[key] !== undefined)
1541 switch (typeof(attr[key])) {
1543 elem.addEventListener(key, attr[key]);
1547 elem.setAttribute(key, JSON.stringify(attr[key]));
1551 elem.setAttribute(key, attr[key]);
1554 if (typeof(data) === 'function')
1558 elem.appendChild(data);
1560 else if (Array.isArray(data)) {
1561 for (var i = 0; i < data.length; i++)
1562 if (isElem(data[i]))
1563 elem.appendChild(data[i]);
1565 elem.appendChild(document.createTextNode('' + data[i]));
1567 else if (data !== null && data !== undefined) {
1568 elem.innerHTML = '' + data;
1574 if (typeof(window.CustomEvent) !== 'function') {
1575 function CustomEvent(event, params) {
1576 params = params || { bubbles: false, cancelable: false, detail: undefined };
1577 var evt = document.createEvent('CustomEvent');
1578 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1582 CustomEvent.prototype = window.Event.prototype;
1583 window.CustomEvent = CustomEvent;
1587 openDropdown: function(sb) {
1588 var st = window.getComputedStyle(sb, null),
1589 ul = sb.querySelector('ul'),
1590 li = ul.querySelectorAll('li'),
1591 fl = findParent(sb, '.cbi-value-field'),
1592 sel = ul.querySelector('[selected]'),
1593 rect = sb.getBoundingClientRect(),
1594 items = Math.min(this.dropdown_items, li.length);
1596 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1597 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1600 sb.setAttribute('open', '');
1602 var pv = ul.cloneNode(true);
1603 pv.classList.add('preview');
1606 fl.classList.add('cbi-dropdown-open');
1608 if ('ontouchstart' in window) {
1609 var vpWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
1610 vpHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
1611 scrollFrom = window.pageYOffset,
1612 scrollTo = scrollFrom + rect.top - vpHeight * 0.5,
1615 ul.style.top = sb.offsetHeight + 'px';
1616 ul.style.left = -rect.left + 'px';
1617 ul.style.right = (rect.right - vpWidth) + 'px';
1618 ul.style.maxHeight = (vpHeight * 0.5) + 'px';
1619 ul.style.WebkitOverflowScrolling = 'touch';
1621 var scrollStep = function(timestamp) {
1624 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1627 var duration = Math.max(timestamp - start, 1);
1628 if (duration < 100) {
1629 document.body.scrollTop = scrollFrom + (scrollTo - scrollFrom) * (duration / 100);
1630 window.requestAnimationFrame(scrollStep);
1633 document.body.scrollTop = scrollTo;
1637 window.requestAnimationFrame(scrollStep);
1640 ul.style.maxHeight = '1px';
1641 ul.style.top = ul.style.bottom = '';
1643 window.requestAnimationFrame(function() {
1644 var height = items * li[Math.max(0, li.length - 2)].offsetHeight;
1646 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1647 ul.style[((rect.top + rect.height + height) > window.innerHeight) ? 'bottom' : 'top'] = rect.height + 'px';
1648 ul.style.maxHeight = height + 'px';
1652 ul.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c) {
1656 ul.classList.add('dropdown');
1658 sb.insertBefore(pv, ul.nextElementSibling);
1660 li.forEach(function(l) {
1661 l.setAttribute('tabindex', 0);
1664 sb.lastElementChild.setAttribute('tabindex', 0);
1666 this.setFocus(sb, sel || li[0], true);
1669 closeDropdown: function(sb, no_focus) {
1670 if (!sb.hasAttribute('open'))
1673 var pv = sb.querySelector('ul.preview'),
1674 ul = sb.querySelector('ul.dropdown'),
1675 li = ul.querySelectorAll('li'),
1676 fl = findParent(sb, '.cbi-value-field');
1678 li.forEach(function(l) { l.removeAttribute('tabindex'); });
1679 sb.lastElementChild.removeAttribute('tabindex');
1682 sb.removeAttribute('open');
1683 sb.style.width = sb.style.height = '';
1685 ul.classList.remove('dropdown');
1686 ul.style.top = ul.style.bottom = ul.style.maxHeight = '';
1689 fl.classList.remove('cbi-dropdown-open');
1692 this.setFocus(sb, sb);
1694 this.saveValues(sb, ul);
1697 toggleItem: function(sb, li, force_state) {
1698 if (li.hasAttribute('unselectable'))
1702 var cbox = li.querySelector('input[type="checkbox"]'),
1703 items = li.parentNode.querySelectorAll('li'),
1704 label = sb.querySelector('ul.preview'),
1705 sel = li.parentNode.querySelectorAll('[selected]').length,
1706 more = sb.querySelector('.more'),
1707 ndisplay = this.display_items,
1710 if (li.hasAttribute('selected')) {
1711 if (force_state !== true) {
1712 if (sel > 1 || this.optional) {
1713 li.removeAttribute('selected');
1714 cbox.checked = cbox.disabled = false;
1718 cbox.disabled = true;
1723 if (force_state !== false) {
1724 li.setAttribute('selected', '');
1725 cbox.checked = true;
1726 cbox.disabled = false;
1731 while (label.firstElementChild)
1732 label.removeChild(label.firstElementChild);
1734 for (var i = 0; i < items.length; i++) {
1735 items[i].removeAttribute('display');
1736 if (items[i].hasAttribute('selected')) {
1737 if (ndisplay-- > 0) {
1738 items[i].setAttribute('display', n++);
1739 label.appendChild(items[i].cloneNode(true));
1741 var c = items[i].querySelector('input[type="checkbox"]');
1743 c.disabled = (sel == 1 && !this.optional);
1748 sb.setAttribute('more', '');
1750 sb.removeAttribute('more');
1752 if (ndisplay === this.display_items)
1753 sb.setAttribute('empty', '');
1755 sb.removeAttribute('empty');
1757 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1760 var sel = li.parentNode.querySelector('[selected]');
1762 sel.removeAttribute('display');
1763 sel.removeAttribute('selected');
1766 li.setAttribute('display', 0);
1767 li.setAttribute('selected', '');
1769 this.closeDropdown(sb, true);
1772 this.saveValues(sb, li.parentNode);
1775 transformItem: function(sb, li) {
1776 var cbox = E('form', {}, E('input', { type: 'checkbox', tabindex: -1, onclick: 'event.preventDefault()' })),
1779 while (li.firstChild)
1780 label.appendChild(li.firstChild);
1782 li.appendChild(cbox);
1783 li.appendChild(label);
1786 saveValues: function(sb, ul) {
1787 var sel = ul.querySelectorAll('li[selected]'),
1788 div = sb.lastElementChild,
1792 while (div.lastElementChild)
1793 div.removeChild(div.lastElementChild);
1795 sel.forEach(function (s) {
1796 if (s.hasAttribute('placeholder'))
1801 value: s.hasAttribute('data-value') ? s.getAttribute('data-value') : s.innerText,
1805 div.appendChild(E('input', {
1807 name: s.hasAttribute('name') ? s.getAttribute('name') : (sb.getAttribute('name') || ''),
1813 strval += strval.length ? ' ' + v.value : v.value;
1822 detail.values = values;
1824 detail.value = values.length ? values[0] : null;
1828 sb.dispatchEvent(new CustomEvent('cbi-dropdown-change', {
1836 setValues: function(sb, values) {
1837 var ul = sb.querySelector('ul');
1840 ul.querySelectorAll('li[data-value]').forEach(function(li) {
1841 if (values === null || !(li.getAttribute('data-value') in values))
1842 this.toggleItem(sb, li, false);
1844 this.toggleItem(sb, li, true);
1848 var ph = ul.querySelector('li[placeholder]');
1850 this.toggleItem(sb, ph);
1852 ul.querySelectorAll('li[data-value]').forEach(function(li) {
1853 if (values !== null && (li.getAttribute('data-value') in values))
1854 this.toggleItem(sb, li);
1859 setFocus: function(sb, elem, scroll) {
1860 if (sb && sb.hasAttribute && sb.hasAttribute('locked-in'))
1863 if (sb.target && findParent(sb.target, 'ul.dropdown'))
1866 document.querySelectorAll('.focus').forEach(function(e) {
1867 if (!matchesElem(e, 'input')) {
1868 e.classList.remove('focus');
1875 elem.classList.add('focus');
1878 elem.parentNode.scrollTop = elem.offsetTop - elem.parentNode.offsetTop;
1882 createItems: function(sb, value) {
1884 val = (value || '').trim(),
1885 ul = sb.querySelector('ul');
1888 val = val.length ? [ val ] : [];
1890 val = val.length ? val.split(/\s+/) : [];
1892 val.forEach(function(item) {
1893 var new_item = null;
1895 ul.childNodes.forEach(function(li) {
1896 if (li.getAttribute && li.getAttribute('data-value') === item)
1902 tpl = sb.querySelector(sbox.template);
1905 markup = (tpl.textContent || tpl.innerHTML || tpl.firstChild.data).replace(/^<!--|-->$/, '').trim();
1907 markup = '<li data-value="{{value}}">{{value}}</li>';
1909 new_item = E(markup.replace(/{{value}}/g, item));
1912 sbox.transformItem(sb, new_item);
1915 var old = ul.querySelector('li[created]');
1917 ul.removeChild(old);
1919 new_item.setAttribute('created', '');
1922 new_item = ul.insertBefore(new_item, ul.lastElementChild);
1925 sbox.toggleItem(sb, new_item, true);
1926 sbox.setFocus(sb, new_item, true);
1930 closeAllDropdowns: function() {
1931 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1932 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1936 handleClick: function(ev) {
1937 var sb = ev.currentTarget;
1939 if (!sb.hasAttribute('open')) {
1940 if (!matchesElem(ev.target, 'input'))
1941 this.openDropdown(sb);
1944 var li = findParent(ev.target, 'li');
1945 if (li && li.parentNode.classList.contains('dropdown'))
1946 this.toggleItem(sb, li);
1947 else if (li && li.parentNode.classList.contains('preview'))
1948 this.closeDropdown(sb);
1951 ev.preventDefault();
1952 ev.stopPropagation();
1955 handleKeydown: function(ev) {
1956 var sb = ev.currentTarget;
1958 if (matchesElem(ev.target, 'input'))
1961 if (!sb.hasAttribute('open')) {
1962 switch (ev.keyCode) {
1967 this.openDropdown(sb);
1968 ev.preventDefault();
1972 var active = findParent(document.activeElement, 'li');
1974 switch (ev.keyCode) {
1976 this.closeDropdown(sb);
1981 if (!active.hasAttribute('selected'))
1982 this.toggleItem(sb, active);
1983 this.closeDropdown(sb);
1984 ev.preventDefault();
1990 this.toggleItem(sb, active);
1991 ev.preventDefault();
1996 if (active && active.previousElementSibling) {
1997 this.setFocus(sb, active.previousElementSibling);
1998 ev.preventDefault();
2003 if (active && active.nextElementSibling) {
2004 this.setFocus(sb, active.nextElementSibling);
2005 ev.preventDefault();
2012 handleDropdownClose: function(ev) {
2013 var sb = ev.currentTarget;
2015 this.closeDropdown(sb, true);
2018 handleDropdownSelect: function(ev) {
2019 var sb = ev.currentTarget,
2020 li = findParent(ev.target, 'li');
2025 this.toggleItem(sb, li);
2026 this.closeDropdown(sb, true);
2029 handleMouseover: function(ev) {
2030 var sb = ev.currentTarget;
2032 if (!sb.hasAttribute('open'))
2035 var li = findParent(ev.target, 'li');
2037 if (li && li.parentNode.classList.contains('dropdown'))
2038 this.setFocus(sb, li);
2041 handleFocus: function(ev) {
2042 var sb = ev.currentTarget;
2044 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
2045 if (s !== sb || sb.hasAttribute('open'))
2046 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
2050 handleCanaryFocus: function(ev) {
2051 this.closeDropdown(ev.currentTarget.parentNode);
2054 handleCreateKeydown: function(ev) {
2055 var input = ev.currentTarget,
2056 sb = findParent(input, '.cbi-dropdown');
2058 switch (ev.keyCode) {
2060 ev.preventDefault();
2062 if (input.classList.contains('cbi-input-invalid'))
2065 this.createItems(sb, input.value);
2072 handleCreateFocus: function(ev) {
2073 var input = ev.currentTarget,
2074 cbox = findParent(input, 'li').querySelector('input[type="checkbox"]'),
2075 sb = findParent(input, '.cbi-dropdown');
2078 cbox.checked = true;
2080 sb.setAttribute('locked-in', '');
2083 handleCreateBlur: function(ev) {
2084 var input = ev.currentTarget,
2085 cbox = findParent(input, 'li').querySelector('input[type="checkbox"]'),
2086 sb = findParent(input, '.cbi-dropdown');
2089 cbox.checked = false;
2091 sb.removeAttribute('locked-in');
2094 handleCreateClick: function(ev) {
2095 ev.currentTarget.querySelector(this.create).focus();
2099 function cbi_dropdown_init(sb) {
2100 if (!(this instanceof cbi_dropdown_init))
2101 return new cbi_dropdown_init(sb);
2103 this.multi = sb.hasAttribute('multiple');
2104 this.optional = sb.hasAttribute('optional');
2105 this.placeholder = sb.getAttribute('placeholder') || '---';
2106 this.display_items = parseInt(sb.getAttribute('display-items') || 3);
2107 this.dropdown_items = parseInt(sb.getAttribute('dropdown-items') || 5);
2108 this.create = sb.getAttribute('item-create') || '.create-item-input';
2109 this.template = sb.getAttribute('item-template') || 'script[type="item-template"]';
2111 var ul = sb.querySelector('ul'),
2112 more = sb.appendChild(E('span', { class: 'more', tabindex: -1 }, '···')),
2113 open = sb.appendChild(E('span', { class: 'open', tabindex: -1 }, '▾')),
2114 canary = sb.appendChild(E('div')),
2115 create = sb.querySelector(this.create),
2116 ndisplay = this.display_items,
2120 var items = ul.querySelectorAll('li');
2122 for (var i = 0; i < items.length; i++) {
2123 this.transformItem(sb, items[i]);
2125 if (items[i].hasAttribute('selected') && ndisplay-- > 0)
2126 items[i].setAttribute('display', n++);
2130 if (this.optional && !ul.querySelector('li[data-value=""]')) {
2131 var placeholder = E('li', { placeholder: '' }, this.placeholder);
2132 ul.firstChild ? ul.insertBefore(placeholder, ul.firstChild) : ul.appendChild(placeholder);
2135 var items = ul.querySelectorAll('li'),
2136 sel = sb.querySelectorAll('[selected]');
2138 sel.forEach(function(s) {
2139 s.removeAttribute('selected');
2142 var s = sel[0] || items[0];
2144 s.setAttribute('selected', '');
2145 s.setAttribute('display', n++);
2151 this.saveValues(sb, ul);
2153 ul.setAttribute('tabindex', -1);
2154 sb.setAttribute('tabindex', 0);
2157 sb.setAttribute('more', '')
2159 sb.removeAttribute('more');
2161 if (ndisplay === this.display_items)
2162 sb.setAttribute('empty', '')
2164 sb.removeAttribute('empty');
2166 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
2169 sb.addEventListener('click', this.handleClick.bind(this));
2170 sb.addEventListener('keydown', this.handleKeydown.bind(this));
2171 sb.addEventListener('cbi-dropdown-close', this.handleDropdownClose.bind(this));
2172 sb.addEventListener('cbi-dropdown-select', this.handleDropdownSelect.bind(this));
2174 if ('ontouchstart' in window) {
2175 sb.addEventListener('touchstart', function(ev) { ev.stopPropagation(); });
2176 window.addEventListener('touchstart', this.closeAllDropdowns);
2179 sb.addEventListener('mouseover', this.handleMouseover.bind(this));
2180 sb.addEventListener('focus', this.handleFocus.bind(this));
2182 canary.addEventListener('focus', this.handleCanaryFocus.bind(this));
2184 window.addEventListener('mouseover', this.setFocus);
2185 window.addEventListener('click', this.closeAllDropdowns);
2189 create.addEventListener('keydown', this.handleCreateKeydown.bind(this));
2190 create.addEventListener('focus', this.handleCreateFocus.bind(this));
2191 create.addEventListener('blur', this.handleCreateBlur.bind(this));
2193 var li = findParent(create, 'li');
2195 li.setAttribute('unselectable', '');
2196 li.addEventListener('click', this.handleCreateClick.bind(this));
2200 cbi_dropdown_init.prototype = CBIDropdown;
2202 function cbi_update_table(table, data, placeholder) {
2203 var target = isElem(table) ? table : document.querySelector(table);
2205 if (!isElem(target))
2208 target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
2211 thead.querySelectorAll('.th').forEach(function(th) {
2215 if (Array.isArray(data)) {
2216 var n = 0, rows = target.querySelectorAll('.tr');
2218 data.forEach(function(row) {
2219 var trow = E('div', { 'class': 'tr' });
2221 for (var i = 0; i < titles.length; i++) {
2222 var text = (titles[i].innerText || '').trim();
2223 var td = trow.appendChild(E('div', {
2224 'class': titles[i].className,
2225 'data-title': (text !== '') ? text : null
2228 td.classList.remove('th');
2229 td.classList.add('td');
2232 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
2235 target.replaceChild(trow, rows[n]);
2237 target.appendChild(trow);
2241 target.removeChild(rows[n]);
2243 if (placeholder && target.firstElementChild === target.lastElementChild) {
2244 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
2245 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
2247 td.classList.remove('th');
2248 td.classList.add('td');
2252 thead.parentNode.style.display = 'none';
2254 thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
2255 if (trow !== thead) {
2257 trow.querySelectorAll('.th, .td').forEach(function(td) {
2258 if (n < titles.length) {
2259 var text = (titles[n++].innerText || '').trim();
2261 td.setAttribute('data-title', text);
2267 thead.parentNode.style.display = '';
2272 var tooltipDiv = null, tooltipTimeout = null;
2274 function showTooltip(ev) {
2275 var target = findParent(ev.target, '[data-tooltip]');
2280 if (tooltipTimeout !== null) {
2281 window.clearTimeout(tooltipTimeout);
2282 tooltipTimeout = null;
2285 var rect = target.getBoundingClientRect(),
2286 x = rect.left + window.pageXOffset,
2287 y = rect.top + rect.height + window.pageYOffset;
2289 tooltipDiv.className = 'cbi-tooltip';
2290 tooltipDiv.innerHTML = '▲ ';
2291 tooltipDiv.firstChild.data += target.getAttribute('data-tooltip');
2293 if (target.hasAttribute('data-tooltip-style'))
2294 tooltipDiv.classList.add(target.getAttribute('data-tooltip-style'));
2296 if ((y + tooltipDiv.offsetHeight) > (window.innerHeight + window.pageYOffset)) {
2297 y -= (tooltipDiv.offsetHeight + target.offsetHeight);
2298 tooltipDiv.firstChild.data = '▼ ' + tooltipDiv.firstChild.data.substr(2);
2301 tooltipDiv.style.top = y + 'px';
2302 tooltipDiv.style.left = x + 'px';
2303 tooltipDiv.style.opacity = 1;
2306 function hideTooltip(ev) {
2307 if (ev.target === tooltipDiv || ev.relatedTarget === tooltipDiv)
2310 if (tooltipTimeout !== null) {
2311 window.clearTimeout(tooltipTimeout);
2312 tooltipTimeout = null;
2315 tooltipDiv.style.opacity = 0;
2316 tooltipTimeout = window.setTimeout(function() { tooltipDiv.removeAttribute('style'); }, 250);
2320 var modalDiv = null;
2322 function showModal(title, children)
2324 var dlg = modalDiv.firstElementChild;
2326 while (dlg.firstChild)
2327 dlg.removeChild(dlg.firstChild);
2329 dlg.setAttribute('class', 'modal');
2330 dlg.appendChild(E('h4', {}, title));
2332 if (!Array.isArray(children))
2333 children = [ children ];
2335 for (var i = 0; i < children.length; i++)
2336 if (isElem(children[i]))
2337 dlg.appendChild(children[i]);
2339 dlg.appendChild(document.createTextNode('' + children[i]));
2341 document.body.classList.add('modal-overlay-active');
2346 function hideModal()
2348 document.body.classList.remove('modal-overlay-active');
2352 document.addEventListener('DOMContentLoaded', function() {
2353 tooltipDiv = document.body.appendChild(E('div', { 'class': 'cbi-tooltip' }));
2354 modalDiv = document.body.appendChild(E('div', { 'id': 'modal_overlay' },
2355 E('div', { 'class': 'modal' })));
2357 document.addEventListener('mouseover', showTooltip, true);
2358 document.addEventListener('mouseout', hideTooltip, true);
2359 document.addEventListener('focus', showTooltip, true);
2360 document.addEventListener('blur', hideTooltip, true);
2362 document.addEventListener('validation-failure', function(ev) {
2363 if (ev.target === document.activeElement)
2367 document.addEventListener('validation-success', function(ev) {
2368 if (ev.target === document.activeElement)
2372 document.querySelectorAll('.table').forEach(cbi_update_table);