b1fc26c74da7699a0ad3056e8549a005b2b8a26b
[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-2012 Jo-Philipp Wich <jow@openwrt.org>
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_t = [];
16 var cbi_strings = { path: {}, label: {} };
17
18 function sfh(s) {
19 if (s === null || s.length === 0)
20 return null;
21
22 var hash = (s.length >>> 0),
23 len = (s.length >>> 2),
24 off = 0, tmp;
25
26 while (len--) {
27 hash += ((s.charCodeAt(off + 1) << 8) + s.charCodeAt(off)) >>> 0;
28 tmp = ((((s.charCodeAt(off + 3) << 8) + s.charCodeAt(off + 2)) << 11) ^ hash) >>> 0;
29 hash = ((hash << 16) ^ tmp) >>> 0;
30 hash += hash >>> 11;
31 off += 4;
32 }
33
34 switch ((s.length & 3) >>> 0) {
35 case 3:
36 hash += ((s.charCodeAt(off + 1) << 8) + s.charCodeAt(off)) >>> 0;
37 hash = (hash ^ (hash << 16)) >>> 0;
38 hash = (hash ^ (s.charCodeAt(off + 2) << 18)) >>> 0;
39 hash += hash >> 11;
40 break;
41
42 case 2:
43 hash += ((s.charCodeAt(off + 1) << 8) + s.charCodeAt(off)) >>> 0;
44 hash = (hash ^ (hash << 11)) >>> 0;
45 hash += hash >>> 17;
46 break;
47
48 case 1:
49 hash += s.charCodeAt(off);
50 hash = (hash ^ (hash << 10)) >>> 0;
51 hash += hash >>> 1;
52 break;
53 }
54
55 hash = (hash ^ (hash << 3)) >>> 0;
56 hash += hash >>> 5;
57 hash = (hash ^ (hash << 4)) >>> 0;
58 hash += hash >>> 17;
59 hash = (hash ^ (hash << 25)) >>> 0;
60 hash += hash >>> 6;
61
62 return (0x100000000 + hash).toString(16).substr(1);
63 }
64
65 function _(s) {
66 return (window.TR && TR[sfh(s)]) || s;
67 }
68
69 function Int(x) {
70 return (/^-?\d+$/.test(x) ? +x : NaN);
71 }
72
73 function Dec(x) {
74 return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
75 }
76
77 function IPv4(x) {
78 if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
79 return null;
80
81 if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
82 return null;
83
84 return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
85 }
86
87 function IPv6(x) {
88 if (x.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
89 var v6 = RegExp.$1, v4 = IPv4(RegExp.$2);
90
91 if (!v4)
92 return null;
93
94 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
95 + ':' + (v4[2] * 256 + v4[3]).toString(16);
96 }
97
98 if (!x.match(/^[a-fA-F0-9:]+$/))
99 return null;
100
101 var prefix_suffix = x.split(/::/);
102
103 if (prefix_suffix.length > 2)
104 return null;
105
106 var prefix = (prefix_suffix[0] || '0').split(/:/);
107 var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
108
109 if (suffix.length ? (prefix.length + suffix.length > 7) : (prefix.length > 8))
110 return null;
111
112 var i, word;
113 var words = [];
114
115 for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
116 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
117 words.push(word);
118 else
119 return null;
120
121 for (i = 0; i < (8 - prefix.length - suffix.length); i++)
122 words.push(0);
123
124 for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
125 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
126 words.push(word);
127 else
128 return null;
129
130 return words;
131 }
132
133 var cbi_validators = {
134
135 'integer': function()
136 {
137 return !!Int(this);
138 },
139
140 'uinteger': function()
141 {
142 return (Int(this) >= 0);
143 },
144
145 'float': function()
146 {
147 return !!Dec(this);
148 },
149
150 'ufloat': function()
151 {
152 return (Dec(this) >= 0);
153 },
154
155 'ipaddr': function()
156 {
157 return cbi_validators.ip4addr.apply(this) ||
158 cbi_validators.ip6addr.apply(this);
159 },
160
161 'ip4addr': function()
162 {
163 var m = this.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?:\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|\/(\d{1,2}))?$/);
164 return !!(m && IPv4(m[1]) && (m[2] ? IPv4(m[2]) : (m[3] ? cbi_validators.ip4prefix.apply(m[3]) : true)));
165 },
166
167 'ip6addr': function()
168 {
169 var m = this.match(/^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/);
170 return !!(m && IPv6(m[1]) && (m[2] ? cbi_validators.ip6prefix.apply(m[2]) : true));
171 },
172
173 'ip4prefix': function()
174 {
175 return !isNaN(this) && this >= 0 && this <= 32;
176 },
177
178 'ip6prefix': function()
179 {
180 return !isNaN(this) && this >= 0 && this <= 128;
181 },
182
183 'cidr': function()
184 {
185 return cbi_validators.cidr4.apply(this) ||
186 cbi_validators.cidr6.apply(this);
187 },
188
189 'cidr4': function()
190 {
191 var m = this.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
192 return !!(m && IPv4(m[1]) && cbi_validators.ip4prefix.apply(m[2]));
193 },
194
195 'cidr6': function()
196 {
197 var m = this.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
198 return !!(m && IPv6(m[1]) && cbi_validators.ip6prefix.apply(m[2]));
199 },
200
201 'ipnet4': function()
202 {
203 var m = this.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
204 return !!(m && IPv4(m[1]) && IPv4(m[2]));
205 },
206
207 'ipnet6': function()
208 {
209 var m = this.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
210 return !!(m && IPv6(m[1]) && IPv6(m[2]));
211 },
212
213 'ip6hostid': function()
214 {
215 if (this == "eui64" || this == "random")
216 return true;
217
218 var v6 = IPv6(this);
219 return !(!v6 || v6[0] || v6[1] || v6[2] || v6[3]);
220 },
221
222 'ipmask': function()
223 {
224 return cbi_validators.ipmask4.apply(this) ||
225 cbi_validators.ipmask6.apply(this);
226 },
227
228 'ipmask4': function()
229 {
230 return cbi_validators.cidr4.apply(this) ||
231 cbi_validators.ipnet4.apply(this) ||
232 cbi_validators.ip4addr.apply(this);
233 },
234
235 'ipmask6': function()
236 {
237 return cbi_validators.cidr6.apply(this) ||
238 cbi_validators.ipnet6.apply(this) ||
239 cbi_validators.ip6addr.apply(this);
240 },
241
242 'port': function()
243 {
244 var p = Int(this);
245 return (p >= 0 && p <= 65535);
246 },
247
248 'portrange': function()
249 {
250 if (this.match(/^(\d+)-(\d+)$/))
251 {
252 var p1 = +RegExp.$1;
253 var p2 = +RegExp.$2;
254 return (p1 <= p2 && p2 <= 65535);
255 }
256
257 return cbi_validators.port.apply(this);
258 },
259
260 'macaddr': function()
261 {
262 return (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
263 },
264
265 'host': function(ipv4only)
266 {
267 return cbi_validators.hostname.apply(this) ||
268 ((ipv4only != 1) && cbi_validators.ipaddr.apply(this)) ||
269 ((ipv4only == 1) && cbi_validators.ip4addr.apply(this));
270 },
271
272 'hostname': function(strict)
273 {
274 if (this.length <= 253)
275 return (this.match(/^[a-zA-Z0-9_]+$/) != null ||
276 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
277 this.match(/[^0-9.]/))) &&
278 (!strict || !this.match(/^_/));
279
280 return false;
281 },
282
283 'network': function()
284 {
285 return cbi_validators.uciname.apply(this) ||
286 cbi_validators.host.apply(this);
287 },
288
289 'hostport': function(ipv4only)
290 {
291 var hp = this.split(/:/);
292
293 if (hp.length == 2)
294 return (cbi_validators.host.apply(hp[0], ipv4only) &&
295 cbi_validators.port.apply(hp[1]));
296
297 return false;
298 },
299
300 'ip4addrport': function()
301 {
302 var hp = this.split(/:/);
303
304 if (hp.length == 2)
305 return (cbi_validators.ipaddr.apply(hp[0]) &&
306 cbi_validators.port.apply(hp[1]));
307 return false;
308 },
309
310 'ipaddrport': function(bracket)
311 {
312 if (this.match(/^([^\[\]:]+):([^:]+)$/)) {
313 var addr = RegExp.$1
314 var port = RegExp.$2
315 return (cbi_validators.ip4addr.apply(addr) &&
316 cbi_validators.port.apply(port));
317 } else if ((bracket == 1) && (this.match(/^\[(.+)\]:([^:]+)$/))) {
318 var addr = RegExp.$1
319 var port = RegExp.$2
320 return (cbi_validators.ip6addr.apply(addr) &&
321 cbi_validators.port.apply(port));
322 } else if ((bracket != 1) && (this.match(/^([^\[\]]+):([^:]+)$/))) {
323 var addr = RegExp.$1
324 var port = RegExp.$2
325 return (cbi_validators.ip6addr.apply(addr) &&
326 cbi_validators.port.apply(port));
327 } else {
328 return false;
329 }
330 },
331
332 'wpakey': function()
333 {
334 var v = this;
335
336 if( v.length == 64 )
337 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
338 else
339 return (v.length >= 8) && (v.length <= 63);
340 },
341
342 'wepkey': function()
343 {
344 var v = this;
345
346 if ( v.substr(0,2) == 's:' )
347 v = v.substr(2);
348
349 if( (v.length == 10) || (v.length == 26) )
350 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
351 else
352 return (v.length == 5) || (v.length == 13);
353 },
354
355 'uciname': function()
356 {
357 return (this.match(/^[a-zA-Z0-9_]+$/) != null);
358 },
359
360 'range': function(min, max)
361 {
362 var val = Dec(this);
363 return (val >= +min && val <= +max);
364 },
365
366 'min': function(min)
367 {
368 return (Dec(this) >= +min);
369 },
370
371 'max': function(max)
372 {
373 return (Dec(this) <= +max);
374 },
375
376 'rangelength': function(min, max)
377 {
378 var val = '' + this;
379 return ((val.length >= +min) && (val.length <= +max));
380 },
381
382 'minlength': function(min)
383 {
384 return ((''+this).length >= +min);
385 },
386
387 'maxlength': function(max)
388 {
389 return ((''+this).length <= +max);
390 },
391
392 'or': function()
393 {
394 for (var i = 0; i < arguments.length; i += 2)
395 {
396 if (typeof arguments[i] != 'function')
397 {
398 if (arguments[i] == this)
399 return true;
400 i--;
401 }
402 else if (arguments[i].apply(this, arguments[i+1]))
403 {
404 return true;
405 }
406 }
407 return false;
408 },
409
410 'and': function()
411 {
412 for (var i = 0; i < arguments.length; i += 2)
413 {
414 if (typeof arguments[i] != 'function')
415 {
416 if (arguments[i] != this)
417 return false;
418 i--;
419 }
420 else if (!arguments[i].apply(this, arguments[i+1]))
421 {
422 return false;
423 }
424 }
425 return true;
426 },
427
428 'neg': function()
429 {
430 return cbi_validators.or.apply(
431 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
432 },
433
434 'list': function(subvalidator, subargs)
435 {
436 if (typeof subvalidator != 'function')
437 return false;
438
439 var tokens = this.match(/[^ \t]+/g);
440 for (var i = 0; i < tokens.length; i++)
441 if (!subvalidator.apply(tokens[i], subargs))
442 return false;
443
444 return true;
445 },
446 'phonedigit': function()
447 {
448 return (this.match(/^[0-9\*#!\.]+$/) != null);
449 },
450 'timehhmmss': function()
451 {
452 return (this.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/) != null);
453 },
454 'dateyyyymmdd': function()
455 {
456 if (this == null) {
457 return false;
458 }
459 if (this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
460 var year = RegExp.$1;
461 var month = RegExp.$2;
462 var day = RegExp.$2
463
464 var days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30 , 31, 30, 31 ];
465 function is_leap_year(year) {
466 return ((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0);
467 }
468 function get_days_in_month(month, year) {
469 if ((month == 2) && is_leap_year(year)) {
470 return 29;
471 } else {
472 return days_in_month[month];
473 }
474 }
475 /* Firewall rules in the past don't make sense */
476 if (year < 2015) {
477 return false;
478 }
479 if ((month <= 0) || (month > 12)) {
480 return false;
481 }
482 if ((day <= 0) || (day > get_days_in_month(month, year))) {
483 return false;
484 }
485 return true;
486
487 } else {
488 return false;
489 }
490 }
491 };
492
493
494 function cbi_d_add(field, dep, index) {
495 var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
496 if (obj) {
497 var entry
498 for (var i=0; i<cbi_d.length; i++) {
499 if (cbi_d[i].id == obj.id) {
500 entry = cbi_d[i];
501 break;
502 }
503 }
504 if (!entry) {
505 entry = {
506 "node": obj,
507 "id": obj.id,
508 "parent": obj.parentNode.id,
509 "deps": [],
510 "index": index
511 };
512 cbi_d.unshift(entry);
513 }
514 entry.deps.push(dep)
515 }
516 }
517
518 function cbi_d_checkvalue(target, ref) {
519 var value = null,
520 query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
521 'select[id="'+target+'"], select[name="'+target+'"]';
522
523 document.querySelectorAll(query).forEach(function(i) {
524 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
525 value = i.value;
526 });
527
528 return (((value !== null) ? value : "") == ref);
529 }
530
531 function cbi_d_check(deps) {
532 var reverse;
533 var def = false;
534 for (var i=0; i<deps.length; i++) {
535 var istat = true;
536 reverse = false;
537 for (var j in deps[i]) {
538 if (j == "!reverse") {
539 reverse = true;
540 } else if (j == "!default") {
541 def = true;
542 istat = false;
543 } else {
544 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
545 }
546 }
547
548 if (istat ^ reverse) {
549 return true;
550 }
551 }
552 return def;
553 }
554
555 function cbi_d_update() {
556 var state = false;
557 for (var i=0; i<cbi_d.length; i++) {
558 var entry = cbi_d[i];
559 var node = document.getElementById(entry.id);
560 var parent = document.getElementById(entry.parent);
561
562 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
563 node.parentNode.removeChild(node);
564 state = true;
565 }
566 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
567 var next = undefined;
568
569 for (next = parent.firstChild; next; next = next.nextSibling) {
570 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
571 break;
572 }
573
574 if (!next)
575 parent.appendChild(entry.node);
576 else
577 parent.insertBefore(entry.node, next);
578
579 state = true;
580 }
581
582 // hide optionals widget if no choices remaining
583 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
584 parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
585 }
586
587 if (entry && entry.parent) {
588 if (!cbi_t_update())
589 cbi_tag_last(parent);
590 }
591
592 if (state)
593 cbi_d_update();
594 }
595
596 function cbi_init() {
597 var nodes;
598
599 nodes = document.querySelectorAll('[data-strings]');
600
601 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
602 var str = JSON.parse(node.getAttribute('data-strings'));
603 for (var key in str) {
604 for (var key2 in str[key]) {
605 var dst = cbi_strings[key] || (cbi_strings[key] = { });
606 dst[key2] = str[key][key2];
607 }
608 }
609 }
610
611 nodes = document.querySelectorAll('[data-depends]');
612
613 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
614 var index = parseInt(node.getAttribute('data-index'), 10);
615 var depends = JSON.parse(node.getAttribute('data-depends'));
616 if (!isNaN(index) && depends.length > 0) {
617 for (var alt = 0; alt < depends.length; alt++)
618 cbi_d_add(node, depends[alt], index);
619 }
620 }
621
622 nodes = document.querySelectorAll('[data-update]');
623
624 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
625 var events = node.getAttribute('data-update').split(' ');
626 for (var j = 0, event; (event = events[j]) !== undefined; j++)
627 cbi_bind(node, event, cbi_d_update);
628 }
629
630 nodes = document.querySelectorAll('[data-choices]');
631
632 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
633 var choices = JSON.parse(node.getAttribute('data-choices'));
634 var options = {};
635
636 for (var j = 0; j < choices[0].length; j++)
637 options[choices[0][j]] = choices[1][j];
638
639 var def = (node.getAttribute('data-optional') === 'true')
640 ? node.placeholder || '' : null;
641
642 cbi_combobox_init(node, options, def,
643 node.getAttribute('data-manual'));
644 }
645
646 nodes = document.querySelectorAll('[data-dynlist]');
647
648 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
649 var choices = JSON.parse(node.getAttribute('data-dynlist'));
650 var options = null;
651
652 if (choices[0] && choices[0].length) {
653 options = {};
654
655 for (var j = 0; j < choices[0].length; j++)
656 options[choices[0][j]] = choices[1][j];
657 }
658
659 cbi_dynlist_init(node, choices[2], choices[3], options);
660 }
661
662 nodes = document.querySelectorAll('[data-type]');
663
664 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
665 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
666 node.getAttribute('data-type'));
667 }
668
669 document.querySelectorAll('.cbi-dropdown').forEach(function(s) {
670 cbi_dropdown_init(s);
671 });
672
673 document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
674 s.parentNode.classList.add('cbi-tooltip-container');
675 });
676
677 document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
678 var handler = function(ev) {
679 var bits = this.name.split(/\./),
680 section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
681
682 section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
683 };
684
685 i.addEventListener('mouseover', handler);
686 i.addEventListener('mouseout', handler);
687 });
688
689 cbi_d_update();
690 }
691
692 function cbi_bind(obj, type, callback, mode) {
693 if (!obj.addEventListener) {
694 obj.attachEvent('on' + type,
695 function(){
696 var e = window.event;
697
698 if (!e.target && e.srcElement)
699 e.target = e.srcElement;
700
701 return !!callback(e);
702 }
703 );
704 } else {
705 obj.addEventListener(type, callback, !!mode);
706 }
707 return obj;
708 }
709
710 function cbi_combobox(id, values, def, man, focus) {
711 var selid = "cbi.combobox." + id;
712 if (document.getElementById(selid)) {
713 return
714 }
715
716 var obj = document.getElementById(id)
717 var sel = document.createElement("select");
718 sel.id = selid;
719 sel.index = obj.index;
720 sel.classList.remove('cbi-input-text');
721 sel.classList.add('cbi-input-select');
722
723 if (obj.nextSibling)
724 obj.parentNode.insertBefore(sel, obj.nextSibling);
725 else
726 obj.parentNode.appendChild(sel);
727
728 var dt = obj.getAttribute('cbi_datatype');
729 var op = obj.getAttribute('cbi_optional');
730
731 if (!values[obj.value]) {
732 if (obj.value == "") {
733 var optdef = document.createElement("option");
734 optdef.value = "";
735 optdef.appendChild(document.createTextNode(typeof(def) === 'string' ? def : _('-- Please choose --')));
736 sel.appendChild(optdef);
737 }
738 else {
739 var opt = document.createElement("option");
740 opt.value = obj.value;
741 opt.selected = "selected";
742 opt.appendChild(document.createTextNode(obj.value));
743 sel.appendChild(opt);
744 }
745 }
746
747 for (var i in values) {
748 var opt = document.createElement("option");
749 opt.value = i;
750
751 if (obj.value == i)
752 opt.selected = "selected";
753
754 opt.appendChild(document.createTextNode(values[i]));
755 sel.appendChild(opt);
756 }
757
758 var optman = document.createElement("option");
759 optman.value = "";
760 optman.appendChild(document.createTextNode(typeof(man) === 'string' ? man : _('-- custom --')));
761 sel.appendChild(optman);
762
763 obj.style.display = "none";
764
765 if (dt)
766 cbi_validate_field(sel, op == 'true', dt);
767
768 cbi_bind(sel, "change", function() {
769 if (sel.selectedIndex == sel.options.length - 1) {
770 obj.style.display = "inline";
771 sel.blur();
772 sel.parentNode.removeChild(sel);
773 obj.focus();
774 }
775 else {
776 obj.value = sel.options[sel.selectedIndex].value;
777 }
778
779 try {
780 cbi_d_update();
781 } catch (e) {
782 //Do nothing
783 }
784 })
785
786 // Retrigger validation in select
787 if (focus) {
788 sel.focus();
789 sel.blur();
790 }
791 }
792
793 function cbi_combobox_init(id, values, def, man) {
794 var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
795 cbi_bind(obj, "blur", function() {
796 cbi_combobox(obj.id, values, def, man, true);
797 });
798 cbi_combobox(obj.id, values, def, man, false);
799 }
800
801 function cbi_filebrowser(id, defpath) {
802 var field = document.getElementById(id);
803 var browser = window.open(
804 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
805 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
806 );
807
808 browser.focus();
809 }
810
811 function cbi_browser_init(id, resource, defpath)
812 {
813 function cbi_browser_btnclick(e) {
814 cbi_filebrowser(id, defpath);
815 return false;
816 }
817
818 var field = document.getElementById(id);
819
820 var btn = document.createElement('img');
821 btn.className = 'cbi-image-button';
822 btn.src = (resource || cbi_strings.path.resource) + '/cbi/folder.gif';
823 field.parentNode.insertBefore(btn, field.nextSibling);
824
825 cbi_bind(btn, 'click', cbi_browser_btnclick);
826 }
827
828 function cbi_dynlist_init(parent, datatype, optional, choices)
829 {
830 var prefix = parent.getAttribute('data-prefix');
831 var holder = parent.getAttribute('data-placeholder');
832
833 var values;
834
835 function cbi_dynlist_redraw(focus, add, del)
836 {
837 values = [ ];
838
839 while (parent.firstChild) {
840 var n = parent.firstChild;
841 var i = +n.index;
842
843 if (i != del) {
844 if (matchesElem(n, 'input'))
845 values.push(n.value || '');
846 else if (matchesElem(n, 'select'))
847 values[values.length-1] = n.options[n.selectedIndex].value;
848 }
849
850 parent.removeChild(n);
851 }
852
853 if (add >= 0) {
854 focus = add+1;
855 values.splice(focus, 0, '');
856 }
857 else if (values.length == 0) {
858 focus = 0;
859 values.push('');
860 }
861
862 for (var i = 0; i < values.length; i++) {
863 var t = document.createElement('input');
864 t.id = prefix + '.' + (i+1);
865 t.name = prefix;
866 t.value = values[i];
867 t.type = 'text';
868 t.index = i;
869 t.className = 'cbi-input-text';
870
871 if (i == 0 && holder)
872 t.placeholder = holder;
873
874 var b = E('div', {
875 class: 'cbi-button cbi-button-' + ((i+1) < values.length ? 'remove' : 'add')
876 }, (i+1) < values.length ? '×' : '+');
877
878 parent.appendChild(t);
879 parent.appendChild(b);
880
881 if (datatype == 'file')
882 cbi_browser_init(t.id, null, parent.getAttribute('data-browser-path'));
883
884 parent.appendChild(document.createElement('br'));
885
886 if (datatype)
887 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
888
889 if (choices) {
890 cbi_combobox_init(t.id, choices, '', _('-- custom --'));
891 b.index = i;
892
893 cbi_bind(b, 'keydown', cbi_dynlist_keydown);
894 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
895
896 if (i == focus || -i == focus)
897 b.focus();
898 }
899 else {
900 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
901 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
902
903 if (i == focus) {
904 t.focus();
905 }
906 else if (-i == focus) {
907 t.focus();
908
909 /* force cursor to end */
910 var v = t.value;
911 t.value = ' '
912 t.value = v;
913 }
914 }
915
916 cbi_bind(b, 'click', cbi_dynlist_btnclick);
917 }
918 }
919
920 function cbi_dynlist_keypress(ev)
921 {
922 ev = ev ? ev : window.event;
923
924 var se = ev.target ? ev.target : ev.srcElement;
925
926 if (se.nodeType == 3)
927 se = se.parentNode;
928
929 switch (ev.keyCode) {
930 /* backspace, delete */
931 case 8:
932 case 46:
933 if (se.value.length == 0) {
934 if (ev.preventDefault)
935 ev.preventDefault();
936
937 return false;
938 }
939
940 return true;
941
942 /* enter, arrow up, arrow down */
943 case 13:
944 case 38:
945 case 40:
946 if (ev.preventDefault)
947 ev.preventDefault();
948
949 return false;
950 }
951
952 return true;
953 }
954
955 function cbi_dynlist_keydown(ev)
956 {
957 ev = ev ? ev : window.event;
958
959 var se = ev.target ? ev.target : ev.srcElement;
960
961 if (se.nodeType == 3)
962 se = se.parentNode;
963
964 var prev = se.previousSibling;
965 while (prev && prev.name != prefix)
966 prev = prev.previousSibling;
967
968 var next = se.nextSibling;
969 while (next && next.name != prefix)
970 next = next.nextSibling;
971
972 /* advance one further in combobox case */
973 if (next && next.nextSibling.name == prefix)
974 next = next.nextSibling;
975
976 switch (ev.keyCode) {
977 /* backspace, delete */
978 case 8:
979 case 46:
980 var del = (matchesElem(se, 'select'))
981 ? true : (se.value.length == 0);
982
983 if (del) {
984 if (ev.preventDefault)
985 ev.preventDefault();
986
987 var focus = se.index;
988 if (ev.keyCode == 8)
989 focus = -focus+1;
990
991 cbi_dynlist_redraw(focus, -1, se.index);
992
993 return false;
994 }
995
996 break;
997
998 /* enter */
999 case 13:
1000 cbi_dynlist_redraw(-1, se.index, -1);
1001 break;
1002
1003 /* arrow up */
1004 case 38:
1005 if (prev)
1006 prev.focus();
1007
1008 break;
1009
1010 /* arrow down */
1011 case 40:
1012 if (next)
1013 next.focus();
1014
1015 break;
1016 }
1017
1018 return true;
1019 }
1020
1021 function cbi_dynlist_btnclick(ev)
1022 {
1023 ev = ev ? ev : window.event;
1024
1025 var se = ev.target ? ev.target : ev.srcElement;
1026 var input = se.previousSibling;
1027 while (input && input.name != prefix)
1028 input = input.previousSibling;
1029
1030 if (se.classList.contains('cbi-button-remove')) {
1031 input.value = '';
1032
1033 cbi_dynlist_keydown({
1034 target: input,
1035 keyCode: 8
1036 });
1037 }
1038 else {
1039 cbi_dynlist_keydown({
1040 target: input,
1041 keyCode: 13
1042 });
1043 }
1044
1045 return false;
1046 }
1047
1048 cbi_dynlist_redraw(NaN, -1, -1);
1049 }
1050
1051
1052 function cbi_t_add(section, tab) {
1053 var t = document.getElementById('tab.' + section + '.' + tab);
1054 var c = document.getElementById('container.' + section + '.' + tab);
1055
1056 if (t && c) {
1057 cbi_t[section] = (cbi_t[section] || [ ]);
1058 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
1059 }
1060 }
1061
1062 function cbi_t_switch(section, tab) {
1063 if (cbi_t[section] && cbi_t[section][tab]) {
1064 var o = cbi_t[section][tab];
1065 var h = document.getElementById('tab.' + section);
1066
1067 for (var tid in cbi_t[section]) {
1068 var o2 = cbi_t[section][tid];
1069
1070 if (o.tab.id != o2.tab.id) {
1071 o2.tab.classList.remove('cbi-tab');
1072 o2.tab.classList.add('cbi-tab-disabled');
1073 o2.container.style.display = 'none';
1074 }
1075 else {
1076 if(h)
1077 h.value = tab;
1078
1079 o2.tab.classList.remove('cbi-tab-disabled');
1080 o2.tab.classList.add('cbi-tab');
1081 o2.container.style.display = 'block';
1082 }
1083 }
1084 }
1085
1086 return false;
1087 }
1088
1089 function cbi_t_update() {
1090 var hl_tabs = [ ];
1091 var updated = false;
1092
1093 for (var sid in cbi_t)
1094 for (var tid in cbi_t[sid]) {
1095 var t = cbi_t[sid][tid].tab;
1096 var c = cbi_t[sid][tid].container;
1097
1098 if (!c.firstElementChild) {
1099 t.style.display = 'none';
1100 }
1101 else if (t.style.display == 'none') {
1102 t.style.display = '';
1103 t.classList.add('cbi-tab-highlighted');
1104 hl_tabs.push(t);
1105 }
1106
1107 cbi_tag_last(c);
1108 updated = true;
1109 }
1110
1111 if (hl_tabs.length > 0)
1112 window.setTimeout(function() {
1113 for (var i = 0; i < hl_tabs.length; i++)
1114 hl_tabs[i].classList.remove('cbi-tab-highlighted');
1115 }, 750);
1116
1117 return updated;
1118 }
1119
1120
1121 function cbi_validate_form(form, errmsg)
1122 {
1123 /* if triggered by a section removal or addition, don't validate */
1124 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
1125 return true;
1126
1127 if (form.cbi_validators) {
1128 for (var i = 0; i < form.cbi_validators.length; i++) {
1129 var validator = form.cbi_validators[i];
1130
1131 if (!validator() && errmsg) {
1132 alert(errmsg);
1133 return false;
1134 }
1135 }
1136 }
1137
1138 return true;
1139 }
1140
1141 function cbi_validate_reset(form)
1142 {
1143 window.setTimeout(
1144 function() { cbi_validate_form(form, null) }, 100
1145 );
1146
1147 return true;
1148 }
1149
1150 function cbi_validate_compile(code)
1151 {
1152 var pos = 0;
1153 var esc = false;
1154 var depth = 0;
1155 var stack = [ ];
1156
1157 code += ',';
1158
1159 for (var i = 0; i < code.length; i++) {
1160 if (esc) {
1161 esc = false;
1162 continue;
1163 }
1164
1165 switch (code.charCodeAt(i))
1166 {
1167 case 92:
1168 esc = true;
1169 break;
1170
1171 case 40:
1172 case 44:
1173 if (depth <= 0) {
1174 if (pos < i) {
1175 var label = code.substring(pos, i);
1176 label = label.replace(/\\(.)/g, '$1');
1177 label = label.replace(/^[ \t]+/g, '');
1178 label = label.replace(/[ \t]+$/g, '');
1179
1180 if (label && !isNaN(label)) {
1181 stack.push(parseFloat(label));
1182 }
1183 else if (label.match(/^(['"]).*\1$/)) {
1184 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
1185 }
1186 else if (typeof cbi_validators[label] == 'function') {
1187 stack.push(cbi_validators[label]);
1188 stack.push(null);
1189 }
1190 else {
1191 throw "Syntax error, unhandled token '"+label+"'";
1192 }
1193 }
1194
1195 pos = i+1;
1196 }
1197
1198 depth += (code.charCodeAt(i) == 40);
1199 break;
1200
1201 case 41:
1202 if (--depth <= 0) {
1203 if (typeof stack[stack.length-2] != 'function')
1204 throw "Syntax error, argument list follows non-function";
1205
1206 stack[stack.length-1] =
1207 arguments.callee(code.substring(pos, i));
1208
1209 pos = i+1;
1210 }
1211
1212 break;
1213 }
1214 }
1215
1216 return stack;
1217 }
1218
1219 function cbi_validate_field(cbid, optional, type)
1220 {
1221 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
1222 var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
1223
1224 if (field && vstack && typeof vstack[0] == "function") {
1225 var validator = function()
1226 {
1227 // is not detached
1228 if (field.form) {
1229 field.classList.remove('cbi-input-invalid');
1230
1231 // validate value
1232 var value = (field.options && field.options.selectedIndex > -1)
1233 ? field.options[field.options.selectedIndex].value : field.value;
1234
1235 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1]))) {
1236 // invalid
1237 field.classList.add('cbi-input-invalid');
1238 return false;
1239 }
1240 }
1241
1242 return true;
1243 };
1244
1245 if (!field.form.cbi_validators)
1246 field.form.cbi_validators = [ ];
1247
1248 field.form.cbi_validators.push(validator);
1249
1250 cbi_bind(field, "blur", validator);
1251 cbi_bind(field, "keyup", validator);
1252
1253 if (matchesElem(field, 'select')) {
1254 cbi_bind(field, "change", validator);
1255 cbi_bind(field, "click", validator);
1256 }
1257
1258 field.setAttribute("cbi_validate", validator);
1259 field.setAttribute("cbi_datatype", type);
1260 field.setAttribute("cbi_optional", (!!optional).toString());
1261
1262 validator();
1263
1264 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1265 if (fcbox)
1266 cbi_validate_field(fcbox, optional, type);
1267 }
1268 }
1269
1270 function cbi_row_swap(elem, up, store)
1271 {
1272 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
1273
1274 if (!tr)
1275 return false;
1276
1277 tr.classList.remove('flash');
1278
1279 if (up) {
1280 var prev = tr.previousElementSibling;
1281
1282 if (prev && prev.classList.contains('cbi-section-table-row'))
1283 tr.parentNode.insertBefore(tr, prev);
1284 else
1285 return;
1286 }
1287 else {
1288 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1289
1290 if (next && next.classList.contains('cbi-section-table-row'))
1291 tr.parentNode.insertBefore(tr, next);
1292 else if (!next)
1293 tr.parentNode.appendChild(tr);
1294 else
1295 return;
1296 }
1297
1298 var ids = [ ];
1299
1300 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1301 var node = tr.parentNode.childNodes[i];
1302 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1303 node.classList.remove('cbi-rowstyle-1');
1304 node.classList.remove('cbi-rowstyle-2');
1305 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1306
1307 if (/-([^\-]+)$/.test(node.id))
1308 ids.push(RegExp.$1);
1309 }
1310 }
1311
1312 var input = document.getElementById(store);
1313 if (input)
1314 input.value = ids.join(' ');
1315
1316 window.scrollTo(0, tr.offsetTop);
1317 void tr.offsetWidth;
1318 tr.classList.add('flash');
1319
1320 return false;
1321 }
1322
1323 function cbi_tag_last(container)
1324 {
1325 var last;
1326
1327 for (var i = 0; i < container.childNodes.length; i++) {
1328 var c = container.childNodes[i];
1329 if (matchesElem(c, 'div')) {
1330 c.classList.remove('cbi-value-last');
1331 last = c;
1332 }
1333 }
1334
1335 if (last)
1336 last.classList.add('cbi-value-last');
1337 }
1338
1339 function cbi_submit(elem, name, value, action)
1340 {
1341 var form = elem.form || findParent(elem, 'form');
1342
1343 if (!form)
1344 return false;
1345
1346 if (action)
1347 form.action = action;
1348
1349 if (name) {
1350 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1351 E('input', { type: 'hidden', name: name });
1352
1353 hidden.value = value || '1';
1354 form.appendChild(hidden);
1355 }
1356
1357 form.submit();
1358 return true;
1359 }
1360
1361 String.prototype.format = function()
1362 {
1363 if (!RegExp)
1364 return;
1365
1366 var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1367 var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1368
1369 function esc(s, r) {
1370 if (typeof(s) !== 'string' && !(s instanceof String))
1371 return '';
1372
1373 for (var i = 0; i < r.length; i += 2)
1374 s = s.replace(r[i], r[i+1]);
1375
1376 return s;
1377 }
1378
1379 var str = this;
1380 var out = '';
1381 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1382 var a = b = [], numSubstitutions = 0, numMatches = 0;
1383
1384 while (a = re.exec(str)) {
1385 var m = a[1];
1386 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1387 var pPrecision = a[6], pType = a[7];
1388
1389 numMatches++;
1390
1391 if (pType == '%') {
1392 subst = '%';
1393 }
1394 else {
1395 if (numSubstitutions < arguments.length) {
1396 var param = arguments[numSubstitutions++];
1397
1398 var pad = '';
1399 if (pPad && pPad.substr(0,1) == "'")
1400 pad = leftpart.substr(1,1);
1401 else if (pPad)
1402 pad = pPad;
1403 else
1404 pad = ' ';
1405
1406 var justifyRight = true;
1407 if (pJustify && pJustify === "-")
1408 justifyRight = false;
1409
1410 var minLength = -1;
1411 if (pMinLength)
1412 minLength = +pMinLength;
1413
1414 var precision = -1;
1415 if (pPrecision && pType == 'f')
1416 precision = +pPrecision.substring(1);
1417
1418 var subst = param;
1419
1420 switch(pType) {
1421 case 'b':
1422 subst = (+param || 0).toString(2);
1423 break;
1424
1425 case 'c':
1426 subst = String.fromCharCode(+param || 0);
1427 break;
1428
1429 case 'd':
1430 subst = ~~(+param || 0);
1431 break;
1432
1433 case 'u':
1434 subst = ~~Math.abs(+param || 0);
1435 break;
1436
1437 case 'f':
1438 subst = (precision > -1)
1439 ? ((+param || 0.0)).toFixed(precision)
1440 : (+param || 0.0);
1441 break;
1442
1443 case 'o':
1444 subst = (+param || 0).toString(8);
1445 break;
1446
1447 case 's':
1448 subst = param;
1449 break;
1450
1451 case 'x':
1452 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1453 break;
1454
1455 case 'X':
1456 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1457 break;
1458
1459 case 'h':
1460 subst = esc(param, html_esc);
1461 break;
1462
1463 case 'q':
1464 subst = esc(param, quot_esc);
1465 break;
1466
1467 case 't':
1468 var td = 0;
1469 var th = 0;
1470 var tm = 0;
1471 var ts = (param || 0);
1472
1473 if (ts > 60) {
1474 tm = Math.floor(ts / 60);
1475 ts = (ts % 60);
1476 }
1477
1478 if (tm > 60) {
1479 th = Math.floor(tm / 60);
1480 tm = (tm % 60);
1481 }
1482
1483 if (th > 24) {
1484 td = Math.floor(th / 24);
1485 th = (th % 24);
1486 }
1487
1488 subst = (td > 0)
1489 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1490 : String.format('%dh %dm %ds', th, tm, ts);
1491
1492 break;
1493
1494 case 'm':
1495 var mf = pMinLength ? +pMinLength : 1000;
1496 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1497
1498 var i = 0;
1499 var val = (+param || 0);
1500 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1501
1502 for (i = 0; (i < units.length) && (val > mf); i++)
1503 val /= mf;
1504
1505 subst = (i ? val.toFixed(pr) : val) + units[i];
1506 pMinLength = null;
1507 break;
1508 }
1509 }
1510 }
1511
1512 if (pMinLength) {
1513 subst = subst.toString();
1514 for (var i = subst.length; i < pMinLength; i++)
1515 if (pJustify == '-')
1516 subst = subst + ' ';
1517 else
1518 subst = pad + subst;
1519 }
1520
1521 out += leftpart + subst;
1522 str = str.substr(m.length);
1523 }
1524
1525 return out + str;
1526 }
1527
1528 String.prototype.nobr = function()
1529 {
1530 return this.replace(/[\s\n]+/g, '&#160;');
1531 }
1532
1533 String.format = function()
1534 {
1535 var a = [ ];
1536
1537 for (var i = 1; i < arguments.length; i++)
1538 a.push(arguments[i]);
1539
1540 return ''.format.apply(arguments[0], a);
1541 }
1542
1543 String.nobr = function()
1544 {
1545 var a = [ ];
1546
1547 for (var i = 1; i < arguments.length; i++)
1548 a.push(arguments[i]);
1549
1550 return ''.nobr.apply(arguments[0], a);
1551 }
1552
1553 if (window.NodeList && !NodeList.prototype.forEach) {
1554 NodeList.prototype.forEach = function (callback, thisArg) {
1555 thisArg = thisArg || window;
1556 for (var i = 0; i < this.length; i++) {
1557 callback.call(thisArg, this[i], i, this);
1558 }
1559 };
1560 }
1561
1562
1563 var dummyElem, domParser;
1564
1565 function isElem(e)
1566 {
1567 return (typeof(e) === 'object' && e !== null && 'nodeType' in e);
1568 }
1569
1570 function toElem(s)
1571 {
1572 var elem;
1573
1574 try {
1575 domParser = domParser || new DOMParser();
1576 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1577 }
1578 catch(e) {}
1579
1580 if (!elem) {
1581 try {
1582 dummyElem = dummyElem || document.createElement('div');
1583 dummyElem.innerHTML = s;
1584 elem = dummyElem.firstChild;
1585 }
1586 catch (e) {}
1587 }
1588
1589 return elem || null;
1590 }
1591
1592 function matchesElem(node, selector)
1593 {
1594 return ((node.matches && node.matches(selector)) ||
1595 (node.msMatchesSelector && node.msMatchesSelector(selector)));
1596 }
1597
1598 function findParent(node, selector)
1599 {
1600 while (node)
1601 if (matchesElem(node, selector))
1602 return node;
1603 else
1604 node = node.parentNode;
1605
1606 return null;
1607 }
1608
1609 function E()
1610 {
1611 var html = arguments[0],
1612 attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null,
1613 data = attr ? arguments[2] : arguments[1],
1614 elem;
1615
1616 if (isElem(html))
1617 elem = html;
1618 else if (html.charCodeAt(0) === 60)
1619 elem = toElem(html);
1620 else
1621 elem = document.createElement(html);
1622
1623 if (!elem)
1624 return null;
1625
1626 if (attr)
1627 for (var key in attr)
1628 if (attr.hasOwnProperty(key) && attr[key] !== null && attr[key] !== undefined)
1629 elem.setAttribute(key, attr[key]);
1630
1631 if (typeof(data) === 'function')
1632 data = data(elem);
1633
1634 if (isElem(data)) {
1635 elem.appendChild(data);
1636 }
1637 else if (Array.isArray(data)) {
1638 for (var i = 0; i < data.length; i++)
1639 if (isElem(data[i]))
1640 elem.appendChild(data[i]);
1641 else
1642 elem.appendChild(document.createTextNode('' + data[i]));
1643 }
1644 else if (data !== null && data !== undefined) {
1645 elem.innerHTML = '' + data;
1646 }
1647
1648 return elem;
1649 }
1650
1651 if (typeof(window.CustomEvent) !== 'function') {
1652 function CustomEvent(event, params) {
1653 params = params || { bubbles: false, cancelable: false, detail: undefined };
1654 var evt = document.createEvent('CustomEvent');
1655 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1656 return evt;
1657 }
1658
1659 CustomEvent.prototype = window.Event.prototype;
1660 window.CustomEvent = CustomEvent;
1661 }
1662
1663 CBIDropdown = {
1664 openDropdown: function(sb) {
1665 var st = window.getComputedStyle(sb, null),
1666 ul = sb.querySelector('ul'),
1667 li = ul.querySelectorAll('li'),
1668 sel = ul.querySelector('[selected]'),
1669 rect = sb.getBoundingClientRect(),
1670 h = sb.clientHeight - parseFloat(st.paddingTop) - parseFloat(st.paddingBottom),
1671 mh = this.dropdown_items * h,
1672 eh = Math.min(mh, li.length * h);
1673
1674 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1675 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1676 });
1677
1678 ul.style.maxHeight = mh + 'px';
1679 sb.setAttribute('open', '');
1680
1681 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1682 ul.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c) {
1683 c.checked = true;
1684 });
1685
1686 ul.style.top = ul.style.bottom = '';
1687 ul.style[((sb.getBoundingClientRect().top + eh) > window.innerHeight) ? 'bottom' : 'top'] = rect.height + 'px';
1688 ul.classList.add('dropdown');
1689
1690 var pv = ul.cloneNode(true);
1691 pv.classList.remove('dropdown');
1692 pv.classList.add('preview');
1693
1694 sb.insertBefore(pv, ul.nextElementSibling);
1695
1696 li.forEach(function(l) {
1697 l.setAttribute('tabindex', 0);
1698 });
1699
1700 sb.lastElementChild.setAttribute('tabindex', 0);
1701
1702 this.setFocus(sb, sel || li[0], true);
1703 },
1704
1705 closeDropdown: function(sb, no_focus) {
1706 if (!sb.hasAttribute('open'))
1707 return;
1708
1709 var pv = sb.querySelector('ul.preview'),
1710 ul = sb.querySelector('ul.dropdown'),
1711 li = ul.querySelectorAll('li');
1712
1713 li.forEach(function(l) { l.removeAttribute('tabindex'); });
1714 sb.lastElementChild.removeAttribute('tabindex');
1715
1716 sb.removeChild(pv);
1717 sb.removeAttribute('open');
1718 sb.style.width = sb.style.height = '';
1719
1720 ul.classList.remove('dropdown');
1721
1722 if (!no_focus)
1723 this.setFocus(sb, sb);
1724
1725 this.saveValues(sb, ul);
1726 },
1727
1728 toggleItem: function(sb, li, force_state) {
1729 if (li.hasAttribute('unselectable'))
1730 return;
1731
1732 if (this.multi) {
1733 var cbox = li.querySelector('input[type="checkbox"]'),
1734 items = li.parentNode.querySelectorAll('li'),
1735 label = sb.querySelector('ul.preview'),
1736 sel = li.parentNode.querySelectorAll('[selected]').length,
1737 more = sb.querySelector('.more'),
1738 ndisplay = this.display_items,
1739 n = 0;
1740
1741 if (li.hasAttribute('selected')) {
1742 if (force_state !== true) {
1743 if (sel > 1 || this.optional) {
1744 li.removeAttribute('selected');
1745 cbox.checked = cbox.disabled = false;
1746 sel--;
1747 }
1748 else {
1749 cbox.disabled = true;
1750 }
1751 }
1752 }
1753 else {
1754 if (force_state !== false) {
1755 li.setAttribute('selected', '');
1756 cbox.checked = true;
1757 cbox.disabled = false;
1758 sel++;
1759 }
1760 }
1761
1762 while (label.firstElementChild)
1763 label.removeChild(label.firstElementChild);
1764
1765 for (var i = 0; i < items.length; i++) {
1766 items[i].removeAttribute('display');
1767 if (items[i].hasAttribute('selected')) {
1768 if (ndisplay-- > 0) {
1769 items[i].setAttribute('display', n++);
1770 label.appendChild(items[i].cloneNode(true));
1771 }
1772 var c = items[i].querySelector('input[type="checkbox"]');
1773 if (c)
1774 c.disabled = (sel == 1 && !this.optional);
1775 }
1776 }
1777
1778 if (ndisplay < 0)
1779 sb.setAttribute('more', '');
1780 else
1781 sb.removeAttribute('more');
1782
1783 if (ndisplay === this.display_items)
1784 sb.setAttribute('empty', '');
1785 else
1786 sb.removeAttribute('empty');
1787
1788 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1789 }
1790 else {
1791 var sel = li.parentNode.querySelector('[selected]');
1792 if (sel) {
1793 sel.removeAttribute('display');
1794 sel.removeAttribute('selected');
1795 }
1796
1797 li.setAttribute('display', 0);
1798 li.setAttribute('selected', '');
1799
1800 this.closeDropdown(sb, true);
1801 }
1802
1803 this.saveValues(sb, li.parentNode);
1804 },
1805
1806 transformItem: function(sb, li) {
1807 var cbox = E('form', {}, E('input', { type: 'checkbox', tabindex: -1, onclick: 'event.preventDefault()' })),
1808 label = E('label');
1809
1810 while (li.firstChild)
1811 label.appendChild(li.firstChild);
1812
1813 li.appendChild(cbox);
1814 li.appendChild(label);
1815 },
1816
1817 saveValues: function(sb, ul) {
1818 var sel = ul.querySelectorAll('[selected]'),
1819 div = sb.lastElementChild;
1820
1821 while (div.lastElementChild)
1822 div.removeChild(div.lastElementChild);
1823
1824 sel.forEach(function (s) {
1825 div.appendChild(E('input', {
1826 type: 'hidden',
1827 name: s.hasAttribute('name') ? s.getAttribute('name') : (sb.getAttribute('name') || ''),
1828 value: s.hasAttribute('data-value') ? s.getAttribute('data-value') : s.innerText
1829 }));
1830 });
1831
1832 cbi_d_update();
1833 },
1834
1835 setFocus: function(sb, elem, scroll) {
1836 if (sb && sb.hasAttribute && sb.hasAttribute('locked-in'))
1837 return;
1838
1839 document.querySelectorAll('.focus').forEach(function(e) {
1840 if (!matchesElem(e, 'input')) {
1841 e.classList.remove('focus');
1842 e.blur();
1843 }
1844 });
1845
1846 if (elem) {
1847 elem.focus();
1848 elem.classList.add('focus');
1849
1850 if (scroll)
1851 elem.parentNode.scrollTop = elem.offsetTop - elem.parentNode.offsetTop;
1852 }
1853 },
1854
1855 createItems: function(sb, value) {
1856 var sbox = this,
1857 val = (value || '').trim().split(/\s+/),
1858 ul = sb.querySelector('ul');
1859
1860 if (!sbox.multi)
1861 val.length = Math.min(val.length, 1);
1862
1863 val.forEach(function(item) {
1864 var new_item = null;
1865
1866 ul.childNodes.forEach(function(li) {
1867 if (li.getAttribute && li.getAttribute('data-value') === item)
1868 new_item = li;
1869 });
1870
1871 if (!new_item) {
1872 var markup,
1873 tpl = sb.querySelector(sbox.template);
1874
1875 if (tpl)
1876 markup = (tpl.textContent || tpl.innerHTML || tpl.firstChild.data).replace(/^<!--|-->$/, '').trim();
1877 else
1878 markup = '<li data-value="{{value}}">{{value}}</li>';
1879
1880 new_item = E(markup.replace(/{{value}}/g, item));
1881
1882 if (sbox.multi) {
1883 sbox.transformItem(sb, new_item);
1884 }
1885 else {
1886 var old = ul.querySelector('li[created]');
1887 if (old)
1888 ul.removeChild(old);
1889
1890 new_item.setAttribute('created', '');
1891 }
1892
1893 new_item = ul.insertBefore(new_item, ul.lastElementChild);
1894 }
1895
1896 sbox.toggleItem(sb, new_item, true);
1897 sbox.setFocus(sb, new_item, true);
1898 });
1899 },
1900
1901 closeAllDropdowns: function() {
1902 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1903 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1904 });
1905 }
1906 };
1907
1908 function cbi_dropdown_init(sb) {
1909 if (!(this instanceof cbi_dropdown_init))
1910 return new cbi_dropdown_init(sb);
1911
1912 this.multi = sb.hasAttribute('multiple');
1913 this.optional = sb.hasAttribute('optional');
1914 this.placeholder = sb.getAttribute('placeholder') || '---';
1915 this.display_items = parseInt(sb.getAttribute('display-items') || 3);
1916 this.dropdown_items = parseInt(sb.getAttribute('dropdown-items') || 5);
1917 this.create = sb.getAttribute('item-create') || '.create-item-input';
1918 this.template = sb.getAttribute('item-template') || 'script[type="item-template"]';
1919
1920 var sbox = this,
1921 ul = sb.querySelector('ul'),
1922 items = ul.querySelectorAll('li'),
1923 more = sb.appendChild(E('span', { class: 'more', tabindex: -1 }, '···')),
1924 open = sb.appendChild(E('span', { class: 'open', tabindex: -1 }, 'â–¾')),
1925 canary = sb.appendChild(E('div')),
1926 create = sb.querySelector(this.create),
1927 ndisplay = this.display_items,
1928 n = 0;
1929
1930 if (this.multi) {
1931 for (var i = 0; i < items.length; i++) {
1932 sbox.transformItem(sb, items[i]);
1933
1934 if (items[i].hasAttribute('selected') && ndisplay-- > 0)
1935 items[i].setAttribute('display', n++);
1936 }
1937 }
1938 else {
1939 var sel = sb.querySelectorAll('[selected]');
1940
1941 sel.forEach(function(s) {
1942 s.removeAttribute('selected');
1943 });
1944
1945 var s = sel[0] || items[0];
1946 if (s) {
1947 s.setAttribute('selected', '');
1948 s.setAttribute('display', n++);
1949 }
1950
1951 ndisplay--;
1952
1953 if (this.optional && !ul.querySelector('li[data-value=""]')) {
1954 var placeholder = E('li', { placeholder: '' }, this.placeholder);
1955 ul.firstChild ? ul.insertBefore(placeholder, ul.firstChild) : ul.appendChild(placeholder);
1956 }
1957 }
1958
1959 sbox.saveValues(sb, ul);
1960
1961 ul.setAttribute('tabindex', -1);
1962 sb.setAttribute('tabindex', 0);
1963
1964 if (ndisplay < 0)
1965 sb.setAttribute('more', '')
1966 else
1967 sb.removeAttribute('more');
1968
1969 if (ndisplay === this.display_items)
1970 sb.setAttribute('empty', '')
1971 else
1972 sb.removeAttribute('empty');
1973
1974 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1975
1976
1977 sb.addEventListener('click', function(ev) {
1978 if (!this.hasAttribute('open')) {
1979 if (!matchesElem(ev.target, 'input'))
1980 sbox.openDropdown(this);
1981 }
1982 else {
1983 var li = findParent(ev.target, 'li');
1984 if (li && li.parentNode.classList.contains('dropdown'))
1985 sbox.toggleItem(this, li);
1986 }
1987
1988 ev.preventDefault();
1989 ev.stopPropagation();
1990 });
1991
1992 sb.addEventListener('keydown', function(ev) {
1993 if (matchesElem(ev.target, 'input'))
1994 return;
1995
1996 if (!this.hasAttribute('open')) {
1997 switch (ev.keyCode) {
1998 case 37:
1999 case 38:
2000 case 39:
2001 case 40:
2002 sbox.openDropdown(this);
2003 ev.preventDefault();
2004 }
2005 }
2006 else
2007 {
2008 var active = findParent(document.activeElement, 'li');
2009
2010 switch (ev.keyCode) {
2011 case 27:
2012 sbox.closeDropdown(this);
2013 break;
2014
2015 case 13:
2016 if (active) {
2017 if (!active.hasAttribute('selected'))
2018 sbox.toggleItem(this, active);
2019 sbox.closeDropdown(this);
2020 ev.preventDefault();
2021 }
2022 break;
2023
2024 case 32:
2025 if (active) {
2026 sbox.toggleItem(this, active);
2027 ev.preventDefault();
2028 }
2029 break;
2030
2031 case 38:
2032 if (active && active.previousElementSibling) {
2033 sbox.setFocus(this, active.previousElementSibling);
2034 ev.preventDefault();
2035 }
2036 break;
2037
2038 case 40:
2039 if (active && active.nextElementSibling) {
2040 sbox.setFocus(this, active.nextElementSibling);
2041 ev.preventDefault();
2042 }
2043 break;
2044 }
2045 }
2046 });
2047
2048 sb.addEventListener('cbi-dropdown-close', function(ev) {
2049 sbox.closeDropdown(this, true);
2050 });
2051
2052 if ('ontouchstart' in window) {
2053 sb.addEventListener('touchstart', function(ev) { ev.stopPropagation(); });
2054 window.addEventListener('touchstart', sbox.closeAllDropdowns);
2055 }
2056 else {
2057 sb.addEventListener('mouseover', function(ev) {
2058 if (!this.hasAttribute('open'))
2059 return;
2060
2061 var li = findParent(ev.target, 'li');
2062 if (li) {
2063 if (li.parentNode.classList.contains('dropdown'))
2064 sbox.setFocus(this, li);
2065
2066 ev.stopPropagation();
2067 }
2068 });
2069
2070 sb.addEventListener('focus', function(ev) {
2071 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
2072 if (s !== this || this.hasAttribute('open'))
2073 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
2074 });
2075 });
2076
2077 canary.addEventListener('focus', function(ev) {
2078 sbox.closeDropdown(this.parentNode);
2079 });
2080
2081 window.addEventListener('mouseover', sbox.setFocus);
2082 window.addEventListener('click', sbox.closeAllDropdowns);
2083 }
2084
2085 if (create) {
2086 create.addEventListener('keydown', function(ev) {
2087 switch (ev.keyCode) {
2088 case 13:
2089 ev.preventDefault();
2090
2091 if (this.classList.contains('cbi-input-invalid'))
2092 return;
2093
2094 sbox.createItems(sb, this.value);
2095 this.value = '';
2096 this.blur();
2097 break;
2098 }
2099 });
2100
2101 create.addEventListener('focus', function(ev) {
2102 var cbox = findParent(this, 'li').querySelector('input[type="checkbox"]');
2103 if (cbox) cbox.checked = true;
2104 sb.setAttribute('locked-in', '');
2105 });
2106
2107 create.addEventListener('blur', function(ev) {
2108 var cbox = findParent(this, 'li').querySelector('input[type="checkbox"]');
2109 if (cbox) cbox.checked = false;
2110 sb.removeAttribute('locked-in');
2111 });
2112
2113 var li = findParent(create, 'li');
2114
2115 li.setAttribute('unselectable', '');
2116 li.addEventListener('click', function(ev) {
2117 this.querySelector(sbox.create).focus();
2118 });
2119 }
2120 }
2121
2122 cbi_dropdown_init.prototype = CBIDropdown;
2123
2124 function cbi_update_table(table, data, placeholder) {
2125 var target = isElem(table) ? table : document.querySelector(table);
2126
2127 if (!isElem(target))
2128 return;
2129
2130 target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
2131 var titles = [];
2132
2133 thead.querySelectorAll('.th').forEach(function(th) {
2134 titles.push(th);
2135 });
2136
2137 if (Array.isArray(data)) {
2138 var n = 0, rows = target.querySelectorAll('.tr');
2139
2140 data.forEach(function(row) {
2141 var trow = E('div', { 'class': 'tr' });
2142
2143 for (var i = 0; i < titles.length; i++) {
2144 var text = (titles[i].innerText || '').trim();
2145 var td = trow.appendChild(E('div', {
2146 'class': titles[i].className,
2147 'data-title': (text !== '') ? text : null
2148 }, row[i] || ''));
2149
2150 td.classList.remove('th');
2151 td.classList.add('td');
2152 }
2153
2154 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
2155
2156 if (rows[n])
2157 target.replaceChild(trow, rows[n]);
2158 else
2159 target.appendChild(trow);
2160 });
2161
2162 while (rows[++n])
2163 target.removeChild(rows[n]);
2164
2165 if (placeholder && target.firstElementChild === target.lastElementChild) {
2166 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
2167 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
2168
2169 td.classList.remove('th');
2170 td.classList.add('td');
2171 }
2172 }
2173 else {
2174 thead.parentNode.style.display = 'none';
2175
2176 thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
2177 if (trow !== thead) {
2178 var n = 0;
2179 trow.querySelectorAll('.th, .td').forEach(function(td) {
2180 if (n < titles.length) {
2181 var text = (titles[n++].innerText || '').trim();
2182 if (text !== '')
2183 td.setAttribute('data-title', text);
2184 }
2185 });
2186 }
2187 });
2188
2189 thead.parentNode.style.display = '';
2190 }
2191 });
2192 }
2193
2194 document.addEventListener('DOMContentLoaded', function() {
2195 document.querySelectorAll('.table').forEach(cbi_update_table);
2196 });