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 var k
= (c
!= null ? trimws(c
) + '\u0001' : '') + trimws(s
);
105 return (window
.TR
&& TR
[sfh(k
)]) || s
;
108 function N_(n
, s
, p
, c
) {
109 if (plural_function
== null && window
.TR
)
110 plural_function
= new Function('n', (TR
['00000000'] || 'plural=(n != 1);') + 'return +plural');
112 var i
= plural_function
? plural_function(n
) : (n
!= 1),
113 k
= (c
!= null ? trimws(c
) + '\u0001' : '') + trimws(s
) + '\u0002' + i
.toString();
115 return (window
.TR
&& TR
[sfh(k
)]) || (i
? p
: s
);
119 function cbi_d_add(field
, dep
, index
) {
120 var obj
= (typeof(field
) === 'string') ? document
.getElementById(field
) : field
;
123 for (var i
=0; i
<cbi_d
.length
; i
++) {
124 if (cbi_d
[i
].id
== obj
.id
) {
133 "parent": obj
.parentNode
.id
,
137 cbi_d
.unshift(entry
);
143 function cbi_d_checkvalue(target
, ref
) {
145 query
= 'input[id="'+target
+'"], input[name="'+target
+'"], ' +
146 'select[id="'+target
+'"], select[name="'+target
+'"]';
148 document
.querySelectorAll(query
).forEach(function(i
) {
149 if (value
=== null && ((i
.type
!== 'radio' && i
.type
!== 'checkbox') || i
.checked
=== true))
153 return (((value
!== null) ? value
: "") == ref
);
156 function cbi_d_check(deps
) {
159 for (var i
=0; i
<deps
.length
; i
++) {
162 for (var j
in deps
[i
]) {
163 if (j
== "!reverse") {
165 } else if (j
== "!default") {
169 istat
= (istat
&& cbi_d_checkvalue(j
, deps
[i
][j
]))
173 if (istat
^ reverse
) {
180 function cbi_d_update() {
182 for (var i
=0; i
<cbi_d
.length
; i
++) {
183 var entry
= cbi_d
[i
];
184 var node
= document
.getElementById(entry
.id
);
185 var parent
= document
.getElementById(entry
.parent
);
187 if (node
&& node
.parentNode
&& !cbi_d_check(entry
.deps
)) {
188 node
.parentNode
.removeChild(node
);
191 else if (parent
&& (!node
|| !node
.parentNode
) && cbi_d_check(entry
.deps
)) {
192 var next
= undefined;
194 for (next
= parent
.firstChild
; next
; next
= next
.nextSibling
) {
195 if (next
.getAttribute
&& parseInt(next
.getAttribute('data-index'), 10) > entry
.index
)
200 parent
.appendChild(entry
.node
);
202 parent
.insertBefore(entry
.node
, next
);
207 // hide optionals widget if no choices remaining
208 if (parent
&& parent
.parentNode
&& parent
.getAttribute('data-optionals'))
209 parent
.parentNode
.style
.display
= (parent
.options
.length
<= 1) ? 'none' : '';
212 if (entry
&& entry
.parent
)
213 cbi_tag_last(parent
);
218 parent
.dispatchEvent(new CustomEvent('dependency-update', { bubbles
: true }));
221 function cbi_init() {
224 document
.querySelectorAll('.cbi-dropdown').forEach(function(node
) {
225 cbi_dropdown_init(node
);
226 node
.addEventListener('cbi-dropdown-change', cbi_d_update
);
229 nodes
= document
.querySelectorAll('[data-strings]');
231 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
232 var str
= JSON
.parse(node
.getAttribute('data-strings'));
233 for (var key
in str
) {
234 for (var key2
in str
[key
]) {
235 var dst
= cbi_strings
[key
] || (cbi_strings
[key
] = { });
236 dst
[key2
] = str
[key
][key2
];
241 nodes
= document
.querySelectorAll('[data-depends]');
243 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
244 var index
= parseInt(node
.getAttribute('data-index'), 10);
245 var depends
= JSON
.parse(node
.getAttribute('data-depends'));
246 if (!isNaN(index
) && depends
.length
> 0) {
247 for (var alt
= 0; alt
< depends
.length
; alt
++)
248 cbi_d_add(node
, depends
[alt
], index
);
252 nodes
= document
.querySelectorAll('[data-update]');
254 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
255 var events
= node
.getAttribute('data-update').split(' ');
256 for (var j
= 0, event
; (event
= events
[j
]) !== undefined; j
++)
257 node
.addEventListener(event
, cbi_d_update
);
260 nodes
= document
.querySelectorAll('[data-choices]');
262 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
263 var choices
= JSON
.parse(node
.getAttribute('data-choices')),
266 for (var j
= 0; j
< choices
[0].length
; j
++)
267 options
[choices
[0][j
]] = choices
[1][j
];
269 var def
= (node
.getAttribute('data-optional') === 'true')
270 ? node
.placeholder
|| '' : null;
272 var cb
= new L
.ui
.Combobox(node
.value
, options
, {
273 name
: node
.getAttribute('name'),
275 select_placeholder
: def
|| _('-- Please choose --'),
276 custom_placeholder
: node
.getAttribute('data-manual') || _('-- custom --')
280 n
.addEventListener('cbi-dropdown-change', cbi_d_update
);
281 node
.parentNode
.replaceChild(n
, node
);
284 nodes
= document
.querySelectorAll('[data-dynlist]');
286 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
287 var choices
= JSON
.parse(node
.getAttribute('data-dynlist')),
288 values
= JSON
.parse(node
.getAttribute('data-values') || '[]'),
291 if (choices
[0] && choices
[0].length
) {
294 for (var j
= 0; j
< choices
[0].length
; j
++)
295 options
[choices
[0][j
]] = choices
[1][j
];
298 var dl
= new L
.ui
.DynamicList(values
, options
, {
299 name
: node
.getAttribute('data-prefix'),
301 datatype
: choices
[2],
302 optional
: choices
[3],
303 placeholder
: node
.getAttribute('data-placeholder')
307 n
.addEventListener('cbi-dynlist-change', cbi_d_update
);
308 node
.parentNode
.replaceChild(n
, node
);
311 nodes
= document
.querySelectorAll('[data-type]');
313 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
314 cbi_validate_field(node
, node
.getAttribute('data-optional') === 'true',
315 node
.getAttribute('data-type'));
318 document
.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s
) {
319 s
.parentNode
.classList
.add('cbi-tooltip-container');
322 document
.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i
) {
323 var handler = function(ev
) {
324 var bits
= this.name
.split(/\./),
325 section
= document
.getElementById('cbi-' + bits
[2] + '-' + bits
[3]);
327 section
.style
.opacity
= (ev
.type
=== 'mouseover') ? 0.5 : '';
330 i
.addEventListener('mouseover', handler
);
331 i
.addEventListener('mouseout', handler
);
336 document
.querySelectorAll('[data-ui-widget]').forEach(function(node
) {
337 var args
= JSON
.parse(node
.getAttribute('data-ui-widget') || '[]'),
338 widget
= new (Function
.prototype.bind
.apply(L
.ui
[args
[0]], args
)),
339 markup
= widget
.render();
341 tasks
.push(Promise
.resolve(markup
).then(function(markup
) {
342 markup
.addEventListener('widget-change', cbi_d_update
);
343 node
.parentNode
.replaceChild(markup
, node
);
347 Promise
.all(tasks
).then(cbi_d_update
);
350 function cbi_validate_form(form
, errmsg
)
352 /* if triggered by a section removal or addition, don't validate */
353 if (form
.cbi_state
== 'add-section' || form
.cbi_state
== 'del-section')
356 if (form
.cbi_validators
) {
357 for (var i
= 0; i
< form
.cbi_validators
.length
; i
++) {
358 var validator
= form
.cbi_validators
[i
];
360 if (!validator() && errmsg
) {
370 function cbi_validate_reset(form
)
373 function() { cbi_validate_form(form
, null) }, 100
379 function cbi_validate_field(cbid
, optional
, type
)
381 var field
= isElem(cbid
) ? cbid
: document
.getElementById(cbid
);
385 var cbiValidator
= L
.validation
.create(field
, type
, optional
);
386 validatorFn
= cbiValidator
.validate
.bind(cbiValidator
);
392 if (validatorFn
!== null) {
393 var form
= findParent(field
, 'form');
395 if (!form
.cbi_validators
)
396 form
.cbi_validators
= [ ];
398 form
.cbi_validators
.push(validatorFn
);
400 field
.addEventListener("blur", validatorFn
);
401 field
.addEventListener("keyup", validatorFn
);
402 field
.addEventListener("cbi-dropdown-change", validatorFn
);
404 if (matchesElem(field
, 'select')) {
405 field
.addEventListener("change", validatorFn
);
406 field
.addEventListener("click", validatorFn
);
413 function cbi_row_swap(elem
, up
, store
)
415 var tr
= findParent(elem
.parentNode
, '.cbi-section-table-row');
420 tr
.classList
.remove('flash');
423 var prev
= tr
.previousElementSibling
;
425 if (prev
&& prev
.classList
.contains('cbi-section-table-row'))
426 tr
.parentNode
.insertBefore(tr
, prev
);
431 var next
= tr
.nextElementSibling
? tr
.nextElementSibling
.nextElementSibling
: null;
433 if (next
&& next
.classList
.contains('cbi-section-table-row'))
434 tr
.parentNode
.insertBefore(tr
, next
);
436 tr
.parentNode
.appendChild(tr
);
443 for (var i
= 0, n
= 0; i
< tr
.parentNode
.childNodes
.length
; i
++) {
444 var node
= tr
.parentNode
.childNodes
[i
];
445 if (node
.classList
&& node
.classList
.contains('cbi-section-table-row')) {
446 node
.classList
.remove('cbi-rowstyle-1');
447 node
.classList
.remove('cbi-rowstyle-2');
448 node
.classList
.add((n
++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
450 if (/-([^\-]+)$/.test(node
.id
))
455 var input
= document
.getElementById(store
);
457 input
.value
= ids
.join(' ');
459 window
.scrollTo(0, tr
.offsetTop
);
461 tr
.classList
.add('flash');
466 function cbi_tag_last(container
)
470 for (var i
= 0; i
< container
.childNodes
.length
; i
++) {
471 var c
= container
.childNodes
[i
];
472 if (matchesElem(c
, 'div')) {
473 c
.classList
.remove('cbi-value-last');
479 last
.classList
.add('cbi-value-last');
482 function cbi_submit(elem
, name
, value
, action
)
484 var form
= elem
.form
|| findParent(elem
, 'form');
490 form
.action
= action
;
493 var hidden
= form
.querySelector('input[type="hidden"][name="%s"]'.format(name
)) ||
494 E('input', { type
: 'hidden', name
: name
});
496 hidden
.value
= value
|| '1';
497 form
.appendChild(hidden
);
504 String
.prototype.format = function()
509 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
510 var quot_esc = [/"/g
, '"', /'/g, '''];
513 if (typeof(s) !== 'string
' && !(s instanceof String))
516 for (var i = 0; i < r.length; i += 2)
517 s = s.replace(r[i], r[i+1]);
524 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
525 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
527 while (a
= re
.exec(str
)) {
529 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
530 var pPrecision
= a
[6], pType
= a
[7];
538 if (numSubstitutions
< arguments
.length
) {
539 var param
= arguments
[numSubstitutions
++];
542 if (pPad
&& pPad
.substr(0,1) == "'")
543 pad
= leftpart
.substr(1,1);
549 var justifyRight
= true;
550 if (pJustify
&& pJustify
=== "-")
551 justifyRight
= false;
555 minLength
= +pMinLength
;
558 if (pPrecision
&& pType
== 'f')
559 precision
= +pPrecision
.substring(1);
565 subst
= Math
.floor(+param
|| 0).toString(2);
569 subst
= String
.fromCharCode(+param
|| 0);
573 subst
= Math
.floor(+param
|| 0).toFixed(0);
578 subst
= Math
.floor((n
< 0) ? 0x100000000 + n
: n
).toFixed(0);
582 subst
= (precision
> -1)
583 ? ((+param
|| 0.0)).toFixed(precision
)
588 subst
= Math
.floor(+param
|| 0).toString(8);
596 subst
= Math
.floor(+param
|| 0).toString(16).toLowerCase();
600 subst
= Math
.floor(+param
|| 0).toString(16).toUpperCase();
604 subst
= esc(param
, html_esc
);
608 subst
= esc(param
, quot_esc
);
615 var ts
= (param
|| 0);
618 tm
= Math
.floor(ts
/ 60);
623 th
= Math
.floor(tm
/ 60);
628 td
= Math
.floor(th
/ 24);
633 ? String
.format('%dd %dh %dm %ds', td
, th
, tm
, ts
)
634 : String
.format('%dh %dm %ds', th
, tm
, ts
);
639 var mf
= pMinLength
? +pMinLength
: 1000;
640 var pr
= pPrecision
? ~~(10 * +('0' + pPrecision
)) : 2;
643 var val
= (+param
|| 0);
644 var units
= [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
646 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
649 subst
= (i
? val
.toFixed(pr
) : val
) + units
[i
];
657 subst
= subst
.toString();
658 for (var i
= subst
.length
; i
< pMinLength
; i
++)
665 out
+= leftpart
+ subst
;
666 str
= str
.substr(m
.length
);
672 String
.prototype.nobr = function()
674 return this.replace(/[\s\n]+/g, ' ');
677 String
.format = function()
681 for (var i
= 1; i
< arguments
.length
; i
++)
682 a
.push(arguments
[i
]);
684 return ''.format
.apply(arguments
[0], a
);
687 String
.nobr = function()
691 for (var i
= 1; i
< arguments
.length
; i
++)
692 a
.push(arguments
[i
]);
694 return ''.nobr
.apply(arguments
[0], a
);
697 if (window
.NodeList
&& !NodeList
.prototype.forEach
) {
698 NodeList
.prototype.forEach = function (callback
, thisArg
) {
699 thisArg
= thisArg
|| window
;
700 for (var i
= 0; i
< this.length
; i
++) {
701 callback
.call(thisArg
, this[i
], i
, this);
706 if (!window
.requestAnimationFrame
) {
707 window
.requestAnimationFrame = function(f
) {
708 window
.setTimeout(function() {
709 f(new Date().getTime())
715 function isElem(e
) { return L
.dom
.elem(e
) }
716 function toElem(s
) { return L
.dom
.parse(s
) }
717 function matchesElem(node
, selector
) { return L
.dom
.matches(node
, selector
) }
718 function findParent(node
, selector
) { return L
.dom
.parent(node
, selector
) }
719 function E() { return L
.dom
.create
.apply(L
.dom
, arguments
) }
721 if (typeof(window
.CustomEvent
) !== 'function') {
722 function CustomEvent(event
, params
) {
723 params
= params
|| { bubbles
: false, cancelable
: false, detail
: undefined };
724 var evt
= document
.createEvent('CustomEvent');
725 evt
.initCustomEvent( event
, params
.bubbles
, params
.cancelable
, params
.detail
);
729 CustomEvent
.prototype = window
.Event
.prototype;
730 window
.CustomEvent
= CustomEvent
;
733 function cbi_dropdown_init(sb
) {
734 var dl
= new L
.ui
.Dropdown(sb
, null, { name
: sb
.getAttribute('name') });
738 function cbi_update_table(table
, data
, placeholder
) {
739 var target
= isElem(table
) ? table
: document
.querySelector(table
);
744 target
.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead
) {
747 thead
.querySelectorAll('.th').forEach(function(th
) {
751 if (Array
.isArray(data
)) {
752 var n
= 0, rows
= target
.querySelectorAll('.tr');
754 data
.forEach(function(row
) {
755 var trow
= E('div', { 'class': 'tr' });
757 for (var i
= 0; i
< titles
.length
; i
++) {
758 var text
= (titles
[i
].innerText
|| '').trim();
759 var td
= trow
.appendChild(E('div', {
760 'class': titles
[i
].className
,
761 'data-title': (text
!== '') ? text
: null
764 td
.classList
.remove('th');
765 td
.classList
.add('td');
768 trow
.classList
.add('cbi-rowstyle-%d'.format((n
++ % 2) ? 2 : 1));
771 target
.replaceChild(trow
, rows
[n
]);
773 target
.appendChild(trow
);
777 target
.removeChild(rows
[n
]);
779 if (placeholder
&& target
.firstElementChild
=== target
.lastElementChild
) {
780 var trow
= target
.appendChild(E('div', { 'class': 'tr placeholder' }));
781 var td
= trow
.appendChild(E('div', { 'class': titles
[0].className
}, placeholder
));
783 td
.classList
.remove('th');
784 td
.classList
.add('td');
788 thead
.parentNode
.style
.display
= 'none';
790 thead
.parentNode
.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow
) {
791 if (trow
!== thead
) {
793 trow
.querySelectorAll('.th, .td').forEach(function(td
) {
794 if (n
< titles
.length
) {
795 var text
= (titles
[n
++].innerText
|| '').trim();
797 td
.setAttribute('data-title', text
);
803 thead
.parentNode
.style
.display
= '';
808 function showModal(title
, children
)
810 return L
.showModal(title
, children
);
815 return L
.hideModal();
819 document
.addEventListener('DOMContentLoaded', function() {
820 document
.addEventListener('validation-failure', function(ev
) {
821 if (ev
.target
=== document
.activeElement
)
825 document
.addEventListener('validation-success', function(ev
) {
826 if (ev
.target
=== document
.activeElement
)
830 document
.querySelectorAll('.table').forEach(cbi_update_table
);