luci-base: cbi.js: handle ui elements which return a promise in render()
[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                 Promise.resolve(markup).then(function(markup) {
325                         markup.addEventListener('widget-change', cbi_d_update);
326                         node.parentNode.replaceChild(markup, node);
327                 });
328         });
329
330         cbi_d_update();
331 }
332
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"
338         );
339
340         browser.focus();
341 }
342
343 function cbi_browser_init(field)
344 {
345         field.parentNode.insertBefore(
346                 E('img', {
347                         'src': L.resource('cbi/folder.gif'),
348                         'class': 'cbi-image-button',
349                         'click': function(ev) {
350                                 cbi_filebrowser(field, field.getAttribute('data-browser'));
351                                 ev.preventDefault();
352                         }
353                 }), field.nextSibling);
354 }
355
356 function cbi_validate_form(form, errmsg)
357 {
358         /* if triggered by a section removal or addition, don't validate */
359         if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
360                 return true;
361
362         if (form.cbi_validators) {
363                 for (var i = 0; i < form.cbi_validators.length; i++) {
364                         var validator = form.cbi_validators[i];
365
366                         if (!validator() && errmsg) {
367                                 alert(errmsg);
368                                 return false;
369                         }
370                 }
371         }
372
373         return true;
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                 if (typeof(s) !== 'string' && !(s instanceof String))
520                         return '';
521
522                 for (var i = 0; i < r.length; i += 2)
523                         s = s.replace(r[i], r[i+1]);
524
525                 return s;
526         }
527
528         var str = this;
529         var out = '';
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;
532
533         while (a = re.exec(str)) {
534                 var m = a[1];
535                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
536                 var pPrecision = a[6], pType = a[7];
537
538                 numMatches++;
539
540                 if (pType == '%') {
541                         subst = '%';
542                 }
543                 else {
544                         if (numSubstitutions < arguments.length) {
545                                 var param = arguments[numSubstitutions++];
546
547                                 var pad = '';
548                                 if (pPad && pPad.substr(0,1) == "'")
549                                         pad = leftpart.substr(1,1);
550                                 else if (pPad)
551                                         pad = pPad;
552                                 else
553                                         pad = ' ';
554
555                                 var justifyRight = true;
556                                 if (pJustify && pJustify === "-")
557                                         justifyRight = false;
558
559                                 var minLength = -1;
560                                 if (pMinLength)
561                                         minLength = +pMinLength;
562
563                                 var precision = -1;
564                                 if (pPrecision && pType == 'f')
565                                         precision = +pPrecision.substring(1);
566
567                                 var subst = param;
568
569                                 switch(pType) {
570                                         case 'b':
571                                                 subst = Math.floor(+param || 0).toString(2);
572                                                 break;
573
574                                         case 'c':
575                                                 subst = String.fromCharCode(+param || 0);
576                                                 break;
577
578                                         case 'd':
579                                                 subst = Math.floor(+param || 0).toFixed(0);
580                                                 break;
581
582                                         case 'u':
583                                                 var n = +param || 0;
584                                                 subst = Math.floor((n < 0) ? 0x100000000 + n : n).toFixed(0);
585                                                 break;
586
587                                         case 'f':
588                                                 subst = (precision > -1)
589                                                         ? ((+param || 0.0)).toFixed(precision)
590                                                         : (+param || 0.0);
591                                                 break;
592
593                                         case 'o':
594                                                 subst = Math.floor(+param || 0).toString(8);
595                                                 break;
596
597                                         case 's':
598                                                 subst = param;
599                                                 break;
600
601                                         case 'x':
602                                                 subst = Math.floor(+param || 0).toString(16).toLowerCase();
603                                                 break;
604
605                                         case 'X':
606                                                 subst = Math.floor(+param || 0).toString(16).toUpperCase();
607                                                 break;
608
609                                         case 'h':
610                                                 subst = esc(param, html_esc);
611                                                 break;
612
613                                         case 'q':
614                                                 subst = esc(param, quot_esc);
615                                                 break;
616
617                                         case 't':
618                                                 var td = 0;
619                                                 var th = 0;
620                                                 var tm = 0;
621                                                 var ts = (param || 0);
622
623                                                 if (ts > 60) {
624                                                         tm = Math.floor(ts / 60);
625                                                         ts = (ts % 60);
626                                                 }
627
628                                                 if (tm > 60) {
629                                                         th = Math.floor(tm / 60);
630                                                         tm = (tm % 60);
631                                                 }
632
633                                                 if (th > 24) {
634                                                         td = Math.floor(th / 24);
635                                                         th = (th % 24);
636                                                 }
637
638                                                 subst = (td > 0)
639                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
640                                                         : String.format('%dh %dm %ds', th, tm, ts);
641
642                                                 break;
643
644                                         case 'm':
645                                                 var mf = pMinLength ? +pMinLength : 1000;
646                                                 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
647
648                                                 var i = 0;
649                                                 var val = (+param || 0);
650                                                 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
651
652                                                 for (i = 0; (i < units.length) && (val > mf); i++)
653                                                         val /= mf;
654
655                                                 subst = (i ? val.toFixed(pr) : val) + units[i];
656                                                 pMinLength = null;
657                                                 break;
658                                 }
659                         }
660                 }
661
662                 if (pMinLength) {
663                         subst = subst.toString();
664                         for (var i = subst.length; i < pMinLength; i++)
665                                 if (pJustify == '-')
666                                         subst = subst + ' ';
667                                 else
668                                         subst = pad + subst;
669                 }
670
671                 out += leftpart + subst;
672                 str = str.substr(m.length);
673         }
674
675         return out + str;
676 }
677
678 String.prototype.nobr = function()
679 {
680         return this.replace(/[\s\n]+/g, '&#160;');
681 }
682
683 String.format = function()
684 {
685         var a = [ ];
686
687         for (var i = 1; i < arguments.length; i++)
688                 a.push(arguments[i]);
689
690         return ''.format.apply(arguments[0], a);
691 }
692
693 String.nobr = function()
694 {
695         var a = [ ];
696
697         for (var i = 1; i < arguments.length; i++)
698                 a.push(arguments[i]);
699
700         return ''.nobr.apply(arguments[0], a);
701 }
702
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);
708                 }
709         };
710 }
711
712 if (!window.requestAnimationFrame) {
713         window.requestAnimationFrame = function(f) {
714                 window.setTimeout(function() {
715                         f(new Date().getTime())
716                 }, 1000/30);
717         };
718 }
719
720
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) }
726
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 );
732                 return evt;
733         }
734
735         CustomEvent.prototype = window.Event.prototype;
736         window.CustomEvent = CustomEvent;
737 }
738
739 function cbi_dropdown_init(sb) {
740         var dl = new L.ui.Dropdown(sb, null, { name: sb.getAttribute('name') });
741         return dl.bind(sb);
742 }
743
744 function cbi_update_table(table, data, placeholder) {
745         var target = isElem(table) ? table : document.querySelector(table);
746
747         if (!isElem(target))
748                 return;
749
750         target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
751                 var titles = [];
752
753                 thead.querySelectorAll('.th').forEach(function(th) {
754                         titles.push(th);
755                 });
756
757                 if (Array.isArray(data)) {
758                         var n = 0, rows = target.querySelectorAll('.tr');
759
760                         data.forEach(function(row) {
761                                 var trow = E('div', { 'class': 'tr' });
762
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
768                                         }, row[i] || ''));
769
770                                         td.classList.remove('th');
771                                         td.classList.add('td');
772                                 }
773
774                                 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
775
776                                 if (rows[n])
777                                         target.replaceChild(trow, rows[n]);
778                                 else
779                                         target.appendChild(trow);
780                         });
781
782                         while (rows[++n])
783                                 target.removeChild(rows[n]);
784
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));
788
789                                 td.classList.remove('th');
790                                 td.classList.add('td');
791                         }
792                 }
793                 else {
794                         thead.parentNode.style.display = 'none';
795
796                         thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
797                                 if (trow !== thead) {
798                                         var n = 0;
799                                         trow.querySelectorAll('.th, .td').forEach(function(td) {
800                                                 if (n < titles.length) {
801                                                         var text = (titles[n++].innerText || '').trim();
802                                                         if (text !== '')
803                                                                 td.setAttribute('data-title', text);
804                                                 }
805                                         });
806                                 }
807                         });
808
809                         thead.parentNode.style.display = '';
810                 }
811         });
812 }
813
814 function showModal(title, children)
815 {
816         return L.showModal(title, children);
817 }
818
819 function hideModal()
820 {
821         return L.hideModal();
822 }
823
824
825 document.addEventListener('DOMContentLoaded', function() {
826         document.addEventListener('validation-failure', function(ev) {
827                 if (ev.target === document.activeElement)
828                         L.showTooltip(ev);
829         });
830
831         document.addEventListener('validation-success', function(ev) {
832                 if (ev.target === document.activeElement)
833                         L.hideTooltip(ev);
834         });
835
836         document.querySelectorAll('.table').forEach(cbi_update_table);
837 });