luci-base: drive-by fixes
[project/luci.git] / modules / luci-base / htdocs / luci-static / resources / form.js
1 'use strict';
2 'require ui';
3 'require uci';
4 'require rpc';
5 'require dom';
6 'require baseclass';
7
8 var scope = this;
9
10 var callSessionAccess = rpc.declare({
11 object: 'session',
12 method: 'access',
13 params: [ 'scope', 'object', 'function' ],
14 expect: { 'access': false }
15 });
16
17 var CBIJSONConfig = baseclass.extend({
18 __init__: function(data) {
19 data = Object.assign({}, data);
20
21 this.data = {};
22
23 var num_sections = 0,
24 section_ids = [];
25
26 for (var sectiontype in data) {
27 if (!data.hasOwnProperty(sectiontype))
28 continue;
29
30 if (Array.isArray(data[sectiontype])) {
31 for (var i = 0, index = 0; i < data[sectiontype].length; i++) {
32 var item = data[sectiontype][i],
33 anonymous, name;
34
35 if (!L.isObject(item))
36 continue;
37
38 if (typeof(item['.name']) == 'string') {
39 name = item['.name'];
40 anonymous = false;
41 }
42 else {
43 name = sectiontype + num_sections;
44 anonymous = true;
45 }
46
47 if (!this.data.hasOwnProperty(name))
48 section_ids.push(name);
49
50 this.data[name] = Object.assign(item, {
51 '.index': num_sections++,
52 '.anonymous': anonymous,
53 '.name': name,
54 '.type': sectiontype
55 });
56 }
57 }
58 else if (L.isObject(data[sectiontype])) {
59 this.data[sectiontype] = Object.assign(data[sectiontype], {
60 '.anonymous': false,
61 '.name': sectiontype,
62 '.type': sectiontype
63 });
64
65 section_ids.push(sectiontype);
66 num_sections++;
67 }
68 }
69
70 section_ids.sort(L.bind(function(a, b) {
71 var indexA = (this.data[a]['.index'] != null) ? +this.data[a]['.index'] : 9999,
72 indexB = (this.data[b]['.index'] != null) ? +this.data[b]['.index'] : 9999;
73
74 if (indexA != indexB)
75 return (indexA - indexB);
76
77 return L.naturalCompare(a, b);
78 }, this));
79
80 for (var i = 0; i < section_ids.length; i++)
81 this.data[section_ids[i]]['.index'] = i;
82 },
83
84 load: function() {
85 return Promise.resolve(this.data);
86 },
87
88 save: function() {
89 return Promise.resolve();
90 },
91
92 get: function(config, section, option) {
93 if (section == null)
94 return null;
95
96 if (option == null)
97 return this.data[section];
98
99 if (!this.data.hasOwnProperty(section))
100 return null;
101
102 var value = this.data[section][option];
103
104 if (Array.isArray(value))
105 return value;
106
107 if (value != null)
108 return String(value);
109
110 return null;
111 },
112
113 set: function(config, section, option, value) {
114 if (section == null || option == null || option.charAt(0) == '.')
115 return;
116
117 if (!this.data.hasOwnProperty(section))
118 return;
119
120 if (value == null)
121 delete this.data[section][option];
122 else if (Array.isArray(value))
123 this.data[section][option] = value;
124 else
125 this.data[section][option] = String(value);
126 },
127
128 unset: function(config, section, option) {
129 return this.set(config, section, option, null);
130 },
131
132 sections: function(config, sectiontype, callback) {
133 var rv = [];
134
135 for (var section_id in this.data)
136 if (sectiontype == null || this.data[section_id]['.type'] == sectiontype)
137 rv.push(this.data[section_id]);
138
139 rv.sort(function(a, b) { return a['.index'] - b['.index'] });
140
141 if (typeof(callback) == 'function')
142 for (var i = 0; i < rv.length; i++)
143 callback.call(this, rv[i], rv[i]['.name']);
144
145 return rv;
146 },
147
148 add: function(config, sectiontype, sectionname) {
149 var num_sections_type = 0, next_index = 0;
150
151 for (var name in this.data) {
152 num_sections_type += (this.data[name]['.type'] == sectiontype);
153 next_index = Math.max(next_index, this.data[name]['.index']);
154 }
155
156 var section_id = sectionname || sectiontype + num_sections_type;
157
158 if (!this.data.hasOwnProperty(section_id)) {
159 this.data[section_id] = {
160 '.name': section_id,
161 '.type': sectiontype,
162 '.anonymous': (sectionname == null),
163 '.index': next_index + 1
164 };
165 }
166
167 return section_id;
168 },
169
170 remove: function(config, section) {
171 if (this.data.hasOwnProperty(section))
172 delete this.data[section];
173 },
174
175 resolveSID: function(config, section_id) {
176 return section_id;
177 },
178
179 move: function(config, section_id1, section_id2, after) {
180 return uci.move.apply(this, [config, section_id1, section_id2, after]);
181 }
182 });
183
184 /**
185 * @class AbstractElement
186 * @memberof LuCI.form
187 * @hideconstructor
188 * @classdesc
189 *
190 * The `AbstractElement` class serves as abstract base for the different form
191 * elements implemented by `LuCI.form`. It provides the common logic for
192 * loading and rendering values, for nesting elements and for defining common
193 * properties.
194 *
195 * This class is private and not directly accessible by user code.
196 */
197 var CBIAbstractElement = baseclass.extend(/** @lends LuCI.form.AbstractElement.prototype */ {
198 __init__: function(title, description) {
199 this.title = title || '';
200 this.description = description || '';
201 this.children = [];
202 },
203
204 /**
205 * Add another form element as children to this element.
206 *
207 * @param {AbstractElement} obj
208 * The form element to add.
209 */
210 append: function(obj) {
211 this.children.push(obj);
212 },
213
214 /**
215 * Parse this elements form input.
216 *
217 * The `parse()` function recursively walks the form element tree and
218 * triggers input value reading and validation for each encountered element.
219 *
220 * Elements which are hidden due to unsatisfied dependencies are skipped.
221 *
222 * @returns {Promise<void>}
223 * Returns a promise resolving once this element's value and the values of
224 * all child elements have been parsed. The returned promise is rejected
225 * if any parsed values are not meeting the validation constraints of their
226 * respective elements.
227 */
228 parse: function() {
229 var args = arguments;
230 this.children.forEach(function(child) {
231 child.parse.apply(child, args);
232 });
233 },
234
235 /**
236 * Render the form element.
237 *
238 * The `render()` function recursively walks the form element tree and
239 * renders the markup for each element, returning the assembled DOM tree.
240 *
241 * @abstract
242 * @returns {Node|Promise<Node>}
243 * May return a DOM Node or a promise resolving to a DOM node containing
244 * the form element's markup, including the markup of any child elements.
245 */
246 render: function() {
247 L.error('InternalError', 'Not implemented');
248 },
249
250 /** @private */
251 loadChildren: function(/* ... */) {
252 var tasks = [];
253
254 if (Array.isArray(this.children))
255 for (var i = 0; i < this.children.length; i++)
256 if (!this.children[i].disable)
257 tasks.push(this.children[i].load.apply(this.children[i], arguments));
258
259 return Promise.all(tasks);
260 },
261
262 /** @private */
263 renderChildren: function(tab_name /*, ... */) {
264 var tasks = [],
265 index = 0;
266
267 if (Array.isArray(this.children))
268 for (var i = 0; i < this.children.length; i++)
269 if (tab_name === null || this.children[i].tab === tab_name)
270 if (!this.children[i].disable)
271 tasks.push(this.children[i].render.apply(
272 this.children[i], this.varargs(arguments, 1, index++)));
273
274 return Promise.all(tasks);
275 },
276
277 /**
278 * Strip any HTML tags from the given input string.
279 *
280 * @param {string} s
281 * The input string to clean.
282 *
283 * @returns {string}
284 * The cleaned input string with HTML tags removed.
285 */
286 stripTags: function(s) {
287 if (typeof(s) == 'string' && !s.match(/[<>]/))
288 return s;
289
290 var x = dom.elem(s) ? s : dom.parse('<div>' + s + '</div>');
291
292 x.querySelectorAll('br').forEach(function(br) {
293 x.replaceChild(document.createTextNode('\n'), br);
294 });
295
296 return (x.textContent || x.innerText || '').replace(/([ \t]*\n)+/g, '\n');
297 },
298
299 /**
300 * Format the given named property as title string.
301 *
302 * This function looks up the given named property and formats its value
303 * suitable for use as element caption or description string. It also
304 * strips any HTML tags from the result.
305 *
306 * If the property value is a string, it is passed to `String.format()`
307 * along with any additional parameters passed to `titleFn()`.
308 *
309 * If the property value is a function, it is invoked with any additional
310 * `titleFn()` parameters as arguments and the obtained return value is
311 * converted to a string.
312 *
313 * In all other cases, `null` is returned.
314 *
315 * @param {string} property
316 * The name of the element property to use.
317 *
318 * @param {...*} fmt_args
319 * Extra values to format the title string with.
320 *
321 * @returns {string|null}
322 * The formatted title string or `null` if the property did not exist or
323 * was neither a string nor a function.
324 */
325 titleFn: function(attr /*, ... */) {
326 var s = null;
327
328 if (typeof(this[attr]) == 'function')
329 s = this[attr].apply(this, this.varargs(arguments, 1));
330 else if (typeof(this[attr]) == 'string')
331 s = (arguments.length > 1) ? ''.format.apply(this[attr], this.varargs(arguments, 1)) : this[attr];
332
333 if (s != null)
334 s = this.stripTags(String(s)).trim();
335
336 if (s == null || s == '')
337 return null;
338
339 return s;
340 }
341 });
342
343 /**
344 * @constructor Map
345 * @memberof LuCI.form
346 * @augments LuCI.form.AbstractElement
347 *
348 * @classdesc
349 *
350 * The `Map` class represents one complete form. A form usually maps one UCI
351 * configuration file and is divided into multiple sections containing multiple
352 * fields each.
353 *
354 * It serves as main entry point into the `LuCI.form` for typical view code.
355 *
356 * @param {string} config
357 * The UCI configuration to map. It is automatically loaded along when the
358 * resulting map instance.
359 *
360 * @param {string} [title]
361 * The title caption of the form. A form title is usually rendered as separate
362 * headline element before the actual form contents. If omitted, the
363 * corresponding headline element will not be rendered.
364 *
365 * @param {string} [description]
366 * The description text of the form which is usually rendered as text
367 * paragraph below the form title and before the actual form contents.
368 * If omitted, the corresponding paragraph element will not be rendered.
369 */
370 var CBIMap = CBIAbstractElement.extend(/** @lends LuCI.form.Map.prototype */ {
371 __init__: function(config /*, ... */) {
372 this.super('__init__', this.varargs(arguments, 1));
373
374 this.config = config;
375 this.parsechain = [ config ];
376 this.data = uci;
377 },
378
379 /**
380 * Toggle readonly state of the form.
381 *
382 * If set to `true`, the Map instance is marked readonly and any form
383 * option elements added to it will inherit the readonly state.
384 *
385 * If left unset, the Map will test the access permission of the primary
386 * uci configuration upon loading and mark the form readonly if no write
387 * permissions are granted.
388 *
389 * @name LuCI.form.Map.prototype#readonly
390 * @type boolean
391 */
392
393 /**
394 * Find all DOM nodes within this Map which match the given search
395 * parameters. This function is essentially a convenience wrapper around
396 * `querySelectorAll()`.
397 *
398 * This function is sensitive to the amount of arguments passed to it;
399 * if only one argument is specified, it is used as selector-expression
400 * as-is. When two arguments are passed, the first argument is treated
401 * as attribute name, the second one as attribute value to match.
402 *
403 * As an example, `map.findElements('input')` would find all `<input>`
404 * nodes while `map.findElements('type', 'text')` would find any DOM node
405 * with a `type="text"` attribute.
406 *
407 * @param {string} selector_or_attrname
408 * If invoked with only one parameter, this argument is a
409 * `querySelectorAll()` compatible selector expression. If invoked with
410 * two parameters, this argument is the attribute name to filter for.
411 *
412 * @param {string} [attrvalue]
413 * In case the function is invoked with two parameters, this argument
414 * specifies the attribute value to match.
415 *
416 * @throws {InternalError}
417 * Throws an `InternalError` if more than two function parameters are
418 * passed.
419 *
420 * @returns {NodeList}
421 * Returns a (possibly empty) DOM `NodeList` containing the found DOM nodes.
422 */
423 findElements: function(/* ... */) {
424 var q = null;
425
426 if (arguments.length == 1)
427 q = arguments[0];
428 else if (arguments.length == 2)
429 q = '[%s="%s"]'.format(arguments[0], arguments[1]);
430 else
431 L.error('InternalError', 'Expecting one or two arguments to findElements()');
432
433 return this.root.querySelectorAll(q);
434 },
435
436 /**
437 * Find the first DOM node within this Map which matches the given search
438 * parameters. This function is essentially a convenience wrapper around
439 * `findElements()` which only returns the first found node.
440 *
441 * This function is sensitive to the amount of arguments passed to it;
442 * if only one argument is specified, it is used as selector-expression
443 * as-is. When two arguments are passed, the first argument is treated
444 * as attribute name, the second one as attribute value to match.
445 *
446 * As an example, `map.findElement('input')` would find the first `<input>`
447 * node while `map.findElement('type', 'text')` would find the first DOM
448 * node with a `type="text"` attribute.
449 *
450 * @param {string} selector_or_attrname
451 * If invoked with only one parameter, this argument is a `querySelector()`
452 * compatible selector expression. If invoked with two parameters, this
453 * argument is the attribute name to filter for.
454 *
455 * @param {string} [attrvalue]
456 * In case the function is invoked with two parameters, this argument
457 * specifies the attribute value to match.
458 *
459 * @throws {InternalError}
460 * Throws an `InternalError` if more than two function parameters are
461 * passed.
462 *
463 * @returns {Node|null}
464 * Returns the first found DOM node or `null` if no element matched.
465 */
466 findElement: function(/* ... */) {
467 var res = this.findElements.apply(this, arguments);
468 return res.length ? res[0] : null;
469 },
470
471 /**
472 * Tie another UCI configuration to the map.
473 *
474 * By default, a map instance will only load the UCI configuration file
475 * specified in the constructor but sometimes access to values from
476 * further configuration files is required. This function allows for such
477 * use cases by registering further UCI configuration files which are
478 * needed by the map.
479 *
480 * @param {string} config
481 * The additional UCI configuration file to tie to the map. If the given
482 * config already is in the list of required files, it will be ignored.
483 */
484 chain: function(config) {
485 if (this.parsechain.indexOf(config) == -1)
486 this.parsechain.push(config);
487 },
488
489 /**
490 * Add a configuration section to the map.
491 *
492 * LuCI forms follow the structure of the underlying UCI configurations,
493 * means that a map, which represents a single UCI configuration, is
494 * divided into multiple sections which in turn contain an arbitrary
495 * number of options.
496 *
497 * While UCI itself only knows two kinds of sections - named and anonymous
498 * ones - the form class offers various flavors of form section elements
499 * to present configuration sections in different ways. Refer to the
500 * documentation of the different section classes for details.
501 *
502 * @param {LuCI.form.AbstractSection} sectionclass
503 * The section class to use for rendering the configuration section.
504 * Note that this value must be the class itself, not a class instance
505 * obtained from calling `new`. It must also be a class derived from
506 * `LuCI.form.AbstractSection`.
507 *
508 * @param {...string} classargs
509 * Additional arguments which are passed as-is to the constructor of the
510 * given section class. Refer to the class specific constructor
511 * documentation for details.
512 *
513 * @returns {LuCI.form.AbstractSection}
514 * Returns the instantiated section class instance.
515 */
516 section: function(cbiClass /*, ... */) {
517 if (!CBIAbstractSection.isSubclass(cbiClass))
518 L.error('TypeError', 'Class must be a descendent of CBIAbstractSection');
519
520 var obj = cbiClass.instantiate(this.varargs(arguments, 1, this));
521 this.append(obj);
522 return obj;
523 },
524
525 /**
526 * Load the configuration covered by this map.
527 *
528 * The `load()` function first loads all referenced UCI configurations,
529 * then it recursively walks the form element tree and invokes the
530 * load function of each child element.
531 *
532 * @returns {Promise<void>}
533 * Returns a promise resolving once the entire form completed loading all
534 * data. The promise may reject with an error if any configuration failed
535 * to load or if any of the child elements load functions rejected with
536 * an error.
537 */
538 load: function() {
539 var doCheckACL = (!(this instanceof CBIJSONMap) && this.readonly == null),
540 loadTasks = [ doCheckACL ? callSessionAccess('uci', this.config, 'write') : true ],
541 configs = this.parsechain || [ this.config ];
542
543 loadTasks.push.apply(loadTasks, configs.map(L.bind(function(config, i) {
544 return i ? L.resolveDefault(this.data.load(config)) : this.data.load(config);
545 }, this)));
546
547 return Promise.all(loadTasks).then(L.bind(function(res) {
548 if (res[0] === false)
549 this.readonly = true;
550
551 return this.loadChildren();
552 }, this));
553 },
554
555 /**
556 * Parse the form input values.
557 *
558 * The `parse()` function recursively walks the form element tree and
559 * triggers input value reading and validation for each child element.
560 *
561 * Elements which are hidden due to unsatisfied dependencies are skipped.
562 *
563 * @returns {Promise<void>}
564 * Returns a promise resolving once the entire form completed parsing all
565 * input values. The returned promise is rejected if any parsed values are
566 * not meeting the validation constraints of their respective elements.
567 */
568 parse: function() {
569 var tasks = [];
570
571 if (Array.isArray(this.children))
572 for (var i = 0; i < this.children.length; i++)
573 tasks.push(this.children[i].parse());
574
575 return Promise.all(tasks);
576 },
577
578 /**
579 * Save the form input values.
580 *
581 * This function parses the current form, saves the resulting UCI changes,
582 * reloads the UCI configuration data and redraws the form elements.
583 *
584 * @param {function} [cb]
585 * An optional callback function that is invoked after the form is parsed
586 * but before the changed UCI data is saved. This is useful to perform
587 * additional data manipulation steps before saving the changes.
588 *
589 * @param {boolean} [silent=false]
590 * If set to `true`, trigger an alert message to the user in case saving
591 * the form data failures. Otherwise fail silently.
592 *
593 * @returns {Promise<void>}
594 * Returns a promise resolving once the entire save operation is complete.
595 * The returned promise is rejected if any step of the save operation
596 * failed.
597 */
598 save: function(cb, silent) {
599 this.checkDepends();
600
601 return this.parse()
602 .then(cb)
603 .then(this.data.save.bind(this.data))
604 .then(this.load.bind(this))
605 .catch(function(e) {
606 if (!silent) {
607 ui.showModal(_('Save error'), [
608 E('p', {}, [ _('An error occurred while saving the form:') ]),
609 E('p', {}, [ E('em', { 'style': 'white-space:pre-wrap' }, [ e.message ]) ]),
610 E('div', { 'class': 'right' }, [
611 E('button', { 'class': 'cbi-button', 'click': ui.hideModal }, [ _('Dismiss') ])
612 ])
613 ]);
614 }
615
616 return Promise.reject(e);
617 }).then(this.renderContents.bind(this));
618 },
619
620 /**
621 * Reset the form by re-rendering its contents. This will revert all
622 * unsaved user inputs to their initial form state.
623 *
624 * @returns {Promise<Node>}
625 * Returns a promise resolving to the toplevel form DOM node once the
626 * re-rendering is complete.
627 */
628 reset: function() {
629 return this.renderContents();
630 },
631
632 /**
633 * Render the form markup.
634 *
635 * @returns {Promise<Node>}
636 * Returns a promise resolving to the toplevel form DOM node once the
637 * rendering is complete.
638 */
639 render: function() {
640 return this.load().then(this.renderContents.bind(this));
641 },
642
643 /** @private */
644 renderContents: function() {
645 var mapEl = this.root || (this.root = E('div', {
646 'id': 'cbi-%s'.format(this.config),
647 'class': 'cbi-map',
648 'cbi-dependency-check': L.bind(this.checkDepends, this)
649 }));
650
651 dom.bindClassInstance(mapEl, this);
652
653 return this.renderChildren(null).then(L.bind(function(nodes) {
654 var initialRender = !mapEl.firstChild;
655
656 dom.content(mapEl, null);
657
658 if (this.title != null && this.title != '')
659 mapEl.appendChild(E('h2', { 'name': 'content' }, this.title));
660
661 if (this.description != null && this.description != '')
662 mapEl.appendChild(E('div', { 'class': 'cbi-map-descr' }, this.description));
663
664 if (this.tabbed)
665 dom.append(mapEl, E('div', { 'class': 'cbi-map-tabbed' }, nodes));
666 else
667 dom.append(mapEl, nodes);
668
669 if (!initialRender) {
670 mapEl.classList.remove('flash');
671
672 window.setTimeout(function() {
673 mapEl.classList.add('flash');
674 }, 1);
675 }
676
677 this.checkDepends();
678
679 var tabGroups = mapEl.querySelectorAll('.cbi-map-tabbed, .cbi-section-node-tabbed');
680
681 for (var i = 0; i < tabGroups.length; i++)
682 ui.tabs.initTabGroup(tabGroups[i].childNodes);
683
684 return mapEl;
685 }, this));
686 },
687
688 /**
689 * Find a form option element instance.
690 *
691 * @param {string} name
692 * The name or the full ID of the option element to look up.
693 *
694 * @param {string} [section_id]
695 * The ID of the UCI section containing the option to look up. May be
696 * omitted if a full ID is passed as first argument.
697 *
698 * @param {string} [config_name]
699 * The name of the UCI configuration the option instance belongs to.
700 * Defaults to the main UCI configuration of the map if omitted.
701 *
702 * @returns {Array<LuCI.form.AbstractValue,string>|null}
703 * Returns a two-element array containing the form option instance as
704 * first item and the corresponding UCI section ID as second item.
705 * Returns `null` if the option could not be found.
706 */
707 lookupOption: function(name, section_id, config_name) {
708 var id, elem, sid, inst;
709
710 if (name.indexOf('.') > -1)
711 id = 'cbid.%s'.format(name);
712 else
713 id = 'cbid.%s.%s.%s'.format(config_name || this.config, section_id, name);
714
715 elem = this.findElement('data-field', id);
716 sid = elem ? id.split(/\./)[2] : null;
717 inst = elem ? dom.findClassInstance(elem) : null;
718
719 return (inst instanceof CBIAbstractValue) ? [ inst, sid ] : null;
720 },
721
722 /** @private */
723 checkDepends: function(ev, n) {
724 var changed = false;
725
726 for (var i = 0, s = this.children[0]; (s = this.children[i]) != null; i++)
727 if (s.checkDepends(ev, n))
728 changed = true;
729
730 if (changed && (n || 0) < 10)
731 this.checkDepends(ev, (n || 10) + 1);
732
733 ui.tabs.updateTabs(ev, this.root);
734 },
735
736 /** @private */
737 isDependencySatisfied: function(depends, config_name, section_id) {
738 var def = false;
739
740 if (!Array.isArray(depends) || !depends.length)
741 return true;
742
743 for (var i = 0; i < depends.length; i++) {
744 var istat = true,
745 reverse = depends[i]['!reverse'],
746 contains = depends[i]['!contains'];
747
748 for (var dep in depends[i]) {
749 if (dep == '!reverse' || dep == '!contains') {
750 continue;
751 }
752 else if (dep == '!default') {
753 def = true;
754 istat = false;
755 }
756 else {
757 var res = this.lookupOption(dep, section_id, config_name),
758 val = (res && res[0].isActive(res[1])) ? res[0].formvalue(res[1]) : null;
759
760 var equal = contains
761 ? isContained(val, depends[i][dep])
762 : isEqual(val, depends[i][dep]);
763
764 istat = (istat && equal);
765 }
766 }
767
768 if (istat ^ reverse)
769 return true;
770 }
771
772 return def;
773 }
774 });
775
776 /**
777 * @constructor JSONMap
778 * @memberof LuCI.form
779 * @augments LuCI.form.Map
780 *
781 * @classdesc
782 *
783 * A `JSONMap` class functions similar to [LuCI.form.Map]{@link LuCI.form.Map}
784 * but uses a multidimensional JavaScript object instead of UCI configuration
785 * as data source.
786 *
787 * @param {Object<string, Object<string, *>|Array<Object<string, *>>>} data
788 * The JavaScript object to use as data source. Internally, the object is
789 * converted into an UCI-like format. Its toplevel keys are treated like UCI
790 * section types while the object or array-of-object values are treated as
791 * section contents.
792 *
793 * @param {string} [title]
794 * The title caption of the form. A form title is usually rendered as separate
795 * headline element before the actual form contents. If omitted, the
796 * corresponding headline element will not be rendered.
797 *
798 * @param {string} [description]
799 * The description text of the form which is usually rendered as text
800 * paragraph below the form title and before the actual form contents.
801 * If omitted, the corresponding paragraph element will not be rendered.
802 */
803 var CBIJSONMap = CBIMap.extend(/** @lends LuCI.form.JSONMap.prototype */ {
804 __init__: function(data /*, ... */) {
805 this.super('__init__', this.varargs(arguments, 1, 'json'));
806
807 this.config = 'json';
808 this.parsechain = [ 'json' ];
809 this.data = new CBIJSONConfig(data);
810 }
811 });
812
813 /**
814 * @class AbstractSection
815 * @memberof LuCI.form
816 * @augments LuCI.form.AbstractElement
817 * @hideconstructor
818 * @classdesc
819 *
820 * The `AbstractSection` class serves as abstract base for the different form
821 * section styles implemented by `LuCI.form`. It provides the common logic for
822 * enumerating underlying configuration section instances, for registering
823 * form options and for handling tabs to segment child options.
824 *
825 * This class is private and not directly accessible by user code.
826 */
827 var CBIAbstractSection = CBIAbstractElement.extend(/** @lends LuCI.form.AbstractSection.prototype */ {
828 __init__: function(map, sectionType /*, ... */) {
829 this.super('__init__', this.varargs(arguments, 2));
830
831 this.sectiontype = sectionType;
832 this.map = map;
833 this.config = map.config;
834
835 this.optional = true;
836 this.addremove = false;
837 this.dynamic = false;
838 },
839
840 /**
841 * Access the parent option container instance.
842 *
843 * In case this section is nested within an option element container,
844 * this property will hold a reference to the parent option instance.
845 *
846 * If this section is not nested, the property is `null`.
847 *
848 * @name LuCI.form.AbstractSection.prototype#parentoption
849 * @type LuCI.form.AbstractValue
850 * @readonly
851 */
852
853 /**
854 * Enumerate the UCI section IDs covered by this form section element.
855 *
856 * @abstract
857 * @throws {InternalError}
858 * Throws an `InternalError` exception if the function is not implemented.
859 *
860 * @returns {string[]}
861 * Returns an array of UCI section IDs covered by this form element.
862 * The sections will be rendered in the same order as the returned array.
863 */
864 cfgsections: function() {
865 L.error('InternalError', 'Not implemented');
866 },
867
868 /**
869 * Filter UCI section IDs to render.
870 *
871 * The filter function is invoked for each UCI section ID of a given type
872 * and controls whether the given UCI section is rendered or ignored by
873 * the form section element.
874 *
875 * The default implementation always returns `true`. User code or
876 * classes extending `AbstractSection` may overwrite this function with
877 * custom implementations.
878 *
879 * @abstract
880 * @param {string} section_id
881 * The UCI section ID to test.
882 *
883 * @returns {boolean}
884 * Returns `true` when the given UCI section ID should be handled and
885 * `false` when it should be ignored.
886 */
887 filter: function(section_id) {
888 return true;
889 },
890
891 /**
892 * Load the configuration covered by this section.
893 *
894 * The `load()` function recursively walks the section element tree and
895 * invokes the load function of each child option element.
896 *
897 * @returns {Promise<void>}
898 * Returns a promise resolving once the values of all child elements have
899 * been loaded. The promise may reject with an error if any of the child
900 * elements load functions rejected with an error.
901 */
902 load: function() {
903 var section_ids = this.cfgsections(),
904 tasks = [];
905
906 if (Array.isArray(this.children))
907 for (var i = 0; i < section_ids.length; i++)
908 tasks.push(this.loadChildren(section_ids[i])
909 .then(Function.prototype.bind.call(function(section_id, set_values) {
910 for (var i = 0; i < set_values.length; i++)
911 this.children[i].cfgvalue(section_id, set_values[i]);
912 }, this, section_ids[i])));
913
914 return Promise.all(tasks);
915 },
916
917 /**
918 * Parse this sections form input.
919 *
920 * The `parse()` function recursively walks the section element tree and
921 * triggers input value reading and validation for each encountered child
922 * option element.
923 *
924 * Options which are hidden due to unsatisfied dependencies are skipped.
925 *
926 * @returns {Promise<void>}
927 * Returns a promise resolving once the values of all child elements have
928 * been parsed. The returned promise is rejected if any parsed values are
929 * not meeting the validation constraints of their respective elements.
930 */
931 parse: function() {
932 var section_ids = this.cfgsections(),
933 tasks = [];
934
935 if (Array.isArray(this.children))
936 for (var i = 0; i < section_ids.length; i++)
937 for (var j = 0; j < this.children.length; j++)
938 tasks.push(this.children[j].parse(section_ids[i]));
939
940 return Promise.all(tasks);
941 },
942
943 /**
944 * Add an option tab to the section.
945 *
946 * The child option elements of a section may be divided into multiple
947 * tabs to provide a better overview to the user.
948 *
949 * Before options can be moved into a tab pane, the corresponding tab
950 * has to be defined first, which is done by calling this function.
951 *
952 * Note that once tabs are defined, user code must use the `taboption()`
953 * method to add options to specific tabs. Option elements added by
954 * `option()` will not be assigned to any tab and not be rendered in this
955 * case.
956 *
957 * @param {string} name
958 * The name of the tab to register. It may be freely chosen and just serves
959 * as an identifier to differentiate tabs.
960 *
961 * @param {string} title
962 * The human readable caption of the tab.
963 *
964 * @param {string} [description]
965 * An additional description text for the corresponding tab pane. It is
966 * displayed as text paragraph below the tab but before the tab pane
967 * contents. If omitted, no description will be rendered.
968 *
969 * @throws {Error}
970 * Throws an exception if a tab with the same `name` already exists.
971 */
972 tab: function(name, title, description) {
973 if (this.tabs && this.tabs[name])
974 throw 'Tab already declared';
975
976 var entry = {
977 name: name,
978 title: title,
979 description: description,
980 children: []
981 };
982
983 this.tabs = this.tabs || [];
984 this.tabs.push(entry);
985 this.tabs[name] = entry;
986
987 this.tab_names = this.tab_names || [];
988 this.tab_names.push(name);
989 },
990
991 /**
992 * Add a configuration option widget to the section.
993 *
994 * Note that [taboption()]{@link LuCI.form.AbstractSection#taboption}
995 * should be used instead if this form section element uses tabs.
996 *
997 * @param {LuCI.form.AbstractValue} optionclass
998 * The option class to use for rendering the configuration option. Note
999 * that this value must be the class itself, not a class instance obtained
1000 * from calling `new`. It must also be a class derived from
1001 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
1002 *
1003 * @param {...*} classargs
1004 * Additional arguments which are passed as-is to the constructor of the
1005 * given option class. Refer to the class specific constructor
1006 * documentation for details.
1007 *
1008 * @throws {TypeError}
1009 * Throws a `TypeError` exception in case the passed class value is not a
1010 * descendant of `AbstractValue`.
1011 *
1012 * @returns {LuCI.form.AbstractValue}
1013 * Returns the instantiated option class instance.
1014 */
1015 option: function(cbiClass /*, ... */) {
1016 if (!CBIAbstractValue.isSubclass(cbiClass))
1017 throw L.error('TypeError', 'Class must be a descendant of CBIAbstractValue');
1018
1019 var obj = cbiClass.instantiate(this.varargs(arguments, 1, this.map, this));
1020 this.append(obj);
1021 return obj;
1022 },
1023
1024 /**
1025 * Add a configuration option widget to a tab of the section.
1026 *
1027 * @param {string} tabName
1028 * The name of the section tab to add the option element to.
1029 *
1030 * @param {LuCI.form.AbstractValue} optionclass
1031 * The option class to use for rendering the configuration option. Note
1032 * that this value must be the class itself, not a class instance obtained
1033 * from calling `new`. It must also be a class derived from
1034 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
1035 *
1036 * @param {...*} classargs
1037 * Additional arguments which are passed as-is to the constructor of the
1038 * given option class. Refer to the class specific constructor
1039 * documentation for details.
1040 *
1041 * @throws {ReferenceError}
1042 * Throws a `ReferenceError` exception when the given tab name does not
1043 * exist.
1044 *
1045 * @throws {TypeError}
1046 * Throws a `TypeError` exception in case the passed class value is not a
1047 * descendant of `AbstractValue`.
1048 *
1049 * @returns {LuCI.form.AbstractValue}
1050 * Returns the instantiated option class instance.
1051 */
1052 taboption: function(tabName /*, ... */) {
1053 if (!this.tabs || !this.tabs[tabName])
1054 throw L.error('ReferenceError', 'Associated tab not declared');
1055
1056 var obj = this.option.apply(this, this.varargs(arguments, 1));
1057 obj.tab = tabName;
1058 this.tabs[tabName].children.push(obj);
1059 return obj;
1060 },
1061
1062 /**
1063 * Query underlying option configuration values.
1064 *
1065 * This function is sensitive to the amount of arguments passed to it;
1066 * if only one argument is specified, the configuration values of all
1067 * options within this section are returned as dictionary.
1068 *
1069 * If both the section ID and an option name are supplied, this function
1070 * returns the configuration value of the specified option only.
1071 *
1072 * @param {string} section_id
1073 * The configuration section ID
1074 *
1075 * @param {string} [option]
1076 * The name of the option to query
1077 *
1078 * @returns {null|string|string[]|Object<string, null|string|string[]>}
1079 * Returns either a dictionary of option names and their corresponding
1080 * configuration values or just a single configuration value, depending
1081 * on the amount of passed arguments.
1082 */
1083 cfgvalue: function(section_id, option) {
1084 var rv = (arguments.length == 1) ? {} : null;
1085
1086 for (var i = 0, o; (o = this.children[i]) != null; i++)
1087 if (rv)
1088 rv[o.option] = o.cfgvalue(section_id);
1089 else if (o.option == option)
1090 return o.cfgvalue(section_id);
1091
1092 return rv;
1093 },
1094
1095 /**
1096 * Query underlying option widget input values.
1097 *
1098 * This function is sensitive to the amount of arguments passed to it;
1099 * if only one argument is specified, the widget input values of all
1100 * options within this section are returned as dictionary.
1101 *
1102 * If both the section ID and an option name are supplied, this function
1103 * returns the widget input value of the specified option only.
1104 *
1105 * @param {string} section_id
1106 * The configuration section ID
1107 *
1108 * @param {string} [option]
1109 * The name of the option to query
1110 *
1111 * @returns {null|string|string[]|Object<string, null|string|string[]>}
1112 * Returns either a dictionary of option names and their corresponding
1113 * widget input values or just a single widget input value, depending
1114 * on the amount of passed arguments.
1115 */
1116 formvalue: function(section_id, option) {
1117 var rv = (arguments.length == 1) ? {} : null;
1118
1119 for (var i = 0, o; (o = this.children[i]) != null; i++) {
1120 var func = this.map.root ? this.children[i].formvalue : this.children[i].cfgvalue;
1121
1122 if (rv)
1123 rv[o.option] = func.call(o, section_id);
1124 else if (o.option == option)
1125 return func.call(o, section_id);
1126 }
1127
1128 return rv;
1129 },
1130
1131 /**
1132 * Obtain underlying option LuCI.ui widget instances.
1133 *
1134 * This function is sensitive to the amount of arguments passed to it;
1135 * if only one argument is specified, the LuCI.ui widget instances of all
1136 * options within this section are returned as dictionary.
1137 *
1138 * If both the section ID and an option name are supplied, this function
1139 * returns the LuCI.ui widget instance value of the specified option only.
1140 *
1141 * @param {string} section_id
1142 * The configuration section ID
1143 *
1144 * @param {string} [option]
1145 * The name of the option to query
1146 *
1147 * @returns {null|LuCI.ui.AbstractElement|Object<string, null|LuCI.ui.AbstractElement>}
1148 * Returns either a dictionary of option names and their corresponding
1149 * widget input values or just a single widget input value, depending
1150 * on the amount of passed arguments.
1151 */
1152 getUIElement: function(section_id, option) {
1153 var rv = (arguments.length == 1) ? {} : null;
1154
1155 for (var i = 0, o; (o = this.children[i]) != null; i++)
1156 if (rv)
1157 rv[o.option] = o.getUIElement(section_id);
1158 else if (o.option == option)
1159 return o.getUIElement(section_id);
1160
1161 return rv;
1162 },
1163
1164 /**
1165 * Obtain underlying option objects.
1166 *
1167 * This function is sensitive to the amount of arguments passed to it;
1168 * if no option name is specified, all options within this section are
1169 * returned as dictionary.
1170 *
1171 * If an option name is supplied, this function returns the matching
1172 * LuCI.form.AbstractValue instance only.
1173 *
1174 * @param {string} [option]
1175 * The name of the option object to obtain
1176 *
1177 * @returns {null|LuCI.form.AbstractValue|Object<string, LuCI.form.AbstractValue>}
1178 * Returns either a dictionary of option names and their corresponding
1179 * option instance objects or just a single object instance value,
1180 * depending on the amount of passed arguments.
1181 */
1182 getOption: function(option) {
1183 var rv = (arguments.length == 0) ? {} : null;
1184
1185 for (var i = 0, o; (o = this.children[i]) != null; i++)
1186 if (rv)
1187 rv[o.option] = o;
1188 else if (o.option == option)
1189 return o;
1190
1191 return rv;
1192 },
1193
1194 /** @private */
1195 renderUCISection: function(section_id) {
1196 var renderTasks = [];
1197
1198 if (!this.tabs)
1199 return this.renderOptions(null, section_id);
1200
1201 for (var i = 0; i < this.tab_names.length; i++)
1202 renderTasks.push(this.renderOptions(this.tab_names[i], section_id));
1203
1204 return Promise.all(renderTasks)
1205 .then(this.renderTabContainers.bind(this, section_id));
1206 },
1207
1208 /** @private */
1209 renderTabContainers: function(section_id, nodes) {
1210 var config_name = this.uciconfig || this.map.config,
1211 containerEls = E([]);
1212
1213 for (var i = 0; i < nodes.length; i++) {
1214 var tab_name = this.tab_names[i],
1215 tab_data = this.tabs[tab_name],
1216 containerEl = E('div', {
1217 'id': 'container.%s.%s.%s'.format(config_name, section_id, tab_name),
1218 'data-tab': tab_name,
1219 'data-tab-title': tab_data.title,
1220 'data-tab-active': tab_name === this.selected_tab
1221 });
1222
1223 if (tab_data.description != null && tab_data.description != '')
1224 containerEl.appendChild(
1225 E('div', { 'class': 'cbi-tab-descr' }, tab_data.description));
1226
1227 containerEl.appendChild(nodes[i]);
1228 containerEls.appendChild(containerEl);
1229 }
1230
1231 return containerEls;
1232 },
1233
1234 /** @private */
1235 renderOptions: function(tab_name, section_id) {
1236 var in_table = (this instanceof CBITableSection);
1237 return this.renderChildren(tab_name, section_id, in_table).then(function(nodes) {
1238 var optionEls = E([]);
1239 for (var i = 0; i < nodes.length; i++)
1240 optionEls.appendChild(nodes[i]);
1241 return optionEls;
1242 });
1243 },
1244
1245 /** @private */
1246 checkDepends: function(ev, n) {
1247 var changed = false,
1248 sids = this.cfgsections();
1249
1250 for (var i = 0, sid = sids[0]; (sid = sids[i]) != null; i++) {
1251 for (var j = 0, o = this.children[0]; (o = this.children[j]) != null; j++) {
1252 var isActive = o.isActive(sid),
1253 isSatisified = o.checkDepends(sid);
1254
1255 if (isActive != isSatisified) {
1256 o.setActive(sid, !isActive);
1257 isActive = !isActive;
1258 changed = true;
1259 }
1260
1261 if (!n && isActive)
1262 o.triggerValidation(sid);
1263 }
1264 }
1265
1266 return changed;
1267 }
1268 });
1269
1270
1271 var isEqual = function(x, y) {
1272 if (typeof(y) == 'object' && y instanceof RegExp)
1273 return (x == null) ? false : y.test(x);
1274
1275 if (x != null && y != null && typeof(x) != typeof(y))
1276 return false;
1277
1278 if ((x == null && y != null) || (x != null && y == null))
1279 return false;
1280
1281 if (Array.isArray(x)) {
1282 if (x.length != y.length)
1283 return false;
1284
1285 for (var i = 0; i < x.length; i++)
1286 if (!isEqual(x[i], y[i]))
1287 return false;
1288 }
1289 else if (typeof(x) == 'object') {
1290 for (var k in x) {
1291 if (x.hasOwnProperty(k) && !y.hasOwnProperty(k))
1292 return false;
1293
1294 if (!isEqual(x[k], y[k]))
1295 return false;
1296 }
1297
1298 for (var k in y)
1299 if (y.hasOwnProperty(k) && !x.hasOwnProperty(k))
1300 return false;
1301 }
1302 else if (x != y) {
1303 return false;
1304 }
1305
1306 return true;
1307 };
1308
1309 var isContained = function(x, y) {
1310 if (Array.isArray(x)) {
1311 for (var i = 0; i < x.length; i++)
1312 if (x[i] == y)
1313 return true;
1314 }
1315 else if (L.isObject(x)) {
1316 if (x.hasOwnProperty(y) && x[y] != null)
1317 return true;
1318 }
1319 else if (typeof(x) == 'string') {
1320 return (x.indexOf(y) > -1);
1321 }
1322
1323 return false;
1324 };
1325
1326 /**
1327 * @class AbstractValue
1328 * @memberof LuCI.form
1329 * @augments LuCI.form.AbstractElement
1330 * @hideconstructor
1331 * @classdesc
1332 *
1333 * The `AbstractValue` class serves as abstract base for the different form
1334 * option styles implemented by `LuCI.form`. It provides the common logic for
1335 * handling option input values, for dependencies among options and for
1336 * validation constraints that should be applied to entered values.
1337 *
1338 * This class is private and not directly accessible by user code.
1339 */
1340 var CBIAbstractValue = CBIAbstractElement.extend(/** @lends LuCI.form.AbstractValue.prototype */ {
1341 __init__: function(map, section, option /*, ... */) {
1342 this.super('__init__', this.varargs(arguments, 3));
1343
1344 this.section = section;
1345 this.option = option;
1346 this.map = map;
1347 this.config = map.config;
1348
1349 this.deps = [];
1350 this.initial = {};
1351 this.rmempty = true;
1352 this.default = null;
1353 this.size = null;
1354 this.optional = false;
1355 this.retain = false;
1356 },
1357
1358 /**
1359 * If set to `false`, the underlying option value is retained upon saving
1360 * the form when the option element is disabled due to unsatisfied
1361 * dependency constraints.
1362 *
1363 * @name LuCI.form.AbstractValue.prototype#rmempty
1364 * @type boolean
1365 * @default true
1366 */
1367
1368 /**
1369 * If set to `true`, the underlying ui input widget is allowed to be empty,
1370 * otherwise the option element is marked invalid when no value is entered
1371 * or selected by the user.
1372 *
1373 * @name LuCI.form.AbstractValue.prototype#optional
1374 * @type boolean
1375 * @default false
1376 */
1377
1378 /**
1379 * If set to `true`, the underlying ui input widget value is not cleared
1380 * from the configuration on unsatisfied dependencies. The default behavior
1381 * is to remove the values of all options whose dependencies are not
1382 * fulfilled.
1383 *
1384 * @name LuCI.form.AbstractValue.prototype#retain
1385 * @type boolean
1386 * @default false
1387 */
1388
1389 /**
1390 * Sets a default value to use when the underlying UCI option is not set.
1391 *
1392 * @name LuCI.form.AbstractValue.prototype#default
1393 * @type *
1394 * @default null
1395 */
1396
1397 /**
1398 * Specifies a datatype constraint expression to validate input values
1399 * against. Refer to {@link LuCI.validation} for details on the format.
1400 *
1401 * If the user entered input does not match the datatype validation, the
1402 * option element is marked as invalid.
1403 *
1404 * @name LuCI.form.AbstractValue.prototype#datatype
1405 * @type string
1406 * @default null
1407 */
1408
1409 /**
1410 * Specifies a custom validation function to test the user input for
1411 * validity. The validation function must return `true` to accept the
1412 * value. Any other return value type is converted to a string and
1413 * displayed to the user as validation error message.
1414 *
1415 * If the user entered input does not pass the validation function, the
1416 * option element is marked as invalid.
1417 *
1418 * @name LuCI.form.AbstractValue.prototype#validate
1419 * @type function
1420 * @default null
1421 */
1422
1423 /**
1424 * Override the UCI configuration name to read the option value from.
1425 *
1426 * By default, the configuration name is inherited from the parent Map.
1427 * By setting this property, a deviating configuration may be specified.
1428 *
1429 * The default is null, means inheriting from the parent form.
1430 *
1431 * @name LuCI.form.AbstractValue.prototype#uciconfig
1432 * @type string
1433 * @default null
1434 */
1435
1436 /**
1437 * Override the UCI section name to read the option value from.
1438 *
1439 * By default, the section ID is inherited from the parent section element.
1440 * By setting this property, a deviating section may be specified.
1441 *
1442 * The default is null, means inheriting from the parent section.
1443 *
1444 * @name LuCI.form.AbstractValue.prototype#ucisection
1445 * @type string
1446 * @default null
1447 */
1448
1449 /**
1450 * Override the UCI option name to read the value from.
1451 *
1452 * By default, the elements name, which is passed as third argument to
1453 * the constructor, is used as UCI option name. By setting this property,
1454 * a deviating UCI option may be specified.
1455 *
1456 * The default is null, means using the option element name.
1457 *
1458 * @name LuCI.form.AbstractValue.prototype#ucioption
1459 * @type string
1460 * @default null
1461 */
1462
1463 /**
1464 * Mark grid section option element as editable.
1465 *
1466 * Options which are displayed in the table portion of a `GridSection`
1467 * instance are rendered as readonly text by default. By setting the
1468 * `editable` property of a child option element to `true`, that element
1469 * is rendered as full input widget within its cell instead of a text only
1470 * preview.
1471 *
1472 * This property has no effect on options that are not children of grid
1473 * section elements.
1474 *
1475 * @name LuCI.form.AbstractValue.prototype#editable
1476 * @type boolean
1477 * @default false
1478 */
1479
1480 /**
1481 * Move grid section option element into the table, the modal popup or both.
1482 *
1483 * If this property is `null` (the default), the option element is
1484 * displayed in both the table preview area and the per-section instance
1485 * modal popup of a grid section. When it is set to `false` the option
1486 * is only shown in the table but not the modal popup. When set to `true`,
1487 * the option is only visible in the modal popup but not the table.
1488 *
1489 * This property has no effect on options that are not children of grid
1490 * section elements.
1491 *
1492 * @name LuCI.form.AbstractValue.prototype#modalonly
1493 * @type boolean
1494 * @default null
1495 */
1496
1497 /**
1498 * Make option element readonly.
1499 *
1500 * This property defaults to the readonly state of the parent form element.
1501 * When set to `true`, the underlying widget is rendered in disabled state,
1502 * means its contents cannot be changed and the widget cannot be interacted
1503 * with.
1504 *
1505 * @name LuCI.form.AbstractValue.prototype#readonly
1506 * @type boolean
1507 * @default false
1508 */
1509
1510 /**
1511 * Override the cell width of a table or grid section child option.
1512 *
1513 * If the property is set to a numeric value, it is treated as pixel width
1514 * which is set on the containing cell element of the option, essentially
1515 * forcing a certain column width. When the property is set to a string
1516 * value, it is applied as-is to the CSS `width` property.
1517 *
1518 * This property has no effect on options that are not children of grid or
1519 * table section elements.
1520 *
1521 * @name LuCI.form.AbstractValue.prototype#width
1522 * @type number|string
1523 * @default null
1524 */
1525
1526 /**
1527 * Register a custom value change handler.
1528 *
1529 * If this property is set to a function value, the function is invoked
1530 * whenever the value of the underlying UI input element is changing.
1531 *
1532 * The invoked handler function will receive the DOM click element as
1533 * first and the underlying configuration section ID as well as the input
1534 * value as second and third argument respectively.
1535 *
1536 * @name LuCI.form.AbstractValue.prototype#onchange
1537 * @type function
1538 * @default null
1539 */
1540
1541 /**
1542 * Add a dependency constraint to the option.
1543 *
1544 * Dependency constraints allow making the presence of option elements
1545 * dependent on the current values of certain other options within the
1546 * same form. An option element with unsatisfied dependencies will be
1547 * hidden from the view and its current value is omitted when saving.
1548 *
1549 * Multiple constraints (that is, multiple calls to `depends()`) are
1550 * treated as alternatives, forming a logical "or" expression.
1551 *
1552 * By passing an object of name => value pairs as first argument, it is
1553 * possible to depend on multiple options simultaneously, allowing to form
1554 * a logical "and" expression.
1555 *
1556 * Option names may be given in "dot notation" which allows to reference
1557 * option elements outside the current form section. If a name without
1558 * dot is specified, it refers to an option within the same configuration
1559 * section. If specified as <code>configname.sectionid.optionname</code>,
1560 * options anywhere within the same form may be specified.
1561 *
1562 * The object notation also allows for a number of special keys which are
1563 * not treated as option names but as modifiers to influence the dependency
1564 * constraint evaluation. The associated value of these special "tag" keys
1565 * is ignored. The recognized tags are:
1566 *
1567 * <ul>
1568 * <li>
1569 * <code>!reverse</code><br>
1570 * Invert the dependency, instead of requiring another option to be
1571 * equal to the dependency value, that option should <em>not</em> be
1572 * equal.
1573 * </li>
1574 * <li>
1575 * <code>!contains</code><br>
1576 * Instead of requiring an exact match, the dependency is considered
1577 * satisfied when the dependency value is contained within the option
1578 * value.
1579 * </li>
1580 * <li>
1581 * <code>!default</code><br>
1582 * The dependency is always satisfied
1583 * </li>
1584 * </ul>
1585 *
1586 * Examples:
1587 *
1588 * <ul>
1589 * <li>
1590 * <code>opt.depends("foo", "test")</code><br>
1591 * Require the value of `foo` to be `test`.
1592 * </li>
1593 * <li>
1594 * <code>opt.depends({ foo: "test" })</code><br>
1595 * Equivalent to the previous example.
1596 * </li>
1597 * <li>
1598 * <code>opt.depends({ foo: /test/ })</code><br>
1599 * Require the value of `foo` to match the regular expression `/test/`.
1600 * </li>
1601 * <li>
1602 * <code>opt.depends({ foo: "test", bar: "qrx" })</code><br>
1603 * Require the value of `foo` to be `test` and the value of `bar` to be
1604 * `qrx`.
1605 * </li>
1606 * <li>
1607 * <code>opt.depends({ foo: "test" })<br>
1608 * opt.depends({ bar: "qrx" })</code><br>
1609 * Require either <code>foo</code> to be set to <code>test</code>,
1610 * <em>or</em> the <code>bar</code> option to be <code>qrx</code>.
1611 * </li>
1612 * <li>
1613 * <code>opt.depends("test.section1.foo", "bar")</code><br>
1614 * Require the "foo" form option within the "section1" section to be
1615 * set to "bar".
1616 * </li>
1617 * <li>
1618 * <code>opt.depends({ foo: "test", "!contains": true })</code><br>
1619 * Require the "foo" option value to contain the substring "test".
1620 * </li>
1621 * </ul>
1622 *
1623 * @param {string|Object<string, string|RegExp>} field
1624 * The name of the option to depend on or an object describing multiple
1625 * dependencies which must be satisfied (a logical "and" expression).
1626 *
1627 * @param {string|RegExp} value
1628 * When invoked with a plain option name as first argument, this parameter
1629 * specifies the expected value. In case an object is passed as first
1630 * argument, this parameter is ignored.
1631 */
1632 depends: function(field, value) {
1633 var deps;
1634
1635 if (typeof(field) === 'string')
1636 deps = {}, deps[field] = value;
1637 else
1638 deps = field;
1639
1640 this.deps.push(deps);
1641 },
1642
1643 /** @private */
1644 transformDepList: function(section_id, deplist) {
1645 var list = deplist || this.deps,
1646 deps = [];
1647
1648 if (Array.isArray(list)) {
1649 for (var i = 0; i < list.length; i++) {
1650 var dep = {};
1651
1652 for (var k in list[i]) {
1653 if (list[i].hasOwnProperty(k)) {
1654 if (k.charAt(0) === '!')
1655 dep[k] = list[i][k];
1656 else if (k.indexOf('.') !== -1)
1657 dep['cbid.%s'.format(k)] = list[i][k];
1658 else
1659 dep['cbid.%s.%s.%s'.format(
1660 this.uciconfig || this.section.uciconfig || this.map.config,
1661 this.ucisection || section_id,
1662 k
1663 )] = list[i][k];
1664 }
1665 }
1666
1667 for (var k in dep) {
1668 if (dep.hasOwnProperty(k)) {
1669 deps.push(dep);
1670 break;
1671 }
1672 }
1673 }
1674 }
1675
1676 return deps;
1677 },
1678
1679 /** @private */
1680 transformChoices: function() {
1681 if (!Array.isArray(this.keylist) || this.keylist.length == 0)
1682 return null;
1683
1684 var choices = {};
1685
1686 for (var i = 0; i < this.keylist.length; i++)
1687 choices[this.keylist[i]] = this.vallist[i];
1688
1689 return choices;
1690 },
1691
1692 /** @private */
1693 checkDepends: function(section_id) {
1694 var config_name = this.uciconfig || this.section.uciconfig || this.map.config,
1695 active = this.map.isDependencySatisfied(this.deps, config_name, section_id);
1696
1697 if (active)
1698 this.updateDefaultValue(section_id);
1699
1700 return active;
1701 },
1702
1703 /** @private */
1704 updateDefaultValue: function(section_id) {
1705 if (!L.isObject(this.defaults))
1706 return;
1707
1708 var config_name = this.uciconfig || this.section.uciconfig || this.map.config,
1709 cfgvalue = L.toArray(this.cfgvalue(section_id))[0],
1710 default_defval = null, satisified_defval = null;
1711
1712 for (var value in this.defaults) {
1713 if (!this.defaults[value] || this.defaults[value].length == 0) {
1714 default_defval = value;
1715 continue;
1716 }
1717 else if (this.map.isDependencySatisfied(this.defaults[value], config_name, section_id)) {
1718 satisified_defval = value;
1719 break;
1720 }
1721 }
1722
1723 if (satisified_defval == null)
1724 satisified_defval = default_defval;
1725
1726 var node = this.map.findElement('id', this.cbid(section_id));
1727 if (node && node.getAttribute('data-changed') != 'true' && satisified_defval != null && cfgvalue == null)
1728 dom.callClassMethod(node, 'setValue', satisified_defval);
1729
1730 this.default = satisified_defval;
1731 },
1732
1733 /**
1734 * Obtain the internal ID ("cbid") of the element instance.
1735 *
1736 * Since each form section element may map multiple underlying
1737 * configuration sections, the configuration section ID is required to
1738 * form a fully qualified ID pointing to the specific element instance
1739 * within the given specific section.
1740 *
1741 * @param {string} section_id
1742 * The configuration section ID
1743 *
1744 * @throws {TypeError}
1745 * Throws a `TypeError` exception when no `section_id` was specified.
1746 *
1747 * @returns {string}
1748 * Returns the element ID.
1749 */
1750 cbid: function(section_id) {
1751 if (section_id == null)
1752 L.error('TypeError', 'Section ID required');
1753
1754 return 'cbid.%s.%s.%s'.format(
1755 this.uciconfig || this.section.uciconfig || this.map.config,
1756 section_id, this.option);
1757 },
1758
1759 /**
1760 * Load the underlying configuration value.
1761 *
1762 * The default implementation of this method reads and returns the
1763 * underlying UCI option value (or the related JavaScript property for
1764 * `JSONMap` instances). It may be overwritten by user code to load data
1765 * from nonstandard sources.
1766 *
1767 * @param {string} section_id
1768 * The configuration section ID
1769 *
1770 * @throws {TypeError}
1771 * Throws a `TypeError` exception when no `section_id` was specified.
1772 *
1773 * @returns {*|Promise<*>}
1774 * Returns the configuration value to initialize the option element with.
1775 * The return value of this function is filtered through `Promise.resolve()`
1776 * so it may return promises if overridden by user code.
1777 */
1778 load: function(section_id) {
1779 if (section_id == null)
1780 L.error('TypeError', 'Section ID required');
1781
1782 return this.map.data.get(
1783 this.uciconfig || this.section.uciconfig || this.map.config,
1784 this.ucisection || section_id,
1785 this.ucioption || this.option);
1786 },
1787
1788 /**
1789 * Obtain the underlying `LuCI.ui` element instance.
1790 *
1791 * @param {string} section_id
1792 * The configuration section ID
1793 *
1794 * @throws {TypeError}
1795 * Throws a `TypeError` exception when no `section_id` was specified.
1796 *
1797 * @return {LuCI.ui.AbstractElement|null}
1798 * Returns the `LuCI.ui` element instance or `null` in case the form
1799 * option implementation does not use `LuCI.ui` widgets.
1800 */
1801 getUIElement: function(section_id) {
1802 var node = this.map.findElement('id', this.cbid(section_id)),
1803 inst = node ? dom.findClassInstance(node) : null;
1804 return (inst instanceof ui.AbstractElement) ? inst : null;
1805 },
1806
1807 /**
1808 * Query the underlying configuration value.
1809 *
1810 * The default implementation of this method returns the cached return
1811 * value of [load()]{@link LuCI.form.AbstractValue#load}. It may be
1812 * overwritten by user code to obtain the configuration value in a
1813 * different way.
1814 *
1815 * @param {string} section_id
1816 * The configuration section ID
1817 *
1818 * @throws {TypeError}
1819 * Throws a `TypeError` exception when no `section_id` was specified.
1820 *
1821 * @returns {*}
1822 * Returns the configuration value.
1823 */
1824 cfgvalue: function(section_id, set_value) {
1825 if (section_id == null)
1826 L.error('TypeError', 'Section ID required');
1827
1828 if (arguments.length == 2) {
1829 this.data = this.data || {};
1830 this.data[section_id] = set_value;
1831 }
1832
1833 return this.data ? this.data[section_id] : null;
1834 },
1835
1836 /**
1837 * Query the current form input value.
1838 *
1839 * The default implementation of this method returns the current input
1840 * value of the underlying [LuCI.ui]{@link LuCI.ui.AbstractElement} widget.
1841 * It may be overwritten by user code to handle input values differently.
1842 *
1843 * @param {string} section_id
1844 * The configuration section ID
1845 *
1846 * @throws {TypeError}
1847 * Throws a `TypeError` exception when no `section_id` was specified.
1848 *
1849 * @returns {*}
1850 * Returns the current input value.
1851 */
1852 formvalue: function(section_id) {
1853 var elem = this.getUIElement(section_id);
1854 return elem ? elem.getValue() : null;
1855 },
1856
1857 /**
1858 * Obtain a textual input representation.
1859 *
1860 * The default implementation of this method returns the HTML escaped
1861 * current input value of the underlying
1862 * [LuCI.ui]{@link LuCI.ui.AbstractElement} widget. User code or specific
1863 * option element implementations may overwrite this function to apply a
1864 * different logic, e.g. to return `Yes` or `No` depending on the checked
1865 * state of checkbox elements.
1866 *
1867 * @param {string} section_id
1868 * The configuration section ID
1869 *
1870 * @throws {TypeError}
1871 * Throws a `TypeError` exception when no `section_id` was specified.
1872 *
1873 * @returns {string}
1874 * Returns the text representation of the current input value.
1875 */
1876 textvalue: function(section_id) {
1877 var cval = this.cfgvalue(section_id);
1878
1879 if (cval == null)
1880 cval = this.default;
1881
1882 if (Array.isArray(cval))
1883 cval = cval.join(' ');
1884
1885 return (cval != null) ? '%h'.format(cval) : null;
1886 },
1887
1888 /**
1889 * Apply custom validation logic.
1890 *
1891 * This method is invoked whenever incremental validation is performed on
1892 * the user input, e.g. on keyup or blur events.
1893 *
1894 * The default implementation of this method does nothing and always
1895 * returns `true`. User code may overwrite this method to provide
1896 * additional validation logic which is not covered by data type
1897 * constraints.
1898 *
1899 * @abstract
1900 * @param {string} section_id
1901 * The configuration section ID
1902 *
1903 * @param {*} value
1904 * The value to validate
1905 *
1906 * @returns {*}
1907 * The method shall return `true` to accept the given value. Any other
1908 * return value is treated as failure, converted to a string and displayed
1909 * as error message to the user.
1910 */
1911 validate: function(section_id, value) {
1912 return true;
1913 },
1914
1915 /**
1916 * Test whether the input value is currently valid.
1917 *
1918 * @param {string} section_id
1919 * The configuration section ID
1920 *
1921 * @returns {boolean}
1922 * Returns `true` if the input value currently is valid, otherwise it
1923 * returns `false`.
1924 */
1925 isValid: function(section_id) {
1926 var elem = this.getUIElement(section_id);
1927 return elem ? elem.isValid() : true;
1928 },
1929
1930 /**
1931 * Returns the current validation error for this input.
1932 *
1933 * @param {string} section_id
1934 * The configuration section ID
1935 *
1936 * @returns {string}
1937 * The validation error at this time
1938 */
1939 getValidationError: function (section_id) {
1940 var elem = this.getUIElement(section_id);
1941 return elem ? elem.getValidationError() : '';
1942 },
1943
1944 /**
1945 * Test whether the option element is currently active.
1946 *
1947 * An element is active when it is not hidden due to unsatisfied dependency
1948 * constraints.
1949 *
1950 * @param {string} section_id
1951 * The configuration section ID
1952 *
1953 * @returns {boolean}
1954 * Returns `true` if the option element currently is active, otherwise it
1955 * returns `false`.
1956 */
1957 isActive: function(section_id) {
1958 var field = this.map.findElement('data-field', this.cbid(section_id));
1959 return (field != null && !field.classList.contains('hidden'));
1960 },
1961
1962 /** @private */
1963 setActive: function(section_id, active) {
1964 var field = this.map.findElement('data-field', this.cbid(section_id));
1965
1966 if (field && field.classList.contains('hidden') == active) {
1967 field.classList[active ? 'remove' : 'add']('hidden');
1968
1969 if (dom.matches(field.parentNode, '.td.cbi-value-field'))
1970 field.parentNode.classList[active ? 'remove' : 'add']('inactive');
1971
1972 return true;
1973 }
1974
1975 return false;
1976 },
1977
1978 /** @private */
1979 triggerValidation: function(section_id) {
1980 var elem = this.getUIElement(section_id);
1981 return elem ? elem.triggerValidation() : true;
1982 },
1983
1984 /**
1985 * Parse the option element input.
1986 *
1987 * The function is invoked when the `parse()` method has been invoked on
1988 * the parent form and triggers input value reading and validation.
1989 *
1990 * @param {string} section_id
1991 * The configuration section ID
1992 *
1993 * @returns {Promise<void>}
1994 * Returns a promise resolving once the input value has been read and
1995 * validated or rejecting in case the input value does not meet the
1996 * validation constraints.
1997 */
1998 parse: function(section_id) {
1999 var active = this.isActive(section_id);
2000
2001 if (active && !this.isValid(section_id)) {
2002 var title = this.stripTags(this.title).trim(),
2003 error = this.getValidationError(section_id);
2004
2005 return Promise.reject(new TypeError(
2006 _('Option "%s" contains an invalid input value.').format(title || this.option) + ' ' + error));
2007 }
2008
2009 if (active) {
2010 var cval = this.cfgvalue(section_id),
2011 fval = this.formvalue(section_id);
2012
2013 if (fval == null || fval == '') {
2014 if (this.rmempty || this.optional) {
2015 return Promise.resolve(this.remove(section_id));
2016 }
2017 else {
2018 var title = this.stripTags(this.title).trim();
2019
2020 return Promise.reject(new TypeError(
2021 _('Option "%s" must not be empty.').format(title || this.option)));
2022 }
2023 }
2024 else if (this.forcewrite || !isEqual(cval, fval)) {
2025 return Promise.resolve(this.write(section_id, fval));
2026 }
2027 }
2028 else if (!this.retain) {
2029 return Promise.resolve(this.remove(section_id));
2030 }
2031
2032 return Promise.resolve();
2033 },
2034
2035 /**
2036 * Write the current input value into the configuration.
2037 *
2038 * This function is invoked upon saving the parent form when the option
2039 * element is valid and when its input value has been changed compared to
2040 * the initial value returned by
2041 * [cfgvalue()]{@link LuCI.form.AbstractValue#cfgvalue}.
2042 *
2043 * The default implementation simply sets the given input value in the
2044 * UCI configuration (or the associated JavaScript object property in
2045 * case of `JSONMap` forms). It may be overwritten by user code to
2046 * implement alternative save logic, e.g. to transform the input value
2047 * before it is written.
2048 *
2049 * @param {string} section_id
2050 * The configuration section ID
2051 *
2052 * @param {string|string[]} formvalue
2053 * The input value to write.
2054 */
2055 write: function(section_id, formvalue) {
2056 return this.map.data.set(
2057 this.uciconfig || this.section.uciconfig || this.map.config,
2058 this.ucisection || section_id,
2059 this.ucioption || this.option,
2060 formvalue);
2061 },
2062
2063 /**
2064 * Remove the corresponding value from the configuration.
2065 *
2066 * This function is invoked upon saving the parent form when the option
2067 * element has been hidden due to unsatisfied dependencies or when the
2068 * user cleared the input value and the option is marked optional.
2069 *
2070 * The default implementation simply removes the associated option from the
2071 * UCI configuration (or the associated JavaScript object property in
2072 * case of `JSONMap` forms). It may be overwritten by user code to
2073 * implement alternative removal logic, e.g. to retain the original value.
2074 *
2075 * @param {string} section_id
2076 * The configuration section ID
2077 */
2078 remove: function(section_id) {
2079 var this_cfg = this.uciconfig || this.section.uciconfig || this.map.config,
2080 this_sid = this.ucisection || section_id,
2081 this_opt = this.ucioption || this.option;
2082
2083 for (var i = 0; i < this.section.children.length; i++) {
2084 var sibling = this.section.children[i];
2085
2086 if (sibling === this || sibling.ucioption == null)
2087 continue;
2088
2089 var sibling_cfg = sibling.uciconfig || sibling.section.uciconfig || sibling.map.config,
2090 sibling_sid = sibling.ucisection || section_id,
2091 sibling_opt = sibling.ucioption || sibling.option;
2092
2093 if (this_cfg != sibling_cfg || this_sid != sibling_sid || this_opt != sibling_opt)
2094 continue;
2095
2096 if (!sibling.isActive(section_id))
2097 continue;
2098
2099 /* found another active option aliasing the same uci option name,
2100 * so we can't remove the value */
2101 return;
2102 }
2103
2104 this.map.data.unset(this_cfg, this_sid, this_opt);
2105 }
2106 });
2107
2108 /**
2109 * @class TypedSection
2110 * @memberof LuCI.form
2111 * @augments LuCI.form.AbstractSection
2112 * @hideconstructor
2113 * @classdesc
2114 *
2115 * The `TypedSection` class maps all or - if `filter()` is overwritten - a
2116 * subset of the underlying UCI configuration sections of a given type.
2117 *
2118 * Layout wise, the configuration section instances mapped by the section
2119 * element (sometimes referred to as "section nodes") are stacked beneath
2120 * each other in a single column, with an optional section remove button next
2121 * to each section node and a section add button at the end, depending on the
2122 * value of the `addremove` property.
2123 *
2124 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2125 * The configuration form this section is added to. It is automatically passed
2126 * by [section()]{@link LuCI.form.Map#section}.
2127 *
2128 * @param {string} section_type
2129 * The type of the UCI section to map.
2130 *
2131 * @param {string} [title]
2132 * The title caption of the form section element.
2133 *
2134 * @param {string} [description]
2135 * The description text of the form section element.
2136 */
2137 var CBITypedSection = CBIAbstractSection.extend(/** @lends LuCI.form.TypedSection.prototype */ {
2138 __name__: 'CBI.TypedSection',
2139
2140 /**
2141 * If set to `true`, the user may add or remove instances from the form
2142 * section widget, otherwise only preexisting sections may be edited.
2143 * The default is `false`.
2144 *
2145 * @name LuCI.form.TypedSection.prototype#addremove
2146 * @type boolean
2147 * @default false
2148 */
2149
2150 /**
2151 * If set to `true`, mapped section instances are treated as anonymous
2152 * UCI sections, which means that section instance elements will be
2153 * rendered without title element and that no name is required when adding
2154 * new sections. The default is `false`.
2155 *
2156 * @name LuCI.form.TypedSection.prototype#anonymous
2157 * @type boolean
2158 * @default false
2159 */
2160
2161 /**
2162 * When set to `true`, instead of rendering section instances one below
2163 * another, treat each instance as separate tab pane and render a tab menu
2164 * at the top of the form section element, allowing the user to switch
2165 * among instances. The default is `false`.
2166 *
2167 * @name LuCI.form.TypedSection.prototype#tabbed
2168 * @type boolean
2169 * @default false
2170 */
2171
2172 /**
2173 * Override the caption used for the section add button at the bottom of
2174 * the section form element. If set to a string, it will be used as-is,
2175 * if set to a function, the function will be invoked and its return value
2176 * is used as caption, after converting it to a string. If this property
2177 * is not set, the default is `Add`.
2178 *
2179 * @name LuCI.form.TypedSection.prototype#addbtntitle
2180 * @type string|function
2181 * @default null
2182 */
2183
2184 /**
2185 * Override the UCI configuration name to read the section IDs from. By
2186 * default, the configuration name is inherited from the parent `Map`.
2187 * By setting this property, a deviating configuration may be specified.
2188 * The default is `null`, means inheriting from the parent form.
2189 *
2190 * @name LuCI.form.TypedSection.prototype#uciconfig
2191 * @type string
2192 * @default null
2193 */
2194
2195 /** @override */
2196 cfgsections: function() {
2197 return this.map.data.sections(this.uciconfig || this.map.config, this.sectiontype)
2198 .map(function(s) { return s['.name'] })
2199 .filter(L.bind(this.filter, this));
2200 },
2201
2202 /** @private */
2203 handleAdd: function(ev, name) {
2204 var config_name = this.uciconfig || this.map.config;
2205
2206 this.map.data.add(config_name, this.sectiontype, name);
2207 return this.map.save(null, true);
2208 },
2209
2210 /** @private */
2211 handleRemove: function(section_id, ev) {
2212 var config_name = this.uciconfig || this.map.config;
2213
2214 this.map.data.remove(config_name, section_id);
2215 return this.map.save(null, true);
2216 },
2217
2218 /** @private */
2219 renderSectionAdd: function(extra_class) {
2220 if (!this.addremove)
2221 return E([]);
2222
2223 var createEl = E('div', { 'class': 'cbi-section-create' }),
2224 config_name = this.uciconfig || this.map.config,
2225 btn_title = this.titleFn('addbtntitle');
2226
2227 if (extra_class != null)
2228 createEl.classList.add(extra_class);
2229
2230 if (this.anonymous) {
2231 createEl.appendChild(E('button', {
2232 'class': 'cbi-button cbi-button-add',
2233 'title': btn_title || _('Add'),
2234 'click': ui.createHandlerFn(this, 'handleAdd'),
2235 'disabled': this.map.readonly || null
2236 }, [ btn_title || _('Add') ]));
2237 }
2238 else {
2239 var nameEl = E('input', {
2240 'type': 'text',
2241 'class': 'cbi-section-create-name',
2242 'disabled': this.map.readonly || null
2243 });
2244
2245 dom.append(createEl, [
2246 E('div', {}, nameEl),
2247 E('button', {
2248 'class': 'cbi-button cbi-button-add',
2249 'title': btn_title || _('Add'),
2250 'click': ui.createHandlerFn(this, function(ev) {
2251 if (nameEl.classList.contains('cbi-input-invalid'))
2252 return;
2253
2254 return this.handleAdd(ev, nameEl.value);
2255 }),
2256 'disabled': this.map.readonly || true
2257 }, [ btn_title || _('Add') ])
2258 ]);
2259
2260 if (this.map.readonly !== true) {
2261 ui.addValidator(nameEl, 'uciname', true, function(v) {
2262 var button = createEl.querySelector('.cbi-section-create > .cbi-button-add');
2263 if (v !== '') {
2264 button.disabled = null;
2265 return true;
2266 }
2267 else {
2268 button.disabled = true;
2269 return _('Expecting: %s').format(_('non-empty value'));
2270 }
2271 }, 'blur', 'keyup');
2272 }
2273 }
2274
2275 return createEl;
2276 },
2277
2278 /** @private */
2279 renderSectionPlaceholder: function() {
2280 return E('em', _('This section contains no values yet'));
2281 },
2282
2283 /** @private */
2284 renderContents: function(cfgsections, nodes) {
2285 var section_id = null,
2286 config_name = this.uciconfig || this.map.config,
2287 sectionEl = E('div', {
2288 'id': 'cbi-%s-%s'.format(config_name, this.sectiontype),
2289 'class': 'cbi-section',
2290 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2291 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2292 });
2293
2294 if (this.title != null && this.title != '')
2295 sectionEl.appendChild(E('h3', {}, this.title));
2296
2297 if (this.description != null && this.description != '')
2298 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2299
2300 for (var i = 0; i < nodes.length; i++) {
2301 if (this.addremove) {
2302 sectionEl.appendChild(
2303 E('div', { 'class': 'cbi-section-remove right' },
2304 E('button', {
2305 'class': 'cbi-button',
2306 'name': 'cbi.rts.%s.%s'.format(config_name, cfgsections[i]),
2307 'data-section-id': cfgsections[i],
2308 'click': ui.createHandlerFn(this, 'handleRemove', cfgsections[i]),
2309 'disabled': this.map.readonly || null
2310 }, [ _('Delete') ])));
2311 }
2312
2313 if (!this.anonymous)
2314 sectionEl.appendChild(E('h3', cfgsections[i].toUpperCase()));
2315
2316 sectionEl.appendChild(E('div', {
2317 'id': 'cbi-%s-%s'.format(config_name, cfgsections[i]),
2318 'class': this.tabs
2319 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
2320 'data-section-id': cfgsections[i]
2321 }, nodes[i]));
2322 }
2323
2324 if (nodes.length == 0)
2325 sectionEl.appendChild(this.renderSectionPlaceholder());
2326
2327 sectionEl.appendChild(this.renderSectionAdd());
2328
2329 dom.bindClassInstance(sectionEl, this);
2330
2331 return sectionEl;
2332 },
2333
2334 /** @override */
2335 render: function() {
2336 var cfgsections = this.cfgsections(),
2337 renderTasks = [];
2338
2339 for (var i = 0; i < cfgsections.length; i++)
2340 renderTasks.push(this.renderUCISection(cfgsections[i]));
2341
2342 return Promise.all(renderTasks).then(this.renderContents.bind(this, cfgsections));
2343 }
2344 });
2345
2346 /**
2347 * @class TableSection
2348 * @memberof LuCI.form
2349 * @augments LuCI.form.TypedSection
2350 * @hideconstructor
2351 * @classdesc
2352 *
2353 * The `TableSection` class maps all or - if `filter()` is overwritten - a
2354 * subset of the underlying UCI configuration sections of a given type.
2355 *
2356 * Layout wise, the configuration section instances mapped by the section
2357 * element (sometimes referred to as "section nodes") are rendered as rows
2358 * within an HTML table element, with an optional section remove button in the
2359 * last column and a section add button below the table, depending on the
2360 * value of the `addremove` property.
2361 *
2362 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2363 * The configuration form this section is added to. It is automatically passed
2364 * by [section()]{@link LuCI.form.Map#section}.
2365 *
2366 * @param {string} section_type
2367 * The type of the UCI section to map.
2368 *
2369 * @param {string} [title]
2370 * The title caption of the form section element.
2371 *
2372 * @param {string} [description]
2373 * The description text of the form section element.
2374 */
2375 var CBITableSection = CBITypedSection.extend(/** @lends LuCI.form.TableSection.prototype */ {
2376 __name__: 'CBI.TableSection',
2377
2378 /**
2379 * Override the per-section instance title caption shown in the first
2380 * column of the table unless `anonymous` is set to true. If set to a
2381 * string, it will be used as `String.format()` pattern with the name of
2382 * the underlying UCI section as first argument, if set to a function, the
2383 * function will be invoked with the section name as first argument and
2384 * its return value is used as caption, after converting it to a string.
2385 * If this property is not set, the default is the name of the underlying
2386 * UCI configuration section.
2387 *
2388 * @name LuCI.form.TableSection.prototype#sectiontitle
2389 * @type string|function
2390 * @default null
2391 */
2392
2393 /**
2394 * Override the per-section instance modal popup title caption shown when
2395 * clicking the `More…` button in a section specifying `max_cols`. If set
2396 * to a string, it will be used as `String.format()` pattern with the name
2397 * of the underlying UCI section as first argument, if set to a function,
2398 * the function will be invoked with the section name as first argument and
2399 * its return value is used as caption, after converting it to a string.
2400 * If this property is not set, the default is the name of the underlying
2401 * UCI configuration section.
2402 *
2403 * @name LuCI.form.TableSection.prototype#modaltitle
2404 * @type string|function
2405 * @default null
2406 */
2407
2408 /**
2409 * Specify a maximum amount of columns to display. By default, one table
2410 * column is rendered for each child option of the form section element.
2411 * When this option is set to a positive number, then no more columns than
2412 * the given amount are rendered. When the number of child options exceeds
2413 * the specified amount, a `More…` button is rendered in the last column,
2414 * opening a modal dialog presenting all options elements in `NamedSection`
2415 * style when clicked.
2416 *
2417 * @name LuCI.form.TableSection.prototype#max_cols
2418 * @type number
2419 * @default null
2420 */
2421
2422 /**
2423 * If set to `true`, alternating `cbi-rowstyle-1` and `cbi-rowstyle-2` CSS
2424 * classes are added to the table row elements. Not all LuCI themes
2425 * implement these row style classes. The default is `false`.
2426 *
2427 * @name LuCI.form.TableSection.prototype#rowcolors
2428 * @type boolean
2429 * @default false
2430 */
2431
2432 /**
2433 * Enables a per-section instance row `Edit` button which triggers a certain
2434 * action when clicked. If set to a string, the string value is used
2435 * as `String.format()` pattern with the name of the underlying UCI section
2436 * as first format argument. The result is then interpreted as URL which
2437 * LuCI will navigate to when the user clicks the edit button.
2438 *
2439 * If set to a function, this function will be registered as click event
2440 * handler on the rendered edit button, receiving the section instance
2441 * name as first and the DOM click event as second argument.
2442 *
2443 * @name LuCI.form.TableSection.prototype#extedit
2444 * @type string|function
2445 * @default null
2446 */
2447
2448 /**
2449 * If set to `true`, a sort button is added to the last column, allowing
2450 * the user to reorder the section instances mapped by the section form
2451 * element.
2452 *
2453 * @name LuCI.form.TableSection.prototype#sortable
2454 * @type boolean
2455 * @default false
2456 */
2457
2458 /**
2459 * If set to `true`, the header row with the options descriptions will
2460 * not be displayed. By default, descriptions row is automatically displayed
2461 * when at least one option has a description.
2462 *
2463 * @name LuCI.form.TableSection.prototype#nodescriptions
2464 * @type boolean
2465 * @default false
2466 */
2467
2468 /**
2469 * The `TableSection` implementation does not support option tabbing, so
2470 * its implementation of `tab()` will always throw an exception when
2471 * invoked.
2472 *
2473 * @override
2474 * @throws Throws an exception when invoked.
2475 */
2476 tab: function() {
2477 throw 'Tabs are not supported by TableSection';
2478 },
2479
2480 /** @private */
2481 renderContents: function(cfgsections, nodes) {
2482 var section_id = null,
2483 config_name = this.uciconfig || this.map.config,
2484 max_cols = isNaN(this.max_cols) ? this.children.length : this.max_cols,
2485 has_more = max_cols < this.children.length,
2486 drag_sort = this.sortable && !('ontouchstart' in window),
2487 touch_sort = this.sortable && ('ontouchstart' in window),
2488 sectionEl = E('div', {
2489 'id': 'cbi-%s-%s'.format(config_name, this.sectiontype),
2490 'class': 'cbi-section cbi-tblsection',
2491 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2492 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2493 }),
2494 tableEl = E('table', {
2495 'class': 'table cbi-section-table'
2496 });
2497
2498 if (this.title != null && this.title != '')
2499 sectionEl.appendChild(E('h3', {}, this.title));
2500
2501 if (this.description != null && this.description != '')
2502 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2503
2504 tableEl.appendChild(this.renderHeaderRows(max_cols));
2505
2506 for (var i = 0; i < nodes.length; i++) {
2507 var sectionname = this.titleFn('sectiontitle', cfgsections[i]);
2508
2509 if (sectionname == null)
2510 sectionname = cfgsections[i];
2511
2512 var trEl = E('tr', {
2513 'id': 'cbi-%s-%s'.format(config_name, cfgsections[i]),
2514 'class': 'tr cbi-section-table-row',
2515 'data-sid': cfgsections[i],
2516 'draggable': (drag_sort || touch_sort) ? true : null,
2517 'mousedown': drag_sort ? L.bind(this.handleDragInit, this) : null,
2518 'dragstart': drag_sort ? L.bind(this.handleDragStart, this) : null,
2519 'dragover': drag_sort ? L.bind(this.handleDragOver, this) : null,
2520 'dragenter': drag_sort ? L.bind(this.handleDragEnter, this) : null,
2521 'dragleave': drag_sort ? L.bind(this.handleDragLeave, this) : null,
2522 'dragend': drag_sort ? L.bind(this.handleDragEnd, this) : null,
2523 'drop': drag_sort ? L.bind(this.handleDrop, this) : null,
2524 'touchmove': touch_sort ? L.bind(this.handleTouchMove, this) : null,
2525 'touchend': touch_sort ? L.bind(this.handleTouchEnd, this) : null,
2526 'data-title': (sectionname && (!this.anonymous || this.sectiontitle)) ? sectionname : null,
2527 'data-section-id': cfgsections[i]
2528 });
2529
2530 if (this.extedit || this.rowcolors)
2531 trEl.classList.add(!(tableEl.childNodes.length % 2)
2532 ? 'cbi-rowstyle-1' : 'cbi-rowstyle-2');
2533
2534 for (var j = 0; j < max_cols && nodes[i].firstChild; j++)
2535 trEl.appendChild(nodes[i].firstChild);
2536
2537 trEl.appendChild(this.renderRowActions(cfgsections[i], has_more ? _('More…') : null));
2538 tableEl.appendChild(trEl);
2539 }
2540
2541 if (nodes.length == 0)
2542 tableEl.appendChild(E('tr', { 'class': 'tr cbi-section-table-row placeholder' },
2543 E('td', { 'class': 'td' }, this.renderSectionPlaceholder())));
2544
2545 sectionEl.appendChild(tableEl);
2546
2547 sectionEl.appendChild(this.renderSectionAdd('cbi-tblsection-create'));
2548
2549 dom.bindClassInstance(sectionEl, this);
2550
2551 return sectionEl;
2552 },
2553
2554 /** @private */
2555 renderHeaderRows: function(max_cols, has_action) {
2556 var has_titles = false,
2557 has_descriptions = false,
2558 max_cols = isNaN(this.max_cols) ? this.children.length : this.max_cols,
2559 has_more = max_cols < this.children.length,
2560 anon_class = (!this.anonymous || this.sectiontitle) ? 'named' : 'anonymous',
2561 trEls = E([]);
2562
2563 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2564 if (opt.modalonly)
2565 continue;
2566
2567 has_titles = has_titles || !!opt.title;
2568 has_descriptions = has_descriptions || !!opt.description;
2569 }
2570
2571 if (has_titles) {
2572 var trEl = E('tr', {
2573 'class': 'tr cbi-section-table-titles ' + anon_class,
2574 'data-title': (!this.anonymous || this.sectiontitle) ? _('Name') : null,
2575 'click': this.sortable ? ui.createHandlerFn(this, 'handleSort') : null
2576 });
2577
2578 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2579 if (opt.modalonly)
2580 continue;
2581
2582 trEl.appendChild(E('th', {
2583 'class': 'th cbi-section-table-cell',
2584 'data-widget': opt.__name__,
2585 'data-sortable-row': this.sortable ? '' : null
2586 }));
2587
2588 if (opt.width != null)
2589 trEl.lastElementChild.style.width =
2590 (typeof(opt.width) == 'number') ? opt.width+'px' : opt.width;
2591
2592 if (opt.titleref)
2593 trEl.lastElementChild.appendChild(E('a', {
2594 'href': opt.titleref,
2595 'class': 'cbi-title-ref',
2596 'title': this.titledesc || _('Go to relevant configuration page')
2597 }, opt.title));
2598 else
2599 dom.content(trEl.lastElementChild, opt.title);
2600 }
2601
2602 if (this.sortable || this.extedit || this.addremove || has_more || has_action)
2603 trEl.appendChild(E('th', {
2604 'class': 'th cbi-section-table-cell cbi-section-actions'
2605 }));
2606
2607 trEls.appendChild(trEl);
2608 }
2609
2610 if (has_descriptions && !this.nodescriptions) {
2611 var trEl = E('tr', {
2612 'class': 'tr cbi-section-table-descr ' + anon_class
2613 });
2614
2615 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2616 if (opt.modalonly)
2617 continue;
2618
2619 trEl.appendChild(E('th', {
2620 'class': 'th cbi-section-table-cell',
2621 'data-widget': opt.__name__
2622 }, opt.description));
2623
2624 if (opt.width != null)
2625 trEl.lastElementChild.style.width =
2626 (typeof(opt.width) == 'number') ? opt.width+'px' : opt.width;
2627 }
2628
2629 if (this.sortable || this.extedit || this.addremove || has_more || has_action)
2630 trEl.appendChild(E('th', {
2631 'class': 'th cbi-section-table-cell cbi-section-actions'
2632 }));
2633
2634 trEls.appendChild(trEl);
2635 }
2636
2637 return trEls;
2638 },
2639
2640 /** @private */
2641 renderRowActions: function(section_id, more_label) {
2642 var config_name = this.uciconfig || this.map.config;
2643
2644 if (!this.sortable && !this.extedit && !this.addremove && !more_label)
2645 return E([]);
2646
2647 var tdEl = E('td', {
2648 'class': 'td cbi-section-table-cell nowrap cbi-section-actions'
2649 }, E('div'));
2650
2651 if (this.sortable) {
2652 dom.append(tdEl.lastElementChild, [
2653 E('button', {
2654 'title': _('Drag to reorder'),
2655 'class': 'cbi-button drag-handle center',
2656 'style': 'cursor:move',
2657 'disabled': this.map.readonly || null
2658 }, '☰')
2659 ]);
2660 }
2661
2662 if (this.extedit) {
2663 var evFn = null;
2664
2665 if (typeof(this.extedit) == 'function')
2666 evFn = L.bind(this.extedit, this);
2667 else if (typeof(this.extedit) == 'string')
2668 evFn = L.bind(function(sid, ev) {
2669 location.href = this.extedit.format(sid);
2670 }, this, section_id);
2671
2672 dom.append(tdEl.lastElementChild,
2673 E('button', {
2674 'title': _('Edit'),
2675 'class': 'cbi-button cbi-button-edit',
2676 'click': evFn
2677 }, [ _('Edit') ])
2678 );
2679 }
2680
2681 if (more_label) {
2682 dom.append(tdEl.lastElementChild,
2683 E('button', {
2684 'title': more_label,
2685 'class': 'cbi-button cbi-button-edit',
2686 'click': ui.createHandlerFn(this, 'renderMoreOptionsModal', section_id)
2687 }, [ more_label ])
2688 );
2689 }
2690
2691 if (this.addremove) {
2692 var btn_title = this.titleFn('removebtntitle', section_id);
2693
2694 dom.append(tdEl.lastElementChild,
2695 E('button', {
2696 'title': btn_title || _('Delete'),
2697 'class': 'cbi-button cbi-button-remove',
2698 'click': ui.createHandlerFn(this, 'handleRemove', section_id),
2699 'disabled': this.map.readonly || null
2700 }, [ btn_title || _('Delete') ])
2701 );
2702 }
2703
2704 return tdEl;
2705 },
2706
2707 /** @private */
2708 handleDragInit: function(ev) {
2709 scope.dragState = { node: ev.target };
2710 },
2711
2712 /** @private */
2713 handleDragStart: function(ev) {
2714 if (!scope.dragState || !scope.dragState.node.classList.contains('drag-handle')) {
2715 scope.dragState = null;
2716 ev.preventDefault();
2717 return false;
2718 }
2719
2720 scope.dragState.node = dom.parent(scope.dragState.node, '.tr');
2721 ev.dataTransfer.setData('text', 'drag');
2722 ev.target.style.opacity = 0.4;
2723 },
2724
2725 /** @private */
2726 handleDragOver: function(ev) {
2727 var n = scope.dragState.targetNode,
2728 r = scope.dragState.rect,
2729 t = r.top + r.height / 2;
2730
2731 if (ev.clientY <= t) {
2732 n.classList.remove('drag-over-below');
2733 n.classList.add('drag-over-above');
2734 }
2735 else {
2736 n.classList.remove('drag-over-above');
2737 n.classList.add('drag-over-below');
2738 }
2739
2740 ev.dataTransfer.dropEffect = 'move';
2741 ev.preventDefault();
2742 return false;
2743 },
2744
2745 /** @private */
2746 handleDragEnter: function(ev) {
2747 scope.dragState.rect = ev.currentTarget.getBoundingClientRect();
2748 scope.dragState.targetNode = ev.currentTarget;
2749 },
2750
2751 /** @private */
2752 handleDragLeave: function(ev) {
2753 ev.currentTarget.classList.remove('drag-over-above');
2754 ev.currentTarget.classList.remove('drag-over-below');
2755 },
2756
2757 /** @private */
2758 handleDragEnd: function(ev) {
2759 var n = ev.target;
2760
2761 n.style.opacity = '';
2762 n.classList.add('flash');
2763 n.parentNode.querySelectorAll('.drag-over-above, .drag-over-below')
2764 .forEach(function(tr) {
2765 tr.classList.remove('drag-over-above');
2766 tr.classList.remove('drag-over-below');
2767 });
2768 },
2769
2770 /** @private */
2771 handleDrop: function(ev) {
2772 var s = scope.dragState;
2773
2774 if (s.node && s.targetNode) {
2775 var config_name = this.uciconfig || this.map.config,
2776 ref_node = s.targetNode,
2777 after = false;
2778
2779 if (ref_node.classList.contains('drag-over-below')) {
2780 ref_node = ref_node.nextElementSibling;
2781 after = true;
2782 }
2783
2784 var sid1 = s.node.getAttribute('data-sid'),
2785 sid2 = s.targetNode.getAttribute('data-sid');
2786
2787 s.node.parentNode.insertBefore(s.node, ref_node);
2788 this.map.data.move(config_name, sid1, sid2, after);
2789 }
2790
2791 scope.dragState = null;
2792 ev.target.style.opacity = '';
2793 ev.stopPropagation();
2794 ev.preventDefault();
2795 return false;
2796 },
2797
2798 /** @private */
2799 determineBackgroundColor: function(node) {
2800 var r = 255, g = 255, b = 255;
2801
2802 while (node) {
2803 var s = window.getComputedStyle(node),
2804 c = (s.getPropertyValue('background-color') || '').replace(/ /g, '');
2805
2806 if (c != '' && c != 'transparent' && c != 'rgba(0,0,0,0)') {
2807 if (/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.test(c)) {
2808 r = parseInt(RegExp.$1, 16);
2809 g = parseInt(RegExp.$2, 16);
2810 b = parseInt(RegExp.$3, 16);
2811 }
2812 else if (/^rgba?\(([0-9]+),([0-9]+),([0-9]+)[,)]$/.test(c)) {
2813 r = +RegExp.$1;
2814 g = +RegExp.$2;
2815 b = +RegExp.$3;
2816 }
2817
2818 break;
2819 }
2820
2821 node = node.parentNode;
2822 }
2823
2824 return [ r, g, b ];
2825 },
2826
2827 /** @private */
2828 handleTouchMove: function(ev) {
2829 if (!ev.target.classList.contains('drag-handle'))
2830 return;
2831
2832 var touchLoc = ev.targetTouches[0],
2833 rowBtn = ev.target,
2834 rowElem = dom.parent(rowBtn, '.tr'),
2835 htmlElem = document.querySelector('html'),
2836 dragHandle = document.querySelector('.touchsort-element'),
2837 viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
2838
2839 if (!dragHandle) {
2840 var rowRect = rowElem.getBoundingClientRect(),
2841 btnRect = rowBtn.getBoundingClientRect(),
2842 paddingLeft = btnRect.left - rowRect.left,
2843 paddingRight = rowRect.right - btnRect.right,
2844 colorBg = this.determineBackgroundColor(rowElem),
2845 colorFg = (colorBg[0] * 0.299 + colorBg[1] * 0.587 + colorBg[2] * 0.114) > 186 ? [ 0, 0, 0 ] : [ 255, 255, 255 ];
2846
2847 dragHandle = E('div', { 'class': 'touchsort-element' }, [
2848 E('strong', [ rowElem.getAttribute('data-title') ]),
2849 rowBtn.cloneNode(true)
2850 ]);
2851
2852 Object.assign(dragHandle.style, {
2853 position: 'absolute',
2854 boxShadow: '0 0 3px rgba(%d, %d, %d, 1)'.format(colorFg[0], colorFg[1], colorFg[2]),
2855 background: 'rgba(%d, %d, %d, 0.8)'.format(colorBg[0], colorBg[1], colorBg[2]),
2856 top: rowRect.top + 'px',
2857 left: rowRect.left + 'px',
2858 width: rowRect.width + 'px',
2859 height: (rowBtn.offsetHeight + 4) + 'px'
2860 });
2861
2862 Object.assign(dragHandle.firstElementChild.style, {
2863 position: 'absolute',
2864 lineHeight: dragHandle.style.height,
2865 whiteSpace: 'nowrap',
2866 overflow: 'hidden',
2867 textOverflow: 'ellipsis',
2868 left: (paddingRight > paddingLeft) ? '' : '5px',
2869 right: (paddingRight > paddingLeft) ? '5px' : '',
2870 width: (Math.max(paddingLeft, paddingRight) - 10) + 'px'
2871 });
2872
2873 Object.assign(dragHandle.lastElementChild.style, {
2874 position: 'absolute',
2875 top: '2px',
2876 left: paddingLeft + 'px',
2877 width: rowBtn.offsetWidth + 'px'
2878 });
2879
2880 document.body.appendChild(dragHandle);
2881
2882 rowElem.classList.remove('flash');
2883 rowBtn.blur();
2884 }
2885
2886 dragHandle.style.top = (touchLoc.pageY - (parseInt(dragHandle.style.height) / 2)) + 'px';
2887
2888 rowElem.parentNode.querySelectorAll('[draggable]').forEach(function(tr, i, trs) {
2889 var trRect = tr.getBoundingClientRect(),
2890 yTop = trRect.top + window.scrollY,
2891 yBottom = trRect.bottom + window.scrollY,
2892 yMiddle = yTop + ((yBottom - yTop) / 2);
2893
2894 tr.classList.remove('drag-over-above', 'drag-over-below');
2895
2896 if ((i == 0 || touchLoc.pageY >= yTop) && touchLoc.pageY <= yMiddle)
2897 tr.classList.add('drag-over-above');
2898 else if ((i == (trs.length - 1) || touchLoc.pageY <= yBottom) && touchLoc.pageY > yMiddle)
2899 tr.classList.add('drag-over-below');
2900 });
2901
2902 /* prevent standard scrolling and scroll page when drag handle is
2903 * moved very close (~30px) to the viewport edge */
2904
2905 ev.preventDefault();
2906
2907 if (touchLoc.clientY < 30)
2908 window.requestAnimationFrame(function() { htmlElem.scrollTop -= 30 });
2909 else if (touchLoc.clientY > viewportHeight - 30)
2910 window.requestAnimationFrame(function() { htmlElem.scrollTop += 30 });
2911 },
2912
2913 /** @private */
2914 handleTouchEnd: function(ev) {
2915 var rowElem = dom.parent(ev.target, '.tr'),
2916 htmlElem = document.querySelector('html'),
2917 dragHandle = document.querySelector('.touchsort-element'),
2918 targetElem = rowElem.parentNode.querySelector('.drag-over-above, .drag-over-below'),
2919 viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
2920
2921 if (!dragHandle)
2922 return;
2923
2924 if (targetElem) {
2925 var isBelow = targetElem.classList.contains('drag-over-below');
2926
2927 rowElem.parentNode.insertBefore(rowElem, isBelow ? targetElem.nextElementSibling : targetElem);
2928
2929 this.map.data.move(
2930 this.uciconfig || this.map.config,
2931 rowElem.getAttribute('data-sid'),
2932 targetElem.getAttribute('data-sid'),
2933 isBelow);
2934
2935 window.requestAnimationFrame(function() {
2936 var rowRect = rowElem.getBoundingClientRect();
2937
2938 if (rowRect.top < 50)
2939 htmlElem.scrollTop = (htmlElem.scrollTop + rowRect.top - 50);
2940 else if (rowRect.bottom > viewportHeight - 50)
2941 htmlElem.scrollTop = (htmlElem.scrollTop + viewportHeight - 50 - rowRect.height);
2942
2943 rowElem.classList.add('flash');
2944 });
2945
2946 targetElem.classList.remove('drag-over-above', 'drag-over-below');
2947 }
2948
2949 document.body.removeChild(dragHandle);
2950 },
2951
2952 /** @private */
2953 handleModalCancel: function(modalMap, ev) {
2954 var prevNode = this.getPreviousModalMap(),
2955 resetTasks = Promise.resolve();
2956
2957 if (prevNode) {
2958 var heading = prevNode.parentNode.querySelector('h4'),
2959 prevMap = dom.findClassInstance(prevNode);
2960
2961 while (prevMap) {
2962 resetTasks = resetTasks
2963 .then(L.bind(prevMap.load, prevMap))
2964 .then(L.bind(prevMap.reset, prevMap));
2965
2966 prevMap = prevMap.parent;
2967 }
2968
2969 prevNode.classList.add('flash');
2970 prevNode.classList.remove('hidden');
2971 prevNode.parentNode.removeChild(prevNode.nextElementSibling);
2972
2973 heading.removeChild(heading.lastElementChild);
2974
2975 if (!this.getPreviousModalMap())
2976 prevNode.parentNode
2977 .querySelector('div.right > button')
2978 .firstChild.data = _('Dismiss');
2979 }
2980 else {
2981 ui.hideModal();
2982 }
2983
2984 return resetTasks;
2985 },
2986
2987 /** @private */
2988 handleModalSave: function(modalMap, ev) {
2989 var mapNode = this.getActiveModalMap(),
2990 activeMap = dom.findClassInstance(mapNode),
2991 saveTasks = activeMap.save(null, true);
2992
2993 while (activeMap.parent) {
2994 activeMap = activeMap.parent;
2995 saveTasks = saveTasks
2996 .then(L.bind(activeMap.load, activeMap))
2997 .then(L.bind(activeMap.reset, activeMap));
2998 }
2999
3000 return saveTasks
3001 .then(L.bind(this.handleModalCancel, this, modalMap, ev, true))
3002 .catch(function() {});
3003 },
3004
3005 /** @private */
3006 handleSort: function(ev) {
3007 if (!ev.target.matches('th[data-sortable-row]'))
3008 return;
3009
3010 var th = ev.target,
3011 descending = (th.getAttribute('data-sort-direction') == 'desc'),
3012 config_name = this.uciconfig || this.map.config,
3013 index = 0,
3014 list = [];
3015
3016 ev.currentTarget.querySelectorAll('th').forEach(function(other_th, i) {
3017 if (other_th !== th)
3018 other_th.removeAttribute('data-sort-direction');
3019 else
3020 index = i;
3021 });
3022
3023 ev.currentTarget.parentNode.querySelectorAll('tr.cbi-section-table-row').forEach(L.bind(function(tr, i) {
3024 var sid = tr.getAttribute('data-sid'),
3025 opt = tr.childNodes[index].getAttribute('data-name'),
3026 val = this.cfgvalue(sid, opt);
3027
3028 tr.querySelectorAll('.flash').forEach(function(n) {
3029 n.classList.remove('flash')
3030 });
3031
3032 list.push([
3033 ui.Table.prototype.deriveSortKey((val != null) ? val.trim() : ''),
3034 tr
3035 ]);
3036 }, this));
3037
3038 list.sort(function(a, b) {
3039 return descending
3040 ? -L.naturalCompare(a[0], b[0])
3041 : L.naturalCompare(a[0], b[0]);
3042 });
3043
3044 window.requestAnimationFrame(L.bind(function() {
3045 var ref_sid, cur_sid;
3046
3047 for (var i = 0; i < list.length; i++) {
3048 list[i][1].childNodes[index].classList.add('flash');
3049 th.parentNode.parentNode.appendChild(list[i][1]);
3050
3051 cur_sid = list[i][1].getAttribute('data-sid');
3052
3053 if (ref_sid)
3054 this.map.data.move(config_name, cur_sid, ref_sid, true);
3055
3056 ref_sid = cur_sid;
3057 }
3058
3059 th.setAttribute('data-sort-direction', descending ? 'asc' : 'desc');
3060 }, this));
3061 },
3062
3063 /**
3064 * Add further options to the per-section instanced modal popup.
3065 *
3066 * This function may be overwritten by user code to perform additional
3067 * setup steps before displaying the more options modal which is useful to
3068 * e.g. query additional data or to inject further option elements.
3069 *
3070 * The default implementation of this function does nothing.
3071 *
3072 * @abstract
3073 * @param {LuCI.form.NamedSection} modalSection
3074 * The `NamedSection` instance about to be rendered in the modal popup.
3075 *
3076 * @param {string} section_id
3077 * The ID of the underlying UCI section the modal popup belongs to.
3078 *
3079 * @param {Event} ev
3080 * The DOM event emitted by clicking the `More…` button.
3081 *
3082 * @returns {*|Promise<*>}
3083 * Return values of this function are ignored but if a promise is returned,
3084 * it is run to completion before the rendering is continued, allowing
3085 * custom logic to perform asynchronous work before the modal dialog
3086 * is shown.
3087 */
3088 addModalOptions: function(modalSection, section_id, ev) {
3089
3090 },
3091
3092 /** @private */
3093 getActiveModalMap: function() {
3094 return document.querySelector('body.modal-overlay-active > #modal_overlay > .modal.cbi-modal > .cbi-map:not(.hidden)');
3095 },
3096
3097 /** @private */
3098 getPreviousModalMap: function() {
3099 var mapNode = this.getActiveModalMap(),
3100 prevNode = mapNode ? mapNode.previousElementSibling : null;
3101
3102 return (prevNode && prevNode.matches('.cbi-map.hidden')) ? prevNode : null;
3103 },
3104
3105 /** @private */
3106 cloneOptions: function(src_section, dest_section) {
3107 for (var i = 0; i < src_section.children.length; i++) {
3108 var o1 = src_section.children[i];
3109
3110 if (o1.modalonly === false && src_section === this)
3111 continue;
3112
3113 var o2;
3114
3115 if (o1.subsection) {
3116 o2 = dest_section.option(o1.constructor, o1.option, o1.subsection.constructor, o1.subsection.sectiontype, o1.subsection.title, o1.subsection.description);
3117
3118 for (var k in o1.subsection) {
3119 if (!o1.subsection.hasOwnProperty(k))
3120 continue;
3121
3122 switch (k) {
3123 case 'map':
3124 case 'children':
3125 case 'parentoption':
3126 continue;
3127
3128 default:
3129 o2.subsection[k] = o1.subsection[k];
3130 }
3131 }
3132
3133 this.cloneOptions(o1.subsection, o2.subsection);
3134 }
3135 else {
3136 o2 = dest_section.option(o1.constructor, o1.option, o1.title, o1.description);
3137 }
3138
3139 for (var k in o1) {
3140 if (!o1.hasOwnProperty(k))
3141 continue;
3142
3143 switch (k) {
3144 case 'map':
3145 case 'section':
3146 case 'option':
3147 case 'title':
3148 case 'description':
3149 case 'subsection':
3150 continue;
3151
3152 default:
3153 o2[k] = o1[k];
3154 }
3155 }
3156 }
3157 },
3158
3159 /** @private */
3160 renderMoreOptionsModal: function(section_id, ev) {
3161 var parent = this.map,
3162 sref = parent.data.get(parent.config, section_id),
3163 mapNode = this.getActiveModalMap(),
3164 activeMap = mapNode ? dom.findClassInstance(mapNode) : null,
3165 stackedMap = activeMap && (activeMap.parent !== parent || activeMap.section !== section_id);
3166
3167 return (stackedMap ? activeMap.save(null, true) : Promise.resolve()).then(L.bind(function() {
3168 section_id = sref['.name'];
3169
3170 var m;
3171
3172 if (parent instanceof CBIJSONMap) {
3173 m = new CBIJSONMap(null, null, null);
3174 m.data = parent.data;
3175 }
3176 else {
3177 m = new CBIMap(parent.config, null, null);
3178 }
3179
3180 var s = m.section(CBINamedSection, section_id, this.sectiontype);
3181
3182 m.parent = parent;
3183 m.section = section_id;
3184 m.readonly = parent.readonly;
3185
3186 s.tabs = this.tabs;
3187 s.tab_names = this.tab_names;
3188
3189 this.cloneOptions(this, s);
3190
3191 return Promise.resolve(this.addModalOptions(s, section_id, ev)).then(function() {
3192 return m.render();
3193 }).then(L.bind(function(nodes) {
3194 var title = parent.title,
3195 name = null;
3196
3197 if ((name = this.titleFn('modaltitle', section_id)) != null)
3198 title = name;
3199 else if ((name = this.titleFn('sectiontitle', section_id)) != null)
3200 title = '%s - %s'.format(parent.title, name);
3201 else if (!this.anonymous)
3202 title = '%s - %s'.format(parent.title, section_id);
3203
3204 if (stackedMap) {
3205 mapNode.parentNode
3206 .querySelector('h4')
3207 .appendChild(E('span', title ? ' » ' + title : ''));
3208
3209 mapNode.parentNode
3210 .querySelector('div.right > button')
3211 .firstChild.data = _('Back');
3212
3213 mapNode.classList.add('hidden');
3214 mapNode.parentNode.insertBefore(nodes, mapNode.nextElementSibling);
3215
3216 nodes.classList.add('flash');
3217 }
3218 else {
3219 ui.showModal(title, [
3220 nodes,
3221 E('div', { 'class': 'right' }, [
3222 E('button', {
3223 'class': 'cbi-button',
3224 'click': ui.createHandlerFn(this, 'handleModalCancel', m)
3225 }, [ _('Dismiss') ]), ' ',
3226 E('button', {
3227 'class': 'cbi-button cbi-button-positive important',
3228 'click': ui.createHandlerFn(this, 'handleModalSave', m),
3229 'disabled': m.readonly || null
3230 }, [ _('Save') ])
3231 ])
3232 ], 'cbi-modal');
3233 }
3234 }, this));
3235 }, this)).catch(L.error);
3236 }
3237 });
3238
3239 /**
3240 * @class GridSection
3241 * @memberof LuCI.form
3242 * @augments LuCI.form.TableSection
3243 * @hideconstructor
3244 * @classdesc
3245 *
3246 * The `GridSection` class maps all or - if `filter()` is overwritten - a
3247 * subset of the underlying UCI configuration sections of a given type.
3248 *
3249 * A grid section functions similar to a {@link LuCI.form.TableSection} but
3250 * supports tabbing in the modal overlay. Option elements added with
3251 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
3252 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
3253 * are displayed in the modal popup.
3254 *
3255 * Another important difference is that the table cells show a readonly text
3256 * preview of the corresponding option elements by default, unless the child
3257 * option element is explicitly made writable by setting the `editable`
3258 * property to `true`.
3259 *
3260 * Additionally, the grid section honours a `modalonly` property of child
3261 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
3262 * documentation for details.
3263 *
3264 * Layout wise, a grid section looks mostly identical to table sections.
3265 *
3266 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3267 * The configuration form this section is added to. It is automatically passed
3268 * by [section()]{@link LuCI.form.Map#section}.
3269 *
3270 * @param {string} section_type
3271 * The type of the UCI section to map.
3272 *
3273 * @param {string} [title]
3274 * The title caption of the form section element.
3275 *
3276 * @param {string} [description]
3277 * The description text of the form section element.
3278 */
3279 var CBIGridSection = CBITableSection.extend(/** @lends LuCI.form.GridSection.prototype */ {
3280 /**
3281 * Add an option tab to the section.
3282 *
3283 * The modal option elements of a grid section may be divided into multiple
3284 * tabs to provide a better overview to the user.
3285 *
3286 * Before options can be moved into a tab pane, the corresponding tab
3287 * has to be defined first, which is done by calling this function.
3288 *
3289 * Note that tabs are only effective in modal popups, options added with
3290 * `option()` will not be assigned to a specific tab and are rendered in
3291 * the table view only.
3292 *
3293 * @param {string} name
3294 * The name of the tab to register. It may be freely chosen and just serves
3295 * as an identifier to differentiate tabs.
3296 *
3297 * @param {string} title
3298 * The human readable caption of the tab.
3299 *
3300 * @param {string} [description]
3301 * An additional description text for the corresponding tab pane. It is
3302 * displayed as text paragraph below the tab but before the tab pane
3303 * contents. If omitted, no description will be rendered.
3304 *
3305 * @throws {Error}
3306 * Throws an exception if a tab with the same `name` already exists.
3307 */
3308 tab: function(name, title, description) {
3309 CBIAbstractSection.prototype.tab.call(this, name, title, description);
3310 },
3311
3312 /** @private */
3313 handleAdd: function(ev, name) {
3314 var config_name = this.uciconfig || this.map.config,
3315 section_id = this.map.data.add(config_name, this.sectiontype, name),
3316 mapNode = this.getPreviousModalMap(),
3317 prevMap = mapNode ? dom.findClassInstance(mapNode) : this.map;
3318
3319 prevMap.addedSection = section_id;
3320
3321 return this.renderMoreOptionsModal(section_id);
3322 },
3323
3324 /** @private */
3325 handleModalSave: function(/* ... */) {
3326 var mapNode = this.getPreviousModalMap(),
3327 prevMap = mapNode ? dom.findClassInstance(mapNode) : this.map;
3328
3329 return this.super('handleModalSave', arguments);
3330 },
3331
3332 /** @private */
3333 handleModalCancel: function(modalMap, ev, isSaving) {
3334 var config_name = this.uciconfig || this.map.config,
3335 mapNode = this.getPreviousModalMap(),
3336 prevMap = mapNode ? dom.findClassInstance(mapNode) : this.map;
3337
3338 if (prevMap.addedSection != null && !isSaving)
3339 this.map.data.remove(config_name, prevMap.addedSection);
3340
3341 delete prevMap.addedSection;
3342
3343 return this.super('handleModalCancel', arguments);
3344 },
3345
3346 /** @private */
3347 renderUCISection: function(section_id) {
3348 return this.renderOptions(null, section_id);
3349 },
3350
3351 /** @private */
3352 renderChildren: function(tab_name, section_id, in_table) {
3353 var tasks = [], index = 0;
3354
3355 for (var i = 0, opt; (opt = this.children[i]) != null; i++) {
3356 if (opt.disable || opt.modalonly)
3357 continue;
3358
3359 if (opt.editable)
3360 tasks.push(opt.render(index++, section_id, in_table));
3361 else
3362 tasks.push(this.renderTextValue(section_id, opt));
3363 }
3364
3365 return Promise.all(tasks);
3366 },
3367
3368 /** @private */
3369 renderTextValue: function(section_id, opt) {
3370 var title = this.stripTags(opt.title).trim(),
3371 descr = this.stripTags(opt.description).trim(),
3372 value = opt.textvalue(section_id);
3373
3374 return E('td', {
3375 'class': 'td cbi-value-field',
3376 'data-title': (title != '') ? title : null,
3377 'data-description': (descr != '') ? descr : null,
3378 'data-name': opt.option,
3379 'data-widget': 'CBI.DummyValue'
3380 }, (value != null) ? value : E('em', _('none')));
3381 },
3382
3383 /** @private */
3384 renderHeaderRows: function(section_id) {
3385 return this.super('renderHeaderRows', [ NaN, true ]);
3386 },
3387
3388 /** @private */
3389 renderRowActions: function(section_id) {
3390 return this.super('renderRowActions', [ section_id, _('Edit') ]);
3391 },
3392
3393 /** @override */
3394 parse: function() {
3395 var section_ids = this.cfgsections(),
3396 tasks = [];
3397
3398 if (Array.isArray(this.children)) {
3399 for (var i = 0; i < section_ids.length; i++) {
3400 for (var j = 0; j < this.children.length; j++) {
3401 if (!this.children[j].editable || this.children[j].modalonly)
3402 continue;
3403
3404 tasks.push(this.children[j].parse(section_ids[i]));
3405 }
3406 }
3407 }
3408
3409 return Promise.all(tasks);
3410 }
3411 });
3412
3413 /**
3414 * @class NamedSection
3415 * @memberof LuCI.form
3416 * @augments LuCI.form.AbstractSection
3417 * @hideconstructor
3418 * @classdesc
3419 *
3420 * The `NamedSection` class maps exactly one UCI section instance which is
3421 * specified when constructing the class instance.
3422 *
3423 * Layout and functionality wise, a named section is essentially a
3424 * `TypedSection` which allows exactly one section node.
3425 *
3426 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3427 * The configuration form this section is added to. It is automatically passed
3428 * by [section()]{@link LuCI.form.Map#section}.
3429 *
3430 * @param {string} section_id
3431 * The name (ID) of the UCI section to map.
3432 *
3433 * @param {string} section_type
3434 * The type of the UCI section to map.
3435 *
3436 * @param {string} [title]
3437 * The title caption of the form section element.
3438 *
3439 * @param {string} [description]
3440 * The description text of the form section element.
3441 */
3442 var CBINamedSection = CBIAbstractSection.extend(/** @lends LuCI.form.NamedSection.prototype */ {
3443 __name__: 'CBI.NamedSection',
3444 __init__: function(map, section_id /*, ... */) {
3445 this.super('__init__', this.varargs(arguments, 2, map));
3446
3447 this.section = section_id;
3448 },
3449
3450 /**
3451 * If set to `true`, the user may remove or recreate the sole mapped
3452 * configuration instance from the form section widget, otherwise only a
3453 * preexisting section may be edited. The default is `false`.
3454 *
3455 * @name LuCI.form.NamedSection.prototype#addremove
3456 * @type boolean
3457 * @default false
3458 */
3459
3460 /**
3461 * Override the UCI configuration name to read the section IDs from. By
3462 * default, the configuration name is inherited from the parent `Map`.
3463 * By setting this property, a deviating configuration may be specified.
3464 * The default is `null`, means inheriting from the parent form.
3465 *
3466 * @name LuCI.form.NamedSection.prototype#uciconfig
3467 * @type string
3468 * @default null
3469 */
3470
3471 /**
3472 * The `NamedSection` class overwrites the generic `cfgsections()`
3473 * implementation to return a one-element array containing the mapped
3474 * section ID as sole element. User code should not normally change this.
3475 *
3476 * @returns {string[]}
3477 * Returns a one-element array containing the mapped section ID.
3478 */
3479 cfgsections: function() {
3480 return [ this.section ];
3481 },
3482
3483 /** @private */
3484 handleAdd: function(ev) {
3485 var section_id = this.section,
3486 config_name = this.uciconfig || this.map.config;
3487
3488 this.map.data.add(config_name, this.sectiontype, section_id);
3489 return this.map.save(null, true);
3490 },
3491
3492 /** @private */
3493 handleRemove: function(ev) {
3494 var section_id = this.section,
3495 config_name = this.uciconfig || this.map.config;
3496
3497 this.map.data.remove(config_name, section_id);
3498 return this.map.save(null, true);
3499 },
3500
3501 /** @private */
3502 renderContents: function(data) {
3503 var ucidata = data[0], nodes = data[1],
3504 section_id = this.section,
3505 config_name = this.uciconfig || this.map.config,
3506 sectionEl = E('div', {
3507 'id': ucidata ? null : 'cbi-%s-%s'.format(config_name, section_id),
3508 'class': 'cbi-section',
3509 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
3510 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
3511 });
3512
3513 if (typeof(this.title) === 'string' && this.title !== '')
3514 sectionEl.appendChild(E('h3', {}, this.title));
3515
3516 if (typeof(this.description) === 'string' && this.description !== '')
3517 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
3518
3519 if (ucidata) {
3520 if (this.addremove) {
3521 sectionEl.appendChild(
3522 E('div', { 'class': 'cbi-section-remove right' },
3523 E('button', {
3524 'class': 'cbi-button',
3525 'click': ui.createHandlerFn(this, 'handleRemove'),
3526 'disabled': this.map.readonly || null
3527 }, [ _('Delete') ])));
3528 }
3529
3530 sectionEl.appendChild(E('div', {
3531 'id': 'cbi-%s-%s'.format(config_name, section_id),
3532 'class': this.tabs
3533 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3534 'data-section-id': section_id
3535 }, nodes));
3536 }
3537 else if (this.addremove) {
3538 sectionEl.appendChild(
3539 E('button', {
3540 'class': 'cbi-button cbi-button-add',
3541 'click': ui.createHandlerFn(this, 'handleAdd'),
3542 'disabled': this.map.readonly || null
3543 }, [ _('Add') ]));
3544 }
3545
3546 dom.bindClassInstance(sectionEl, this);
3547
3548 return sectionEl;
3549 },
3550
3551 /** @override */
3552 render: function() {
3553 var config_name = this.uciconfig || this.map.config,
3554 section_id = this.section;
3555
3556 return Promise.all([
3557 this.map.data.get(config_name, section_id),
3558 this.renderUCISection(section_id)
3559 ]).then(this.renderContents.bind(this));
3560 }
3561 });
3562
3563 /**
3564 * @class Value
3565 * @memberof LuCI.form
3566 * @augments LuCI.form.AbstractValue
3567 * @hideconstructor
3568 * @classdesc
3569 *
3570 * The `Value` class represents a simple one-line form input using the
3571 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3572 * {@link LuCI.ui.Combobox} class as underlying widget.
3573 *
3574 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3575 * The configuration form this section is added to. It is automatically passed
3576 * by [option()]{@link LuCI.form.AbstractSection#option} or
3577 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3578 * option to the section.
3579 *
3580 * @param {LuCI.form.AbstractSection} section
3581 * The configuration section this option is added to. It is automatically passed
3582 * by [option()]{@link LuCI.form.AbstractSection#option} or
3583 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3584 * option to the section.
3585 *
3586 * @param {string} option
3587 * The name of the UCI option to map.
3588 *
3589 * @param {string} [title]
3590 * The title caption of the option element.
3591 *
3592 * @param {string} [description]
3593 * The description text of the option element.
3594 */
3595 var CBIValue = CBIAbstractValue.extend(/** @lends LuCI.form.Value.prototype */ {
3596 __name__: 'CBI.Value',
3597
3598 /**
3599 * If set to `true`, the field is rendered as password input, otherwise
3600 * as plain text input.
3601 *
3602 * @name LuCI.form.Value.prototype#password
3603 * @type boolean
3604 * @default false
3605 */
3606
3607 /**
3608 * Set a placeholder string to use when the input field is empty.
3609 *
3610 * @name LuCI.form.Value.prototype#placeholder
3611 * @type string
3612 * @default null
3613 */
3614
3615 /**
3616 * Add a predefined choice to the form option. By adding one or more
3617 * choices, the plain text input field is turned into a combobox widget
3618 * which prompts the user to select a predefined choice, or to enter a
3619 * custom value.
3620 *
3621 * @param {string} key
3622 * The choice value to add.
3623 *
3624 * @param {Node|string} val
3625 * The caption for the choice value. May be a DOM node, a document fragment
3626 * or a plain text string. If omitted, the `key` value is used as caption.
3627 */
3628 value: function(key, val) {
3629 this.keylist = this.keylist || [];
3630 this.keylist.push(String(key));
3631
3632 this.vallist = this.vallist || [];
3633 this.vallist.push(dom.elem(val) ? val : String(val != null ? val : key));
3634 },
3635
3636 /** @override */
3637 render: function(option_index, section_id, in_table) {
3638 return Promise.resolve(this.cfgvalue(section_id))
3639 .then(this.renderWidget.bind(this, section_id, option_index))
3640 .then(this.renderFrame.bind(this, section_id, in_table, option_index));
3641 },
3642
3643 /** @private */
3644 handleValueChange: function(section_id, state, ev) {
3645 if (typeof(this.onchange) != 'function')
3646 return;
3647
3648 var value = this.formvalue(section_id);
3649
3650 if (isEqual(value, state.previousValue))
3651 return;
3652
3653 state.previousValue = value;
3654 this.onchange.call(this, ev, section_id, value);
3655 },
3656
3657 /** @private */
3658 renderFrame: function(section_id, in_table, option_index, nodes) {
3659 var config_name = this.uciconfig || this.section.uciconfig || this.map.config,
3660 depend_list = this.transformDepList(section_id),
3661 optionEl;
3662
3663 if (in_table) {
3664 var title = this.stripTags(this.title).trim();
3665 optionEl = E('td', {
3666 'class': 'td cbi-value-field',
3667 'data-title': (title != '') ? title : null,
3668 'data-description': this.stripTags(this.description).trim(),
3669 'data-name': this.option,
3670 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3671 }, E('div', {
3672 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3673 'data-index': option_index,
3674 'data-depends': depend_list,
3675 'data-field': this.cbid(section_id)
3676 }));
3677 }
3678 else {
3679 optionEl = E('div', {
3680 'class': 'cbi-value',
3681 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3682 'data-index': option_index,
3683 'data-depends': depend_list,
3684 'data-field': this.cbid(section_id),
3685 'data-name': this.option,
3686 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3687 });
3688
3689 if (this.last_child)
3690 optionEl.classList.add('cbi-value-last');
3691
3692 if (typeof(this.title) === 'string' && this.title !== '') {
3693 optionEl.appendChild(E('label', {
3694 'class': 'cbi-value-title',
3695 'for': 'widget.cbid.%s.%s.%s'.format(config_name, section_id, this.option),
3696 'click': function(ev) {
3697 var node = ev.currentTarget,
3698 elem = node.nextElementSibling.querySelector('#' + node.getAttribute('for')) || node.nextElementSibling.querySelector('[data-widget-id="' + node.getAttribute('for') + '"]');
3699
3700 if (elem) {
3701 elem.click();
3702 elem.focus();
3703 }
3704 }
3705 },
3706 this.titleref ? E('a', {
3707 'class': 'cbi-title-ref',
3708 'href': this.titleref,
3709 'title': this.titledesc || _('Go to relevant configuration page')
3710 }, this.title) : this.title));
3711
3712 optionEl.appendChild(E('div', { 'class': 'cbi-value-field' }));
3713 }
3714 }
3715
3716 if (nodes)
3717 (optionEl.lastChild || optionEl).appendChild(nodes);
3718
3719 if (!in_table && typeof(this.description) === 'string' && this.description !== '')
3720 dom.append(optionEl.lastChild || optionEl,
3721 E('div', { 'class': 'cbi-value-description' }, this.description.trim()));
3722
3723 if (depend_list && depend_list.length)
3724 optionEl.classList.add('hidden');
3725
3726 optionEl.addEventListener('widget-change',
3727 L.bind(this.map.checkDepends, this.map));
3728
3729 optionEl.addEventListener('widget-change',
3730 L.bind(this.handleValueChange, this, section_id, {}));
3731
3732 dom.bindClassInstance(optionEl, this);
3733
3734 return optionEl;
3735 },
3736
3737 /** @private */
3738 renderWidget: function(section_id, option_index, cfgvalue) {
3739 var value = (cfgvalue != null) ? cfgvalue : this.default,
3740 choices = this.transformChoices(),
3741 widget;
3742
3743 if (choices) {
3744 var placeholder = (this.optional || this.rmempty)
3745 ? E('em', _('unspecified')) : _('-- Please choose --');
3746
3747 widget = new ui.Combobox(Array.isArray(value) ? value.join(' ') : value, choices, {
3748 id: this.cbid(section_id),
3749 sort: this.keylist,
3750 optional: this.optional || this.rmempty,
3751 datatype: this.datatype,
3752 select_placeholder: this.placeholder || placeholder,
3753 validate: L.bind(this.validate, this, section_id),
3754 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3755 });
3756 }
3757 else {
3758 widget = new ui.Textfield(Array.isArray(value) ? value.join(' ') : value, {
3759 id: this.cbid(section_id),
3760 password: this.password,
3761 optional: this.optional || this.rmempty,
3762 datatype: this.datatype,
3763 placeholder: this.placeholder,
3764 validate: L.bind(this.validate, this, section_id),
3765 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3766 });
3767 }
3768
3769 return widget.render();
3770 }
3771 });
3772
3773 /**
3774 * @class DynamicList
3775 * @memberof LuCI.form
3776 * @augments LuCI.form.Value
3777 * @hideconstructor
3778 * @classdesc
3779 *
3780 * The `DynamicList` class represents a multi value widget allowing the user
3781 * to enter multiple unique values, optionally selected from a set of
3782 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3783 *
3784 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3785 * The configuration form this section is added to. It is automatically passed
3786 * by [option()]{@link LuCI.form.AbstractSection#option} or
3787 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3788 * option to the section.
3789 *
3790 * @param {LuCI.form.AbstractSection} section
3791 * The configuration section this option is added to. It is automatically passed
3792 * by [option()]{@link LuCI.form.AbstractSection#option} or
3793 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3794 * option to the section.
3795 *
3796 * @param {string} option
3797 * The name of the UCI option to map.
3798 *
3799 * @param {string} [title]
3800 * The title caption of the option element.
3801 *
3802 * @param {string} [description]
3803 * The description text of the option element.
3804 */
3805 var CBIDynamicList = CBIValue.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3806 __name__: 'CBI.DynamicList',
3807
3808 /** @private */
3809 renderWidget: function(section_id, option_index, cfgvalue) {
3810 var value = (cfgvalue != null) ? cfgvalue : this.default,
3811 choices = this.transformChoices(),
3812 items = L.toArray(value);
3813
3814 var widget = new ui.DynamicList(items, choices, {
3815 id: this.cbid(section_id),
3816 sort: this.keylist,
3817 optional: this.optional || this.rmempty,
3818 datatype: this.datatype,
3819 placeholder: this.placeholder,
3820 validate: L.bind(this.validate, this, section_id),
3821 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3822 });
3823
3824 return widget.render();
3825 },
3826 });
3827
3828 /**
3829 * @class ListValue
3830 * @memberof LuCI.form
3831 * @augments LuCI.form.Value
3832 * @hideconstructor
3833 * @classdesc
3834 *
3835 * The `ListValue` class implements a simple static HTML select element
3836 * allowing the user to choose a single value from a set of predefined choices.
3837 * It builds upon the {@link LuCI.ui.Select} widget.
3838 *
3839 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3840 * The configuration form this section is added to. It is automatically passed
3841 * by [option()]{@link LuCI.form.AbstractSection#option} or
3842 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3843 * option to the section.
3844 *
3845 * @param {LuCI.form.AbstractSection} section
3846 * The configuration section this option is added to. It is automatically passed
3847 * by [option()]{@link LuCI.form.AbstractSection#option} or
3848 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3849 * option to the section.
3850 *
3851 * @param {string} option
3852 * The name of the UCI option to map.
3853 *
3854 * @param {string} [title]
3855 * The title caption of the option element.
3856 *
3857 * @param {string} [description]
3858 * The description text of the option element.
3859 */
3860 var CBIListValue = CBIValue.extend(/** @lends LuCI.form.ListValue.prototype */ {
3861 __name__: 'CBI.ListValue',
3862
3863 __init__: function() {
3864 this.super('__init__', arguments);
3865 this.widget = 'select';
3866 this.orientation = 'horizontal';
3867 this.deplist = [];
3868 },
3869
3870 /**
3871 * Set the size attribute of the underlying HTML select element.
3872 *
3873 * @name LuCI.form.ListValue.prototype#size
3874 * @type number
3875 * @default null
3876 */
3877
3878 /**
3879 * Set the type of the underlying form controls.
3880 *
3881 * May be one of `select` or `radio`. If set to `select`, an HTML
3882 * select element is rendered, otherwise a collection of `radio`
3883 * elements is used.
3884 *
3885 * @name LuCI.form.ListValue.prototype#widget
3886 * @type string
3887 * @default select
3888 */
3889
3890 /**
3891 * Set the orientation of the underlying radio or checkbox elements.
3892 *
3893 * May be one of `horizontal` or `vertical`. Only applies to non-select
3894 * widget types.
3895 *
3896 * @name LuCI.form.ListValue.prototype#orientation
3897 * @type string
3898 * @default horizontal
3899 */
3900
3901 /** @private */
3902 renderWidget: function(section_id, option_index, cfgvalue) {
3903 var choices = this.transformChoices();
3904 var widget = new ui.Select((cfgvalue != null) ? cfgvalue : this.default, choices, {
3905 id: this.cbid(section_id),
3906 size: this.size,
3907 sort: this.keylist,
3908 widget: this.widget,
3909 optional: this.optional,
3910 orientation: this.orientation,
3911 placeholder: this.placeholder,
3912 validate: L.bind(this.validate, this, section_id),
3913 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3914 });
3915
3916 return widget.render();
3917 },
3918 });
3919
3920 /**
3921 * @class FlagValue
3922 * @memberof LuCI.form
3923 * @augments LuCI.form.Value
3924 * @hideconstructor
3925 * @classdesc
3926 *
3927 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3928 * implement a simple checkbox element.
3929 *
3930 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3931 * The configuration form this section is added to. It is automatically passed
3932 * by [option()]{@link LuCI.form.AbstractSection#option} or
3933 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3934 * option to the section.
3935 *
3936 * @param {LuCI.form.AbstractSection} section
3937 * The configuration section this option is added to. It is automatically passed
3938 * by [option()]{@link LuCI.form.AbstractSection#option} or
3939 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3940 * option to the section.
3941 *
3942 * @param {string} option
3943 * The name of the UCI option to map.
3944 *
3945 * @param {string} [title]
3946 * The title caption of the option element.
3947 *
3948 * @param {string} [description]
3949 * The description text of the option element.
3950 */
3951 var CBIFlagValue = CBIValue.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3952 __name__: 'CBI.FlagValue',
3953
3954 __init__: function() {
3955 this.super('__init__', arguments);
3956
3957 this.enabled = '1';
3958 this.disabled = '0';
3959 this.default = this.disabled;
3960 },
3961
3962 /**
3963 * Sets the input value to use for the checkbox checked state.
3964 *
3965 * @name LuCI.form.FlagValue.prototype#enabled
3966 * @type string
3967 * @default 1
3968 */
3969
3970 /**
3971 * Sets the input value to use for the checkbox unchecked state.
3972 *
3973 * @name LuCI.form.FlagValue.prototype#disabled
3974 * @type string
3975 * @default 0
3976 */
3977
3978 /**
3979 * Set a tooltip for the flag option.
3980 *
3981 * If set to a string, it will be used as-is as a tooltip.
3982 *
3983 * If set to a function, the function will be invoked and the return
3984 * value will be shown as a tooltip. If the return value of the function
3985 * is `null` no tooltip will be set.
3986 *
3987 * @name LuCI.form.FlagValue.prototype#tooltip
3988 * @type string|function
3989 * @default null
3990 */
3991
3992 /**
3993 * Set a tooltip icon for the flag option.
3994 *
3995 * If set, this icon will be shown for the default one.
3996 * This could also be a png icon from the resources directory.
3997 *
3998 * @name LuCI.form.FlagValue.prototype#tooltipicon
3999 * @type string
4000 * @default 'ℹ️';
4001 */
4002
4003 /** @private */
4004 renderWidget: function(section_id, option_index, cfgvalue) {
4005 var tooltip = null;
4006
4007 if (typeof(this.tooltip) == 'function')
4008 tooltip = this.tooltip.apply(this, [section_id]);
4009 else if (typeof(this.tooltip) == 'string')
4010 tooltip = (arguments.length > 1) ? ''.format.apply(this.tooltip, this.varargs(arguments, 1)) : this.tooltip;
4011
4012 var widget = new ui.Checkbox((cfgvalue != null) ? cfgvalue : this.default, {
4013 id: this.cbid(section_id),
4014 value_enabled: this.enabled,
4015 value_disabled: this.disabled,
4016 validate: L.bind(this.validate, this, section_id),
4017 tooltip: tooltip,
4018 tooltipicon: this.tooltipicon,
4019 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4020 });
4021
4022 return widget.render();
4023 },
4024
4025 /**
4026 * Query the checked state of the underlying checkbox widget and return
4027 * either the `enabled` or the `disabled` property value, depending on
4028 * the checked state.
4029 *
4030 * @override
4031 */
4032 formvalue: function(section_id) {
4033 var elem = this.getUIElement(section_id),
4034 checked = elem ? elem.isChecked() : false;
4035 return checked ? this.enabled : this.disabled;
4036 },
4037
4038 /**
4039 * Query the checked state of the underlying checkbox widget and return
4040 * either a localized `Yes` or `No` string, depending on the checked state.
4041 *
4042 * @override
4043 */
4044 textvalue: function(section_id) {
4045 var cval = this.cfgvalue(section_id);
4046
4047 if (cval == null)
4048 cval = this.default;
4049
4050 return (cval == this.enabled) ? _('Yes') : _('No');
4051 },
4052
4053 /** @override */
4054 parse: function(section_id) {
4055 if (this.isActive(section_id)) {
4056 var fval = this.formvalue(section_id);
4057
4058 if (!this.isValid(section_id)) {
4059 var title = this.stripTags(this.title).trim();
4060 var error = this.getValidationError(section_id);
4061 return Promise.reject(new TypeError(
4062 _('Option "%s" contains an invalid input value.').format(title || this.option) + ' ' + error));
4063 }
4064
4065 if (fval == this.default && (this.optional || this.rmempty))
4066 return Promise.resolve(this.remove(section_id));
4067 else
4068 return Promise.resolve(this.write(section_id, fval));
4069 }
4070 else if (!this.retain) {
4071 return Promise.resolve(this.remove(section_id));
4072 }
4073 },
4074 });
4075
4076 /**
4077 * @class MultiValue
4078 * @memberof LuCI.form
4079 * @augments LuCI.form.DynamicList
4080 * @hideconstructor
4081 * @classdesc
4082 *
4083 * The `MultiValue` class is a modified variant of the `DynamicList` element
4084 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
4085 * select dropdown element.
4086 *
4087 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4088 * The configuration form this section is added to. It is automatically passed
4089 * by [option()]{@link LuCI.form.AbstractSection#option} or
4090 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4091 * option to the section.
4092 *
4093 * @param {LuCI.form.AbstractSection} section
4094 * The configuration section this option is added to. It is automatically passed
4095 * by [option()]{@link LuCI.form.AbstractSection#option} or
4096 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4097 * option to the section.
4098 *
4099 * @param {string} option
4100 * The name of the UCI option to map.
4101 *
4102 * @param {string} [title]
4103 * The title caption of the option element.
4104 *
4105 * @param {string} [description]
4106 * The description text of the option element.
4107 */
4108 var CBIMultiValue = CBIDynamicList.extend(/** @lends LuCI.form.MultiValue.prototype */ {
4109 __name__: 'CBI.MultiValue',
4110
4111 __init__: function() {
4112 this.super('__init__', arguments);
4113 this.placeholder = _('-- Please choose --');
4114 },
4115
4116 /**
4117 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
4118 * property of the underlying dropdown widget. If omitted, the value of
4119 * the `size` property is used or `3` when `size` is unspecified as well.
4120 *
4121 * @name LuCI.form.MultiValue.prototype#display_size
4122 * @type number
4123 * @default null
4124 */
4125
4126 /**
4127 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
4128 * property of the underlying dropdown widget. If omitted, the value of
4129 * the `size` property is used or `-1` when `size` is unspecified as well.
4130 *
4131 * @name LuCI.form.MultiValue.prototype#dropdown_size
4132 * @type number
4133 * @default null
4134 */
4135
4136 /** @private */
4137 renderWidget: function(section_id, option_index, cfgvalue) {
4138 var value = (cfgvalue != null) ? cfgvalue : this.default,
4139 choices = this.transformChoices();
4140
4141 var widget = new ui.Dropdown(L.toArray(value), choices, {
4142 id: this.cbid(section_id),
4143 sort: this.keylist,
4144 multiple: true,
4145 optional: this.optional || this.rmempty,
4146 select_placeholder: this.placeholder,
4147 display_items: this.display_size || this.size || 3,
4148 dropdown_items: this.dropdown_size || this.size || -1,
4149 validate: L.bind(this.validate, this, section_id),
4150 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4151 });
4152
4153 return widget.render();
4154 },
4155 });
4156
4157 /**
4158 * @class TextValue
4159 * @memberof LuCI.form
4160 * @augments LuCI.form.Value
4161 * @hideconstructor
4162 * @classdesc
4163 *
4164 * The `TextValue` class implements a multi-line textarea input using
4165 * {@link LuCI.ui.Textarea}.
4166 *
4167 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4168 * The configuration form this section is added to. It is automatically passed
4169 * by [option()]{@link LuCI.form.AbstractSection#option} or
4170 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4171 * option to the section.
4172 *
4173 * @param {LuCI.form.AbstractSection} section
4174 * The configuration section this option is added to. It is automatically passed
4175 * by [option()]{@link LuCI.form.AbstractSection#option} or
4176 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4177 * option to the section.
4178 *
4179 * @param {string} option
4180 * The name of the UCI option to map.
4181 *
4182 * @param {string} [title]
4183 * The title caption of the option element.
4184 *
4185 * @param {string} [description]
4186 * The description text of the option element.
4187 */
4188 var CBITextValue = CBIValue.extend(/** @lends LuCI.form.TextValue.prototype */ {
4189 __name__: 'CBI.TextValue',
4190
4191 /** @ignore */
4192 value: null,
4193
4194 /**
4195 * Enforces the use of a monospace font for the textarea contents when set
4196 * to `true`.
4197 *
4198 * @name LuCI.form.TextValue.prototype#monospace
4199 * @type boolean
4200 * @default false
4201 */
4202
4203 /**
4204 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
4205 * property of the underlying textarea widget.
4206 *
4207 * @name LuCI.form.TextValue.prototype#cols
4208 * @type number
4209 * @default null
4210 */
4211
4212 /**
4213 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
4214 * property of the underlying textarea widget.
4215 *
4216 * @name LuCI.form.TextValue.prototype#rows
4217 * @type number
4218 * @default null
4219 */
4220
4221 /**
4222 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
4223 * property of the underlying textarea widget.
4224 *
4225 * @name LuCI.form.TextValue.prototype#wrap
4226 * @type number
4227 * @default null
4228 */
4229
4230 /** @private */
4231 renderWidget: function(section_id, option_index, cfgvalue) {
4232 var value = (cfgvalue != null) ? cfgvalue : this.default;
4233
4234 var widget = new ui.Textarea(value, {
4235 id: this.cbid(section_id),
4236 optional: this.optional || this.rmempty,
4237 placeholder: this.placeholder,
4238 monospace: this.monospace,
4239 cols: this.cols,
4240 rows: this.rows,
4241 wrap: this.wrap,
4242 validate: L.bind(this.validate, this, section_id),
4243 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4244 });
4245
4246 return widget.render();
4247 }
4248 });
4249
4250 /**
4251 * @class DummyValue
4252 * @memberof LuCI.form
4253 * @augments LuCI.form.Value
4254 * @hideconstructor
4255 * @classdesc
4256 *
4257 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4258 * renders the underlying UCI option or default value as readonly text.
4259 *
4260 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4261 * The configuration form this section is added to. It is automatically passed
4262 * by [option()]{@link LuCI.form.AbstractSection#option} or
4263 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4264 * option to the section.
4265 *
4266 * @param {LuCI.form.AbstractSection} section
4267 * The configuration section this option is added to. It is automatically passed
4268 * by [option()]{@link LuCI.form.AbstractSection#option} or
4269 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4270 * option to the section.
4271 *
4272 * @param {string} option
4273 * The name of the UCI option to map.
4274 *
4275 * @param {string} [title]
4276 * The title caption of the option element.
4277 *
4278 * @param {string} [description]
4279 * The description text of the option element.
4280 */
4281 var CBIDummyValue = CBIValue.extend(/** @lends LuCI.form.DummyValue.prototype */ {
4282 __name__: 'CBI.DummyValue',
4283
4284 /**
4285 * Set a URL which is opened when clicking on the dummy value text.
4286 *
4287 * By setting this property, the dummy value text is wrapped in an `<a>`
4288 * element with the property value used as `href` attribute.
4289 *
4290 * @name LuCI.form.DummyValue.prototype#href
4291 * @type string
4292 * @default null
4293 */
4294
4295 /**
4296 * Treat the UCI option value (or the `default` property value) as HTML.
4297 *
4298 * By default, the value text is HTML escaped before being rendered as
4299 * text. In some cases it may be needed to actually interpret and render
4300 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
4301 *
4302 * @name LuCI.form.DummyValue.prototype#rawhtml
4303 * @type boolean
4304 * @default null
4305 */
4306
4307 /**
4308 * Render the UCI option value as hidden using the HTML display: none style property.
4309 *
4310 * By default, the value is displayed
4311 *
4312 * @name LuCI.form.DummyValue.prototype#hidden
4313 * @type boolean
4314 * @default null
4315 */
4316
4317 /** @private */
4318 renderWidget: function(section_id, option_index, cfgvalue) {
4319 var value = (cfgvalue != null) ? cfgvalue : this.default,
4320 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
4321 outputEl = E('div', { 'style': this.hidden ? 'display:none' : null });
4322
4323 if (this.href && !((this.readonly != null) ? this.readonly : this.map.readonly))
4324 outputEl.appendChild(E('a', { 'href': this.href }));
4325
4326 dom.append(outputEl.lastChild || outputEl,
4327 this.rawhtml ? value : [ value ]);
4328
4329 return E([
4330 outputEl,
4331 hiddenEl.render()
4332 ]);
4333 },
4334
4335 /** @override */
4336 remove: function() {},
4337
4338 /** @override */
4339 write: function() {}
4340 });
4341
4342 /**
4343 * @class ButtonValue
4344 * @memberof LuCI.form
4345 * @augments LuCI.form.Value
4346 * @hideconstructor
4347 * @classdesc
4348 *
4349 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4350 * renders the underlying UCI option or default value as readonly text.
4351 *
4352 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4353 * The configuration form this section is added to. It is automatically passed
4354 * by [option()]{@link LuCI.form.AbstractSection#option} or
4355 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4356 * option to the section.
4357 *
4358 * @param {LuCI.form.AbstractSection} section
4359 * The configuration section this option is added to. It is automatically passed
4360 * by [option()]{@link LuCI.form.AbstractSection#option} or
4361 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4362 * option to the section.
4363 *
4364 * @param {string} option
4365 * The name of the UCI option to map.
4366 *
4367 * @param {string} [title]
4368 * The title caption of the option element.
4369 *
4370 * @param {string} [description]
4371 * The description text of the option element.
4372 */
4373 var CBIButtonValue = CBIValue.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
4374 __name__: 'CBI.ButtonValue',
4375
4376 /**
4377 * Override the rendered button caption.
4378 *
4379 * By default, the option title - which is passed as fourth argument to the
4380 * constructor - is used as caption for the button element. When setting
4381 * this property to a string, it is used as `String.format()` pattern with
4382 * the underlying UCI section name passed as first format argument. When
4383 * set to a function, it is invoked passing the section ID as sole argument
4384 * and the resulting return value is converted to a string before being
4385 * used as button caption.
4386 *
4387 * The default is `null`, means the option title is used as caption.
4388 *
4389 * @name LuCI.form.ButtonValue.prototype#inputtitle
4390 * @type string|function
4391 * @default null
4392 */
4393
4394 /**
4395 * Override the button style class.
4396 *
4397 * By setting this property, a specific `cbi-button-*` CSS class can be
4398 * selected to influence the style of the resulting button.
4399 *
4400 * Suitable values which are implemented by most themes are `positive`,
4401 * `negative` and `primary`.
4402 *
4403 * The default is `null`, means a neutral button styling is used.
4404 *
4405 * @name LuCI.form.ButtonValue.prototype#inputstyle
4406 * @type string
4407 * @default null
4408 */
4409
4410 /**
4411 * Override the button click action.
4412 *
4413 * By default, the underlying UCI option (or default property) value is
4414 * copied into a hidden field tied to the button element and the save
4415 * action is triggered on the parent form element.
4416 *
4417 * When this property is set to a function, it is invoked instead of
4418 * performing the default actions. The handler function will receive the
4419 * DOM click element as first and the underlying configuration section ID
4420 * as second argument.
4421 *
4422 * @name LuCI.form.ButtonValue.prototype#onclick
4423 * @type function
4424 * @default null
4425 */
4426
4427 /** @private */
4428 renderWidget: function(section_id, option_index, cfgvalue) {
4429 var value = (cfgvalue != null) ? cfgvalue : this.default,
4430 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
4431 outputEl = E('div'),
4432 btn_title = this.titleFn('inputtitle', section_id) || this.titleFn('title', section_id);
4433
4434 if (value !== false)
4435 dom.content(outputEl, [
4436 E('button', {
4437 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle || 'button'),
4438 'click': ui.createHandlerFn(this, function(section_id, ev) {
4439 if (this.onclick)
4440 return this.onclick(ev, section_id);
4441
4442 ev.currentTarget.parentNode.nextElementSibling.value = value;
4443 return this.map.save();
4444 }, section_id),
4445 'disabled': ((this.readonly != null) ? this.readonly : this.map.readonly) || null
4446 }, [ btn_title ])
4447 ]);
4448 else
4449 dom.content(outputEl, ' - ');
4450
4451 return E([
4452 outputEl,
4453 hiddenEl.render()
4454 ]);
4455 }
4456 });
4457
4458 /**
4459 * @class HiddenValue
4460 * @memberof LuCI.form
4461 * @augments LuCI.form.Value
4462 * @hideconstructor
4463 * @classdesc
4464 *
4465 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
4466 *
4467 * Hidden value widgets used to be necessary in legacy code which actually
4468 * submitted the underlying HTML form the server. With client side handling of
4469 * forms, there are more efficient ways to store hidden state data.
4470 *
4471 * Since this widget has no visible content, the title and description values
4472 * of this form element should be set to `null` as well to avoid a broken or
4473 * distorted form layout when rendering the option element.
4474 *
4475 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4476 * The configuration form this section is added to. It is automatically passed
4477 * by [option()]{@link LuCI.form.AbstractSection#option} or
4478 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4479 * option to the section.
4480 *
4481 * @param {LuCI.form.AbstractSection} section
4482 * The configuration section this option is added to. It is automatically passed
4483 * by [option()]{@link LuCI.form.AbstractSection#option} or
4484 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4485 * option to the section.
4486 *
4487 * @param {string} option
4488 * The name of the UCI option to map.
4489 *
4490 * @param {string} [title]
4491 * The title caption of the option element.
4492 *
4493 * @param {string} [description]
4494 * The description text of the option element.
4495 */
4496 var CBIHiddenValue = CBIValue.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
4497 __name__: 'CBI.HiddenValue',
4498
4499 /** @private */
4500 renderWidget: function(section_id, option_index, cfgvalue) {
4501 var widget = new ui.Hiddenfield((cfgvalue != null) ? cfgvalue : this.default, {
4502 id: this.cbid(section_id)
4503 });
4504
4505 return widget.render();
4506 }
4507 });
4508
4509 /**
4510 * @class FileUpload
4511 * @memberof LuCI.form
4512 * @augments LuCI.form.Value
4513 * @hideconstructor
4514 * @classdesc
4515 *
4516 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
4517 * offers the ability to browse, upload and select remote files.
4518 *
4519 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4520 * The configuration form this section is added to. It is automatically passed
4521 * by [option()]{@link LuCI.form.AbstractSection#option} or
4522 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4523 * option to the section.
4524 *
4525 * @param {LuCI.form.AbstractSection} section
4526 * The configuration section this option is added to. It is automatically passed
4527 * by [option()]{@link LuCI.form.AbstractSection#option} or
4528 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4529 * option to the section.
4530 *
4531 * @param {string} option
4532 * The name of the UCI option to map.
4533 *
4534 * @param {string} [title]
4535 * The title caption of the option element.
4536 *
4537 * @param {string} [description]
4538 * The description text of the option element.
4539 */
4540 var CBIFileUpload = CBIValue.extend(/** @lends LuCI.form.FileUpload.prototype */ {
4541 __name__: 'CBI.FileSelect',
4542
4543 __init__: function(/* ... */) {
4544 this.super('__init__', arguments);
4545
4546 this.show_hidden = false;
4547 this.enable_upload = true;
4548 this.enable_remove = true;
4549 this.root_directory = '/etc/luci-uploads';
4550 },
4551
4552 /**
4553 * Toggle display of hidden files.
4554 *
4555 * Display hidden files when rendering the remote directory listing.
4556 * Note that this is merely a cosmetic feature, hidden files are always
4557 * included in received remote file listings.
4558 *
4559 * The default is `false`, means hidden files are not displayed.
4560 *
4561 * @name LuCI.form.FileUpload.prototype#show_hidden
4562 * @type boolean
4563 * @default false
4564 */
4565
4566 /**
4567 * Toggle file upload functionality.
4568 *
4569 * When set to `true`, the underlying widget provides a button which lets
4570 * the user select and upload local files to the remote system.
4571 * Note that this is merely a cosmetic feature, remote upload access is
4572 * controlled by the session ACL rules.
4573 *
4574 * The default is `true`, means file upload functionality is displayed.
4575 *
4576 * @name LuCI.form.FileUpload.prototype#enable_upload
4577 * @type boolean
4578 * @default true
4579 */
4580
4581 /**
4582 * Toggle remote file delete functionality.
4583 *
4584 * When set to `true`, the underlying widget provides a buttons which let
4585 * the user delete files from remote directories. Note that this is merely
4586 * a cosmetic feature, remote delete permissions are controlled by the
4587 * session ACL rules.
4588 *
4589 * The default is `true`, means file removal buttons are displayed.
4590 *
4591 * @name LuCI.form.FileUpload.prototype#enable_remove
4592 * @type boolean
4593 * @default true
4594 */
4595
4596 /**
4597 * Specify the root directory for file browsing.
4598 *
4599 * This property defines the topmost directory the file browser widget may
4600 * navigate to, the UI will not allow browsing directories outside this
4601 * prefix. Note that this is merely a cosmetic feature, remote file access
4602 * and directory listing permissions are controlled by the session ACL
4603 * rules.
4604 *
4605 * The default is `/etc/luci-uploads`.
4606 *
4607 * @name LuCI.form.FileUpload.prototype#root_directory
4608 * @type string
4609 * @default /etc/luci-uploads
4610 */
4611
4612 /** @private */
4613 renderWidget: function(section_id, option_index, cfgvalue) {
4614 var browserEl = new ui.FileUpload((cfgvalue != null) ? cfgvalue : this.default, {
4615 id: this.cbid(section_id),
4616 name: this.cbid(section_id),
4617 show_hidden: this.show_hidden,
4618 enable_upload: this.enable_upload,
4619 enable_remove: this.enable_remove,
4620 root_directory: this.root_directory,
4621 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4622 });
4623
4624 return browserEl.render();
4625 }
4626 });
4627
4628 /**
4629 * @class SectionValue
4630 * @memberof LuCI.form
4631 * @augments LuCI.form.Value
4632 * @hideconstructor
4633 * @classdesc
4634 *
4635 * The `SectionValue` widget embeds a form section element within an option
4636 * element container, allowing to nest form sections into other sections.
4637 *
4638 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4639 * The configuration form this section is added to. It is automatically passed
4640 * by [option()]{@link LuCI.form.AbstractSection#option} or
4641 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4642 * option to the section.
4643 *
4644 * @param {LuCI.form.AbstractSection} section
4645 * The configuration section this option is added to. It is automatically passed
4646 * by [option()]{@link LuCI.form.AbstractSection#option} or
4647 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4648 * option to the section.
4649 *
4650 * @param {string} option
4651 * The internal name of the option element holding the section. Since a section
4652 * container element does not read or write any configuration itself, the name
4653 * is only used internally and does not need to relate to any underlying UCI
4654 * option name.
4655 *
4656 * @param {LuCI.form.AbstractSection} subsection_class
4657 * The class to use for instantiating the nested section element. Note that
4658 * the class value itself is expected here, not a class instance obtained by
4659 * calling `new`. The given class argument must be a subclass of the
4660 * `AbstractSection` class.
4661 *
4662 * @param {...*} [class_args]
4663 * All further arguments are passed as-is to the subclass constructor. Refer
4664 * to the corresponding class constructor documentations for details.
4665 */
4666 var CBISectionValue = CBIValue.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4667 __name__: 'CBI.ContainerValue',
4668 __init__: function(map, section, option, cbiClass /*, ... */) {
4669 this.super('__init__', [map, section, option]);
4670
4671 if (!CBIAbstractSection.isSubclass(cbiClass))
4672 throw 'Sub section must be a descendent of CBIAbstractSection';
4673
4674 this.subsection = cbiClass.instantiate(this.varargs(arguments, 4, this.map));
4675 this.subsection.parentoption = this;
4676 },
4677
4678 /**
4679 * Access the embedded section instance.
4680 *
4681 * This property holds a reference to the instantiated nested section.
4682 *
4683 * @name LuCI.form.SectionValue.prototype#subsection
4684 * @type LuCI.form.AbstractSection
4685 * @readonly
4686 */
4687
4688 /** @override */
4689 load: function(section_id) {
4690 return this.subsection.load(section_id);
4691 },
4692
4693 /** @override */
4694 parse: function(section_id) {
4695 return this.subsection.parse(section_id);
4696 },
4697
4698 /** @private */
4699 renderWidget: function(section_id, option_index, cfgvalue) {
4700 return this.subsection.render(section_id);
4701 },
4702
4703 /** @private */
4704 checkDepends: function(section_id) {
4705 this.subsection.checkDepends(section_id);
4706 return CBIValue.prototype.checkDepends.apply(this, [ section_id ]);
4707 },
4708
4709 /**
4710 * Since the section container is not rendering an own widget,
4711 * its `value()` implementation is a no-op.
4712 *
4713 * @override
4714 */
4715 value: function() {},
4716
4717 /**
4718 * Since the section container is not tied to any UCI configuration,
4719 * its `write()` implementation is a no-op.
4720 *
4721 * @override
4722 */
4723 write: function() {},
4724
4725 /**
4726 * Since the section container is not tied to any UCI configuration,
4727 * its `remove()` implementation is a no-op.
4728 *
4729 * @override
4730 */
4731 remove: function() {},
4732
4733 /**
4734 * Since the section container is not tied to any UCI configuration,
4735 * its `cfgvalue()` implementation will always return `null`.
4736 *
4737 * @override
4738 * @returns {null}
4739 */
4740 cfgvalue: function() { return null },
4741
4742 /**
4743 * Since the section container is not tied to any UCI configuration,
4744 * its `formvalue()` implementation will always return `null`.
4745 *
4746 * @override
4747 * @returns {null}
4748 */
4749 formvalue: function() { return null }
4750 });
4751
4752 /**
4753 * @class form
4754 * @memberof LuCI
4755 * @hideconstructor
4756 * @classdesc
4757 *
4758 * The LuCI form class provides high level abstractions for creating
4759 * UCI- or JSON backed configurations forms.
4760 *
4761 * To import the class in views, use `'require form'`, to import it in
4762 * external JavaScript, use `L.require("form").then(...)`.
4763 *
4764 * A typical form is created by first constructing a
4765 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4766 * by subsequently adding sections and options to it. Finally
4767 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4768 * assemble the HTML markup and insert it into the DOM.
4769 *
4770 * Example:
4771 *
4772 * <pre>
4773 * 'use strict';
4774 * 'require form';
4775 *
4776 * var m, s, o;
4777 *
4778 * m = new form.Map('example', 'Example form',
4779 * 'This is an example form mapping the contents of /etc/config/example');
4780 *
4781 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4782 * 'This sections maps "config example first_section" of /etc/config/example');
4783 *
4784 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4785 *
4786 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4787 * o.value('choice1', 'The first choice');
4788 * o.value('choice2', 'The second choice');
4789 *
4790 * m.render().then(function(node) {
4791 * document.body.appendChild(node);
4792 * });
4793 * </pre>
4794 */
4795 return baseclass.extend(/** @lends LuCI.form.prototype */ {
4796 Map: CBIMap,
4797 JSONMap: CBIJSONMap,
4798 AbstractSection: CBIAbstractSection,
4799 AbstractValue: CBIAbstractValue,
4800
4801 TypedSection: CBITypedSection,
4802 TableSection: CBITableSection,
4803 GridSection: CBIGridSection,
4804 NamedSection: CBINamedSection,
4805
4806 Value: CBIValue,
4807 DynamicList: CBIDynamicList,
4808 ListValue: CBIListValue,
4809 Flag: CBIFlagValue,
4810 MultiValue: CBIMultiValue,
4811 TextValue: CBITextValue,
4812 DummyValue: CBIDummyValue,
4813 Button: CBIButtonValue,
4814 HiddenValue: CBIHiddenValue,
4815 FileUpload: CBIFileUpload,
4816 SectionValue: CBISectionValue
4817 });