luci-base: luci.js: support registering request progress handlers
[oweals/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 function _(s) {
98         return (window.TR && TR[sfh(s)]) || s;
99 }
100
101
102 function cbi_d_add(field, dep, index) {
103         var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
104         if (obj) {
105                 var entry
106                 for (var i=0; i<cbi_d.length; i++) {
107                         if (cbi_d[i].id == obj.id) {
108                                 entry = cbi_d[i];
109                                 break;
110                         }
111                 }
112                 if (!entry) {
113                         entry = {
114                                 "node": obj,
115                                 "id": obj.id,
116                                 "parent": obj.parentNode.id,
117                                 "deps": [],
118                                 "index": index
119                         };
120                         cbi_d.unshift(entry);
121                 }
122                 entry.deps.push(dep)
123         }
124 }
125
126 function cbi_d_checkvalue(target, ref) {
127         var value = null,
128             query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
129                     'select[id="'+target+'"], select[name="'+target+'"]';
130
131         document.querySelectorAll(query).forEach(function(i) {
132                 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
133                         value = i.value;
134         });
135
136         return (((value !== null) ? value : "") == ref);
137 }
138
139 function cbi_d_check(deps) {
140         var reverse;
141         var def = false;
142         for (var i=0; i<deps.length; i++) {
143                 var istat = true;
144                 reverse = false;
145                 for (var j in deps[i]) {
146                         if (j == "!reverse") {
147                                 reverse = true;
148                         } else if (j == "!default") {
149                                 def = true;
150                                 istat = false;
151                         } else {
152                                 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
153                         }
154                 }
155
156                 if (istat ^ reverse) {
157                         return true;
158                 }
159         }
160         return def;
161 }
162
163 function cbi_d_update() {
164         var state = false;
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);
169
170                 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
171                         node.parentNode.removeChild(node);
172                         state = true;
173                 }
174                 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
175                         var next = undefined;
176
177                         for (next = parent.firstChild; next; next = next.nextSibling) {
178                                 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
179                                         break;
180                         }
181
182                         if (!next)
183                                 parent.appendChild(entry.node);
184                         else
185                                 parent.insertBefore(entry.node, next);
186
187                         state = true;
188                 }
189
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' : '';
193         }
194
195         if (entry && entry.parent)
196                 cbi_tag_last(parent);
197
198         if (state)
199                 cbi_d_update();
200         else if (parent)
201                 parent.dispatchEvent(new CustomEvent('dependency-update', { bubbles: true }));
202 }
203
204 function cbi_init() {
205         var nodes;
206
207         document.querySelectorAll('.cbi-dropdown').forEach(function(node) {
208                 cbi_dropdown_init(node);
209                 node.addEventListener('cbi-dropdown-change', cbi_d_update);
210         });
211
212         nodes = document.querySelectorAll('[data-strings]');
213
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];
220                         }
221                 }
222         }
223
224         nodes = document.querySelectorAll('[data-depends]');
225
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);
232                 }
233         }
234
235         nodes = document.querySelectorAll('[data-update]');
236
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);
241         }
242
243         nodes = document.querySelectorAll('[data-choices]');
244
245         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
246                 var choices = JSON.parse(node.getAttribute('data-choices')),
247                     options = {};
248
249                 for (var j = 0; j < choices[0].length; j++)
250                         options[choices[0][j]] = choices[1][j];
251
252                 var def = (node.getAttribute('data-optional') === 'true')
253                         ? node.placeholder || '' : null;
254
255                 var cb = new L.ui.Combobox(node.value, options, {
256                         name: node.getAttribute('name'),
257                         sort: choices[0],
258                         select_placeholder: def || _('-- Please choose --'),
259                         custom_placeholder: node.getAttribute('data-manual') || _('-- custom --')
260                 });
261
262                 var n = cb.render();
263                 n.addEventListener('cbi-dropdown-change', cbi_d_update);
264                 node.parentNode.replaceChild(n, node);
265         }
266
267         nodes = document.querySelectorAll('[data-dynlist]');
268
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') || '[]'),
272                     options = null;
273
274                 if (choices[0] && choices[0].length) {
275                         options = {};
276
277                         for (var j = 0; j < choices[0].length; j++)
278                                 options[choices[0][j]] = choices[1][j];
279                 }
280
281                 var dl = new L.ui.DynamicList(values, options, {
282                         name: node.getAttribute('data-prefix'),
283                         sort: choices[0],
284                         datatype: choices[2],
285                         optional: choices[3],
286                         placeholder: node.getAttribute('data-placeholder')
287                 });
288
289                 var n = dl.render();
290                 n.addEventListener('cbi-dynlist-change', cbi_d_update);
291                 node.parentNode.replaceChild(n, node);
292         }
293
294         nodes = document.querySelectorAll('[data-type]');
295
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'));
299         }
300
301         document.querySelectorAll('[data-browser]').forEach(cbi_browser_init);
302
303         document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
304                 s.parentNode.classList.add('cbi-tooltip-container');
305         });
306
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]);
311
312                     section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
313                 };
314
315                 i.addEventListener('mouseover', handler);
316                 i.addEventListener('mouseout', handler);
317         });
318
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();
323
324                 markup.addEventListener('widget-change', cbi_d_update);
325                 node.parentNode.replaceChild(markup, node);
326         });
327
328         cbi_d_update();
329 }
330
331 function cbi_filebrowser(id, defpath) {
332         var field   = L.dom.elem(id) ? id : document.getElementById(id);
333         var browser = window.open(
334                 cbi_strings.path.browser + (field.value || defpath || '') + '?field=' + field.id,
335                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
336         );
337
338         browser.focus();
339 }
340
341 function cbi_browser_init(field)
342 {
343         field.parentNode.insertBefore(
344                 E('img', {
345                         'src': L.resource('cbi/folder.gif'),
346                         'class': 'cbi-image-button',
347                         'click': function(ev) {
348                                 cbi_filebrowser(field, field.getAttribute('data-browser'));
349                                 ev.preventDefault();
350                         }
351                 }), field.nextSibling);
352 }
353
354 function cbi_validate_form(form, errmsg)
355 {
356         /* if triggered by a section removal or addition, don't validate */
357         if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
358                 return true;
359
360         if (form.cbi_validators) {
361                 for (var i = 0; i < form.cbi_validators.length; i++) {
362                         var validator = form.cbi_validators[i];
363
364                         if (!validator() && errmsg) {
365                                 alert(errmsg);
366                                 return false;
367                         }
368                 }
369         }
370
371         return true;
372 }
373
374 function cbi_validate_reset(form)
375 {
376         window.setTimeout(
377                 function() { cbi_validate_form(form, null) }, 100
378         );
379
380         return true;
381 }
382
383 function cbi_validate_field(cbid, optional, type)
384 {
385         var field = isElem(cbid) ? cbid : document.getElementById(cbid);
386         var validatorFn;
387
388         try {
389                 var cbiValidator = L.validation.create(field, type, optional);
390                 validatorFn = cbiValidator.validate.bind(cbiValidator);
391         }
392         catch(e) {
393                 validatorFn = null;
394         };
395
396         if (validatorFn !== null) {
397                 var form = findParent(field, 'form');
398
399                 if (!form.cbi_validators)
400                         form.cbi_validators = [ ];
401
402                 form.cbi_validators.push(validatorFn);
403
404                 field.addEventListener("blur",  validatorFn);
405                 field.addEventListener("keyup", validatorFn);
406                 field.addEventListener("cbi-dropdown-change", validatorFn);
407
408                 if (matchesElem(field, 'select')) {
409                         field.addEventListener("change", validatorFn);
410                         field.addEventListener("click",  validatorFn);
411                 }
412
413                 validatorFn();
414         }
415 }
416
417 function cbi_row_swap(elem, up, store)
418 {
419         var tr = findParent(elem.parentNode, '.cbi-section-table-row');
420
421         if (!tr)
422                 return false;
423
424         tr.classList.remove('flash');
425
426         if (up) {
427                 var prev = tr.previousElementSibling;
428
429                 if (prev && prev.classList.contains('cbi-section-table-row'))
430                         tr.parentNode.insertBefore(tr, prev);
431                 else
432                         return;
433         }
434         else {
435                 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
436
437                 if (next && next.classList.contains('cbi-section-table-row'))
438                         tr.parentNode.insertBefore(tr, next);
439                 else if (!next)
440                         tr.parentNode.appendChild(tr);
441                 else
442                         return;
443         }
444
445         var ids = [ ];
446
447         for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
448                 var node = tr.parentNode.childNodes[i];
449                 if (node.classList && node.classList.contains('cbi-section-table-row')) {
450                         node.classList.remove('cbi-rowstyle-1');
451                         node.classList.remove('cbi-rowstyle-2');
452                         node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
453
454                         if (/-([^\-]+)$/.test(node.id))
455                                 ids.push(RegExp.$1);
456                 }
457         }
458
459         var input = document.getElementById(store);
460         if (input)
461                 input.value = ids.join(' ');
462
463         window.scrollTo(0, tr.offsetTop);
464         void tr.offsetWidth;
465         tr.classList.add('flash');
466
467         return false;
468 }
469
470 function cbi_tag_last(container)
471 {
472         var last;
473
474         for (var i = 0; i < container.childNodes.length; i++) {
475                 var c = container.childNodes[i];
476                 if (matchesElem(c, 'div')) {
477                         c.classList.remove('cbi-value-last');
478                         last = c;
479                 }
480         }
481
482         if (last)
483                 last.classList.add('cbi-value-last');
484 }
485
486 function cbi_submit(elem, name, value, action)
487 {
488         var form = elem.form || findParent(elem, 'form');
489
490         if (!form)
491                 return false;
492
493         if (action)
494                 form.action = action;
495
496         if (name) {
497                 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
498                         E('input', { type: 'hidden', name: name });
499
500                 hidden.value = value || '1';
501                 form.appendChild(hidden);
502         }
503
504         form.submit();
505         return true;
506 }
507
508 String.prototype.format = function()
509 {
510         if (!RegExp)
511                 return;
512
513         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
514         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
515
516         function esc(s, r) {
517                 if (typeof(s) !== 'string' && !(s instanceof String))
518                         return '';
519
520                 for (var i = 0; i < r.length; i += 2)
521                         s = s.replace(r[i], r[i+1]);
522
523                 return s;
524         }
525
526         var str = this;
527         var out = '';
528         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
529         var a = b = [], numSubstitutions = 0, numMatches = 0;
530
531         while (a = re.exec(str)) {
532                 var m = a[1];
533                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
534                 var pPrecision = a[6], pType = a[7];
535
536                 numMatches++;
537
538                 if (pType == '%') {
539                         subst = '%';
540                 }
541                 else {
542                         if (numSubstitutions < arguments.length) {
543                                 var param = arguments[numSubstitutions++];
544
545                                 var pad = '';
546                                 if (pPad && pPad.substr(0,1) == "'")
547                                         pad = leftpart.substr(1,1);
548                                 else if (pPad)
549                                         pad = pPad;
550                                 else
551                                         pad = ' ';
552
553                                 var justifyRight = true;
554                                 if (pJustify && pJustify === "-")
555                                         justifyRight = false;
556
557                                 var minLength = -1;
558                                 if (pMinLength)
559                                         minLength = +pMinLength;
560
561                                 var precision = -1;
562                                 if (pPrecision && pType == 'f')
563                                         precision = +pPrecision.substring(1);
564
565                                 var subst = param;
566
567                                 switch(pType) {
568                                         case 'b':
569                                                 subst = (~~param || 0).toString(2);
570                                                 break;
571
572                                         case 'c':
573                                                 subst = String.fromCharCode(+param || 0);
574                                                 break;
575
576                                         case 'd':
577                                                 subst = (~~param || 0);
578                                                 break;
579
580                                         case 'u':
581                                                 subst = ~~Math.abs(+param || 0);
582                                                 break;
583
584                                         case 'f':
585                                                 subst = (precision > -1)
586                                                         ? ((+param || 0.0)).toFixed(precision)
587                                                         : (+param || 0.0);
588                                                 break;
589
590                                         case 'o':
591                                                 subst = (~~param || 0).toString(8);
592                                                 break;
593
594                                         case 's':
595                                                 subst = param;
596                                                 break;
597
598                                         case 'x':
599                                                 subst = ('' + (~~param || 0).toString(16)).toLowerCase();
600                                                 break;
601
602                                         case 'X':
603                                                 subst = ('' + (~~param || 0).toString(16)).toUpperCase();
604                                                 break;
605
606                                         case 'h':
607                                                 subst = esc(param, html_esc);
608                                                 break;
609
610                                         case 'q':
611                                                 subst = esc(param, quot_esc);
612                                                 break;
613
614                                         case 't':
615                                                 var td = 0;
616                                                 var th = 0;
617                                                 var tm = 0;
618                                                 var ts = (param || 0);
619
620                                                 if (ts > 60) {
621                                                         tm = Math.floor(ts / 60);
622                                                         ts = (ts % 60);
623                                                 }
624
625                                                 if (tm > 60) {
626                                                         th = Math.floor(tm / 60);
627                                                         tm = (tm % 60);
628                                                 }
629
630                                                 if (th > 24) {
631                                                         td = Math.floor(th / 24);
632                                                         th = (th % 24);
633                                                 }
634
635                                                 subst = (td > 0)
636                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
637                                                         : String.format('%dh %dm %ds', th, tm, ts);
638
639                                                 break;
640
641                                         case 'm':
642                                                 var mf = pMinLength ? +pMinLength : 1000;
643                                                 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
644
645                                                 var i = 0;
646                                                 var val = (+param || 0);
647                                                 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
648
649                                                 for (i = 0; (i < units.length) && (val > mf); i++)
650                                                         val /= mf;
651
652                                                 subst = (i ? val.toFixed(pr) : val) + units[i];
653                                                 pMinLength = null;
654                                                 break;
655                                 }
656                         }
657                 }
658
659                 if (pMinLength) {
660                         subst = subst.toString();
661                         for (var i = subst.length; i < pMinLength; i++)
662                                 if (pJustify == '-')
663                                         subst = subst + ' ';
664                                 else
665                                         subst = pad + subst;
666                 }
667
668                 out += leftpart + subst;
669                 str = str.substr(m.length);
670         }
671
672         return out + str;
673 }
674
675 String.prototype.nobr = function()
676 {
677         return this.replace(/[\s\n]+/g, '&#160;');
678 }
679
680 String.format = function()
681 {
682         var a = [ ];
683
684         for (var i = 1; i < arguments.length; i++)
685                 a.push(arguments[i]);
686
687         return ''.format.apply(arguments[0], a);
688 }
689
690 String.nobr = function()
691 {
692         var a = [ ];
693
694         for (var i = 1; i < arguments.length; i++)
695                 a.push(arguments[i]);
696
697         return ''.nobr.apply(arguments[0], a);
698 }
699
700 if (window.NodeList && !NodeList.prototype.forEach) {
701         NodeList.prototype.forEach = function (callback, thisArg) {
702                 thisArg = thisArg || window;
703                 for (var i = 0; i < this.length; i++) {
704                         callback.call(thisArg, this[i], i, this);
705                 }
706         };
707 }
708
709 if (!window.requestAnimationFrame) {
710         window.requestAnimationFrame = function(f) {
711                 window.setTimeout(function() {
712                         f(new Date().getTime())
713                 }, 1000/30);
714         };
715 }
716
717
718 function isElem(e) { return L.dom.elem(e) }
719 function toElem(s) { return L.dom.parse(s) }
720 function matchesElem(node, selector) { return L.dom.matches(node, selector) }
721 function findParent(node, selector) { return L.dom.parent(node, selector) }
722 function E() { return L.dom.create.apply(L.dom, arguments) }
723
724 if (typeof(window.CustomEvent) !== 'function') {
725         function CustomEvent(event, params) {
726                 params = params || { bubbles: false, cancelable: false, detail: undefined };
727                 var evt = document.createEvent('CustomEvent');
728                     evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
729                 return evt;
730         }
731
732         CustomEvent.prototype = window.Event.prototype;
733         window.CustomEvent = CustomEvent;
734 }
735
736 function cbi_dropdown_init(sb) {
737         var dl = new L.ui.Dropdown(sb, null, { name: sb.getAttribute('name') });
738         return dl.bind(sb);
739 }
740
741 function cbi_update_table(table, data, placeholder) {
742         var target = isElem(table) ? table : document.querySelector(table);
743
744         if (!isElem(target))
745                 return;
746
747         target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
748                 var titles = [];
749
750                 thead.querySelectorAll('.th').forEach(function(th) {
751                         titles.push(th);
752                 });
753
754                 if (Array.isArray(data)) {
755                         var n = 0, rows = target.querySelectorAll('.tr');
756
757                         data.forEach(function(row) {
758                                 var trow = E('div', { 'class': 'tr' });
759
760                                 for (var i = 0; i < titles.length; i++) {
761                                         var text = (titles[i].innerText || '').trim();
762                                         var td = trow.appendChild(E('div', {
763                                                 'class': titles[i].className,
764                                                 'data-title': (text !== '') ? text : null
765                                         }, row[i] || ''));
766
767                                         td.classList.remove('th');
768                                         td.classList.add('td');
769                                 }
770
771                                 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
772
773                                 if (rows[n])
774                                         target.replaceChild(trow, rows[n]);
775                                 else
776                                         target.appendChild(trow);
777                         });
778
779                         while (rows[++n])
780                                 target.removeChild(rows[n]);
781
782                         if (placeholder && target.firstElementChild === target.lastElementChild) {
783                                 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
784                                 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
785
786                                 td.classList.remove('th');
787                                 td.classList.add('td');
788                         }
789                 }
790                 else {
791                         thead.parentNode.style.display = 'none';
792
793                         thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
794                                 if (trow !== thead) {
795                                         var n = 0;
796                                         trow.querySelectorAll('.th, .td').forEach(function(td) {
797                                                 if (n < titles.length) {
798                                                         var text = (titles[n++].innerText || '').trim();
799                                                         if (text !== '')
800                                                                 td.setAttribute('data-title', text);
801                                                 }
802                                         });
803                                 }
804                         });
805
806                         thead.parentNode.style.display = '';
807                 }
808         });
809 }
810
811 function showModal(title, children)
812 {
813         return L.showModal(title, children);
814 }
815
816 function hideModal()
817 {
818         return L.hideModal();
819 }
820
821
822 document.addEventListener('DOMContentLoaded', function() {
823         document.addEventListener('validation-failure', function(ev) {
824                 if (ev.target === document.activeElement)
825                         L.showTooltip(ev);
826         });
827
828         document.addEventListener('validation-success', function(ev) {
829                 if (ev.target === document.activeElement)
830                         L.hideTooltip(ev);
831         });
832
833         document.querySelectorAll('.table').forEach(cbi_update_table);
834 });