Merge pull request #5448 from clayface/master
[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 if (input.value !== '') {
374 button.disabled = false;
375 }
376 else {
377 button.disabled = true;
378 }
379 }
380
381 function cbi_validate_reset(form)
382 {
383 window.setTimeout(
384 function() { cbi_validate_form(form, null) }, 100
385 );
386
387 return true;
388 }
389
390 function cbi_validate_field(cbid, optional, type)
391 {
392 var field = isElem(cbid) ? cbid : document.getElementById(cbid);
393 var validatorFn;
394
395 try {
396 var cbiValidator = L.validation.create(field, type, optional);
397 validatorFn = cbiValidator.validate.bind(cbiValidator);
398 }
399 catch(e) {
400 validatorFn = null;
401 };
402
403 if (validatorFn !== null) {
404 var form = findParent(field, 'form');
405
406 if (!form.cbi_validators)
407 form.cbi_validators = [ ];
408
409 form.cbi_validators.push(validatorFn);
410
411 field.addEventListener("blur", validatorFn);
412 field.addEventListener("keyup", validatorFn);
413 field.addEventListener("cbi-dropdown-change", validatorFn);
414
415 if (matchesElem(field, 'select')) {
416 field.addEventListener("change", validatorFn);
417 field.addEventListener("click", validatorFn);
418 }
419
420 validatorFn();
421 }
422 }
423
424 function cbi_row_swap(elem, up, store)
425 {
426 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
427
428 if (!tr)
429 return false;
430
431 tr.classList.remove('flash');
432
433 if (up) {
434 var prev = tr.previousElementSibling;
435
436 if (prev && prev.classList.contains('cbi-section-table-row'))
437 tr.parentNode.insertBefore(tr, prev);
438 else
439 return;
440 }
441 else {
442 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
443
444 if (next && next.classList.contains('cbi-section-table-row'))
445 tr.parentNode.insertBefore(tr, next);
446 else if (!next)
447 tr.parentNode.appendChild(tr);
448 else
449 return;
450 }
451
452 var ids = [ ];
453
454 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
455 var node = tr.parentNode.childNodes[i];
456 if (node.classList && node.classList.contains('cbi-section-table-row')) {
457 node.classList.remove('cbi-rowstyle-1');
458 node.classList.remove('cbi-rowstyle-2');
459 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
460
461 if (/-([^\-]+)$/.test(node.id))
462 ids.push(RegExp.$1);
463 }
464 }
465
466 var input = document.getElementById(store);
467 if (input)
468 input.value = ids.join(' ');
469
470 window.scrollTo(0, tr.offsetTop);
471 void tr.offsetWidth;
472 tr.classList.add('flash');
473
474 return false;
475 }
476
477 function cbi_tag_last(container)
478 {
479 var last;
480
481 for (var i = 0; i < container.childNodes.length; i++) {
482 var c = container.childNodes[i];
483 if (matchesElem(c, 'div')) {
484 c.classList.remove('cbi-value-last');
485 last = c;
486 }
487 }
488
489 if (last)
490 last.classList.add('cbi-value-last');
491 }
492
493 function cbi_submit(elem, name, value, action)
494 {
495 var form = elem.form || findParent(elem, 'form');
496
497 if (!form)
498 return false;
499
500 if (action)
501 form.action = action;
502
503 if (name) {
504 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
505 E('input', { type: 'hidden', name: name });
506
507 hidden.value = value || '1';
508 form.appendChild(hidden);
509 }
510
511 form.submit();
512 return true;
513 }
514
515 String.prototype.format = function()
516 {
517 if (!RegExp)
518 return;
519
520 var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
521 var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
522
523 function esc(s, r) {
524 var t = typeof(s);
525
526 if (s == null || t === 'object' || t === 'function')
527 return '';
528
529 if (t !== 'string')
530 s = String(s);
531
532 for (var i = 0; i < r.length; i += 2)
533 s = s.replace(r[i], r[i+1]);
534
535 return s;
536 }
537
538 var str = this;
539 var out = '';
540 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
541 var a = b = [], numSubstitutions = 0, numMatches = 0;
542
543 while (a = re.exec(str)) {
544 var m = a[1];
545 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
546 var pPrecision = a[6], pType = a[7];
547
548 numMatches++;
549
550 if (pType == '%') {
551 subst = '%';
552 }
553 else {
554 if (numSubstitutions < arguments.length) {
555 var param = arguments[numSubstitutions++];
556
557 var pad = '';
558 if (pPad && pPad.substr(0,1) == "'")
559 pad = leftpart.substr(1,1);
560 else if (pPad)
561 pad = pPad;
562 else
563 pad = ' ';
564
565 var justifyRight = true;
566 if (pJustify && pJustify === "-")
567 justifyRight = false;
568
569 var minLength = -1;
570 if (pMinLength)
571 minLength = +pMinLength;
572
573 var precision = -1;
574 if (pPrecision && pType == 'f')
575 precision = +pPrecision.substring(1);
576
577 var subst = param;
578
579 switch(pType) {
580 case 'b':
581 subst = Math.floor(+param || 0).toString(2);
582 break;
583
584 case 'c':
585 subst = String.fromCharCode(+param || 0);
586 break;
587
588 case 'd':
589 subst = Math.floor(+param || 0).toFixed(0);
590 break;
591
592 case 'u':
593 var n = +param || 0;
594 subst = Math.floor((n < 0) ? 0x100000000 + n : n).toFixed(0);
595 break;
596
597 case 'f':
598 subst = (precision > -1)
599 ? ((+param || 0.0)).toFixed(precision)
600 : (+param || 0.0);
601 break;
602
603 case 'o':
604 subst = Math.floor(+param || 0).toString(8);
605 break;
606
607 case 's':
608 subst = param;
609 break;
610
611 case 'x':
612 subst = Math.floor(+param || 0).toString(16).toLowerCase();
613 break;
614
615 case 'X':
616 subst = Math.floor(+param || 0).toString(16).toUpperCase();
617 break;
618
619 case 'h':
620 subst = esc(param, html_esc);
621 break;
622
623 case 'q':
624 subst = esc(param, quot_esc);
625 break;
626
627 case 't':
628 var td = 0;
629 var th = 0;
630 var tm = 0;
631 var ts = (param || 0);
632
633 if (ts > 59) {
634 tm = Math.floor(ts / 60);
635 ts = (ts % 60);
636 }
637
638 if (tm > 59) {
639 th = Math.floor(tm / 60);
640 tm = (tm % 60);
641 }
642
643 if (th > 23) {
644 td = Math.floor(th / 24);
645 th = (th % 24);
646 }
647
648 subst = (td > 0)
649 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
650 : String.format('%dh %dm %ds', th, tm, ts);
651
652 break;
653
654 case 'm':
655 var mf = pMinLength ? +pMinLength : 1000;
656 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
657
658 var i = 0;
659 var val = (+param || 0);
660 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
661
662 for (i = 0; (i < units.length) && (val > mf); i++)
663 val /= mf;
664
665 if (i)
666 subst = val.toFixed(pr) + units[i] + (mf == 1024 ? 'i' : '');
667 else
668 subst = val + ' ';
669
670 pMinLength = null;
671 break;
672 }
673 }
674 }
675
676 if (pMinLength) {
677 subst = subst.toString();
678 for (var i = subst.length; i < pMinLength; i++)
679 if (pJustify == '-')
680 subst = subst + ' ';
681 else
682 subst = pad + subst;
683 }
684
685 out += leftpart + subst;
686 str = str.substr(m.length);
687 }
688
689 return out + str;
690 }
691
692 String.prototype.nobr = function()
693 {
694 return this.replace(/[\s\n]+/g, '&#160;');
695 }
696
697 String.format = function()
698 {
699 var a = [ ];
700
701 for (var i = 1; i < arguments.length; i++)
702 a.push(arguments[i]);
703
704 return ''.format.apply(arguments[0], a);
705 }
706
707 String.nobr = function()
708 {
709 var a = [ ];
710
711 for (var i = 1; i < arguments.length; i++)
712 a.push(arguments[i]);
713
714 return ''.nobr.apply(arguments[0], a);
715 }
716
717 if (window.NodeList && !NodeList.prototype.forEach) {
718 NodeList.prototype.forEach = function (callback, thisArg) {
719 thisArg = thisArg || window;
720 for (var i = 0; i < this.length; i++) {
721 callback.call(thisArg, this[i], i, this);
722 }
723 };
724 }
725
726 if (!window.requestAnimationFrame) {
727 window.requestAnimationFrame = function(f) {
728 window.setTimeout(function() {
729 f(new Date().getTime())
730 }, 1000/30);
731 };
732 }
733
734
735 function isElem(e) { return L.dom.elem(e) }
736 function toElem(s) { return L.dom.parse(s) }
737 function matchesElem(node, selector) { return L.dom.matches(node, selector) }
738 function findParent(node, selector) { return L.dom.parent(node, selector) }
739 function E() { return L.dom.create.apply(L.dom, arguments) }
740
741 if (typeof(window.CustomEvent) !== 'function') {
742 function CustomEvent(event, params) {
743 params = params || { bubbles: false, cancelable: false, detail: undefined };
744 var evt = document.createEvent('CustomEvent');
745 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
746 return evt;
747 }
748
749 CustomEvent.prototype = window.Event.prototype;
750 window.CustomEvent = CustomEvent;
751 }
752
753 function cbi_dropdown_init(sb) {
754 if (sb && L.dom.findClassInstance(sb) instanceof L.ui.Dropdown)
755 return;
756
757 var dl = new L.ui.Dropdown(sb, null, { name: sb.getAttribute('name') });
758 return dl.bind(sb);
759 }
760
761 function cbi_update_table(table, data, placeholder) {
762 var target = isElem(table) ? table : document.querySelector(table);
763
764 if (!isElem(target))
765 return;
766
767 var t = L.dom.findClassInstance(target);
768
769 if (!(t instanceof L.ui.Table)) {
770 t = new L.ui.Table(target);
771 L.dom.bindClassInstance(target, t);
772 }
773
774 t.update(data, placeholder);
775 }
776
777 function showModal(title, children)
778 {
779 return L.showModal(title, children);
780 }
781
782 function hideModal()
783 {
784 return L.hideModal();
785 }
786
787
788 document.addEventListener('DOMContentLoaded', function() {
789 document.addEventListener('validation-failure', function(ev) {
790 if (ev.target === document.activeElement)
791 L.showTooltip(ev);
792 });
793
794 document.addEventListener('validation-success', function(ev) {
795 if (ev.target === document.activeElement)
796 L.hideTooltip(ev);
797 });
798
799 document.querySelectorAll('.table').forEach(cbi_update_table);
800 });