2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2018 Jo-Philipp Wich <jo@mein.io>
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
11 http://www.apache.org/licenses/LICENSE-2.0
15 var cbi_strings = { path: {}, label: {} };
17 function s8(bytes, off) {
19 return (n > 0x7F) ? (n - 256) >>> 0 : n;
22 function u16(bytes, off) {
23 return ((bytes[off + 1] << 8) + bytes[off]) >>> 0;
27 if (s === null || s.length === 0)
32 for (var i = 0; i < s.length; i++) {
33 var ch = s.charCodeAt(i);
38 bytes.push(((ch >>> 6) & 0x1F) | 0xC0,
40 else if (ch <= 0xFFFF)
41 bytes.push(((ch >>> 12) & 0x0F) | 0xE0,
42 ((ch >>> 6) & 0x3F) | 0x80,
44 else if (code <= 0x10FFFF)
45 bytes.push(((ch >>> 18) & 0x07) | 0xF0,
46 ((ch >>> 12) & 0x3F) | 0x80,
47 ((ch >> 6) & 0x3F) | 0x80,
54 var hash = (bytes.length >>> 0),
55 len = (bytes.length >>> 2),
59 hash += u16(bytes, off);
60 tmp = ((u16(bytes, off + 2) << 11) ^ hash) >>> 0;
61 hash = ((hash << 16) ^ tmp) >>> 0;
66 switch ((bytes.length & 3) >>> 0) {
68 hash += u16(bytes, off);
69 hash = (hash ^ (hash << 16)) >>> 0;
70 hash = (hash ^ (s8(bytes, off + 2) << 18)) >>> 0;
75 hash += u16(bytes, off);
76 hash = (hash ^ (hash << 11)) >>> 0;
81 hash += s8(bytes, off);
82 hash = (hash ^ (hash << 10)) >>> 0;
87 hash = (hash ^ (hash << 3)) >>> 0;
89 hash = (hash ^ (hash << 4)) >>> 0;
91 hash = (hash ^ (hash << 25)) >>> 0;
94 return (0x100000000 + hash).toString(16).substr(1);
98 return (window.TR && TR[sfh(s)]) || s;
102 return (/^-?\d+$/.test(x) ? +x : NaN);
106 return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
110 if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
113 if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
116 return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
120 if (x.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
121 var v6 = RegExp.$1, v4 = IPv4(RegExp.$2);
126 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
127 + ':' + (v4[2] * 256 + v4[3]).toString(16);
130 if (!x.match(/^[a-fA-F0-9:]+$/))
133 var prefix_suffix = x.split(/::/);
135 if (prefix_suffix.length > 2)
138 var prefix = (prefix_suffix[0] || '0').split(/:/);
139 var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
141 if (suffix.length ? (prefix.length + suffix.length > 7)
142 : ((prefix_suffix.length < 2 && prefix.length < 8) || prefix.length > 8))
148 for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
149 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
154 for (i = 0; i < (8 - prefix.length - suffix.length); i++)
157 for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
158 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
166 var CBIValidatorPrototype = {
167 apply: function(name, value, args) {
170 if (typeof(name) === 'function')
172 else if (typeof(this.types[name]) === 'function')
173 func = this.types[name];
177 if (value !== undefined && value !== null)
180 return func.apply(this, args);
183 assert: function(condition, message) {
185 this.field.classList.add('cbi-input-invalid');
186 this.error = message;
190 this.field.classList.remove('cbi-input-invalid');
195 compile: function(code) {
203 for (var i = 0; i < code.length; i++) {
209 switch (code.charCodeAt(i))
219 var label = code.substring(pos, i);
220 label = label.replace(/\\(.)/g, '$1');
221 label = label.replace(/^[ \t]+/g, '');
222 label = label.replace(/[ \t]+$/g, '');
224 if (label && !isNaN(label)) {
225 stack.push(parseFloat(label));
227 else if (label.match(/^(['"]).*\1$/)) {
228 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
230 else if (typeof this.types[label] == 'function') {
231 stack.push(this.types[label]);
235 throw "Syntax error, unhandled token '"+label+"'";
242 depth += (code.charCodeAt(i) == 40);
247 if (typeof stack[stack.length-2] != 'function')
248 throw "Syntax error, argument list follows non-function";
250 stack[stack.length-1] = this.compile(code.substring(pos, i));
261 validate: function() {
262 /* element is detached */
263 if (!findParent(this.field, 'body') && !findParent(this.field, '[data-field]'))
266 this.field.classList.remove('cbi-input-invalid');
267 this.value = (this.field.value != null) ? this.field.value : '';
272 if (this.value.length === 0)
273 valid = this.assert(this.optional, _('non-empty value'));
275 valid = this.vstack[0].apply(this, this.vstack[1]);
277 if (valid !== true) {
278 this.field.setAttribute('data-tooltip', _('Expecting %s').format(this.error));
279 this.field.setAttribute('data-tooltip-style', 'error');
280 this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
284 if (typeof(this.vfunc) == 'function')
285 valid = this.vfunc(this.value);
287 if (valid !== true) {
288 this.assert(false, valid);
289 this.field.setAttribute('data-tooltip', valid);
290 this.field.setAttribute('data-tooltip-style', 'error');
291 this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
295 this.field.removeAttribute('data-tooltip');
296 this.field.removeAttribute('data-tooltip-style');
297 this.field.dispatchEvent(new CustomEvent('validation-success', { bubbles: true }));
302 integer: function() {
303 return this.assert(Int(this.value) !== NaN, _('valid integer value'));
306 uinteger: function() {
307 return this.assert(Int(this.value) >= 0, _('positive integer value'));
311 return this.assert(Dec(this.value) !== NaN, _('valid decimal value'));
315 return this.assert(Dec(this.value) >= 0, _('positive decimal value'));
318 ipaddr: function(nomask) {
319 return this.assert(this.apply('ip4addr', null, [nomask]) || this.apply('ip6addr', null, [nomask]),
320 nomask ? _('valid IP address') : _('valid IP address or prefix'));
323 ip4addr: function(nomask) {
324 var re = nomask ? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
325 m = this.value.match(re);
327 return this.assert(m && IPv4(m[1]) && (m[2] ? IPv4(m[2]) : (m[3] ? this.apply('ip4prefix', m[3]) : true)),
328 nomask ? _('valid IPv4 address') : _('valid IPv4 address or network'));
331 ip6addr: function(nomask) {
332 var re = nomask ? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
333 m = this.value.match(re);
335 return this.assert(m && IPv6(m[1]) && (m[2] ? this.apply('ip6prefix', m[2]) : true),
336 nomask ? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
339 ip4prefix: function() {
340 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 32,
341 _('valid IPv4 prefix value (0-32)'));
344 ip6prefix: function() {
345 return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 128,
346 _('valid IPv6 prefix value (0-128)'));
350 return this.assert(this.apply('cidr4') || this.apply('cidr6'), _('valid IPv4 or IPv6 CIDR'));
354 var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
355 return this.assert(m && IPv4(m[1]) && this.apply('ip4prefix', m[2]), _('valid IPv4 CIDR'));
359 var m = this.value.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
360 return this.assert(m && IPv6(m[1]) && this.apply('ip6prefix', m[2]), _('valid IPv6 CIDR'));
364 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})$/);
365 return this.assert(m && IPv4(m[1]) && IPv4(m[2]), _('IPv4 network in address/netmask notation'));
369 var m = this.value.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
370 return this.assert(m && IPv6(m[1]) && IPv6(m[2]), _('IPv6 network in address/netmask notation'));
373 ip6hostid: function() {
374 if (this.value == "eui64" || this.value == "random")
377 var v6 = IPv6(this.value);
378 return this.assert(!(!v6 || v6[0] || v6[1] || v6[2] || v6[3]), _('valid IPv6 host id'));
382 return this.assert(this.apply('ipmask4') || this.apply('ipmask6'),
383 _('valid network in address/netmask notation'));
386 ipmask4: function() {
387 return this.assert(this.apply('cidr4') || this.apply('ipnet4') || this.apply('ip4addr'),
388 _('valid IPv4 network'));
391 ipmask6: function() {
392 return this.assert(this.apply('cidr6') || this.apply('ipnet6') || this.apply('ip6addr'),
393 _('valid IPv6 network'));
397 var p = Int(this.value);
398 return this.assert(p >= 0 && p <= 65535, _('valid port value'));
401 portrange: function() {
402 if (this.value.match(/^(\d+)-(\d+)$/)) {
405 return this.assert(p1 <= p2 && p2 <= 65535,
406 _('valid port or port range (port1-port2)'));
409 return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
412 macaddr: function() {
413 return this.assert(this.value.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null,
414 _('valid MAC address'));
417 host: function(ipv4only) {
418 return this.assert(this.apply('hostname') || this.apply(ipv4only == 1 ? 'ip4addr' : 'ipaddr'),
419 _('valid hostname or IP address'));
422 hostname: function(strict) {
423 if (this.value.length <= 253)
425 (this.value.match(/^[a-zA-Z0-9_]+$/) != null ||
426 (this.value.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
427 this.value.match(/[^0-9.]/))) &&
428 (!strict || !this.value.match(/^_/)),
429 _('valid hostname'));
431 return this.assert(false, _('valid hostname'));
434 network: function() {
435 return this.assert(this.apply('uciname') || this.apply('host'),
436 _('valid UCI identifier, hostname or IP address'));
439 hostport: function(ipv4only) {
440 var hp = this.value.split(/:/);
441 return this.assert(hp.length == 2 && this.apply('host', hp[0], [ipv4only]) && this.apply('port', hp[1]),
442 _('valid host:port'));
445 ip4addrport: function() {
446 var hp = this.value.split(/:/);
447 return this.assert(hp.length == 2 && this.apply('ip4addr', hp[0], [true]) && this.apply('port', hp[1]),
448 _('valid IPv4 address:port'));
451 ipaddrport: function(bracket) {
452 var m4 = this.value.match(/^([^\[\]:]+):(\d+)$/),
453 m6 = this.value.match((bracket == 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
456 return this.assert(this.apply('ip4addr', m4[1], [true]) && this.apply('port', m4[2]),
457 _('valid address:port'));
459 return this.assert(m6 && this.apply('ip6addr', m6[1], [true]) && this.apply('port', m6[2]),
460 _('valid address:port'));
467 return this.assert(v.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
469 return this.assert((v.length >= 8) && (v.length <= 63), _('key between 8 and 63 characters'));
475 if (v.substr(0, 2) === 's:')
478 if ((v.length == 10) || (v.length == 26))
479 return this.assert(v.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
481 return this.assert((v.length === 5) || (v.length === 13), _('key with either 5 or 13 characters'));
484 uciname: function() {
485 return this.assert(this.value.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
488 range: function(min, max) {
489 var val = Dec(this.value);
490 return this.assert(val >= +min && val <= +max, _('value between %f and %f').format(min, max));
494 return this.assert(Dec(this.value) >= +min, _('value greater or equal to %f').format(min));
498 return this.assert(Dec(this.value) <= +max, _('value smaller or equal to %f').format(max));
501 rangelength: function(min, max) {
502 var val = '' + this.value;
503 return this.assert((val.length >= +min) && (val.length <= +max),
504 _('value between %d and %d characters').format(min, max));
507 minlength: function(min) {
508 return this.assert((''+this.value).length >= +min,
509 _('value with at least %d characters').format(min));
512 maxlength: function(max) {
513 return this.assert((''+this.value).length <= +max,
514 _('value with at most %d characters').format(max));
520 for (var i = 0; i < arguments.length; i += 2) {
521 if (typeof arguments[i] != 'function') {
522 if (arguments[i] == this.value)
523 return this.assert(true);
524 errors.push('"%s"'.format(arguments[i]));
527 else if (arguments[i].apply(this, arguments[i+1])) {
528 return this.assert(true);
531 errors.push(this.error);
535 return this.assert(false, _('one of:\n - %s'.format(errors.join('\n - '))));
539 for (var i = 0; i < arguments.length; i += 2) {
540 if (typeof arguments[i] != 'function') {
541 if (arguments[i] != this.value)
542 return this.assert(false, '"%s"'.format(arguments[i]));
545 else if (!arguments[i].apply(this, arguments[i+1])) {
546 return this.assert(false, this.error);
550 return this.assert(true);
554 return this.apply('or', this.value.replace(/^[ \t]*![ \t]*/, ''), arguments);
557 list: function(subvalidator, subargs) {
558 this.field.setAttribute('data-is-list', 'true');
560 var tokens = this.value.match(/[^ \t]+/g);
561 for (var i = 0; i < tokens.length; i++)
562 if (!this.apply(subvalidator, tokens[i], subargs))
563 return this.assert(false, this.error);
565 return this.assert(true);
568 phonedigit: function() {
569 return this.assert(this.value.match(/^[0-9\*#!\.]+$/),
570 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
573 timehhmmss: function() {
574 return this.assert(this.value.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
575 _('valid time (HH:MM:SS)'));
578 dateyyyymmdd: function() {
579 if (this.value.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
580 var year = +RegExp.$1,
583 days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
585 function is_leap_year(year) {
586 return ((!(year % 4) && (year % 100)) || !(year % 400));
589 function get_days_in_month(month, year) {
590 return (month === 2 && is_leap_year(year)) ? 29 : days_in_month[month - 1];
593 /* Firewall rules in the past don't make sense */
594 return this.assert(year >= 2015 && month && month <= 12 && day && day <= get_days_in_month(month, year),
595 _('valid date (YYYY-MM-DD)'));
599 return this.assert(false, _('valid date (YYYY-MM-DD)'));
602 unique: function(subvalidator, subargs) {
604 option = findParent(ctx.field, '[data-type][data-name]'),
605 section = findParent(option, '.cbi-section'),
606 query = '[data-type="%s"][data-name="%s"]'.format(option.getAttribute('data-type'), option.getAttribute('data-name')),
609 section.querySelectorAll(query).forEach(function(sibling) {
610 if (sibling === option)
613 var values = L.dom.callClassMethod(sibling.querySelector('[data-idref]'), 'getValue');
615 if (!Array.isArray(values) && sibling.querySelector('[data-is-list]'))
616 values = String(values || '').match(/[^ \t]+/g) || [];
617 else if (!Array.isArray(values))
618 values = (values != null) ? [ values ] : [];
620 if (values.indexOf(ctx.value) != -1)
625 return this.assert(false, _('unique value'));
627 if (typeof(subvalidator) === 'function')
628 return this.apply(subvalidator, undefined, subargs);
630 return this.assert(true);
633 hexstring: function() {
634 return this.assert(this.value.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
635 _('hexadecimal encoded value'));
644 function CBIValidator(field, type, optional, vfunc)
647 this.optional = optional;
649 this.vstack = this.compile(type);
652 CBIValidator.prototype = CBIValidatorPrototype;
655 function cbi_d_add(field, dep, index) {
656 var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
659 for (var i=0; i<cbi_d.length; i++) {
660 if (cbi_d[i].id == obj.id) {
669 "parent": obj.parentNode.id,
673 cbi_d.unshift(entry);
679 function cbi_d_checkvalue(target, ref) {
681 query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
682 'select[id="'+target+'"], select[name="'+target+'"]';
684 document.querySelectorAll(query).forEach(function(i) {
685 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
689 return (((value !== null) ? value : "") == ref);
692 function cbi_d_check(deps) {
695 for (var i=0; i<deps.length; i++) {
698 for (var j in deps[i]) {
699 if (j == "!reverse") {
701 } else if (j == "!default") {
705 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
709 if (istat ^ reverse) {
716 function cbi_d_update() {
718 for (var i=0; i<cbi_d.length; i++) {
719 var entry = cbi_d[i];
720 var node = document.getElementById(entry.id);
721 var parent = document.getElementById(entry.parent);
723 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
724 node.parentNode.removeChild(node);
727 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
728 var next = undefined;
730 for (next = parent.firstChild; next; next = next.nextSibling) {
731 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
736 parent.appendChild(entry.node);
738 parent.insertBefore(entry.node, next);
743 // hide optionals widget if no choices remaining
744 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
745 parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
748 if (entry && entry.parent)
749 cbi_tag_last(parent);
754 parent.dispatchEvent(new CustomEvent('dependency-update', { bubbles: true }));
757 function cbi_init() {
760 document.querySelectorAll('.cbi-dropdown').forEach(function(node) {
761 cbi_dropdown_init(node);
762 node.addEventListener('cbi-dropdown-change', cbi_d_update);
765 nodes = document.querySelectorAll('[data-strings]');
767 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
768 var str = JSON.parse(node.getAttribute('data-strings'));
769 for (var key in str) {
770 for (var key2 in str[key]) {
771 var dst = cbi_strings[key] || (cbi_strings[key] = { });
772 dst[key2] = str[key][key2];
777 nodes = document.querySelectorAll('[data-depends]');
779 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
780 var index = parseInt(node.getAttribute('data-index'), 10);
781 var depends = JSON.parse(node.getAttribute('data-depends'));
782 if (!isNaN(index) && depends.length > 0) {
783 for (var alt = 0; alt < depends.length; alt++)
784 cbi_d_add(node, depends[alt], index);
788 nodes = document.querySelectorAll('[data-update]');
790 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
791 var events = node.getAttribute('data-update').split(' ');
792 for (var j = 0, event; (event = events[j]) !== undefined; j++)
793 node.addEventListener(event, cbi_d_update);
796 nodes = document.querySelectorAll('[data-choices]');
798 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
799 var choices = JSON.parse(node.getAttribute('data-choices')),
802 for (var j = 0; j < choices[0].length; j++)
803 options[choices[0][j]] = choices[1][j];
805 var def = (node.getAttribute('data-optional') === 'true')
806 ? node.placeholder || '' : null;
808 var cb = new L.ui.Combobox(node.value, options, {
809 name: node.getAttribute('name'),
811 select_placeholder: def || _('-- Please choose --'),
812 custom_placeholder: node.getAttribute('data-manual') || _('-- custom --')
816 n.addEventListener('cbi-dropdown-change', cbi_d_update);
817 node.parentNode.replaceChild(n, node);
820 nodes = document.querySelectorAll('[data-dynlist]');
822 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
823 var choices = JSON.parse(node.getAttribute('data-dynlist')),
824 values = JSON.parse(node.getAttribute('data-values') || '[]'),
827 if (choices[0] && choices[0].length) {
830 for (var j = 0; j < choices[0].length; j++)
831 options[choices[0][j]] = choices[1][j];
834 var dl = new L.ui.DynamicList(values, options, {
835 name: node.getAttribute('data-prefix'),
837 datatype: choices[2],
838 optional: choices[3],
839 placeholder: node.getAttribute('data-placeholder')
843 n.addEventListener('cbi-dynlist-change', cbi_d_update);
844 node.parentNode.replaceChild(n, node);
847 nodes = document.querySelectorAll('[data-type]');
849 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
850 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
851 node.getAttribute('data-type'));
854 document.querySelectorAll('[data-browser]').forEach(cbi_browser_init);
856 document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
857 s.parentNode.classList.add('cbi-tooltip-container');
860 document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
861 var handler = function(ev) {
862 var bits = this.name.split(/\./),
863 section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
865 section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
868 i.addEventListener('mouseover', handler);
869 i.addEventListener('mouseout', handler);
872 document.querySelectorAll('[data-ui-widget]').forEach(function(node) {
873 var args = JSON.parse(node.getAttribute('data-ui-widget') || '[]'),
874 widget = new (Function.prototype.bind.apply(L.ui[args[0]], args)),
875 markup = widget.render();
877 markup.addEventListener('widget-change', cbi_d_update);
878 node.parentNode.replaceChild(markup, node);
884 function cbi_filebrowser(id, defpath) {
885 var field = L.dom.elem(id) ? id : document.getElementById(id);
886 var browser = window.open(
887 cbi_strings.path.browser + (field.value || defpath || '') + '?field=' + field.id,
888 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
894 function cbi_browser_init(field)
896 field.parentNode.insertBefore(
898 'src': L.resource('cbi/folder.gif'),
899 'class': 'cbi-image-button',
900 'click': function(ev) {
901 cbi_filebrowser(field, field.getAttribute('data-browser'));
904 }), field.nextSibling);
907 function cbi_validate_form(form, errmsg)
909 /* if triggered by a section removal or addition, don't validate */
910 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
913 if (form.cbi_validators) {
914 for (var i = 0; i < form.cbi_validators.length; i++) {
915 var validator = form.cbi_validators[i];
917 if (!validator() && errmsg) {
927 function cbi_validate_reset(form)
930 function() { cbi_validate_form(form, null) }, 100
936 function cbi_validate_field(cbid, optional, type)
938 var field = isElem(cbid) ? cbid : document.getElementById(cbid);
942 var cbiValidator = new CBIValidator(field, type, optional);
943 validatorFn = cbiValidator.validate.bind(cbiValidator);
949 if (validatorFn !== null) {
950 var form = findParent(field, 'form');
952 if (!form.cbi_validators)
953 form.cbi_validators = [ ];
955 form.cbi_validators.push(validatorFn);
957 field.addEventListener("blur", validatorFn);
958 field.addEventListener("keyup", validatorFn);
959 field.addEventListener("cbi-dropdown-change", validatorFn);
961 if (matchesElem(field, 'select')) {
962 field.addEventListener("change", validatorFn);
963 field.addEventListener("click", validatorFn);
970 function cbi_row_swap(elem, up, store)
972 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
977 tr.classList.remove('flash');
980 var prev = tr.previousElementSibling;
982 if (prev && prev.classList.contains('cbi-section-table-row'))
983 tr.parentNode.insertBefore(tr, prev);
988 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
990 if (next && next.classList.contains('cbi-section-table-row'))
991 tr.parentNode.insertBefore(tr, next);
993 tr.parentNode.appendChild(tr);
1000 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1001 var node = tr.parentNode.childNodes[i];
1002 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1003 node.classList.remove('cbi-rowstyle-1');
1004 node.classList.remove('cbi-rowstyle-2');
1005 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1007 if (/-([^\-]+)$/.test(node.id))
1008 ids.push(RegExp.$1);
1012 var input = document.getElementById(store);
1014 input.value = ids.join(' ');
1016 window.scrollTo(0, tr.offsetTop);
1017 void tr.offsetWidth;
1018 tr.classList.add('flash');
1023 function cbi_tag_last(container)
1027 for (var i = 0; i < container.childNodes.length; i++) {
1028 var c = container.childNodes[i];
1029 if (matchesElem(c, 'div')) {
1030 c.classList.remove('cbi-value-last');
1036 last.classList.add('cbi-value-last');
1039 function cbi_submit(elem, name, value, action)
1041 var form = elem.form || findParent(elem, 'form');
1047 form.action = action;
1050 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1051 E('input', { type: 'hidden', name: name });
1053 hidden.value = value || '1';
1054 form.appendChild(hidden);
1061 String.prototype.format = function()
1066 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1067 var quot_esc = [/"/g, '"', /'/g, '''];
1069 function esc(s, r) {
1070 if (typeof(s) !== 'string' && !(s instanceof String))
1073 for (var i = 0; i < r.length; i += 2)
1074 s = s.replace(r[i], r[i+1]);
1081 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1082 var a = b = [], numSubstitutions = 0, numMatches = 0;
1084 while (a = re.exec(str)) {
1086 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1087 var pPrecision = a[6], pType = a[7];
1095 if (numSubstitutions < arguments.length) {
1096 var param = arguments[numSubstitutions++];
1099 if (pPad && pPad.substr(0,1) == "'")
1100 pad = leftpart.substr(1,1);
1106 var justifyRight = true;
1107 if (pJustify && pJustify === "-")
1108 justifyRight = false;
1112 minLength = +pMinLength;
1115 if (pPrecision && pType == 'f')
1116 precision = +pPrecision.substring(1);
1122 subst = (+param || 0).toString(2);
1126 subst = String.fromCharCode(+param || 0);
1130 subst = ~~(+param || 0);
1134 subst = ~~Math.abs(+param || 0);
1138 subst = (precision > -1)
1139 ? ((+param || 0.0)).toFixed(precision)
1144 subst = (+param || 0).toString(8);
1152 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1156 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1160 subst = esc(param, html_esc);
1164 subst = esc(param, quot_esc);
1171 var ts = (param || 0);
1174 tm = Math.floor(ts / 60);
1179 th = Math.floor(tm / 60);
1184 td = Math.floor(th / 24);
1189 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1190 : String.format('%dh %dm %ds', th, tm, ts);
1195 var mf = pMinLength ? +pMinLength : 1000;
1196 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1199 var val = (+param || 0);
1200 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1202 for (i = 0; (i < units.length) && (val > mf); i++)
1205 subst = (i ? val.toFixed(pr) : val) + units[i];
1213 subst = subst.toString();
1214 for (var i = subst.length; i < pMinLength; i++)
1215 if (pJustify == '-')
1216 subst = subst + ' ';
1218 subst = pad + subst;
1221 out += leftpart + subst;
1222 str = str.substr(m.length);
1228 String.prototype.nobr = function()
1230 return this.replace(/[\s\n]+/g, ' ');
1233 String.format = function()
1237 for (var i = 1; i < arguments.length; i++)
1238 a.push(arguments[i]);
1240 return ''.format.apply(arguments[0], a);
1243 String.nobr = function()
1247 for (var i = 1; i < arguments.length; i++)
1248 a.push(arguments[i]);
1250 return ''.nobr.apply(arguments[0], a);
1253 if (window.NodeList && !NodeList.prototype.forEach) {
1254 NodeList.prototype.forEach = function (callback, thisArg) {
1255 thisArg = thisArg || window;
1256 for (var i = 0; i < this.length; i++) {
1257 callback.call(thisArg, this[i], i, this);
1262 if (!window.requestAnimationFrame) {
1263 window.requestAnimationFrame = function(f) {
1264 window.setTimeout(function() {
1265 f(new Date().getTime())
1271 function isElem(e) { return L.dom.elem(e) }
1272 function toElem(s) { return L.dom.parse(s) }
1273 function matchesElem(node, selector) { return L.dom.matches(node, selector) }
1274 function findParent(node, selector) { return L.dom.parent(node, selector) }
1275 function E() { return L.dom.create.apply(L.dom, arguments) }
1277 if (typeof(window.CustomEvent) !== 'function') {
1278 function CustomEvent(event, params) {
1279 params = params || { bubbles: false, cancelable: false, detail: undefined };
1280 var evt = document.createEvent('CustomEvent');
1281 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1285 CustomEvent.prototype = window.Event.prototype;
1286 window.CustomEvent = CustomEvent;
1289 function cbi_dropdown_init(sb) {
1290 var dl = new L.ui.Dropdown(sb, null, { name: sb.getAttribute('name') });
1294 function cbi_update_table(table, data, placeholder) {
1295 var target = isElem(table) ? table : document.querySelector(table);
1297 if (!isElem(target))
1300 target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
1303 thead.querySelectorAll('.th').forEach(function(th) {
1307 if (Array.isArray(data)) {
1308 var n = 0, rows = target.querySelectorAll('.tr');
1310 data.forEach(function(row) {
1311 var trow = E('div', { 'class': 'tr' });
1313 for (var i = 0; i < titles.length; i++) {
1314 var text = (titles[i].innerText || '').trim();
1315 var td = trow.appendChild(E('div', {
1316 'class': titles[i].className,
1317 'data-title': (text !== '') ? text : null
1320 td.classList.remove('th');
1321 td.classList.add('td');
1324 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
1327 target.replaceChild(trow, rows[n]);
1329 target.appendChild(trow);
1333 target.removeChild(rows[n]);
1335 if (placeholder && target.firstElementChild === target.lastElementChild) {
1336 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
1337 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
1339 td.classList.remove('th');
1340 td.classList.add('td');
1344 thead.parentNode.style.display = 'none';
1346 thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
1347 if (trow !== thead) {
1349 trow.querySelectorAll('.th, .td').forEach(function(td) {
1350 if (n < titles.length) {
1351 var text = (titles[n++].innerText || '').trim();
1353 td.setAttribute('data-title', text);
1359 thead.parentNode.style.display = '';
1364 function showModal(title, children)
1366 return L.showModal(title, children);
1369 function hideModal()
1371 return L.hideModal();
1375 document.addEventListener('DOMContentLoaded', function() {
1376 document.addEventListener('validation-failure', function(ev) {
1377 if (ev.target === document.activeElement)
1381 document.addEventListener('validation-success', function(ev) {
1382 if (ev.target === document.activeElement)
1386 document.querySelectorAll('.table').forEach(cbi_update_table);