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