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 function cbi_d_add(field
, dep
, index
) {
103 var obj
= (typeof(field
) === 'string') ? document
.getElementById(field
) : field
;
106 for (var i
=0; i
<cbi_d
.length
; i
++) {
107 if (cbi_d
[i
].id
== obj
.id
) {
116 "parent": obj
.parentNode
.id
,
120 cbi_d
.unshift(entry
);
126 function cbi_d_checkvalue(target
, ref
) {
128 query
= 'input[id="'+target
+'"], input[name="'+target
+'"], ' +
129 'select[id="'+target
+'"], select[name="'+target
+'"]';
131 document
.querySelectorAll(query
).forEach(function(i
) {
132 if (value
=== null && ((i
.type
!== 'radio' && i
.type
!== 'checkbox') || i
.checked
=== true))
136 return (((value
!== null) ? value
: "") == ref
);
139 function cbi_d_check(deps
) {
142 for (var i
=0; i
<deps
.length
; i
++) {
145 for (var j
in deps
[i
]) {
146 if (j
== "!reverse") {
148 } else if (j
== "!default") {
152 istat
= (istat
&& cbi_d_checkvalue(j
, deps
[i
][j
]))
156 if (istat
^ reverse
) {
163 function cbi_d_update() {
165 for (var i
=0; i
<cbi_d
.length
; i
++) {
166 var entry
= cbi_d
[i
];
167 var node
= document
.getElementById(entry
.id
);
168 var parent
= document
.getElementById(entry
.parent
);
170 if (node
&& node
.parentNode
&& !cbi_d_check(entry
.deps
)) {
171 node
.parentNode
.removeChild(node
);
174 else if (parent
&& (!node
|| !node
.parentNode
) && cbi_d_check(entry
.deps
)) {
175 var next
= undefined;
177 for (next
= parent
.firstChild
; next
; next
= next
.nextSibling
) {
178 if (next
.getAttribute
&& parseInt(next
.getAttribute('data-index'), 10) > entry
.index
)
183 parent
.appendChild(entry
.node
);
185 parent
.insertBefore(entry
.node
, next
);
190 // hide optionals widget if no choices remaining
191 if (parent
&& parent
.parentNode
&& parent
.getAttribute('data-optionals'))
192 parent
.parentNode
.style
.display
= (parent
.options
.length
<= 1) ? 'none' : '';
195 if (entry
&& entry
.parent
)
196 cbi_tag_last(parent
);
201 parent
.dispatchEvent(new CustomEvent('dependency-update', { bubbles
: true }));
204 function cbi_init() {
207 document
.querySelectorAll('.cbi-dropdown').forEach(function(node
) {
208 cbi_dropdown_init(node
);
209 node
.addEventListener('cbi-dropdown-change', cbi_d_update
);
212 nodes
= document
.querySelectorAll('[data-strings]');
214 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
215 var str
= JSON
.parse(node
.getAttribute('data-strings'));
216 for (var key
in str
) {
217 for (var key2
in str
[key
]) {
218 var dst
= cbi_strings
[key
] || (cbi_strings
[key
] = { });
219 dst
[key2
] = str
[key
][key2
];
224 nodes
= document
.querySelectorAll('[data-depends]');
226 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
227 var index
= parseInt(node
.getAttribute('data-index'), 10);
228 var depends
= JSON
.parse(node
.getAttribute('data-depends'));
229 if (!isNaN(index
) && depends
.length
> 0) {
230 for (var alt
= 0; alt
< depends
.length
; alt
++)
231 cbi_d_add(node
, depends
[alt
], index
);
235 nodes
= document
.querySelectorAll('[data-update]');
237 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
238 var events
= node
.getAttribute('data-update').split(' ');
239 for (var j
= 0, event
; (event
= events
[j
]) !== undefined; j
++)
240 node
.addEventListener(event
, cbi_d_update
);
243 nodes
= document
.querySelectorAll('[data-choices]');
245 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
246 var choices
= JSON
.parse(node
.getAttribute('data-choices')),
249 for (var j
= 0; j
< choices
[0].length
; j
++)
250 options
[choices
[0][j
]] = choices
[1][j
];
252 var def
= (node
.getAttribute('data-optional') === 'true')
253 ? node
.placeholder
|| '' : null;
255 var cb
= new L
.ui
.Combobox(node
.value
, options
, {
256 name
: node
.getAttribute('name'),
258 select_placeholder
: def
|| _('-- Please choose --'),
259 custom_placeholder
: node
.getAttribute('data-manual') || _('-- custom --')
263 n
.addEventListener('cbi-dropdown-change', cbi_d_update
);
264 node
.parentNode
.replaceChild(n
, node
);
267 nodes
= document
.querySelectorAll('[data-dynlist]');
269 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
270 var choices
= JSON
.parse(node
.getAttribute('data-dynlist')),
271 values
= JSON
.parse(node
.getAttribute('data-values') || '[]'),
274 if (choices
[0] && choices
[0].length
) {
277 for (var j
= 0; j
< choices
[0].length
; j
++)
278 options
[choices
[0][j
]] = choices
[1][j
];
281 var dl
= new L
.ui
.DynamicList(values
, options
, {
282 name
: node
.getAttribute('data-prefix'),
284 datatype
: choices
[2],
285 optional
: choices
[3],
286 placeholder
: node
.getAttribute('data-placeholder')
290 n
.addEventListener('cbi-dynlist-change', cbi_d_update
);
291 node
.parentNode
.replaceChild(n
, node
);
294 nodes
= document
.querySelectorAll('[data-type]');
296 for (var i
= 0, node
; (node
= nodes
[i
]) !== undefined; i
++) {
297 cbi_validate_field(node
, node
.getAttribute('data-optional') === 'true',
298 node
.getAttribute('data-type'));
301 document
.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s
) {
302 s
.parentNode
.classList
.add('cbi-tooltip-container');
305 document
.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i
) {
306 var handler = function(ev
) {
307 var bits
= this.name
.split(/\./),
308 section
= document
.getElementById('cbi-' + bits
[2] + '-' + bits
[3]);
310 section
.style
.opacity
= (ev
.type
=== 'mouseover') ? 0.5 : '';
313 i
.addEventListener('mouseover', handler
);
314 i
.addEventListener('mouseout', handler
);
319 document
.querySelectorAll('[data-ui-widget]').forEach(function(node
) {
320 var args
= JSON
.parse(node
.getAttribute('data-ui-widget') || '[]'),
321 widget
= new (Function
.prototype.bind
.apply(L
.ui
[args
[0]], args
)),
322 markup
= widget
.render();
324 tasks
.push(Promise
.resolve(markup
).then(function(markup
) {
325 markup
.addEventListener('widget-change', cbi_d_update
);
326 node
.parentNode
.replaceChild(markup
, node
);
330 Promise
.all(tasks
).then(cbi_d_update
);
333 function cbi_validate_form(form
, errmsg
)
335 /* if triggered by a section removal or addition, don't validate */
336 if (form
.cbi_state
== 'add-section' || form
.cbi_state
== 'del-section')
339 if (form
.cbi_validators
) {
340 for (var i
= 0; i
< form
.cbi_validators
.length
; i
++) {
341 var validator
= form
.cbi_validators
[i
];
343 if (!validator() && errmsg
) {
353 function cbi_validate_reset(form
)
356 function() { cbi_validate_form(form
, null) }, 100
362 function cbi_validate_field(cbid
, optional
, type
)
364 var field
= isElem(cbid
) ? cbid
: document
.getElementById(cbid
);
368 var cbiValidator
= L
.validation
.create(field
, type
, optional
);
369 validatorFn
= cbiValidator
.validate
.bind(cbiValidator
);
375 if (validatorFn
!== null) {
376 var form
= findParent(field
, 'form');
378 if (!form
.cbi_validators
)
379 form
.cbi_validators
= [ ];
381 form
.cbi_validators
.push(validatorFn
);
383 field
.addEventListener("blur", validatorFn
);
384 field
.addEventListener("keyup", validatorFn
);
385 field
.addEventListener("cbi-dropdown-change", validatorFn
);
387 if (matchesElem(field
, 'select')) {
388 field
.addEventListener("change", validatorFn
);
389 field
.addEventListener("click", validatorFn
);
396 function cbi_row_swap(elem
, up
, store
)
398 var tr
= findParent(elem
.parentNode
, '.cbi-section-table-row');
403 tr
.classList
.remove('flash');
406 var prev
= tr
.previousElementSibling
;
408 if (prev
&& prev
.classList
.contains('cbi-section-table-row'))
409 tr
.parentNode
.insertBefore(tr
, prev
);
414 var next
= tr
.nextElementSibling
? tr
.nextElementSibling
.nextElementSibling
: null;
416 if (next
&& next
.classList
.contains('cbi-section-table-row'))
417 tr
.parentNode
.insertBefore(tr
, next
);
419 tr
.parentNode
.appendChild(tr
);
426 for (var i
= 0, n
= 0; i
< tr
.parentNode
.childNodes
.length
; i
++) {
427 var node
= tr
.parentNode
.childNodes
[i
];
428 if (node
.classList
&& node
.classList
.contains('cbi-section-table-row')) {
429 node
.classList
.remove('cbi-rowstyle-1');
430 node
.classList
.remove('cbi-rowstyle-2');
431 node
.classList
.add((n
++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
433 if (/-([^\-]+)$/.test(node
.id
))
438 var input
= document
.getElementById(store
);
440 input
.value
= ids
.join(' ');
442 window
.scrollTo(0, tr
.offsetTop
);
444 tr
.classList
.add('flash');
449 function cbi_tag_last(container
)
453 for (var i
= 0; i
< container
.childNodes
.length
; i
++) {
454 var c
= container
.childNodes
[i
];
455 if (matchesElem(c
, 'div')) {
456 c
.classList
.remove('cbi-value-last');
462 last
.classList
.add('cbi-value-last');
465 function cbi_submit(elem
, name
, value
, action
)
467 var form
= elem
.form
|| findParent(elem
, 'form');
473 form
.action
= action
;
476 var hidden
= form
.querySelector('input[type="hidden"][name="%s"]'.format(name
)) ||
477 E('input', { type
: 'hidden', name
: name
});
479 hidden
.value
= value
|| '1';
480 form
.appendChild(hidden
);
487 String
.prototype.format = function()
492 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
493 var quot_esc = [/"/g
, '"', /'/g, '''];
496 if (typeof(s) !== 'string
' && !(s instanceof String))
499 for (var i = 0; i < r.length; i += 2)
500 s = s.replace(r[i], r[i+1]);
507 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
508 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
510 while (a
= re
.exec(str
)) {
512 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
513 var pPrecision
= a
[6], pType
= a
[7];
521 if (numSubstitutions
< arguments
.length
) {
522 var param
= arguments
[numSubstitutions
++];
525 if (pPad
&& pPad
.substr(0,1) == "'")
526 pad
= leftpart
.substr(1,1);
532 var justifyRight
= true;
533 if (pJustify
&& pJustify
=== "-")
534 justifyRight
= false;
538 minLength
= +pMinLength
;
541 if (pPrecision
&& pType
== 'f')
542 precision
= +pPrecision
.substring(1);
548 subst
= Math
.floor(+param
|| 0).toString(2);
552 subst
= String
.fromCharCode(+param
|| 0);
556 subst
= Math
.floor(+param
|| 0).toFixed(0);
561 subst
= Math
.floor((n
< 0) ? 0x100000000 + n
: n
).toFixed(0);
565 subst
= (precision
> -1)
566 ? ((+param
|| 0.0)).toFixed(precision
)
571 subst
= Math
.floor(+param
|| 0).toString(8);
579 subst
= Math
.floor(+param
|| 0).toString(16).toLowerCase();
583 subst
= Math
.floor(+param
|| 0).toString(16).toUpperCase();
587 subst
= esc(param
, html_esc
);
591 subst
= esc(param
, quot_esc
);
598 var ts
= (param
|| 0);
601 tm
= Math
.floor(ts
/ 60);
606 th
= Math
.floor(tm
/ 60);
611 td
= Math
.floor(th
/ 24);
616 ? String
.format('%dd %dh %dm %ds', td
, th
, tm
, ts
)
617 : String
.format('%dh %dm %ds', th
, tm
, ts
);
622 var mf
= pMinLength
? +pMinLength
: 1000;
623 var pr
= pPrecision
? ~~(10 * +('0' + pPrecision
)) : 2;
626 var val
= (+param
|| 0);
627 var units
= [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
629 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
632 subst
= (i
? val
.toFixed(pr
) : val
) + units
[i
];
640 subst
= subst
.toString();
641 for (var i
= subst
.length
; i
< pMinLength
; i
++)
648 out
+= leftpart
+ subst
;
649 str
= str
.substr(m
.length
);
655 String
.prototype.nobr = function()
657 return this.replace(/[\s\n]+/g, ' ');
660 String
.format = function()
664 for (var i
= 1; i
< arguments
.length
; i
++)
665 a
.push(arguments
[i
]);
667 return ''.format
.apply(arguments
[0], a
);
670 String
.nobr = function()
674 for (var i
= 1; i
< arguments
.length
; i
++)
675 a
.push(arguments
[i
]);
677 return ''.nobr
.apply(arguments
[0], a
);
680 if (window
.NodeList
&& !NodeList
.prototype.forEach
) {
681 NodeList
.prototype.forEach = function (callback
, thisArg
) {
682 thisArg
= thisArg
|| window
;
683 for (var i
= 0; i
< this.length
; i
++) {
684 callback
.call(thisArg
, this[i
], i
, this);
689 if (!window
.requestAnimationFrame
) {
690 window
.requestAnimationFrame = function(f
) {
691 window
.setTimeout(function() {
692 f(new Date().getTime())
698 function isElem(e
) { return L
.dom
.elem(e
) }
699 function toElem(s
) { return L
.dom
.parse(s
) }
700 function matchesElem(node
, selector
) { return L
.dom
.matches(node
, selector
) }
701 function findParent(node
, selector
) { return L
.dom
.parent(node
, selector
) }
702 function E() { return L
.dom
.create
.apply(L
.dom
, arguments
) }
704 if (typeof(window
.CustomEvent
) !== 'function') {
705 function CustomEvent(event
, params
) {
706 params
= params
|| { bubbles
: false, cancelable
: false, detail
: undefined };
707 var evt
= document
.createEvent('CustomEvent');
708 evt
.initCustomEvent( event
, params
.bubbles
, params
.cancelable
, params
.detail
);
712 CustomEvent
.prototype = window
.Event
.prototype;
713 window
.CustomEvent
= CustomEvent
;
716 function cbi_dropdown_init(sb
) {
717 var dl
= new L
.ui
.Dropdown(sb
, null, { name
: sb
.getAttribute('name') });
721 function cbi_update_table(table
, data
, placeholder
) {
722 var target
= isElem(table
) ? table
: document
.querySelector(table
);
727 target
.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead
) {
730 thead
.querySelectorAll('.th').forEach(function(th
) {
734 if (Array
.isArray(data
)) {
735 var n
= 0, rows
= target
.querySelectorAll('.tr');
737 data
.forEach(function(row
) {
738 var trow
= E('div', { 'class': 'tr' });
740 for (var i
= 0; i
< titles
.length
; i
++) {
741 var text
= (titles
[i
].innerText
|| '').trim();
742 var td
= trow
.appendChild(E('div', {
743 'class': titles
[i
].className
,
744 'data-title': (text
!== '') ? text
: null
747 td
.classList
.remove('th');
748 td
.classList
.add('td');
751 trow
.classList
.add('cbi-rowstyle-%d'.format((n
++ % 2) ? 2 : 1));
754 target
.replaceChild(trow
, rows
[n
]);
756 target
.appendChild(trow
);
760 target
.removeChild(rows
[n
]);
762 if (placeholder
&& target
.firstElementChild
=== target
.lastElementChild
) {
763 var trow
= target
.appendChild(E('div', { 'class': 'tr placeholder' }));
764 var td
= trow
.appendChild(E('div', { 'class': titles
[0].className
}, placeholder
));
766 td
.classList
.remove('th');
767 td
.classList
.add('td');
771 thead
.parentNode
.style
.display
= 'none';
773 thead
.parentNode
.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow
) {
774 if (trow
!== thead
) {
776 trow
.querySelectorAll('.th, .td').forEach(function(td
) {
777 if (n
< titles
.length
) {
778 var text
= (titles
[n
++].innerText
|| '').trim();
780 td
.setAttribute('data-title', text
);
786 thead
.parentNode
.style
.display
= '';
791 function showModal(title
, children
)
793 return L
.showModal(title
, children
);
798 return L
.hideModal();
802 document
.addEventListener('DOMContentLoaded', function() {
803 document
.addEventListener('validation-failure', function(ev
) {
804 if (ev
.target
=== document
.activeElement
)
808 document
.addEventListener('validation-success', function(ev
) {
809 if (ev
.target
=== document
.activeElement
)
813 document
.querySelectorAll('.table').forEach(cbi_update_table
);