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('[data-browser]').forEach(cbi_browser_init);
303 document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
304 s.parentNode.classList.add('cbi-tooltip-container');
307 document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
308 var handler = function(ev) {
309 var bits = this.name.split(/\./),
310 section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
312 section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
315 i.addEventListener('mouseover', handler);
316 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 Promise.resolve(markup).then(function(markup) {
325 markup.addEventListener('widget-change', cbi_d_update);
326 node.parentNode.replaceChild(markup, node);
333 function cbi_filebrowser(id, defpath) {
334 var field = L.dom.elem(id) ? id : document.getElementById(id);
335 var browser = window.open(
336 cbi_strings.path.browser + (field.value || defpath || '') + '?field=' + field.id,
337 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
343 function cbi_browser_init(field)
345 field.parentNode.insertBefore(
347 'src': L.resource('cbi/folder.gif'),
348 'class': 'cbi-image-button',
349 'click': function(ev) {
350 cbi_filebrowser(field, field.getAttribute('data-browser'));
353 }), field.nextSibling);
356 function cbi_validate_form(form, errmsg)
358 /* if triggered by a section removal or addition, don't validate */
359 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
362 if (form.cbi_validators) {
363 for (var i = 0; i < form.cbi_validators.length; i++) {
364 var validator = form.cbi_validators[i];
366 if (!validator() && errmsg) {
376 function cbi_validate_reset(form)
379 function() { cbi_validate_form(form, null) }, 100
385 function cbi_validate_field(cbid, optional, type)
387 var field = isElem(cbid) ? cbid : document.getElementById(cbid);
391 var cbiValidator = L.validation.create(field, type, optional);
392 validatorFn = cbiValidator.validate.bind(cbiValidator);
398 if (validatorFn !== null) {
399 var form = findParent(field, 'form');
401 if (!form.cbi_validators)
402 form.cbi_validators = [ ];
404 form.cbi_validators.push(validatorFn);
406 field.addEventListener("blur", validatorFn);
407 field.addEventListener("keyup", validatorFn);
408 field.addEventListener("cbi-dropdown-change", validatorFn);
410 if (matchesElem(field, 'select')) {
411 field.addEventListener("change", validatorFn);
412 field.addEventListener("click", validatorFn);
419 function cbi_row_swap(elem, up, store)
421 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
426 tr.classList.remove('flash');
429 var prev = tr.previousElementSibling;
431 if (prev && prev.classList.contains('cbi-section-table-row'))
432 tr.parentNode.insertBefore(tr, prev);
437 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
439 if (next && next.classList.contains('cbi-section-table-row'))
440 tr.parentNode.insertBefore(tr, next);
442 tr.parentNode.appendChild(tr);
449 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
450 var node = tr.parentNode.childNodes[i];
451 if (node.classList && node.classList.contains('cbi-section-table-row')) {
452 node.classList.remove('cbi-rowstyle-1');
453 node.classList.remove('cbi-rowstyle-2');
454 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
456 if (/-([^\-]+)$/.test(node.id))
461 var input = document.getElementById(store);
463 input.value = ids.join(' ');
465 window.scrollTo(0, tr.offsetTop);
467 tr.classList.add('flash');
472 function cbi_tag_last(container)
476 for (var i = 0; i < container.childNodes.length; i++) {
477 var c = container.childNodes[i];
478 if (matchesElem(c, 'div')) {
479 c.classList.remove('cbi-value-last');
485 last.classList.add('cbi-value-last');
488 function cbi_submit(elem, name, value, action)
490 var form = elem.form || findParent(elem, 'form');
496 form.action = action;
499 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
500 E('input', { type: 'hidden', name: name });
502 hidden.value = value || '1';
503 form.appendChild(hidden);
510 String.prototype.format = function()
515 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
516 var quot_esc = [/"/g, '"', /'/g, '''];
519 if (typeof(s) !== 'string' && !(s instanceof String))
522 for (var i = 0; i < r.length; i += 2)
523 s = s.replace(r[i], r[i+1]);
530 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
531 var a = b = [], numSubstitutions = 0, numMatches = 0;
533 while (a = re.exec(str)) {
535 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
536 var pPrecision = a[6], pType = a[7];
544 if (numSubstitutions < arguments.length) {
545 var param = arguments[numSubstitutions++];
548 if (pPad && pPad.substr(0,1) == "'")
549 pad = leftpart.substr(1,1);
555 var justifyRight = true;
556 if (pJustify && pJustify === "-")
557 justifyRight = false;
561 minLength = +pMinLength;
564 if (pPrecision && pType == 'f')
565 precision = +pPrecision.substring(1);
571 subst = Math.floor(+param || 0).toString(2);
575 subst = String.fromCharCode(+param || 0);
579 subst = Math.floor(+param || 0).toFixed(0);
584 subst = Math.floor((n < 0) ? 0x100000000 + n : n).toFixed(0);
588 subst = (precision > -1)
589 ? ((+param || 0.0)).toFixed(precision)
594 subst = Math.floor(+param || 0).toString(8);
602 subst = Math.floor(+param || 0).toString(16).toLowerCase();
606 subst = Math.floor(+param || 0).toString(16).toUpperCase();
610 subst = esc(param, html_esc);
614 subst = esc(param, quot_esc);
621 var ts = (param || 0);
624 tm = Math.floor(ts / 60);
629 th = Math.floor(tm / 60);
634 td = Math.floor(th / 24);
639 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
640 : String.format('%dh %dm %ds', th, tm, ts);
645 var mf = pMinLength ? +pMinLength : 1000;
646 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
649 var val = (+param || 0);
650 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
652 for (i = 0; (i < units.length) && (val > mf); i++)
655 subst = (i ? val.toFixed(pr) : val) + units[i];
663 subst = subst.toString();
664 for (var i = subst.length; i < pMinLength; i++)
671 out += leftpart + subst;
672 str = str.substr(m.length);
678 String.prototype.nobr = function()
680 return this.replace(/[\s\n]+/g, ' ');
683 String.format = function()
687 for (var i = 1; i < arguments.length; i++)
688 a.push(arguments[i]);
690 return ''.format.apply(arguments[0], a);
693 String.nobr = function()
697 for (var i = 1; i < arguments.length; i++)
698 a.push(arguments[i]);
700 return ''.nobr.apply(arguments[0], a);
703 if (window.NodeList && !NodeList.prototype.forEach) {
704 NodeList.prototype.forEach = function (callback, thisArg) {
705 thisArg = thisArg || window;
706 for (var i = 0; i < this.length; i++) {
707 callback.call(thisArg, this[i], i, this);
712 if (!window.requestAnimationFrame) {
713 window.requestAnimationFrame = function(f) {
714 window.setTimeout(function() {
715 f(new Date().getTime())
721 function isElem(e) { return L.dom.elem(e) }
722 function toElem(s) { return L.dom.parse(s) }
723 function matchesElem(node, selector) { return L.dom.matches(node, selector) }
724 function findParent(node, selector) { return L.dom.parent(node, selector) }
725 function E() { return L.dom.create.apply(L.dom, arguments) }
727 if (typeof(window.CustomEvent) !== 'function') {
728 function CustomEvent(event, params) {
729 params = params || { bubbles: false, cancelable: false, detail: undefined };
730 var evt = document.createEvent('CustomEvent');
731 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
735 CustomEvent.prototype = window.Event.prototype;
736 window.CustomEvent = CustomEvent;
739 function cbi_dropdown_init(sb) {
740 var dl = new L.ui.Dropdown(sb, null, { name: sb.getAttribute('name') });
744 function cbi_update_table(table, data, placeholder) {
745 var target = isElem(table) ? table : document.querySelector(table);
750 target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
753 thead.querySelectorAll('.th').forEach(function(th) {
757 if (Array.isArray(data)) {
758 var n = 0, rows = target.querySelectorAll('.tr');
760 data.forEach(function(row) {
761 var trow = E('div', { 'class': 'tr' });
763 for (var i = 0; i < titles.length; i++) {
764 var text = (titles[i].innerText || '').trim();
765 var td = trow.appendChild(E('div', {
766 'class': titles[i].className,
767 'data-title': (text !== '') ? text : null
770 td.classList.remove('th');
771 td.classList.add('td');
774 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
777 target.replaceChild(trow, rows[n]);
779 target.appendChild(trow);
783 target.removeChild(rows[n]);
785 if (placeholder && target.firstElementChild === target.lastElementChild) {
786 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
787 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
789 td.classList.remove('th');
790 td.classList.add('td');
794 thead.parentNode.style.display = 'none';
796 thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
797 if (trow !== thead) {
799 trow.querySelectorAll('.th, .td').forEach(function(td) {
800 if (n < titles.length) {
801 var text = (titles[n++].innerText || '').trim();
803 td.setAttribute('data-title', text);
809 thead.parentNode.style.display = '';
814 function showModal(title, children)
816 return L.showModal(title, children);
821 return L.hideModal();
825 document.addEventListener('DOMContentLoaded', function() {
826 document.addEventListener('validation-failure', function(ev) {
827 if (ev.target === document.activeElement)
831 document.addEventListener('validation-success', function(ev) {
832 if (ev.target === document.activeElement)
836 document.querySelectorAll('.table').forEach(cbi_update_table);