d962a1d1af49fe10f62efc04d1d63ace50153b5e
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);
97 var plural_function
= null;
100 return String(s
).trim().replace(/[ \t\n]+/g, ' ');
104 return (window
.TR
&& TR
[sfh(trimws(s
))]) || s
;
107 function N_(n
, s
, p
, c
) {
108 if (plural_function
== null && window
.TR
)
109 plural_function
= new Function('n', (TR
['00000000'] || 'plural=(n != 1);') + 'return +plural');
111 var i
= plural_function
? plural_function(n
) : (n
!= 1),
112 k
= (c
!= null ? trimws(c
) + '\u0001' : '') + trimws(s
) + '\u0002' + i
.toString();
114 return (window
.TR
&& TR
[sfh(k
)]) || (i
? p
: s
);
118 function cbi_d_add(field
, dep
, index
) {
119 var obj
= (typeof(field
) === 'string') ? document
.getElementById(field
) : field
;
122 for (var i
=0; i
<cbi_d
.length
; i
++) {
123 if (cbi_d
[i
].id
== obj
.id
) {
132 "parent": obj
.parentNode
.id
,
136 cbi_d
.unshift(entry
);
142 function cbi_d_checkvalue(target
, ref
) {
144 query
= 'input[id="'+target
+'"], input[name="'+target
+'"], ' +
145 'select[id="'+target
+'"], select[name="'+target
+'"]';
147 document
.querySelectorAll(query
).forEach(function(i
) {
148 if (value
=== null && ((i
.type
!== 'radio' && i
.type
!== 'checkbox') || i
.checked
=== true))
152 return (((value
!== null) ? value
: "") == ref
);
155 function cbi_d_check(deps
) {
158 for (var i
=0; i
<deps
.length
; i
++) {
161 for (var j
in deps
[i
]) {
162 if (j
== "!reverse") {
164 } else if (j
== "!default") {
168 istat
= (istat
&& cbi_d_checkvalue(j
, deps
[i
][j
]))
172 if (istat
^ reverse
) {
179 function cbi_d_update() {
181 for (var i
=0; i
<cbi_d
.length
; i
++) {
182 var entry
= cbi_d
[i
];
183 var node
= document
.getElementById(entry
.id
);
184 var parent
= document
.getElementById(entry
.parent
);
186 if (node
&& node
.parentNode
&& !cbi_d_check(entry
.deps
)) {
187 node
.parentNode
.removeChild(node
);
190 else if (parent
&& (!node
|| !node
.parentNode
) && cbi_d_check(entry
.deps
)) {
191 var next
= undefined;
193 for (next
= parent
.firstChild
; next
; next
= next
.nextSibling
) {
194 if (next
.getAttribute
&& parseInt(next
.getAttribute('data-index'), 10) > entry
.index
)
199 parent
.appendChild(entry
.node
);
201 parent
.insertBefore(entry
.node
, next
);
206 // hide optionals widget if no choices remaining
207 if (parent
&& parent
.parentNode
&& parent
.getAttribute('data-optionals'))
208 parent
.parentNode
.style
.display
= (parent
.options
.length
<= 1) ? 'none' : '';
211 if (entry
&& entry
.parent
)
212 cbi_tag_last(parent
);
217 parent
.dispatchEvent(new CustomEvent('dependency-update', { bubbles
: true }));
220 function cbi_init() {
223 document
.querySelectorAll('.cbi-dropdown').forEach(function(node
) {
224 cbi_dropdown_init(node
);
225 node
.addEventListener('cbi-dropdown-change', cbi_d_update
);
228 nodes
= document
.querySelectorAll('[data-strings]');
230 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
231 var str
= JSON
.parse(node
.getAttribute('data-strings'));
232 for (var key
in str
) {
233 for (var key2
in str
[key
]) {
234 var dst
= cbi_strings
[key
] || (cbi_strings
[key
] = { });
235 dst
[key2
] = str
[key
][key2
];
240 nodes
= document
.querySelectorAll('[data-depends]');
242 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
243 var index
= parseInt(node
.getAttribute('data-index'), 10);
244 var depends
= JSON
.parse(node
.getAttribute('data-depends'));
245 if (!isNaN(index
) && depends
.length
> 0) {
246 for (var alt
= 0; alt
< depends
.length
; alt
++)
247 cbi_d_add(node
, depends
[alt
], index
);
251 nodes
= document
.querySelectorAll('[data-update]');
253 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
254 var events
= node
.getAttribute('data-update').split(' ');
255 for (var j
= 0, event
; (event
= events
[j
]) !== undefined; j
++)
256 node
.addEventListener(event
, cbi_d_update
);
259 nodes
= document
.querySelectorAll('[data-choices]');
261 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
262 var choices
= JSON
.parse(node
.getAttribute('data-choices')),
265 for (var j
= 0; j
< choices
[0].length
; j
++)
266 options
[choices
[0][j
]] = choices
[1][j
];
268 var def
= (node
.getAttribute('data-optional') === 'true')
269 ? node
.placeholder
|| '' : null;
271 var cb
= new L
.ui
.Combobox(node
.value
, options
, {
272 name
: node
.getAttribute('name'),
274 select_placeholder
: def
|| _('-- Please choose --'),
275 custom_placeholder
: node
.getAttribute('data-manual') || _('-- custom --')
279 n
.addEventListener('cbi-dropdown-change', cbi_d_update
);
280 node
.parentNode
.replaceChild(n
, node
);
283 nodes
= document
.querySelectorAll('[data-dynlist]');
285 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
286 var choices
= JSON
.parse(node
.getAttribute('data-dynlist')),
287 values
= JSON
.parse(node
.getAttribute('data-values') || '[]'),
290 if (choices
[0] && choices
[0].length
) {
293 for (var j
= 0; j
< choices
[0].length
; j
++)
294 options
[choices
[0][j
]] = choices
[1][j
];
297 var dl
= new L
.ui
.DynamicList(values
, options
, {
298 name
: node
.getAttribute('data-prefix'),
300 datatype
: choices
[2],
301 optional
: choices
[3],
302 placeholder
: node
.getAttribute('data-placeholder')
306 n
.addEventListener('cbi-dynlist-change', cbi_d_update
);
307 node
.parentNode
.replaceChild(n
, node
);
310 nodes
= document
.querySelectorAll('[data-type]');
312 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
313 cbi_validate_field(node
, node
.getAttribute('data-optional') === 'true',
314 node
.getAttribute('data-type'));
317 document
.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s
) {
318 s
.parentNode
.classList
.add('cbi-tooltip-container');
321 document
.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i
) {
322 var handler = function(ev
) {
323 var bits
= this.name
.split(/\./),
324 section
= document
.getElementById('cbi-' + bits
[2] + '-' + bits
[3]);
326 section
.style
.opacity
= (ev
.type
=== 'mouseover') ? 0.5 : '';
329 i
.addEventListener('mouseover', handler
);
330 i
.addEventListener('mouseout', handler
);
335 document
.querySelectorAll('[data-ui-widget]').forEach(function(node
) {
336 var args
= JSON
.parse(node
.getAttribute('data-ui-widget') || '[]'),
337 widget
= new (Function
.prototype.bind
.apply(L
.ui
[args
[0]], args
)),
338 markup
= widget
.render();
340 tasks
.push(Promise
.resolve(markup
).then(function(markup
) {
341 markup
.addEventListener('widget-change', cbi_d_update
);
342 node
.parentNode
.replaceChild(markup
, node
);
346 Promise
.all(tasks
).then(cbi_d_update
);
349 function cbi_validate_form(form
, errmsg
)
351 /* if triggered by a section removal or addition, don't validate */
352 if (form
.cbi_state
== 'add-section' || form
.cbi_state
== 'del-section')
355 if (form
.cbi_validators
) {
356 for (var i
= 0; i
< form
.cbi_validators
.length
; i
++) {
357 var validator
= form
.cbi_validators
[i
];
359 if (!validator() && errmsg
) {
369 function cbi_validate_reset(form
)
372 function() { cbi_validate_form(form
, null) }, 100
378 function cbi_validate_field(cbid
, optional
, type
)
380 var field
= isElem(cbid
) ? cbid
: document
.getElementById(cbid
);
384 var cbiValidator
= L
.validation
.create(field
, type
, optional
);
385 validatorFn
= cbiValidator
.validate
.bind(cbiValidator
);
391 if (validatorFn
!== null) {
392 var form
= findParent(field
, 'form');
394 if (!form
.cbi_validators
)
395 form
.cbi_validators
= [ ];
397 form
.cbi_validators
.push(validatorFn
);
399 field
.addEventListener("blur", validatorFn
);
400 field
.addEventListener("keyup", validatorFn
);
401 field
.addEventListener("cbi-dropdown-change", validatorFn
);
403 if (matchesElem(field
, 'select')) {
404 field
.addEventListener("change", validatorFn
);
405 field
.addEventListener("click", validatorFn
);
412 function cbi_row_swap(elem
, up
, store
)
414 var tr
= findParent(elem
.parentNode
, '.cbi-section-table-row');
419 tr
.classList
.remove('flash');
422 var prev
= tr
.previousElementSibling
;
424 if (prev
&& prev
.classList
.contains('cbi-section-table-row'))
425 tr
.parentNode
.insertBefore(tr
, prev
);
430 var next
= tr
.nextElementSibling
? tr
.nextElementSibling
.nextElementSibling
: null;
432 if (next
&& next
.classList
.contains('cbi-section-table-row'))
433 tr
.parentNode
.insertBefore(tr
, next
);
435 tr
.parentNode
.appendChild(tr
);
442 for (var i
= 0, n
= 0; i
< tr
.parentNode
.childNodes
.length
; i
++) {
443 var node
= tr
.parentNode
.childNodes
[i
];
444 if (node
.classList
&& node
.classList
.contains('cbi-section-table-row')) {
445 node
.classList
.remove('cbi-rowstyle-1');
446 node
.classList
.remove('cbi-rowstyle-2');
447 node
.classList
.add((n
++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
449 if (/-([^\-]+)$/.test(node
.id
))
454 var input
= document
.getElementById(store
);
456 input
.value
= ids
.join(' ');
458 window
.scrollTo(0, tr
.offsetTop
);
460 tr
.classList
.add('flash');
465 function cbi_tag_last(container
)
469 for (var i
= 0; i
< container
.childNodes
.length
; i
++) {
470 var c
= container
.childNodes
[i
];
471 if (matchesElem(c
, 'div')) {
472 c
.classList
.remove('cbi-value-last');
478 last
.classList
.add('cbi-value-last');
481 function cbi_submit(elem
, name
, value
, action
)
483 var form
= elem
.form
|| findParent(elem
, 'form');
489 form
.action
= action
;
492 var hidden
= form
.querySelector('input[type="hidden"][name="%s"]'.format(name
)) ||
493 E('input', { type
: 'hidden', name
: name
});
495 hidden
.value
= value
|| '1';
496 form
.appendChild(hidden
);
503 String
.prototype.format = function()
508 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
509 var quot_esc = [/"/g
, '"', /'/g, '''];
512 if (typeof(s) !== 'string
' && !(s instanceof String))
515 for (var i = 0; i < r.length; i += 2)
516 s = s.replace(r[i], r[i+1]);
523 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
524 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
526 while (a
= re
.exec(str
)) {
528 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
529 var pPrecision
= a
[6], pType
= a
[7];
537 if (numSubstitutions
< arguments
.length
) {
538 var param
= arguments
[numSubstitutions
++];
541 if (pPad
&& pPad
.substr(0,1) == "'")
542 pad
= leftpart
.substr(1,1);
548 var justifyRight
= true;
549 if (pJustify
&& pJustify
=== "-")
550 justifyRight
= false;
554 minLength
= +pMinLength
;
557 if (pPrecision
&& pType
== 'f')
558 precision
= +pPrecision
.substring(1);
564 subst
= Math
.floor(+param
|| 0).toString(2);
568 subst
= String
.fromCharCode(+param
|| 0);
572 subst
= Math
.floor(+param
|| 0).toFixed(0);
577 subst
= Math
.floor((n
< 0) ? 0x100000000 + n
: n
).toFixed(0);
581 subst
= (precision
> -1)
582 ? ((+param
|| 0.0)).toFixed(precision
)
587 subst
= Math
.floor(+param
|| 0).toString(8);
595 subst
= Math
.floor(+param
|| 0).toString(16).toLowerCase();
599 subst
= Math
.floor(+param
|| 0).toString(16).toUpperCase();
603 subst
= esc(param
, html_esc
);
607 subst
= esc(param
, quot_esc
);
614 var ts
= (param
|| 0);
617 tm
= Math
.floor(ts
/ 60);
622 th
= Math
.floor(tm
/ 60);
627 td
= Math
.floor(th
/ 24);
632 ? String
.format('%dd %dh %dm %ds', td
, th
, tm
, ts
)
633 : String
.format('%dh %dm %ds', th
, tm
, ts
);
638 var mf
= pMinLength
? +pMinLength
: 1000;
639 var pr
= pPrecision
? ~~(10 * +('0' + pPrecision
)) : 2;
642 var val
= (+param
|| 0);
643 var units
= [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
645 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
648 subst
= (i
? val
.toFixed(pr
) : val
) + units
[i
];
656 subst
= subst
.toString();
657 for (var i
= subst
.length
; i
< pMinLength
; i
++)
664 out
+= leftpart
+ subst
;
665 str
= str
.substr(m
.length
);
671 String
.prototype.nobr = function()
673 return this.replace(/[\s\n]+/g, ' ');
676 String
.format = function()
680 for (var i
= 1; i
< arguments
.length
; i
++)
681 a
.push(arguments
[i
]);
683 return ''.format
.apply(arguments
[0], a
);
686 String
.nobr = function()
690 for (var i
= 1; i
< arguments
.length
; i
++)
691 a
.push(arguments
[i
]);
693 return ''.nobr
.apply(arguments
[0], a
);
696 if (window
.NodeList
&& !NodeList
.prototype.forEach
) {
697 NodeList
.prototype.forEach = function (callback
, thisArg
) {
698 thisArg
= thisArg
|| window
;
699 for (var i
= 0; i
< this.length
; i
++) {
700 callback
.call(thisArg
, this[i
], i
, this);
705 if (!window
.requestAnimationFrame
) {
706 window
.requestAnimationFrame = function(f
) {
707 window
.setTimeout(function() {
708 f(new Date().getTime())
714 function isElem(e
) { return L
.dom
.elem(e
) }
715 function toElem(s
) { return L
.dom
.parse(s
) }
716 function matchesElem(node
, selector
) { return L
.dom
.matches(node
, selector
) }
717 function findParent(node
, selector
) { return L
.dom
.parent(node
, selector
) }
718 function E() { return L
.dom
.create
.apply(L
.dom
, arguments
) }
720 if (typeof(window
.CustomEvent
) !== 'function') {
721 function CustomEvent(event
, params
) {
722 params
= params
|| { bubbles
: false, cancelable
: false, detail
: undefined };
723 var evt
= document
.createEvent('CustomEvent');
724 evt
.initCustomEvent( event
, params
.bubbles
, params
.cancelable
, params
.detail
);
728 CustomEvent
.prototype = window
.Event
.prototype;
729 window
.CustomEvent
= CustomEvent
;
732 function cbi_dropdown_init(sb
) {
733 var dl
= new L
.ui
.Dropdown(sb
, null, { name
: sb
.getAttribute('name') });
737 function cbi_update_table(table
, data
, placeholder
) {
738 var target
= isElem(table
) ? table
: document
.querySelector(table
);
743 target
.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead
) {
746 thead
.querySelectorAll('.th').forEach(function(th
) {
750 if (Array
.isArray(data
)) {
751 var n
= 0, rows
= target
.querySelectorAll('.tr');
753 data
.forEach(function(row
) {
754 var trow
= E('div', { 'class': 'tr' });
756 for (var i
= 0; i
< titles
.length
; i
++) {
757 var text
= (titles
[i
].innerText
|| '').trim();
758 var td
= trow
.appendChild(E('div', {
759 'class': titles
[i
].className
,
760 'data-title': (text
!== '') ? text
: null
763 td
.classList
.remove('th');
764 td
.classList
.add('td');
767 trow
.classList
.add('cbi-rowstyle-%d'.format((n
++ % 2) ? 2 : 1));
770 target
.replaceChild(trow
, rows
[n
]);
772 target
.appendChild(trow
);
776 target
.removeChild(rows
[n
]);
778 if (placeholder
&& target
.firstElementChild
=== target
.lastElementChild
) {
779 var trow
= target
.appendChild(E('div', { 'class': 'tr placeholder' }));
780 var td
= trow
.appendChild(E('div', { 'class': titles
[0].className
}, placeholder
));
782 td
.classList
.remove('th');
783 td
.classList
.add('td');
787 thead
.parentNode
.style
.display
= 'none';
789 thead
.parentNode
.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow
) {
790 if (trow
!== thead
) {
792 trow
.querySelectorAll('.th, .td').forEach(function(td
) {
793 if (n
< titles
.length
) {
794 var text
= (titles
[n
++].innerText
|| '').trim();
796 td
.setAttribute('data-title', text
);
802 thead
.parentNode
.style
.display
= '';
807 function showModal(title
, children
)
809 return L
.showModal(title
, children
);
814 return L
.hideModal();
818 document
.addEventListener('DOMContentLoaded', function() {
819 document
.addEventListener('validation-failure', function(ev
) {
820 if (ev
.target
=== document
.activeElement
)
824 document
.addEventListener('validation-success', function(ev
) {
825 if (ev
.target
=== document
.activeElement
)
829 document
.querySelectorAll('.table').forEach(cbi_update_table
);