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);
317 document.querySelectorAll('[data-ui-widget]').forEach(function(node) {
318 var args = JSON.parse(node.getAttribute('data-ui-widget') || '[]'),
319 widget = new (Function.prototype.bind.apply(L.ui[args[0]], args)),
320 markup = widget.render();
322 Promise.resolve(markup).then(function(markup) {
323 markup.addEventListener('widget-change', cbi_d_update);
324 node.parentNode.replaceChild(markup, node);
331 function cbi_validate_form(form, errmsg)
333 /* if triggered by a section removal or addition, don't validate */
334 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
337 if (form.cbi_validators) {
338 for (var i = 0; i < form.cbi_validators.length; i++) {
339 var validator = form.cbi_validators[i];
341 if (!validator() && errmsg) {
351 function cbi_validate_reset(form)
354 function() { cbi_validate_form(form, null) }, 100
360 function cbi_validate_field(cbid, optional, type)
362 var field = isElem(cbid) ? cbid : document.getElementById(cbid);
366 var cbiValidator = L.validation.create(field, type, optional);
367 validatorFn = cbiValidator.validate.bind(cbiValidator);
373 if (validatorFn !== null) {
374 var form = findParent(field, 'form');
376 if (!form.cbi_validators)
377 form.cbi_validators = [ ];
379 form.cbi_validators.push(validatorFn);
381 field.addEventListener("blur", validatorFn);
382 field.addEventListener("keyup", validatorFn);
383 field.addEventListener("cbi-dropdown-change", validatorFn);
385 if (matchesElem(field, 'select')) {
386 field.addEventListener("change", validatorFn);
387 field.addEventListener("click", validatorFn);
394 function cbi_row_swap(elem, up, store)
396 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
401 tr.classList.remove('flash');
404 var prev = tr.previousElementSibling;
406 if (prev && prev.classList.contains('cbi-section-table-row'))
407 tr.parentNode.insertBefore(tr, prev);
412 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
414 if (next && next.classList.contains('cbi-section-table-row'))
415 tr.parentNode.insertBefore(tr, next);
417 tr.parentNode.appendChild(tr);
424 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
425 var node = tr.parentNode.childNodes[i];
426 if (node.classList && node.classList.contains('cbi-section-table-row')) {
427 node.classList.remove('cbi-rowstyle-1');
428 node.classList.remove('cbi-rowstyle-2');
429 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
431 if (/-([^\-]+)$/.test(node.id))
436 var input = document.getElementById(store);
438 input.value = ids.join(' ');
440 window.scrollTo(0, tr.offsetTop);
442 tr.classList.add('flash');
447 function cbi_tag_last(container)
451 for (var i = 0; i < container.childNodes.length; i++) {
452 var c = container.childNodes[i];
453 if (matchesElem(c, 'div')) {
454 c.classList.remove('cbi-value-last');
460 last.classList.add('cbi-value-last');
463 function cbi_submit(elem, name, value, action)
465 var form = elem.form || findParent(elem, 'form');
471 form.action = action;
474 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
475 E('input', { type: 'hidden', name: name });
477 hidden.value = value || '1';
478 form.appendChild(hidden);
485 String.prototype.format = function()
490 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
491 var quot_esc = [/"/g, '"', /'/g, '''];
494 if (typeof(s) !== 'string' && !(s instanceof String))
497 for (var i = 0; i < r.length; i += 2)
498 s = s.replace(r[i], r[i+1]);
505 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
506 var a = b = [], numSubstitutions = 0, numMatches = 0;
508 while (a = re.exec(str)) {
510 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
511 var pPrecision = a[6], pType = a[7];
519 if (numSubstitutions < arguments.length) {
520 var param = arguments[numSubstitutions++];
523 if (pPad && pPad.substr(0,1) == "'")
524 pad = leftpart.substr(1,1);
530 var justifyRight = true;
531 if (pJustify && pJustify === "-")
532 justifyRight = false;
536 minLength = +pMinLength;
539 if (pPrecision && pType == 'f')
540 precision = +pPrecision.substring(1);
546 subst = Math.floor(+param || 0).toString(2);
550 subst = String.fromCharCode(+param || 0);
554 subst = Math.floor(+param || 0).toFixed(0);
559 subst = Math.floor((n < 0) ? 0x100000000 + n : n).toFixed(0);
563 subst = (precision > -1)
564 ? ((+param || 0.0)).toFixed(precision)
569 subst = Math.floor(+param || 0).toString(8);
577 subst = Math.floor(+param || 0).toString(16).toLowerCase();
581 subst = Math.floor(+param || 0).toString(16).toUpperCase();
585 subst = esc(param, html_esc);
589 subst = esc(param, quot_esc);
596 var ts = (param || 0);
599 tm = Math.floor(ts / 60);
604 th = Math.floor(tm / 60);
609 td = Math.floor(th / 24);
614 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
615 : String.format('%dh %dm %ds', th, tm, ts);
620 var mf = pMinLength ? +pMinLength : 1000;
621 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
624 var val = (+param || 0);
625 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
627 for (i = 0; (i < units.length) && (val > mf); i++)
630 subst = (i ? val.toFixed(pr) : val) + units[i];
638 subst = subst.toString();
639 for (var i = subst.length; i < pMinLength; i++)
646 out += leftpart + subst;
647 str = str.substr(m.length);
653 String.prototype.nobr = function()
655 return this.replace(/[\s\n]+/g, ' ');
658 String.format = function()
662 for (var i = 1; i < arguments.length; i++)
663 a.push(arguments[i]);
665 return ''.format.apply(arguments[0], a);
668 String.nobr = function()
672 for (var i = 1; i < arguments.length; i++)
673 a.push(arguments[i]);
675 return ''.nobr.apply(arguments[0], a);
678 if (window.NodeList && !NodeList.prototype.forEach) {
679 NodeList.prototype.forEach = function (callback, thisArg) {
680 thisArg = thisArg || window;
681 for (var i = 0; i < this.length; i++) {
682 callback.call(thisArg, this[i], i, this);
687 if (!window.requestAnimationFrame) {
688 window.requestAnimationFrame = function(f) {
689 window.setTimeout(function() {
690 f(new Date().getTime())
696 function isElem(e) { return L.dom.elem(e) }
697 function toElem(s) { return L.dom.parse(s) }
698 function matchesElem(node, selector) { return L.dom.matches(node, selector) }
699 function findParent(node, selector) { return L.dom.parent(node, selector) }
700 function E() { return L.dom.create.apply(L.dom, arguments) }
702 if (typeof(window.CustomEvent) !== 'function') {
703 function CustomEvent(event, params) {
704 params = params || { bubbles: false, cancelable: false, detail: undefined };
705 var evt = document.createEvent('CustomEvent');
706 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
710 CustomEvent.prototype = window.Event.prototype;
711 window.CustomEvent = CustomEvent;
714 function cbi_dropdown_init(sb) {
715 var dl = new L.ui.Dropdown(sb, null, { name: sb.getAttribute('name') });
719 function cbi_update_table(table, data, placeholder) {
720 var target = isElem(table) ? table : document.querySelector(table);
725 target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
728 thead.querySelectorAll('.th').forEach(function(th) {
732 if (Array.isArray(data)) {
733 var n = 0, rows = target.querySelectorAll('.tr');
735 data.forEach(function(row) {
736 var trow = E('div', { 'class': 'tr' });
738 for (var i = 0; i < titles.length; i++) {
739 var text = (titles[i].innerText || '').trim();
740 var td = trow.appendChild(E('div', {
741 'class': titles[i].className,
742 'data-title': (text !== '') ? text : null
745 td.classList.remove('th');
746 td.classList.add('td');
749 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
752 target.replaceChild(trow, rows[n]);
754 target.appendChild(trow);
758 target.removeChild(rows[n]);
760 if (placeholder && target.firstElementChild === target.lastElementChild) {
761 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
762 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
764 td.classList.remove('th');
765 td.classList.add('td');
769 thead.parentNode.style.display = 'none';
771 thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
772 if (trow !== thead) {
774 trow.querySelectorAll('.th, .td').forEach(function(td) {
775 if (n < titles.length) {
776 var text = (titles[n++].innerText || '').trim();
778 td.setAttribute('data-title', text);
784 thead.parentNode.style.display = '';
789 function showModal(title, children)
791 return L.showModal(title, children);
796 return L.hideModal();
800 document.addEventListener('DOMContentLoaded', function() {
801 document.addEventListener('validation-failure', function(ev) {
802 if (ev.target === document.activeElement)
806 document.addEventListener('validation-success', function(ev) {
807 if (ev.target === document.activeElement)
811 document.querySelectorAll('.table').forEach(cbi_update_table);