luci-proto-modemmanager: Added logging level option and debugmode
[project/luci.git] / modules / luci-base / htdocs / luci-static / resources / cbi.js
1 /*
2 LuCI - Lua Configuration Interface
3
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2018 Jo-Philipp Wich <jo@mein.io>
6
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
10
11 http://www.apache.org/licenses/LICENSE-2.0
12 */
13
14 var cbi_d = [];
15 var cbi_strings = { path: {}, label: {} };
16
17 function s8(bytes, off) {
18 var n = bytes[off];
19 return (n > 0x7F) ? (n - 256) >>> 0 : n;
20 }
21
22 function u16(bytes, off) {
23 return ((bytes[off + 1] << 8) + bytes[off]) >>> 0;
24 }
25
26 function sfh(s) {
27 if (s === null || s.length === 0)
28 return null;
29
30 var bytes = [];
31
32 for (var i = 0; i < s.length; i++) {
33 var ch = s.charCodeAt(i);
34
35 if (ch <= 0x7F)
36 bytes.push(ch);
37 else if (ch <= 0x7FF)
38 bytes.push(((ch >>> 6) & 0x1F) | 0xC0,
39 ( ch & 0x3F) | 0x80);
40 else if (ch <= 0xFFFF)
41 bytes.push(((ch >>> 12) & 0x0F) | 0xE0,
42 ((ch >>> 6) & 0x3F) | 0x80,
43 ( ch & 0x3F) | 0x80);
44 else if (code <= 0x10FFFF)
45 bytes.push(((ch >>> 18) & 0x07) | 0xF0,
46 ((ch >>> 12) & 0x3F) | 0x80,
47 ((ch >> 6) & 0x3F) | 0x80,
48 ( ch & 0x3F) | 0x80);
49 }
50
51 if (!bytes.length)
52 return null;
53
54 var hash = (bytes.length >>> 0),
55 len = (bytes.length >>> 2),
56 off = 0, tmp;
57
58 while (len--) {
59 hash += u16(bytes, off);
60 tmp = ((u16(bytes, off + 2) << 11) ^ hash) >>> 0;
61 hash = ((hash << 16) ^ tmp) >>> 0;
62 hash += hash >>> 11;
63 off += 4;
64 }
65
66 switch ((bytes.length & 3) >>> 0) {
67 case 3:
68 hash += u16(bytes, off);
69 hash = (hash ^ (hash << 16)) >>> 0;
70 hash = (hash ^ (s8(bytes, off + 2) << 18)) >>> 0;
71 hash += hash >>> 11;
72 break;
73
74 case 2:
75 hash += u16(bytes, off);
76 hash = (hash ^ (hash << 11)) >>> 0;
77 hash += hash >>> 17;
78 break;
79
80 case 1:
81 hash += s8(bytes, off);
82 hash = (hash ^ (hash << 10)) >>> 0;
83 hash += hash >>> 1;
84 break;
85 }
86
87 hash = (hash ^ (hash << 3)) >>> 0;
88 hash += hash >>> 5;
89 hash = (hash ^ (hash << 4)) >>> 0;
90 hash += hash >>> 17;
91 hash = (hash ^ (hash << 25)) >>> 0;
92 hash += hash >>> 6;
93
94 return (0x100000000 + hash).toString(16).substr(1);
95 }
96
97 var plural_function = null;
98
99 function trimws(s) {
100 return String(s).trim().replace(/[ \t\n]+/g, ' ');
101 }
102
103 function _(s, c) {
104 var k = (c != null ? trimws(c) + '\u0001' : '') + trimws(s);
105 return (window.TR && TR[sfh(k)]) || s;
106 }
107
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');
111
112 var i = plural_function ? plural_function(n) : (n != 1),
113 k = (c != null ? trimws(c) + '\u0001' : '') + trimws(s) + '\u0002' + i.toString();
114
115 return (window.TR && TR[sfh(k)]) || (i ? p : s);
116 }
117
118
119 function cbi_d_add(field, dep, index) {
120 var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
121 if (obj) {
122 var entry
123 for (var i=0; i<cbi_d.length; i++) {
124 if (cbi_d[i].id == obj.id) {
125 entry = cbi_d[i];
126 break;
127 }
128 }
129 if (!entry) {
130 entry = {
131 "node": obj,
132 "id": obj.id,
133 "parent": obj.parentNode.id,
134 "deps": [],
135 "index": index
136 };
137 cbi_d.unshift(entry);
138 }
139 entry.deps.push(dep)
140 }
141 }
142
143 function cbi_d_checkvalue(target, ref) {
144 var value = null,
145 query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
146 'select[id="'+target+'"], select[name="'+target+'"]';
147
148 document.querySelectorAll(query).forEach(function(i) {
149 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
150 value = i.value;
151 });
152
153 return (((value !== null) ? value : "") == ref);
154 }
155
156 function cbi_d_check(deps) {
157 var reverse;
158 var def = false;
159 for (var i=0; i<deps.length; i++) {
160 var istat = true;
161 reverse = false;
162 for (var j in deps[i]) {
163 if (j == "!reverse") {
164 reverse = true;
165 } else if (j == "!default") {
166 def = true;
167 istat = false;
168 } else {
169 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
170 }
171 }
172
173 if (istat ^ reverse) {
174 return true;
175 }
176 }
177 return def;
178 }
179
180 function cbi_d_update() {
181 var state = false;
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);
186
187 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
188 node.parentNode.removeChild(node);
189 state = true;
190 }
191 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
192 var next = undefined;
193
194 for (next = parent.firstChild; next; next = next.nextSibling) {
195 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
196 break;
197 }
198
199 if (!next)
200 parent.appendChild(entry.node);
201 else
202 parent.insertBefore(entry.node, next);
203
204 state = true;
205 }
206
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' : '';
210 }
211
212 if (entry && entry.parent)
213 cbi_tag_last(parent);
214
215 if (state)
216 cbi_d_update();
217 else if (parent)
218 parent.dispatchEvent(new CustomEvent('dependency-update', { bubbles: true }));
219 }
220
221 function cbi_init() {
222 var nodes;
223
224 document.querySelectorAll('.cbi-dropdown').forEach(function(node) {
225 cbi_dropdown_init(node);
226 node.addEventListener('cbi-dropdown-change', cbi_d_update);
227 });
228
229 nodes = document.querySelectorAll('[data-strings]');
230
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];
237 }
238 }
239 }
240
241 nodes = document.querySelectorAll('[data-depends]');
242
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);
249 }
250 }
251
252 nodes = document.querySelectorAll('[data-update]');
253
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);
258 }
259
260 nodes = document.querySelectorAll('[data-choices]');
261
262 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
263 var choices = JSON.parse(node.getAttribute('data-choices')),
264 options = {};
265
266 for (var j = 0; j < choices[0].length; j++)
267 options[choices[0][j]] = choices[1][j];
268
269 var def = (node.getAttribute('data-optional') === 'true')
270 ? node.placeholder || '' : null;
271
272 var cb = new L.ui.Combobox(node.value, options, {
273 name: node.getAttribute('name'),
274 sort: choices[0],
275 select_placeholder: def || _('-- Please choose --'),
276 custom_placeholder: node.getAttribute('data-manual') || _('-- custom --')
277 });
278
279 var n = cb.render();
280 n.addEventListener('cbi-dropdown-change', cbi_d_update);
281 node.parentNode.replaceChild(n, node);
282 }
283
284 nodes = document.querySelectorAll('[data-dynlist]');
285
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') || '[]'),
289 options = null;
290
291 if (choices[0] && choices[0].length) {
292 options = {};
293
294 for (var j = 0; j < choices[0].length; j++)
295 options[choices[0][j]] = choices[1][j];
296 }
297
298 var dl = new L.ui.DynamicList(values, options, {
299 name: node.getAttribute('data-prefix'),
300 sort: choices[0],
301 datatype: choices[2],
302 optional: choices[3],
303 placeholder: node.getAttribute('data-placeholder')
304 });
305
306 var n = dl.render();
307 n.addEventListener('cbi-dynlist-change', cbi_d_update);
308 node.parentNode.replaceChild(n, node);
309 }
310
311 nodes = document.querySelectorAll('[data-type]');
312
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'));
316 }
317
318 document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
319 s.parentNode.classList.add('cbi-tooltip-container');
320 });
321
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]);
326
327 section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
328 };
329
330 i.addEventListener('mouseover', handler);
331 i.addEventListener('mouseout', handler);
332 });
333
334 var tasks = [];
335
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();
340
341 tasks.push(Promise.resolve(markup).then(function(markup) {
342 markup.addEventListener('widget-change', cbi_d_update);
343 node.parentNode.replaceChild(markup, node);
344 }));
345 });
346
347 Promise.all(tasks).then(cbi_d_update);
348 }
349
350 function cbi_validate_form(form, errmsg)
351 {
352 /* if triggered by a section removal or addition, don't validate */
353 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
354 return true;
355
356 if (form.cbi_validators) {
357 for (var i = 0; i < form.cbi_validators.length; i++) {
358 var validator = form.cbi_validators[i];
359
360 if (!validator() && errmsg) {
361 alert(errmsg);
362 return false;
363 }
364 }
365 }
366
367 return true;
368 }
369
370 function cbi_validate_named_section_add(input)
371 {
372 var button = input.parentNode.parentNode.querySelector('.cbi-button-add');
373 button.disabled = input.value === '';
374 }
375
376 function cbi_validate_reset(form)
377 {
378 window.setTimeout(
379 function() { cbi_validate_form(form, null) }, 100
380 );
381
382 return true;
383 }
384
385 function cbi_validate_field(cbid, optional, type)
386 {
387 var field = isElem(cbid) ? cbid : document.getElementById(cbid);
388 var validatorFn;
389
390 try {
391 var cbiValidator = L.validation.create(field, type, optional);
392 validatorFn = cbiValidator.validate.bind(cbiValidator);
393 }
394 catch(e) {
395 validatorFn = null;
396 };
397
398 if (validatorFn !== null) {
399 var form = findParent(field, 'form');
400
401 if (!form.cbi_validators)
402 form.cbi_validators = [ ];
403
404 form.cbi_validators.push(validatorFn);
405
406 field.addEventListener("blur", validatorFn);
407 field.addEventListener("keyup", validatorFn);
408 field.addEventListener("cbi-dropdown-change", validatorFn);
409
410 if (matchesElem(field, 'select')) {
411 field.addEventListener("change", validatorFn);
412 field.addEventListener("click", validatorFn);
413 }
414
415 validatorFn();
416 }
417 }
418
419 function cbi_row_swap(elem, up, store)
420 {
421 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
422
423 if (!tr)
424 return false;
425
426 tr.classList.remove('flash');
427
428 if (up) {
429 var prev = tr.previousElementSibling;
430
431 if (prev && prev.classList.contains('cbi-section-table-row'))
432 tr.parentNode.insertBefore(tr, prev);
433 else
434 return;
435 }
436 else {
437 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
438
439 if (next && next.classList.contains('cbi-section-table-row'))
440 tr.parentNode.insertBefore(tr, next);
441 else if (!next)
442 tr.parentNode.appendChild(tr);
443 else
444 return;
445 }
446
447 var ids = [ ];
448
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');
455
456 if (/-([^\-]+)$/.test(node.id))
457 ids.push(RegExp.$1);
458 }
459 }
460
461 var input = document.getElementById(store);
462 if (input)
463 input.value = ids.join(' ');
464
465 window.scrollTo(0, tr.offsetTop);
466 void tr.offsetWidth;
467 tr.classList.add('flash');
468
469 return false;
470 }
471
472 function cbi_tag_last(container)
473 {
474 var last;
475
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');
480 last = c;
481 }
482 }
483
484 if (last)
485 last.classList.add('cbi-value-last');
486 }
487
488 function cbi_submit(elem, name, value, action)
489 {
490 var form = elem.form || findParent(elem, 'form');
491
492 if (!form)
493 return false;
494
495 if (action)
496 form.action = action;
497
498 if (name) {
499 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
500 E('input', { type: 'hidden', name: name });
501
502 hidden.value = value || '1';
503 form.appendChild(hidden);
504 }
505
506 form.submit();
507 return true;
508 }
509
510 String.prototype.format = function()
511 {
512 if (!RegExp)
513 return;
514
515 var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
516 var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
517
518 function esc(s, r) {
519 var t = typeof(s);
520
521 if (s == null || t === 'object' || t === 'function')
522 return '';
523
524 if (t !== 'string')
525 s = String(s);
526
527 for (var i = 0; i < r.length; i += 2)
528 s = s.replace(r[i], r[i+1]);
529
530 return s;
531 }
532
533 var str = this;
534 var out = '';
535 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
536 var a = b = [], numSubstitutions = 0, numMatches = 0;
537
538 while (a = re.exec(str)) {
539 var m = a[1];
540 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
541 var pPrecision = a[6], pType = a[7];
542
543 numMatches++;
544
545 if (pType == '%') {
546 subst = '%';
547 }
548 else {
549 if (numSubstitutions < arguments.length) {
550 var param = arguments[numSubstitutions++];
551
552 var pad = '';
553 if (pPad && pPad.substr(0,1) == "'")
554 pad = leftpart.substr(1,1);
555 else if (pPad)
556 pad = pPad;
557 else
558 pad = ' ';
559
560 var justifyRight = true;
561 if (pJustify && pJustify === "-")
562 justifyRight = false;
563
564 var minLength = -1;
565 if (pMinLength)
566 minLength = +pMinLength;
567
568 var precision = -1;
569 if (pPrecision && pType == 'f')
570 precision = +pPrecision.substring(1);
571
572 var subst = param;
573
574 switch(pType) {
575 case 'b':
576 subst = Math.floor(+param || 0).toString(2);
577 break;
578
579 case 'c':
580 subst = String.fromCharCode(+param || 0);
581 break;
582
583 case 'd':
584 subst = Math.floor(+param || 0).toFixed(0);
585 break;
586
587 case 'u':
588 var n = +param || 0;
589 subst = Math.floor((n < 0) ? 0x100000000 + n : n).toFixed(0);
590 break;
591
592 case 'f':
593 subst = (precision > -1)
594 ? ((+param || 0.0)).toFixed(precision)
595 : (+param || 0.0);
596 break;
597
598 case 'o':
599 subst = Math.floor(+param || 0).toString(8);
600 break;
601
602 case 's':
603 subst = param;
604 break;
605
606 case 'x':
607 subst = Math.floor(+param || 0).toString(16).toLowerCase();
608 break;
609
610 case 'X':
611 subst = Math.floor(+param || 0).toString(16).toUpperCase();
612 break;
613
614 case 'h':
615 subst = esc(param, html_esc);
616 break;
617
618 case 'q':
619 subst = esc(param, quot_esc);
620 break;
621
622 case 't':
623 var td = 0;
624 var th = 0;
625 var tm = 0;
626 var ts = (param || 0);
627
628 if (ts > 59) {
629 tm = Math.floor(ts / 60);
630 ts = (ts % 60);
631 }
632
633 if (tm > 59) {
634 th = Math.floor(tm / 60);
635 tm = (tm % 60);
636 }
637
638 if (th > 23) {
639 td = Math.floor(th / 24);
640 th = (th % 24);
641 }
642
643 subst = (td > 0)
644 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
645 : String.format('%dh %dm %ds', th, tm, ts);
646
647 break;
648
649 case 'm':
650 var mf = pMinLength ? +pMinLength : 1000;
651 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
652
653 var i = 0;
654 var val = (+param || 0);
655 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
656
657 for (i = 0; (i < units.length) && (val > mf); i++)
658 val /= mf;
659
660 if (i)
661 subst = val.toFixed(pr) + units[i] + (mf == 1024 ? 'i' : '');
662 else
663 subst = val + ' ';
664
665 pMinLength = null;
666 break;
667 }
668 }
669 }
670
671 if (pMinLength) {
672 subst = subst.toString();
673 for (var i = subst.length; i < pMinLength; i++)
674 if (pJustify == '-')
675 subst = subst + ' ';
676 else
677 subst = pad + subst;
678 }
679
680 out += leftpart + subst;
681 str = str.substr(m.length);
682 }
683
684 return out + str;
685 }
686
687 String.prototype.nobr = function()
688 {
689 return this.replace(/[\s\n]+/g, '&#160;');
690 }
691
692 String.format = function()
693 {
694 var a = [ ];
695
696 for (var i = 1; i < arguments.length; i++)
697 a.push(arguments[i]);
698
699 return ''.format.apply(arguments[0], a);
700 }
701
702 String.nobr = function()
703 {
704 var a = [ ];
705
706 for (var i = 1; i < arguments.length; i++)
707 a.push(arguments[i]);
708
709 return ''.nobr.apply(arguments[0], a);
710 }
711
712 if (window.NodeList && !NodeList.prototype.forEach) {
713 NodeList.prototype.forEach = function (callback, thisArg) {
714 thisArg = thisArg || window;
715 for (var i = 0; i < this.length; i++) {
716 callback.call(thisArg, this[i], i, this);
717 }
718 };
719 }
720
721 if (!window.requestAnimationFrame) {
722 window.requestAnimationFrame = function(f) {
723 window.setTimeout(function() {
724 f(new Date().getTime())
725 }, 1000/30);
726 };
727 }
728
729
730 function isElem(e) { return L.dom.elem(e) }
731 function toElem(s) { return L.dom.parse(s) }
732 function matchesElem(node, selector) { return L.dom.matches(node, selector) }
733 function findParent(node, selector) { return L.dom.parent(node, selector) }
734 function E() { return L.dom.create.apply(L.dom, arguments) }
735
736 if (typeof(window.CustomEvent) !== 'function') {
737 function CustomEvent(event, params) {
738 params = params || { bubbles: false, cancelable: false, detail: undefined };
739 var evt = document.createEvent('CustomEvent');
740 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
741 return evt;
742 }
743
744 CustomEvent.prototype = window.Event.prototype;
745 window.CustomEvent = CustomEvent;
746 }
747
748 function cbi_dropdown_init(sb) {
749 if (sb && L.dom.findClassInstance(sb) instanceof L.ui.Dropdown)
750 return;
751
752 var dl = new L.ui.Dropdown(sb, null, { name: sb.getAttribute('name') });
753 return dl.bind(sb);
754 }
755
756 function cbi_update_table(table, data, placeholder) {
757 var target = isElem(table) ? table : document.querySelector(table);
758
759 if (!isElem(target))
760 return;
761
762 var t = L.dom.findClassInstance(target);
763
764 if (!(t instanceof L.ui.Table)) {
765 t = new L.ui.Table(target);
766 L.dom.bindClassInstance(target, t);
767 }
768
769 t.update(data, placeholder);
770 }
771
772 function showModal(title, children)
773 {
774 return L.showModal(title, children);
775 }
776
777 function hideModal()
778 {
779 return L.hideModal();
780 }
781
782
783 document.addEventListener('DOMContentLoaded', function() {
784 document.addEventListener('validation-failure', function(ev) {
785 if (ev.target === document.activeElement)
786 L.showTooltip(ev);
787 });
788
789 document.addEventListener('validation-success', function(ev) {
790 if (ev.target === document.activeElement)
791 L.hideTooltip(ev);
792 });
793
794 L.require('ui').then(function(ui) {
795 document.querySelectorAll('.table').forEach(cbi_update_table);
796 });
797 });