10 var callSessionAccess
= rpc
.declare({
13 params
: [ 'scope', 'object', 'function' ],
14 expect
: { 'access': false }
17 var CBIJSONConfig
= baseclass
.extend({
18 __init__: function(data
) {
19 data
= Object
.assign({}, data
);
26 for (var sectiontype
in data
) {
27 if (!data
.hasOwnProperty(sectiontype
))
30 if (L
.isObject(data
[sectiontype
])) {
31 this.data
[sectiontype
] = Object
.assign(data
[sectiontype
], {
37 section_ids
.push(sectiontype
);
40 else if (Array
.isArray(data
[sectiontype
])) {
41 for (var i
= 0, index
= 0; i
< data
[sectiontype
].length
; i
++) {
42 var item
= data
[sectiontype
][i
],
45 if (!L
.isObject(item
))
48 if (typeof(item
['.name']) == 'string') {
53 name
= sectiontype
+ num_sections
;
57 if (!this.data
.hasOwnProperty(name
))
58 section_ids
.push(name
);
60 this.data
[name
] = Object
.assign(item
, {
61 '.index': num_sections
++,
62 '.anonymous': anonymous
,
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;
75 return (indexA
- indexB
);
80 for (var i
= 0; i
< section_ids
.length
; i
++)
81 this.data
[section_ids
[i
]]['.index'] = i
;
85 return Promise
.resolve(this.data
);
89 return Promise
.resolve();
92 get: function(config
, section
, option
) {
97 return this.data
[section
];
99 if (!this.data
.hasOwnProperty(section
))
102 var value
= this.data
[section
][option
];
104 if (Array
.isArray(value
))
108 return String(value
);
113 set: function(config
, section
, option
, value
) {
114 if (section
== null || option
== null || option
.charAt(0) == '.')
117 if (!this.data
.hasOwnProperty(section
))
121 delete this.data
[section
][option
];
122 else if (Array
.isArray(value
))
123 this.data
[section
][option
] = value
;
125 this.data
[section
][option
] = String(value
);
128 unset: function(config
, section
, option
) {
129 return this.set(config
, section
, option
, null);
132 sections: function(config
, sectiontype
, callback
) {
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
]);
139 rv
.sort(function(a
, b
) { return a
['.index'] - b
['.index'] });
141 if (typeof(callback
) == 'function')
142 for (var i
= 0; i
< rv
.length
; i
++)
143 callback
.call(this, rv
[i
], rv
[i
]['.name']);
148 add: function(config
, sectiontype
, sectionname
) {
149 var num_sections_type
= 0, next_index
= 0;
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']);
156 var section_id
= sectionname
|| sectiontype
+ num_sections_type
;
158 if (!this.data
.hasOwnProperty(section_id
)) {
159 this.data
[section_id
] = {
161 '.type': sectiontype
,
162 '.anonymous': (sectionname
== null),
163 '.index': next_index
+ 1
170 remove: function(config
, section
) {
171 if (this.data
.hasOwnProperty(section
))
172 delete this.data
[section
];
175 resolveSID: function(config
, section_id
) {
179 move: function(config
, section_id1
, section_id2
, after
) {
180 return uci
.move.apply(this, [config
, section_id1
, section_id2
, after
]);
185 * @class AbstractElement
186 * @memberof LuCI.form
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
195 * This class is private and not directly accessible by user code.
197 var CBIAbstractElement
= baseclass
.extend(/** @lends LuCI.form.AbstractElement.prototype */ {
198 __init__: function(title
, description
) {
199 this.title
= title
|| '';
200 this.description
= description
|| '';
205 * Add another form element as children to this element.
207 * @param {AbstractElement} element
208 * The form element to add.
210 append: function(obj
) {
211 this.children
.push(obj
);
215 * Parse this elements form input.
217 * The `parse()` function recursively walks the form element tree and
218 * triggers input value reading and validation for each encountered element.
220 * Elements which are hidden due to unsatisified dependencies are skipped.
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.
229 var args
= arguments
;
230 this.children
.forEach(function(child
) {
231 child
.parse
.apply(child
, args
);
236 * Render the form element.
238 * The `render()` function recursively walks the form element tree and
239 * renders the markup for each element, returning the assembled DOM tree.
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.
247 L
.error('InternalError', 'Not implemented');
251 loadChildren: function(/* ... */) {
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
));
259 return Promise
.all(tasks
);
263 renderChildren: function(tab_name
/*, ... */) {
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
++)));
274 return Promise
.all(tasks
);
278 * Strip any HTML tags from the given input string.
280 * @param {string} input
281 * The input string to clean.
284 * The cleaned input string with HTML removes removed.
286 stripTags: function(s
) {
287 if (typeof(s
) == 'string' && !s
.match(/[<>]/))
290 var x
= E('div', {}, s
);
291 return x
.textContent
|| x
.innerText
|| '';
295 * Format the given named property as title string.
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.
301 * If the property value is a string, it is passed to `String.format()`
302 * along with any additional parameters passed to `titleFn()`.
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.
308 * In all other cases, `null` is returned.
310 * @param {string} property
311 * The name of the element property to use.
313 * @param {...*} fmt_args
314 * Extra values to format the title string with.
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.
320 titleFn: function(attr
/*, ... */) {
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
];
329 s
= this.stripTags(String(s
)).trim();
331 if (s
== null || s
== '')
340 * @memberof LuCI.form
341 * @augments LuCI.form.AbstractElement
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
349 * It serves as main entry point into the `LuCI.form` for typical view code.
351 * @param {string} config
352 * The UCI configuration to map. It is automatically loaded along when the
353 * resulting map instance.
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.
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.
365 var CBIMap
= CBIAbstractElement
.extend(/** @lends LuCI.form.Map.prototype */ {
366 __init__: function(config
/*, ... */) {
367 this.super('__init__', this.varargs(arguments
, 1));
369 this.config
= config
;
370 this.parsechain
= [ config
];
375 * Toggle readonly state of the form.
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.
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.
384 * @name LuCI.form.Map.prototype#readonly
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()`.
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.
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.
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.
407 * @param {string} [attrvalue]
408 * In case the function is invoked with two parameters, this argument
409 * specifies the attribute value to match.
411 * @throws {InternalError}
412 * Throws an `InternalError` if more than two function parameters are
415 * @returns {NodeList}
416 * Returns a (possibly empty) DOM `NodeList` containing the found DOM nodes.
418 findElements: function(/* ... */) {
421 if (arguments
.length
== 1)
423 else if (arguments
.length
== 2)
424 q
= '[%s="%s"]'.format(arguments
[0], arguments
[1]);
426 L
.error('InternalError', 'Expecting one or two arguments to findElements()');
428 return this.root
.querySelectorAll(q
);
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.
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.
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.
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.
450 * @param {string} [attrvalue]
451 * In case the function is invoked with two parameters, this argument
452 * specifies the attribute value to match.
454 * @throws {InternalError}
455 * Throws an `InternalError` if more than two function parameters are
458 * @returns {Node|null}
459 * Returns the first found DOM node or `null` if no element matched.
461 findElement: function(/* ... */) {
462 var res
= this.findElements
.apply(this, arguments
);
463 return res
.length
? res
[0] : null;
467 * Tie another UCI configuration to the map.
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
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.
479 chain: function(config
) {
480 if (this.parsechain
.indexOf(config
) == -1)
481 this.parsechain
.push(config
);
485 * Add a configuration section to the map.
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
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.
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`.
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.
508 * @returns {LuCI.form.AbstractSection}
509 * Returns the instantiated section class instance.
511 section: function(cbiClass
/*, ... */) {
512 if (!CBIAbstractSection
.isSubclass(cbiClass
))
513 L
.error('TypeError', 'Class must be a descendent of CBIAbstractSection');
515 var obj
= cbiClass
.instantiate(this.varargs(arguments
, 1, this));
521 * Load the configuration covered by this map.
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.
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
534 var doCheckACL
= (!(this instanceof CBIJSONMap
) && this.readonly
== null),
535 loadTasks
= [ doCheckACL
? callSessionAccess('uci', this.config
, 'write') : true ],
536 configs
= this.parsechain
|| [ this.config
];
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
);
542 return Promise
.all(loadTasks
).then(L
.bind(function(res
) {
543 if (res
[0] === false)
544 this.readonly
= true;
546 return this.loadChildren();
551 * Parse the form input values.
553 * The `parse()` function recursively walks the form element tree and
554 * triggers input value reading and validation for each child element.
556 * Elements which are hidden due to unsatisified dependencies are skipped.
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.
566 if (Array
.isArray(this.children
))
567 for (var i
= 0; i
< this.children
.length
; i
++)
568 tasks
.push(this.children
[i
].parse());
570 return Promise
.all(tasks
);
574 * Save the form input values.
576 * This function parses the current form, saves the resulting UCI changes,
577 * reloads the UCI configuration data and redraws the form elements.
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.
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.
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
593 save: function(cb
, silent
) {
598 .then(this.data
.save
.bind(this.data
))
599 .then(this.load
.bind(this))
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', { 'click': ui
.hideModal
}, [ _('Dismiss') ])
611 return Promise
.reject(e
);
612 }).then(this.renderContents
.bind(this));
616 * Reset the form by re-rendering its contents. This will revert all
617 * unsaved user inputs to their initial form state.
619 * @returns {Promise<Node>}
620 * Returns a promise resolving to the toplevel form DOM node once the
621 * re-rendering is complete.
624 return this.renderContents();
628 * Render the form markup.
630 * @returns {Promise<Node>}
631 * Returns a promise resolving to the toplevel form DOM node once the
632 * rendering is complete.
635 return this.load().then(this.renderContents
.bind(this));
639 renderContents: function() {
640 var mapEl
= this.root
|| (this.root
= E('div', {
641 'id': 'cbi-%s'.format(this.config
),
643 'cbi-dependency-check': L
.bind(this.checkDepends
, this)
646 dom
.bindClassInstance(mapEl
, this);
648 return this.renderChildren(null).then(L
.bind(function(nodes
) {
649 var initialRender
= !mapEl
.firstChild
;
651 dom
.content(mapEl
, null);
653 if (this.title
!= null && this.title
!= '')
654 mapEl
.appendChild(E('h2', { 'name': 'content' }, this.title
));
656 if (this.description
!= null && this.description
!= '')
657 mapEl
.appendChild(E('div', { 'class': 'cbi-map-descr' }, this.description
));
660 dom
.append(mapEl
, E('div', { 'class': 'cbi-map-tabbed' }, nodes
));
662 dom
.append(mapEl
, nodes
);
664 if (!initialRender
) {
665 mapEl
.classList
.remove('flash');
667 window
.setTimeout(function() {
668 mapEl
.classList
.add('flash');
674 var tabGroups
= mapEl
.querySelectorAll('.cbi-map-tabbed, .cbi-section-node-tabbed');
676 for (var i
= 0; i
< tabGroups
.length
; i
++)
677 ui
.tabs
.initTabGroup(tabGroups
[i
].childNodes
);
684 * Find a form option element instance.
686 * @param {string} name_or_id
687 * The name or the full ID of the option element to look up.
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.
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.
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.
702 lookupOption: function(name
, section_id
, config_name
) {
703 var id
, elem
, sid
, inst
;
705 if (name
.indexOf('.') > -1)
706 id
= 'cbid.%s'.format(name
);
708 id
= 'cbid.%s.%s.%s'.format(config_name
|| this.config
, section_id
, name
);
710 elem
= this.findElement('data-field', id
);
711 sid
= elem
? id
.split(/\./)[2] : null;
712 inst
= elem
? dom
.findClassInstance(elem
) : null;
714 return (inst
instanceof CBIAbstractValue
) ? [ inst
, sid
] : null;
718 checkDepends: function(ev
, n
) {
721 for (var i
= 0, s
= this.children
[0]; (s
= this.children
[i
]) != null; i
++)
722 if (s
.checkDepends(ev
, n
))
725 if (changed
&& (n
|| 0) < 10)
726 this.checkDepends(ev
, (n
|| 10) + 1);
728 ui
.tabs
.updateTabs(ev
, this.root
);
732 isDependencySatisfied: function(depends
, config_name
, section_id
) {
735 if (!Array
.isArray(depends
) || !depends
.length
)
738 for (var i
= 0; i
< depends
.length
; i
++) {
740 reverse
= depends
[i
]['!reverse'],
741 contains
= depends
[i
]['!contains'];
743 for (var dep
in depends
[i
]) {
744 if (dep
== '!reverse' || dep
== '!contains') {
747 else if (dep
== '!default') {
752 var res
= this.lookupOption(dep
, section_id
, config_name
),
753 val
= (res
&& res
[0].isActive(res
[1])) ? res
[0].formvalue(res
[1]) : null;
756 ? isContained(val
, depends
[i
][dep
])
757 : isEqual(val
, depends
[i
][dep
]);
759 istat
= (istat
&& equal
);
772 * @constructor JSONMap
773 * @memberof LuCI.form
774 * @augments LuCI.form.Map
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
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
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.
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.
798 var CBIJSONMap
= CBIMap
.extend(/** @lends LuCI.form.JSONMap.prototype */ {
799 __init__: function(data
/*, ... */) {
800 this.super('__init__', this.varargs(arguments
, 1, 'json'));
802 this.config
= 'json';
803 this.parsechain
= [ 'json' ];
804 this.data
= new CBIJSONConfig(data
);
809 * @class AbstractSection
810 * @memberof LuCI.form
811 * @augments LuCI.form.AbstractElement
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.
820 * This class is private and not directly accessible by user code.
822 var CBIAbstractSection
= CBIAbstractElement
.extend(/** @lends LuCI.form.AbstractSection.prototype */ {
823 __init__: function(map
, sectionType
/*, ... */) {
824 this.super('__init__', this.varargs(arguments
, 2));
826 this.sectiontype
= sectionType
;
828 this.config
= map
.config
;
830 this.optional
= true;
831 this.addremove
= false;
832 this.dynamic
= false;
836 * Access the parent option container instance.
838 * In case this section is nested within an option element container,
839 * this property will hold a reference to the parent option instance.
841 * If this section is not nested, the property is `null`.
843 * @name LuCI.form.AbstractSection.prototype#parentoption
844 * @type LuCI.form.AbstractValue
849 * Enumerate the UCI section IDs covered by this form section element.
852 * @throws {InternalError}
853 * Throws an `InternalError` exception if the function is not implemented.
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.
859 cfgsections: function() {
860 L
.error('InternalError', 'Not implemented');
864 * Filter UCI section IDs to render.
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.
870 * The default implementation always returns `true`. User code or
871 * classes extending `AbstractSection` may overwrite this function with
872 * custom implementations.
875 * @param {string} section_id
876 * The UCI section ID to test.
879 * Returns `true` when the given UCI section ID should be handled and
880 * `false` when it should be ignored.
882 filter: function(section_id
) {
887 * Load the configuration covered by this section.
889 * The `load()` function recursively walks the section element tree and
890 * invokes the load function of each child option element.
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.
898 var section_ids
= this.cfgsections(),
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
])));
909 return Promise
.all(tasks
);
913 * Parse this sections form input.
915 * The `parse()` function recursively walks the section element tree and
916 * triggers input value reading and validation for each encountered child
919 * Options which are hidden due to unsatisified dependencies are skipped.
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.
927 var section_ids
= this.cfgsections(),
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
]));
935 return Promise
.all(tasks
);
939 * Add an option tab to the section.
941 * The child option elements of a section may be divided into multiple
942 * tabs to provide a better overview to the user.
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.
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
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.
956 * @param {string} title
957 * The human readable caption of the tab.
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.
965 * Throws an exeption if a tab with the same `name` already exists.
967 tab: function(name
, title
, description
) {
968 if (this.tabs
&& this.tabs
[name
])
969 throw 'Tab already declared';
974 description
: description
,
978 this.tabs
= this.tabs
|| [];
979 this.tabs
.push(entry
);
980 this.tabs
[name
] = entry
;
982 this.tab_names
= this.tab_names
|| [];
983 this.tab_names
.push(name
);
987 * Add a configuration option widget to the section.
989 * Note that [taboption()]{@link LuCI.form.AbstractSection#taboption}
990 * should be used instead if this form section element uses tabs.
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}.
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.
1003 * @throws {TypeError}
1004 * Throws a `TypeError` exception in case the passed class value is not a
1005 * descendent of `AbstractValue`.
1007 * @returns {LuCI.form.AbstractValue}
1008 * Returns the instantiated option class instance.
1010 option: function(cbiClass
/*, ... */) {
1011 if (!CBIAbstractValue
.isSubclass(cbiClass
))
1012 throw L
.error('TypeError', 'Class must be a descendent of CBIAbstractValue');
1014 var obj
= cbiClass
.instantiate(this.varargs(arguments
, 1, this.map
, this));
1020 * Add a configuration option widget to a tab of the section.
1022 * @param {string} tabname
1023 * The name of the section tab to add the option element to.
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}.
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.
1036 * @throws {ReferenceError}
1037 * Throws a `ReferenceError` exception when the given tab name does not
1040 * @throws {TypeError}
1041 * Throws a `TypeError` exception in case the passed class value is not a
1042 * descendent of `AbstractValue`.
1044 * @returns {LuCI.form.AbstractValue}
1045 * Returns the instantiated option class instance.
1047 taboption: function(tabName
/*, ... */) {
1048 if (!this.tabs
|| !this.tabs
[tabName
])
1049 throw L
.error('ReferenceError', 'Associated tab not declared');
1051 var obj
= this.option
.apply(this, this.varargs(arguments
, 1));
1053 this.tabs
[tabName
].children
.push(obj
);
1058 renderUCISection: function(section_id
) {
1059 var renderTasks
= [];
1062 return this.renderOptions(null, section_id
);
1064 for (var i
= 0; i
< this.tab_names
.length
; i
++)
1065 renderTasks
.push(this.renderOptions(this.tab_names
[i
], section_id
));
1067 return Promise
.all(renderTasks
)
1068 .then(this.renderTabContainers
.bind(this, section_id
));
1072 renderTabContainers: function(section_id
, nodes
) {
1073 var config_name
= this.uciconfig
|| this.map
.config
,
1074 containerEls
= E([]);
1076 for (var i
= 0; i
< nodes
.length
; i
++) {
1077 var tab_name
= this.tab_names
[i
],
1078 tab_data
= this.tabs
[tab_name
],
1079 containerEl
= E('div', {
1080 'id': 'container.%s.%s.%s'.format(config_name
, section_id
, tab_name
),
1081 'data-tab': tab_name
,
1082 'data-tab-title': tab_data
.title
,
1083 'data-tab-active': tab_name
=== this.selected_tab
1086 if (tab_data
.description
!= null && tab_data
.description
!= '')
1087 containerEl
.appendChild(
1088 E('div', { 'class': 'cbi-tab-descr' }, tab_data
.description
));
1090 containerEl
.appendChild(nodes
[i
]);
1091 containerEls
.appendChild(containerEl
);
1094 return containerEls
;
1098 renderOptions: function(tab_name
, section_id
) {
1099 var in_table
= (this instanceof CBITableSection
);
1100 return this.renderChildren(tab_name
, section_id
, in_table
).then(function(nodes
) {
1101 var optionEls
= E([]);
1102 for (var i
= 0; i
< nodes
.length
; i
++)
1103 optionEls
.appendChild(nodes
[i
]);
1109 checkDepends: function(ev
, n
) {
1110 var changed
= false,
1111 sids
= this.cfgsections();
1113 for (var i
= 0, sid
= sids
[0]; (sid
= sids
[i
]) != null; i
++) {
1114 for (var j
= 0, o
= this.children
[0]; (o
= this.children
[j
]) != null; j
++) {
1115 var isActive
= o
.isActive(sid
),
1116 isSatisified
= o
.checkDepends(sid
);
1118 if (isActive
!= isSatisified
) {
1119 o
.setActive(sid
, !isActive
);
1120 isActive
= !isActive
;
1125 o
.triggerValidation(sid
);
1134 var isEqual = function(x
, y
) {
1135 if (x
!= null && y
!= null && typeof(x
) != typeof(y
))
1138 if ((x
== null && y
!= null) || (x
!= null && y
== null))
1141 if (Array
.isArray(x
)) {
1142 if (x
.length
!= y
.length
)
1145 for (var i
= 0; i
< x
.length
; i
++)
1146 if (!isEqual(x
[i
], y
[i
]))
1149 else if (typeof(x
) == 'object') {
1151 if (x
.hasOwnProperty(k
) && !y
.hasOwnProperty(k
))
1154 if (!isEqual(x
[k
], y
[k
]))
1159 if (y
.hasOwnProperty(k
) && !x
.hasOwnProperty(k
))
1169 var isContained = function(x
, y
) {
1170 if (Array
.isArray(x
)) {
1171 for (var i
= 0; i
< x
.length
; i
++)
1175 else if (L
.isObject(x
)) {
1176 if (x
.hasOwnProperty(y
) && x
[y
] != null)
1179 else if (typeof(x
) == 'string') {
1180 return (x
.indexOf(y
) > -1);
1187 * @class AbstractValue
1188 * @memberof LuCI.form
1189 * @augments LuCI.form.AbstractElement
1193 * The `AbstractValue` class serves as abstract base for the different form
1194 * option styles implemented by `LuCI.form`. It provides the common logic for
1195 * handling option input values, for dependencies among options and for
1196 * validation constraints that should be applied to entered values.
1198 * This class is private and not directly accessible by user code.
1200 var CBIAbstractValue
= CBIAbstractElement
.extend(/** @lends LuCI.form.AbstractValue.prototype */ {
1201 __init__: function(map
, section
, option
/*, ... */) {
1202 this.super('__init__', this.varargs(arguments
, 3));
1204 this.section
= section
;
1205 this.option
= option
;
1207 this.config
= map
.config
;
1211 this.rmempty
= true;
1212 this.default = null;
1214 this.optional
= false;
1218 * If set to `false`, the underlying option value is retained upon saving
1219 * the form when the option element is disabled due to unsatisfied
1220 * dependency constraints.
1222 * @name LuCI.form.AbstractValue.prototype#rmempty
1228 * If set to `true`, the underlying ui input widget is allowed to be empty,
1229 * otherwise the option element is marked invalid when no value is entered
1230 * or selected by the user.
1232 * @name LuCI.form.AbstractValue.prototype#optional
1238 * Sets a default value to use when the underlying UCI option is not set.
1240 * @name LuCI.form.AbstractValue.prototype#default
1246 * Specifies a datatype constraint expression to validate input values
1247 * against. Refer to {@link LuCI.validation} for details on the format.
1249 * If the user entered input does not match the datatype validation, the
1250 * option element is marked as invalid.
1252 * @name LuCI.form.AbstractValue.prototype#datatype
1258 * Specifies a custom validation function to test the user input for
1259 * validity. The validation function must return `true` to accept the
1260 * value. Any other return value type is converted to a string and
1261 * displayed to the user as validation error message.
1263 * If the user entered input does not pass the validation function, the
1264 * option element is marked as invalid.
1266 * @name LuCI.form.AbstractValue.prototype#validate
1272 * Override the UCI configuration name to read the option value from.
1274 * By default, the configuration name is inherited from the parent Map.
1275 * By setting this property, a deviating configuration may be specified.
1277 * The default is null, means inheriting from the parent form.
1279 * @name LuCI.form.AbstractValue.prototype#uciconfig
1285 * Override the UCI section name to read the option value from.
1287 * By default, the section ID is inherited from the parent section element.
1288 * By setting this property, a deviating section may be specified.
1290 * The default is null, means inheriting from the parent section.
1292 * @name LuCI.form.AbstractValue.prototype#ucisection
1298 * Override the UCI option name to read the value from.
1300 * By default, the elements name, which is passed as third argument to
1301 * the constructor, is used as UCI option name. By setting this property,
1302 * a deviating UCI option may be specified.
1304 * The default is null, means using the option element name.
1306 * @name LuCI.form.AbstractValue.prototype#ucioption
1312 * Mark grid section option element as editable.
1314 * Options which are displayed in the table portion of a `GridSection`
1315 * instance are rendered as readonly text by default. By setting the
1316 * `editable` property of a child option element to `true`, that element
1317 * is rendered as full input widget within its cell instead of a text only
1320 * This property has no effect on options that are not children of grid
1323 * @name LuCI.form.AbstractValue.prototype#editable
1329 * Move grid section option element into the table, the modal popup or both.
1331 * If this property is `null` (the default), the option element is
1332 * displayed in both the table preview area and the per-section instance
1333 * modal popup of a grid section. When it is set to `false` the option
1334 * is only shown in the table but not the modal popup. When set to `true`,
1335 * the option is only visible in the modal popup but not the table.
1337 * This property has no effect on options that are not children of grid
1340 * @name LuCI.form.AbstractValue.prototype#modalonly
1346 * Make option element readonly.
1348 * This property defaults to the readonly state of the parent form element.
1349 * When set to `true`, the underlying widget is rendered in disabled state,
1350 * means its contents cannot be changed and the widget cannot be interacted
1353 * @name LuCI.form.AbstractValue.prototype#readonly
1359 * Override the cell width of a table or grid section child option.
1361 * If the property is set to a numeric value, it is treated as pixel width
1362 * which is set on the containing cell element of the option, essentially
1363 * forcing a certain column width. When the property is set to a string
1364 * value, it is applied as-is to the CSS `width` property.
1366 * This property has no effect on options that are not children of grid or
1367 * table section elements.
1369 * @name LuCI.form.AbstractValue.prototype#width
1370 * @type number|string
1375 * Add a dependency contraint to the option.
1377 * Dependency constraints allow making the presence of option elements
1378 * dependant on the current values of certain other options within the
1379 * same form. An option element with unsatisfied dependencies will be
1380 * hidden from the view and its current value is omitted when saving.
1382 * Multiple constraints (that is, multiple calls to `depends()`) are
1383 * treated as alternatives, forming a logical "or" expression.
1385 * By passing an object of name => value pairs as first argument, it is
1386 * possible to depend on multiple options simultaneously, allowing to form
1387 * a logical "and" expression.
1389 * Option names may be given in "dot notation" which allows to reference
1390 * option elements outside of the current form section. If a name without
1391 * dot is specified, it refers to an option within the same configuration
1392 * section. If specified as <code>configname.sectionid.optionname</code>,
1393 * options anywhere within the same form may be specified.
1395 * The object notation also allows for a number of special keys which are
1396 * not treated as option names but as modifiers to influence the dependency
1397 * constraint evaluation. The associated value of these special "tag" keys
1398 * is ignored. The recognized tags are:
1402 * <code>!reverse</code><br>
1403 * Invert the dependency, instead of requiring another option to be
1404 * equal to the dependency value, that option should <em>not</em> be
1408 * <code>!contains</code><br>
1409 * Instead of requiring an exact match, the dependency is considered
1410 * satisfied when the dependency value is contained within the option
1414 * <code>!default</code><br>
1415 * The dependency is always satisfied
1423 * <code>opt.depends("foo", "test")</code><br>
1424 * Require the value of `foo` to be `test`.
1427 * <code>opt.depends({ foo: "test" })</code><br>
1428 * Equivalent to the previous example.
1431 * <code>opt.depends({ foo: "test", bar: "qrx" })</code><br>
1432 * Require the value of `foo` to be `test` and the value of `bar` to be
1436 * <code>opt.depends({ foo: "test" })<br>
1437 * opt.depends({ bar: "qrx" })</code><br>
1438 * Require either <code>foo</code> to be set to <code>test</code>,
1439 * <em>or</em> the <code>bar</code> option to be <code>qrx</code>.
1442 * <code>opt.depends("test.section1.foo", "bar")</code><br>
1443 * Require the "foo" form option within the "section1" section to be
1447 * <code>opt.depends({ foo: "test", "!contains": true })</code><br>
1448 * Require the "foo" option value to contain the substring "test".
1452 * @param {string|Object<string, string|boolean>} optionname_or_depends
1453 * The name of the option to depend on or an object describing multiple
1454 * dependencies which must be satified (a logical "and" expression).
1456 * @param {string} optionvalue
1457 * When invoked with a plain option name as first argument, this parameter
1458 * specifies the expected value. In case an object is passed as first
1459 * argument, this parameter is ignored.
1461 depends: function(field
, value
) {
1464 if (typeof(field
) === 'string')
1465 deps
= {}, deps
[field
] = value
;
1469 this.deps
.push(deps
);
1473 transformDepList: function(section_id
, deplist
) {
1474 var list
= deplist
|| this.deps
,
1477 if (Array
.isArray(list
)) {
1478 for (var i
= 0; i
< list
.length
; i
++) {
1481 for (var k
in list
[i
]) {
1482 if (list
[i
].hasOwnProperty(k
)) {
1483 if (k
.charAt(0) === '!')
1484 dep
[k
] = list
[i
][k
];
1485 else if (k
.indexOf('.') !== -1)
1486 dep
['cbid.%s'.format(k
)] = list
[i
][k
];
1488 dep
['cbid.%s.%s.%s'.format(
1489 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1490 this.ucisection
|| section_id
,
1496 for (var k
in dep
) {
1497 if (dep
.hasOwnProperty(k
)) {
1509 transformChoices: function() {
1510 if (!Array
.isArray(this.keylist
) || this.keylist
.length
== 0)
1515 for (var i
= 0; i
< this.keylist
.length
; i
++)
1516 choices
[this.keylist
[i
]] = this.vallist
[i
];
1522 checkDepends: function(section_id
) {
1523 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1524 active
= this.map
.isDependencySatisfied(this.deps
, config_name
, section_id
);
1527 this.updateDefaultValue(section_id
);
1533 updateDefaultValue: function(section_id
) {
1534 if (!L
.isObject(this.defaults
))
1537 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1538 cfgvalue
= L
.toArray(this.cfgvalue(section_id
))[0],
1539 default_defval
= null, satisified_defval
= null;
1541 for (var value
in this.defaults
) {
1542 if (!this.defaults
[value
] || this.defaults
[value
].length
== 0) {
1543 default_defval
= value
;
1546 else if (this.map
.isDependencySatisfied(this.defaults
[value
], config_name
, section_id
)) {
1547 satisified_defval
= value
;
1552 if (satisified_defval
== null)
1553 satisified_defval
= default_defval
;
1555 var node
= this.map
.findElement('id', this.cbid(section_id
));
1556 if (node
&& node
.getAttribute('data-changed') != 'true' && satisified_defval
!= null && cfgvalue
== null)
1557 dom
.callClassMethod(node
, 'setValue', satisified_defval
);
1559 this.default = satisified_defval
;
1563 * Obtain the internal ID ("cbid") of the element instance.
1565 * Since each form section element may map multiple underlying
1566 * configuration sections, the configuration section ID is required to
1567 * form a fully qualified ID pointing to the specific element instance
1568 * within the given specific section.
1570 * @param {string} section_id
1571 * The configuration section ID
1573 * @throws {TypeError}
1574 * Throws a `TypeError` exception when no `section_id` was specified.
1577 * Returns the element ID.
1579 cbid: function(section_id
) {
1580 if (section_id
== null)
1581 L
.error('TypeError', 'Section ID required');
1583 return 'cbid.%s.%s.%s'.format(
1584 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1585 section_id
, this.option
);
1589 * Load the underlying configuration value.
1591 * The default implementation of this method reads and returns the
1592 * underlying UCI option value (or the related JavaScript property for
1593 * `JSONMap` instances). It may be overwritten by user code to load data
1594 * from nonstandard sources.
1596 * @param {string} section_id
1597 * The configuration section ID
1599 * @throws {TypeError}
1600 * Throws a `TypeError` exception when no `section_id` was specified.
1602 * @returns {*|Promise<*>}
1603 * Returns the configuration value to initialize the option element with.
1604 * The return value of this function is filtered through `Promise.resolve()`
1605 * so it may return promises if overridden by user code.
1607 load: function(section_id
) {
1608 if (section_id
== null)
1609 L
.error('TypeError', 'Section ID required');
1611 return this.map
.data
.get(
1612 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1613 this.ucisection
|| section_id
,
1614 this.ucioption
|| this.option
);
1618 * Obtain the underlying `LuCI.ui` element instance.
1620 * @param {string} section_id
1621 * The configuration section ID
1623 * @throws {TypeError}
1624 * Throws a `TypeError` exception when no `section_id` was specified.
1626 * @return {LuCI.ui.AbstractElement|null}
1627 * Returns the `LuCI.ui` element instance or `null` in case the form
1628 * option implementation does not use `LuCI.ui` widgets.
1630 getUIElement: function(section_id
) {
1631 var node
= this.map
.findElement('id', this.cbid(section_id
)),
1632 inst
= node
? dom
.findClassInstance(node
) : null;
1633 return (inst
instanceof ui
.AbstractElement
) ? inst
: null;
1637 * Query the underlying configuration value.
1639 * The default implementation of this method returns the cached return
1640 * value of [load()]{@link LuCI.form.AbstractValue#load}. It may be
1641 * overwritten by user code to obtain the configuration value in a
1644 * @param {string} section_id
1645 * The configuration section ID
1647 * @throws {TypeError}
1648 * Throws a `TypeError` exception when no `section_id` was specified.
1651 * Returns the configuration value.
1653 cfgvalue: function(section_id
, set_value
) {
1654 if (section_id
== null)
1655 L
.error('TypeError', 'Section ID required');
1657 if (arguments
.length
== 2) {
1658 this.data
= this.data
|| {};
1659 this.data
[section_id
] = set_value
;
1662 return this.data
? this.data
[section_id
] : null;
1666 * Query the current form input value.
1668 * The default implementation of this method returns the current input
1669 * value of the underlying [LuCI.ui]{@link LuCI.ui.AbstractElement} widget.
1670 * It may be overwritten by user code to handle input values differently.
1672 * @param {string} section_id
1673 * The configuration section ID
1675 * @throws {TypeError}
1676 * Throws a `TypeError` exception when no `section_id` was specified.
1679 * Returns the current input value.
1681 formvalue: function(section_id
) {
1682 var elem
= this.getUIElement(section_id
);
1683 return elem
? elem
.getValue() : null;
1687 * Obtain a textual input representation.
1689 * The default implementation of this method returns the HTML escaped
1690 * current input value of the underlying
1691 * [LuCI.ui]{@link LuCI.ui.AbstractElement} widget. User code or specific
1692 * option element implementations may overwrite this function to apply a
1693 * different logic, e.g. to return `Yes` or `No` depending on the checked
1694 * state of checkbox elements.
1696 * @param {string} section_id
1697 * The configuration section ID
1699 * @throws {TypeError}
1700 * Throws a `TypeError` exception when no `section_id` was specified.
1703 * Returns the text representation of the current input value.
1705 textvalue: function(section_id
) {
1706 var cval
= this.cfgvalue(section_id
);
1709 cval
= this.default;
1711 return (cval
!= null) ? '%h'.format(cval
) : null;
1715 * Apply custom validation logic.
1717 * This method is invoked whenever incremental validation is performed on
1718 * the user input, e.g. on keyup or blur events.
1720 * The default implementation of this method does nothing and always
1721 * returns `true`. User code may overwrite this method to provide
1722 * additional validation logic which is not covered by data type
1726 * @param {string} section_id
1727 * The configuration section ID
1730 * The value to validate
1733 * The method shall return `true` to accept the given value. Any other
1734 * return value is treated as failure, converted to a string and displayed
1735 * as error message to the user.
1737 validate: function(section_id
, value
) {
1742 * Test whether the input value is currently valid.
1744 * @param {string} section_id
1745 * The configuration section ID
1747 * @returns {boolean}
1748 * Returns `true` if the input value currently is valid, otherwise it
1751 isValid: function(section_id
) {
1752 var elem
= this.getUIElement(section_id
);
1753 return elem
? elem
.isValid() : true;
1757 * Test whether the option element is currently active.
1759 * An element is active when it is not hidden due to unsatisfied dependency
1762 * @param {string} section_id
1763 * The configuration section ID
1765 * @returns {boolean}
1766 * Returns `true` if the option element currently is active, otherwise it
1769 isActive: function(section_id
) {
1770 var field
= this.map
.findElement('data-field', this.cbid(section_id
));
1771 return (field
!= null && !field
.classList
.contains('hidden'));
1775 setActive: function(section_id
, active
) {
1776 var field
= this.map
.findElement('data-field', this.cbid(section_id
));
1778 if (field
&& field
.classList
.contains('hidden') == active
) {
1779 field
.classList
[active
? 'remove' : 'add']('hidden');
1781 if (dom
.matches(field
.parentNode
, '.td.cbi-value-field'))
1782 field
.parentNode
.classList
[active
? 'remove' : 'add']('inactive');
1791 triggerValidation: function(section_id
) {
1792 var elem
= this.getUIElement(section_id
);
1793 return elem
? elem
.triggerValidation() : true;
1797 * Parse the option element input.
1799 * The function is invoked when the `parse()` method has been invoked on
1800 * the parent form and triggers input value reading and validation.
1802 * @param {string} section_id
1803 * The configuration section ID
1805 * @returns {Promise<void>}
1806 * Returns a promise resolving once the input value has been read and
1807 * validated or rejecting in case the input value does not meet the
1808 * validation constraints.
1810 parse: function(section_id
) {
1811 var active
= this.isActive(section_id
),
1812 cval
= this.cfgvalue(section_id
),
1813 fval
= active
? this.formvalue(section_id
) : null;
1815 if (active
&& !this.isValid(section_id
)) {
1816 var title
= this.stripTags(this.title
).trim();
1817 return Promise
.reject(new TypeError(_('Option "%s" contains an invalid input value.').format(title
|| this.option
)));
1820 if (fval
!= '' && fval
!= null) {
1821 if (this.forcewrite
|| !isEqual(cval
, fval
))
1822 return Promise
.resolve(this.write(section_id
, fval
));
1825 if (!active
|| this.rmempty
|| this.optional
) {
1826 return Promise
.resolve(this.remove(section_id
));
1828 else if (!isEqual(cval
, fval
)) {
1829 var title
= this.stripTags(this.title
).trim();
1830 return Promise
.reject(new TypeError(_('Option "%s" must not be empty.').format(title
|| this.option
)));
1834 return Promise
.resolve();
1838 * Write the current input value into the configuration.
1840 * This function is invoked upon saving the parent form when the option
1841 * element is valid and when its input value has been changed compared to
1842 * the initial value returned by
1843 * [cfgvalue()]{@link LuCI.form.AbstractValue#cfgvalue}.
1845 * The default implementation simply sets the given input value in the
1846 * UCI configuration (or the associated JavaScript object property in
1847 * case of `JSONMap` forms). It may be overwritten by user code to
1848 * implement alternative save logic, e.g. to transform the input value
1849 * before it is written.
1851 * @param {string} section_id
1852 * The configuration section ID
1854 * @param {string|string[]} formvalue
1855 * The input value to write.
1857 write: function(section_id
, formvalue
) {
1858 return this.map
.data
.set(
1859 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1860 this.ucisection
|| section_id
,
1861 this.ucioption
|| this.option
,
1866 * Remove the corresponding value from the configuration.
1868 * This function is invoked upon saving the parent form when the option
1869 * element has been hidden due to unsatisfied dependencies or when the
1870 * user cleared the input value and the option is marked optional.
1872 * The default implementation simply removes the associated option from the
1873 * UCI configuration (or the associated JavaScript object property in
1874 * case of `JSONMap` forms). It may be overwritten by user code to
1875 * implement alternative removal logic, e.g. to retain the original value.
1877 * @param {string} section_id
1878 * The configuration section ID
1880 remove: function(section_id
) {
1881 return this.map
.data
.unset(
1882 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1883 this.ucisection
|| section_id
,
1884 this.ucioption
|| this.option
);
1889 * @class TypedSection
1890 * @memberof LuCI.form
1891 * @augments LuCI.form.AbstractSection
1895 * The `TypedSection` class maps all or - if `filter()` is overwritten - a
1896 * subset of the underlying UCI configuration sections of a given type.
1898 * Layout wise, the configuration section instances mapped by the section
1899 * element (sometimes referred to as "section nodes") are stacked beneath
1900 * each other in a single column, with an optional section remove button next
1901 * to each section node and a section add button at the end, depending on the
1902 * value of the `addremove` property.
1904 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
1905 * The configuration form this section is added to. It is automatically passed
1906 * by [section()]{@link LuCI.form.Map#section}.
1908 * @param {string} section_type
1909 * The type of the UCI section to map.
1911 * @param {string} [title]
1912 * The title caption of the form section element.
1914 * @param {string} [description]
1915 * The description text of the form section element.
1917 var CBITypedSection
= CBIAbstractSection
.extend(/** @lends LuCI.form.TypedSection.prototype */ {
1918 __name__
: 'CBI.TypedSection',
1921 * If set to `true`, the user may add or remove instances from the form
1922 * section widget, otherwise only preexisting sections may be edited.
1923 * The default is `false`.
1925 * @name LuCI.form.TypedSection.prototype#addremove
1931 * If set to `true`, mapped section instances are treated as anonymous
1932 * UCI sections, which means that section instance elements will be
1933 * rendered without title element and that no name is required when adding
1934 * new sections. The default is `false`.
1936 * @name LuCI.form.TypedSection.prototype#anonymous
1942 * When set to `true`, instead of rendering section instances one below
1943 * another, treat each instance as separate tab pane and render a tab menu
1944 * at the top of the form section element, allowing the user to switch
1945 * among instances. The default is `false`.
1947 * @name LuCI.form.TypedSection.prototype#tabbed
1953 * Override the caption used for the section add button at the bottom of
1954 * the section form element. If set to a string, it will be used as-is,
1955 * if set to a function, the function will be invoked and its return value
1956 * is used as caption, after converting it to a string. If this property
1957 * is not set, the default is `Add`.
1959 * @name LuCI.form.TypedSection.prototype#addbtntitle
1960 * @type string|function
1965 * Override the UCI configuration name to read the section IDs from. By
1966 * default, the configuration name is inherited from the parent `Map`.
1967 * By setting this property, a deviating configuration may be specified.
1968 * The default is `null`, means inheriting from the parent form.
1970 * @name LuCI.form.TypedSection.prototype#uciconfig
1976 cfgsections: function() {
1977 return this.map
.data
.sections(this.uciconfig
|| this.map
.config
, this.sectiontype
)
1978 .map(function(s
) { return s
['.name'] })
1979 .filter(L
.bind(this.filter
, this));
1983 handleAdd: function(ev
, name
) {
1984 var config_name
= this.uciconfig
|| this.map
.config
;
1986 this.map
.data
.add(config_name
, this.sectiontype
, name
);
1987 return this.map
.save(null, true);
1991 handleRemove: function(section_id
, ev
) {
1992 var config_name
= this.uciconfig
|| this.map
.config
;
1994 this.map
.data
.remove(config_name
, section_id
);
1995 return this.map
.save(null, true);
1999 renderSectionAdd: function(extra_class
) {
2000 if (!this.addremove
)
2003 var createEl
= E('div', { 'class': 'cbi-section-create' }),
2004 config_name
= this.uciconfig
|| this.map
.config
,
2005 btn_title
= this.titleFn('addbtntitle');
2007 if (extra_class
!= null)
2008 createEl
.classList
.add(extra_class
);
2010 if (this.anonymous
) {
2011 createEl
.appendChild(E('button', {
2012 'class': 'cbi-button cbi-button-add',
2013 'title': btn_title
|| _('Add'),
2014 'click': ui
.createHandlerFn(this, 'handleAdd'),
2015 'disabled': this.map
.readonly
|| null
2016 }, [ btn_title
|| _('Add') ]));
2019 var nameEl
= E('input', {
2021 'class': 'cbi-section-create-name',
2022 'disabled': this.map
.readonly
|| null
2025 dom
.append(createEl
, [
2026 E('div', {}, nameEl
),
2028 'class': 'cbi-button cbi-button-add',
2030 'value': btn_title
|| _('Add'),
2031 'title': btn_title
|| _('Add'),
2032 'click': ui
.createHandlerFn(this, function(ev
) {
2033 if (nameEl
.classList
.contains('cbi-input-invalid'))
2036 return this.handleAdd(ev
, nameEl
.value
);
2038 'disabled': this.map
.readonly
|| null
2042 ui
.addValidator(nameEl
, 'uciname', true, 'blur', 'keyup');
2049 renderSectionPlaceholder: function() {
2051 E('em', _('This section contains no values yet')),
2057 renderContents: function(cfgsections
, nodes
) {
2058 var section_id
= null,
2059 config_name
= this.uciconfig
|| this.map
.config
,
2060 sectionEl
= E('div', {
2061 'id': 'cbi-%s-%s'.format(config_name
, this.sectiontype
),
2062 'class': 'cbi-section',
2063 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2064 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2067 if (this.title
!= null && this.title
!= '')
2068 sectionEl
.appendChild(E('legend', {}, this.title
));
2070 if (this.description
!= null && this.description
!= '')
2071 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2073 for (var i
= 0; i
< nodes
.length
; i
++) {
2074 if (this.addremove
) {
2075 sectionEl
.appendChild(
2076 E('div', { 'class': 'cbi-section-remove right' },
2078 'class': 'cbi-button',
2079 'name': 'cbi.rts.%s.%s'.format(config_name
, cfgsections
[i
]),
2080 'data-section-id': cfgsections
[i
],
2081 'click': ui
.createHandlerFn(this, 'handleRemove', cfgsections
[i
]),
2082 'disabled': this.map
.readonly
|| null
2083 }, [ _('Delete') ])));
2086 if (!this.anonymous
)
2087 sectionEl
.appendChild(E('h3', cfgsections
[i
].toUpperCase()));
2089 sectionEl
.appendChild(E('div', {
2090 'id': 'cbi-%s-%s'.format(config_name
, cfgsections
[i
]),
2092 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
2093 'data-section-id': cfgsections
[i
]
2097 if (nodes
.length
== 0)
2098 sectionEl
.appendChild(this.renderSectionPlaceholder());
2100 sectionEl
.appendChild(this.renderSectionAdd());
2102 dom
.bindClassInstance(sectionEl
, this);
2108 render: function() {
2109 var cfgsections
= this.cfgsections(),
2112 for (var i
= 0; i
< cfgsections
.length
; i
++)
2113 renderTasks
.push(this.renderUCISection(cfgsections
[i
]));
2115 return Promise
.all(renderTasks
).then(this.renderContents
.bind(this, cfgsections
));
2120 * @class TableSection
2121 * @memberof LuCI.form
2122 * @augments LuCI.form.TypedSection
2126 * The `TableSection` class maps all or - if `filter()` is overwritten - a
2127 * subset of the underlying UCI configuration sections of a given type.
2129 * Layout wise, the configuration section instances mapped by the section
2130 * element (sometimes referred to as "section nodes") are rendered as rows
2131 * within an HTML table element, with an optional section remove button in the
2132 * last column and a section add button below the table, depending on the
2133 * value of the `addremove` property.
2135 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2136 * The configuration form this section is added to. It is automatically passed
2137 * by [section()]{@link LuCI.form.Map#section}.
2139 * @param {string} section_type
2140 * The type of the UCI section to map.
2142 * @param {string} [title]
2143 * The title caption of the form section element.
2145 * @param {string} [description]
2146 * The description text of the form section element.
2148 var CBITableSection
= CBITypedSection
.extend(/** @lends LuCI.form.TableSection.prototype */ {
2149 __name__
: 'CBI.TableSection',
2152 * If set to `true`, the user may add or remove instances from the form
2153 * section widget, otherwise only preexisting sections may be edited.
2154 * The default is `false`.
2156 * @name LuCI.form.TableSection.prototype#addremove
2162 * If set to `true`, mapped section instances are treated as anonymous
2163 * UCI sections, which means that section instance elements will be
2164 * rendered without title element and that no name is required when adding
2165 * new sections. The default is `false`.
2167 * @name LuCI.form.TableSection.prototype#anonymous
2173 * Override the caption used for the section add button at the bottom of
2174 * the section form element. If set to a string, it will be used as-is,
2175 * if set to a function, the function will be invoked and its return value
2176 * is used as caption, after converting it to a string. If this property
2177 * is not set, the default is `Add`.
2179 * @name LuCI.form.TableSection.prototype#addbtntitle
2180 * @type string|function
2185 * Override the per-section instance title caption shown in the first
2186 * column of the table unless `anonymous` is set to true. If set to a
2187 * string, it will be used as `String.format()` pattern with the name of
2188 * the underlying UCI section as first argument, if set to a function, the
2189 * function will be invoked with the section name as first argument and
2190 * its return value is used as caption, after converting it to a string.
2191 * If this property is not set, the default is the name of the underlying
2192 * UCI configuration section.
2194 * @name LuCI.form.TableSection.prototype#sectiontitle
2195 * @type string|function
2200 * Override the per-section instance modal popup title caption shown when
2201 * clicking the `More…` button in a section specifying `max_cols`. If set
2202 * to a string, it will be used as `String.format()` pattern with the name
2203 * of the underlying UCI section as first argument, if set to a function,
2204 * the function will be invoked with the section name as first argument and
2205 * its return value is used as caption, after converting it to a string.
2206 * If this property is not set, the default is the name of the underlying
2207 * UCI configuration section.
2209 * @name LuCI.form.TableSection.prototype#modaltitle
2210 * @type string|function
2215 * Override the UCI configuration name to read the section IDs from. By
2216 * default, the configuration name is inherited from the parent `Map`.
2217 * By setting this property, a deviating configuration may be specified.
2218 * The default is `null`, means inheriting from the parent form.
2220 * @name LuCI.form.TableSection.prototype#uciconfig
2226 * Specify a maximum amount of columns to display. By default, one table
2227 * column is rendered for each child option of the form section element.
2228 * When this option is set to a positive number, then no more columns than
2229 * the given amount are rendered. When the number of child options exceeds
2230 * the specified amount, a `More…` button is rendered in the last column,
2231 * opening a modal dialog presenting all options elements in `NamedSection`
2232 * style when clicked.
2234 * @name LuCI.form.TableSection.prototype#max_cols
2240 * If set to `true`, alternating `cbi-rowstyle-1` and `cbi-rowstyle-2` CSS
2241 * classes are added to the table row elements. Not all LuCI themes
2242 * implement these row style classes. The default is `false`.
2244 * @name LuCI.form.TableSection.prototype#rowcolors
2250 * Enables a per-section instance row `Edit` button which triggers a certain
2251 * action when clicked. If set to a string, the string value is used
2252 * as `String.format()` pattern with the name of the underlying UCI section
2253 * as first format argument. The result is then interpreted as URL which
2254 * LuCI will navigate to when the user clicks the edit button.
2256 * If set to a function, this function will be registered as click event
2257 * handler on the rendered edit button, receiving the section instance
2258 * name as first and the DOM click event as second argument.
2260 * @name LuCI.form.TableSection.prototype#extedit
2261 * @type string|function
2266 * If set to `true`, a sort button is added to the last column, allowing
2267 * the user to reorder the section instances mapped by the section form
2270 * @name LuCI.form.TableSection.prototype#sortable
2276 * If set to `true`, the header row with the options descriptions will
2277 * not be displayed. By default, descriptions row is automatically displayed
2278 * when at least one option has a description.
2280 * @name LuCI.form.TableSection.prototype#nodescriptions
2286 * The `TableSection` implementation does not support option tabbing, so
2287 * its implementation of `tab()` will always throw an exception when
2291 * @throws Throws an exception when invoked.
2294 throw 'Tabs are not supported by TableSection';
2298 renderContents: function(cfgsections
, nodes
) {
2299 var section_id
= null,
2300 config_name
= this.uciconfig
|| this.map
.config
,
2301 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2302 has_more
= max_cols
< this.children
.length
,
2303 sectionEl
= E('div', {
2304 'id': 'cbi-%s-%s'.format(config_name
, this.sectiontype
),
2305 'class': 'cbi-section cbi-tblsection',
2306 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2307 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2309 tableEl
= E('div', {
2310 'class': 'table cbi-section-table'
2313 if (this.title
!= null && this.title
!= '')
2314 sectionEl
.appendChild(E('h3', {}, this.title
));
2316 if (this.description
!= null && this.description
!= '')
2317 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2319 tableEl
.appendChild(this.renderHeaderRows(max_cols
));
2321 for (var i
= 0; i
< nodes
.length
; i
++) {
2322 var sectionname
= this.titleFn('sectiontitle', cfgsections
[i
]);
2324 if (sectionname
== null)
2325 sectionname
= cfgsections
[i
];
2327 var trEl
= E('div', {
2328 'id': 'cbi-%s-%s'.format(config_name
, cfgsections
[i
]),
2329 'class': 'tr cbi-section-table-row',
2330 'data-sid': cfgsections
[i
],
2331 'draggable': this.sortable
? true : null,
2332 'mousedown': this.sortable
? L
.bind(this.handleDragInit
, this) : null,
2333 'dragstart': this.sortable
? L
.bind(this.handleDragStart
, this) : null,
2334 'dragover': this.sortable
? L
.bind(this.handleDragOver
, this) : null,
2335 'dragenter': this.sortable
? L
.bind(this.handleDragEnter
, this) : null,
2336 'dragleave': this.sortable
? L
.bind(this.handleDragLeave
, this) : null,
2337 'dragend': this.sortable
? L
.bind(this.handleDragEnd
, this) : null,
2338 'drop': this.sortable
? L
.bind(this.handleDrop
, this) : null,
2339 'data-title': (sectionname
&& (!this.anonymous
|| this.sectiontitle
)) ? sectionname
: null,
2340 'data-section-id': cfgsections
[i
]
2343 if (this.extedit
|| this.rowcolors
)
2344 trEl
.classList
.add(!(tableEl
.childNodes
.length
% 2)
2345 ? 'cbi-rowstyle-1' : 'cbi-rowstyle-2');
2347 for (var j
= 0; j
< max_cols
&& nodes
[i
].firstChild
; j
++)
2348 trEl
.appendChild(nodes
[i
].firstChild
);
2350 trEl
.appendChild(this.renderRowActions(cfgsections
[i
], has_more
? _('More…') : null));
2351 tableEl
.appendChild(trEl
);
2354 if (nodes
.length
== 0)
2355 tableEl
.appendChild(E('div', { 'class': 'tr cbi-section-table-row placeholder' },
2356 E('div', { 'class': 'td' },
2357 E('em', {}, _('This section contains no values yet')))));
2359 sectionEl
.appendChild(tableEl
);
2361 sectionEl
.appendChild(this.renderSectionAdd('cbi-tblsection-create'));
2363 dom
.bindClassInstance(sectionEl
, this);
2369 renderHeaderRows: function(max_cols
, has_action
) {
2370 var has_titles
= false,
2371 has_descriptions
= false,
2372 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2373 has_more
= max_cols
< this.children
.length
,
2374 anon_class
= (!this.anonymous
|| this.sectiontitle
) ? 'named' : 'anonymous',
2377 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2381 has_titles
= has_titles
|| !!opt
.title
;
2382 has_descriptions
= has_descriptions
|| !!opt
.description
;
2386 var trEl
= E('div', {
2387 'class': 'tr cbi-section-table-titles ' + anon_class
,
2388 'data-title': (!this.anonymous
|| this.sectiontitle
) ? _('Name') : null
2391 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2395 trEl
.appendChild(E('div', {
2396 'class': 'th cbi-section-table-cell',
2397 'data-widget': opt
.__name__
2400 if (opt
.width
!= null)
2401 trEl
.lastElementChild
.style
.width
=
2402 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2405 trEl
.lastElementChild
.appendChild(E('a', {
2406 'href': opt
.titleref
,
2407 'class': 'cbi-title-ref',
2408 'title': this.titledesc
|| _('Go to relevant configuration page')
2411 dom
.content(trEl
.lastElementChild
, opt
.title
);
2414 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2415 trEl
.appendChild(E('div', {
2416 'class': 'th cbi-section-table-cell cbi-section-actions'
2419 trEls
.appendChild(trEl
);
2422 if (has_descriptions
&& !this.nodescriptions
) {
2423 var trEl
= E('div', {
2424 'class': 'tr cbi-section-table-descr ' + anon_class
2427 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2431 trEl
.appendChild(E('div', {
2432 'class': 'th cbi-section-table-cell',
2433 'data-widget': opt
.__name__
2434 }, opt
.description
));
2436 if (opt
.width
!= null)
2437 trEl
.lastElementChild
.style
.width
=
2438 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2441 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2442 trEl
.appendChild(E('div', {
2443 'class': 'th cbi-section-table-cell cbi-section-actions'
2446 trEls
.appendChild(trEl
);
2453 renderRowActions: function(section_id
, more_label
) {
2454 var config_name
= this.uciconfig
|| this.map
.config
;
2456 if (!this.sortable
&& !this.extedit
&& !this.addremove
&& !more_label
)
2459 var tdEl
= E('div', {
2460 'class': 'td cbi-section-table-cell nowrap cbi-section-actions'
2463 if (this.sortable
) {
2464 dom
.append(tdEl
.lastElementChild
, [
2466 'title': _('Drag to reorder'),
2467 'class': 'btn cbi-button drag-handle center',
2468 'style': 'cursor:move',
2469 'disabled': this.map
.readonly
|| null
2477 if (typeof(this.extedit
) == 'function')
2478 evFn
= L
.bind(this.extedit
, this);
2479 else if (typeof(this.extedit
) == 'string')
2480 evFn
= L
.bind(function(sid
, ev
) {
2481 location
.href
= this.extedit
.format(sid
);
2482 }, this, section_id
);
2484 dom
.append(tdEl
.lastElementChild
,
2487 'class': 'cbi-button cbi-button-edit',
2494 dom
.append(tdEl
.lastElementChild
,
2496 'title': more_label
,
2497 'class': 'cbi-button cbi-button-edit',
2498 'click': ui
.createHandlerFn(this, 'renderMoreOptionsModal', section_id
)
2503 if (this.addremove
) {
2504 var btn_title
= this.titleFn('removebtntitle', section_id
);
2506 dom
.append(tdEl
.lastElementChild
,
2508 'title': btn_title
|| _('Delete'),
2509 'class': 'cbi-button cbi-button-remove',
2510 'click': ui
.createHandlerFn(this, 'handleRemove', section_id
),
2511 'disabled': this.map
.readonly
|| null
2512 }, [ btn_title
|| _('Delete') ])
2520 handleDragInit: function(ev
) {
2521 scope
.dragState
= { node
: ev
.target
};
2525 handleDragStart: function(ev
) {
2526 if (!scope
.dragState
|| !scope
.dragState
.node
.classList
.contains('drag-handle')) {
2527 scope
.dragState
= null;
2528 ev
.preventDefault();
2532 scope
.dragState
.node
= dom
.parent(scope
.dragState
.node
, '.tr');
2533 ev
.dataTransfer
.setData('text', 'drag');
2534 ev
.target
.style
.opacity
= 0.4;
2538 handleDragOver: function(ev
) {
2539 var n
= scope
.dragState
.targetNode
,
2540 r
= scope
.dragState
.rect
,
2541 t
= r
.top
+ r
.height
/ 2;
2543 if (ev
.clientY
<= t
) {
2544 n
.classList
.remove('drag-over-below');
2545 n
.classList
.add('drag-over-above');
2548 n
.classList
.remove('drag-over-above');
2549 n
.classList
.add('drag-over-below');
2552 ev
.dataTransfer
.dropEffect
= 'move';
2553 ev
.preventDefault();
2558 handleDragEnter: function(ev
) {
2559 scope
.dragState
.rect
= ev
.currentTarget
.getBoundingClientRect();
2560 scope
.dragState
.targetNode
= ev
.currentTarget
;
2564 handleDragLeave: function(ev
) {
2565 ev
.currentTarget
.classList
.remove('drag-over-above');
2566 ev
.currentTarget
.classList
.remove('drag-over-below');
2570 handleDragEnd: function(ev
) {
2573 n
.style
.opacity
= '';
2574 n
.classList
.add('flash');
2575 n
.parentNode
.querySelectorAll('.drag-over-above, .drag-over-below')
2576 .forEach(function(tr
) {
2577 tr
.classList
.remove('drag-over-above');
2578 tr
.classList
.remove('drag-over-below');
2583 handleDrop: function(ev
) {
2584 var s
= scope
.dragState
;
2586 if (s
.node
&& s
.targetNode
) {
2587 var config_name
= this.uciconfig
|| this.map
.config
,
2588 ref_node
= s
.targetNode
,
2591 if (ref_node
.classList
.contains('drag-over-below')) {
2592 ref_node
= ref_node
.nextElementSibling
;
2596 var sid1
= s
.node
.getAttribute('data-sid'),
2597 sid2
= s
.targetNode
.getAttribute('data-sid');
2599 s
.node
.parentNode
.insertBefore(s
.node
, ref_node
);
2600 this.map
.data
.move(config_name
, sid1
, sid2
, after
);
2603 scope
.dragState
= null;
2604 ev
.target
.style
.opacity
= '';
2605 ev
.stopPropagation();
2606 ev
.preventDefault();
2611 handleModalCancel: function(modalMap
, ev
) {
2612 return Promise
.resolve(ui
.hideModal());
2616 handleModalSave: function(modalMap
, ev
) {
2617 return modalMap
.save()
2618 .then(L
.bind(this.map
.load
, this.map
))
2619 .then(L
.bind(this.map
.reset
, this.map
))
2621 .catch(function() {});
2625 * Add further options to the per-section instanced modal popup.
2627 * This function may be overwritten by user code to perform additional
2628 * setup steps before displaying the more options modal which is useful to
2629 * e.g. query additional data or to inject further option elements.
2631 * The default implementation of this function does nothing.
2634 * @param {LuCI.form.NamedSection} modalSection
2635 * The `NamedSection` instance about to be rendered in the modal popup.
2637 * @param {string} section_id
2638 * The ID of the underlying UCI section the modal popup belongs to.
2641 * The DOM event emitted by clicking the `More…` button.
2643 * @returns {*|Promise<*>}
2644 * Return values of this function are ignored but if a promise is returned,
2645 * it is run to completion before the rendering is continued, allowing
2646 * custom logic to perform asynchroneous work before the modal dialog
2649 addModalOptions: function(modalSection
, section_id
, ev
) {
2654 renderMoreOptionsModal: function(section_id
, ev
) {
2655 var parent
= this.map
,
2656 title
= parent
.title
,
2658 m
= new CBIMap(this.map
.config
, null, null),
2659 s
= m
.section(CBINamedSection
, section_id
, this.sectiontype
);
2662 m
.readonly
= parent
.readonly
;
2665 s
.tab_names
= this.tab_names
;
2667 if ((name
= this.titleFn('modaltitle', section_id
)) != null)
2669 else if ((name
= this.titleFn('sectiontitle', section_id
)) != null)
2670 title
= '%s - %s'.format(parent
.title
, name
);
2671 else if (!this.anonymous
)
2672 title
= '%s - %s'.format(parent
.title
, section_id
);
2674 for (var i
= 0; i
< this.children
.length
; i
++) {
2675 var o1
= this.children
[i
];
2677 if (o1
.modalonly
=== false)
2680 var o2
= s
.option(o1
.constructor, o1
.option
, o1
.title
, o1
.description
);
2683 if (!o1
.hasOwnProperty(k
))
2700 return Promise
.resolve(this.addModalOptions(s
, section_id
, ev
)).then(L
.bind(m
.render
, m
)).then(L
.bind(function(nodes
) {
2701 ui
.showModal(title
, [
2703 E('div', { 'class': 'right' }, [
2706 'click': ui
.createHandlerFn(this, 'handleModalCancel', m
)
2707 }, [ _('Dismiss') ]), ' ',
2709 'class': 'cbi-button cbi-button-positive important',
2710 'click': ui
.createHandlerFn(this, 'handleModalSave', m
),
2711 'disabled': m
.readonly
|| null
2715 }, this)).catch(L
.error
);
2720 * @class GridSection
2721 * @memberof LuCI.form
2722 * @augments LuCI.form.TableSection
2726 * The `GridSection` class maps all or - if `filter()` is overwritten - a
2727 * subset of the underlying UCI configuration sections of a given type.
2729 * A grid section functions similar to a {@link LuCI.form.TableSection} but
2730 * supports tabbing in the modal overlay. Option elements added with
2731 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
2732 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
2733 * are displayed in the modal popup.
2735 * Another important difference is that the table cells show a readonly text
2736 * preview of the corresponding option elements by default, unless the child
2737 * option element is explicitely made writable by setting the `editable`
2738 * property to `true`.
2740 * Additionally, the grid section honours a `modalonly` property of child
2741 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
2742 * documentation for details.
2744 * Layout wise, a grid section looks mostly identical to table sections.
2746 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2747 * The configuration form this section is added to. It is automatically passed
2748 * by [section()]{@link LuCI.form.Map#section}.
2750 * @param {string} section_type
2751 * The type of the UCI section to map.
2753 * @param {string} [title]
2754 * The title caption of the form section element.
2756 * @param {string} [description]
2757 * The description text of the form section element.
2759 var CBIGridSection
= CBITableSection
.extend(/** @lends LuCI.form.GridSection.prototype */ {
2761 * Add an option tab to the section.
2763 * The modal option elements of a grid section may be divided into multiple
2764 * tabs to provide a better overview to the user.
2766 * Before options can be moved into a tab pane, the corresponding tab
2767 * has to be defined first, which is done by calling this function.
2769 * Note that tabs are only effective in modal popups, options added with
2770 * `option()` will not be assigned to a specific tab and are rendered in
2771 * the table view only.
2773 * @param {string} name
2774 * The name of the tab to register. It may be freely chosen and just serves
2775 * as an identifier to differentiate tabs.
2777 * @param {string} title
2778 * The human readable caption of the tab.
2780 * @param {string} [description]
2781 * An additional description text for the corresponding tab pane. It is
2782 * displayed as text paragraph below the tab but before the tab pane
2783 * contents. If omitted, no description will be rendered.
2786 * Throws an exeption if a tab with the same `name` already exists.
2788 tab: function(name
, title
, description
) {
2789 CBIAbstractSection
.prototype.tab
.call(this, name
, title
, description
);
2793 handleAdd: function(ev
, name
) {
2794 var config_name
= this.uciconfig
|| this.map
.config
,
2795 section_id
= this.map
.data
.add(config_name
, this.sectiontype
, name
);
2797 this.addedSection
= section_id
;
2798 return this.renderMoreOptionsModal(section_id
);
2802 handleModalSave: function(/* ... */) {
2803 return this.super('handleModalSave', arguments
)
2804 .then(L
.bind(function() { this.addedSection
= null }, this));
2808 handleModalCancel: function(/* ... */) {
2809 var config_name
= this.uciconfig
|| this.map
.config
;
2811 if (this.addedSection
!= null) {
2812 this.map
.data
.remove(config_name
, this.addedSection
);
2813 this.addedSection
= null;
2816 return this.super('handleModalCancel', arguments
);
2820 renderUCISection: function(section_id
) {
2821 return this.renderOptions(null, section_id
);
2825 renderChildren: function(tab_name
, section_id
, in_table
) {
2826 var tasks
= [], index
= 0;
2828 for (var i
= 0, opt
; (opt
= this.children
[i
]) != null; i
++) {
2829 if (opt
.disable
|| opt
.modalonly
)
2833 tasks
.push(opt
.render(index
++, section_id
, in_table
));
2835 tasks
.push(this.renderTextValue(section_id
, opt
));
2838 return Promise
.all(tasks
);
2842 renderTextValue: function(section_id
, opt
) {
2843 var title
= this.stripTags(opt
.title
).trim(),
2844 descr
= this.stripTags(opt
.description
).trim(),
2845 value
= opt
.textvalue(section_id
);
2848 'class': 'td cbi-value-field',
2849 'data-title': (title
!= '') ? title
: null,
2850 'data-description': (descr
!= '') ? descr
: null,
2851 'data-name': opt
.option
,
2852 'data-widget': opt
.typename
|| opt
.__name__
2853 }, (value
!= null) ? value
: E('em', _('none')));
2857 renderHeaderRows: function(section_id
) {
2858 return this.super('renderHeaderRows', [ NaN
, true ]);
2862 renderRowActions: function(section_id
) {
2863 return this.super('renderRowActions', [ section_id
, _('Edit') ]);
2868 var section_ids
= this.cfgsections(),
2871 if (Array
.isArray(this.children
)) {
2872 for (var i
= 0; i
< section_ids
.length
; i
++) {
2873 for (var j
= 0; j
< this.children
.length
; j
++) {
2874 if (!this.children
[j
].editable
|| this.children
[j
].modalonly
)
2877 tasks
.push(this.children
[j
].parse(section_ids
[i
]));
2882 return Promise
.all(tasks
);
2887 * @class NamedSection
2888 * @memberof LuCI.form
2889 * @augments LuCI.form.AbstractSection
2893 * The `NamedSection` class maps exactly one UCI section instance which is
2894 * specified when constructing the class instance.
2896 * Layout and functionality wise, a named section is essentially a
2897 * `TypedSection` which allows exactly one section node.
2899 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2900 * The configuration form this section is added to. It is automatically passed
2901 * by [section()]{@link LuCI.form.Map#section}.
2903 * @param {string} section_id
2904 * The name (ID) of the UCI section to map.
2906 * @param {string} section_type
2907 * The type of the UCI section to map.
2909 * @param {string} [title]
2910 * The title caption of the form section element.
2912 * @param {string} [description]
2913 * The description text of the form section element.
2915 var CBINamedSection
= CBIAbstractSection
.extend(/** @lends LuCI.form.NamedSection.prototype */ {
2916 __name__
: 'CBI.NamedSection',
2917 __init__: function(map
, section_id
/*, ... */) {
2918 this.super('__init__', this.varargs(arguments
, 2, map
));
2920 this.section
= section_id
;
2924 * If set to `true`, the user may remove or recreate the sole mapped
2925 * configuration instance from the form section widget, otherwise only a
2926 * preexisting section may be edited. The default is `false`.
2928 * @name LuCI.form.NamedSection.prototype#addremove
2934 * Override the UCI configuration name to read the section IDs from. By
2935 * default, the configuration name is inherited from the parent `Map`.
2936 * By setting this property, a deviating configuration may be specified.
2937 * The default is `null`, means inheriting from the parent form.
2939 * @name LuCI.form.NamedSection.prototype#uciconfig
2945 * The `NamedSection` class overwrites the generic `cfgsections()`
2946 * implementation to return a one-element array containing the mapped
2947 * section ID as sole element. User code should not normally change this.
2949 * @returns {string[]}
2950 * Returns a one-element array containing the mapped section ID.
2952 cfgsections: function() {
2953 return [ this.section
];
2957 handleAdd: function(ev
) {
2958 var section_id
= this.section
,
2959 config_name
= this.uciconfig
|| this.map
.config
;
2961 this.map
.data
.add(config_name
, this.sectiontype
, section_id
);
2962 return this.map
.save(null, true);
2966 handleRemove: function(ev
) {
2967 var section_id
= this.section
,
2968 config_name
= this.uciconfig
|| this.map
.config
;
2970 this.map
.data
.remove(config_name
, section_id
);
2971 return this.map
.save(null, true);
2975 renderContents: function(data
) {
2976 var ucidata
= data
[0], nodes
= data
[1],
2977 section_id
= this.section
,
2978 config_name
= this.uciconfig
|| this.map
.config
,
2979 sectionEl
= E('div', {
2980 'id': ucidata
? null : 'cbi-%s-%s'.format(config_name
, section_id
),
2981 'class': 'cbi-section',
2982 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2983 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2986 if (typeof(this.title
) === 'string' && this.title
!== '')
2987 sectionEl
.appendChild(E('legend', {}, this.title
));
2989 if (typeof(this.description
) === 'string' && this.description
!== '')
2990 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2993 if (this.addremove
) {
2994 sectionEl
.appendChild(
2995 E('div', { 'class': 'cbi-section-remove right' },
2997 'class': 'cbi-button',
2998 'click': ui
.createHandlerFn(this, 'handleRemove'),
2999 'disabled': this.map
.readonly
|| null
3000 }, [ _('Delete') ])));
3003 sectionEl
.appendChild(E('div', {
3004 'id': 'cbi-%s-%s'.format(config_name
, section_id
),
3006 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3007 'data-section-id': section_id
3010 else if (this.addremove
) {
3011 sectionEl
.appendChild(
3013 'class': 'cbi-button cbi-button-add',
3014 'click': ui
.createHandlerFn(this, 'handleAdd'),
3015 'disabled': this.map
.readonly
|| null
3019 dom
.bindClassInstance(sectionEl
, this);
3025 render: function() {
3026 var config_name
= this.uciconfig
|| this.map
.config
,
3027 section_id
= this.section
;
3029 return Promise
.all([
3030 this.map
.data
.get(config_name
, section_id
),
3031 this.renderUCISection(section_id
)
3032 ]).then(this.renderContents
.bind(this));
3038 * @memberof LuCI.form
3039 * @augments LuCI.form.AbstractValue
3043 * The `Value` class represents a simple one-line form input using the
3044 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3045 * {@link LuCI.ui.Combobox} class as underlying widget.
3047 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3048 * The configuration form this section is added to. It is automatically passed
3049 * by [option()]{@link LuCI.form.AbstractSection#option} or
3050 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3051 * option to the section.
3053 * @param {LuCI.form.AbstractSection} section
3054 * The configuration section this option is added to. It is automatically passed
3055 * by [option()]{@link LuCI.form.AbstractSection#option} or
3056 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3057 * option to the section.
3059 * @param {string} option
3060 * The name of the UCI option to map.
3062 * @param {string} [title]
3063 * The title caption of the option element.
3065 * @param {string} [description]
3066 * The description text of the option element.
3068 var CBIValue
= CBIAbstractValue
.extend(/** @lends LuCI.form.Value.prototype */ {
3069 __name__
: 'CBI.Value',
3072 * If set to `true`, the field is rendered as password input, otherwise
3073 * as plain text input.
3075 * @name LuCI.form.Value.prototype#password
3081 * Set a placeholder string to use when the input field is empty.
3083 * @name LuCI.form.Value.prototype#placeholder
3089 * Add a predefined choice to the form option. By adding one or more
3090 * choices, the plain text input field is turned into a combobox widget
3091 * which prompts the user to select a predefined choice, or to enter a
3094 * @param {string} key
3095 * The choice value to add.
3097 * @param {Node|string} value
3098 * The caption for the choice value. May be a DOM node, a document fragment
3099 * or a plain text string. If omitted, the `key` value is used as caption.
3101 value: function(key
, val
) {
3102 this.keylist
= this.keylist
|| [];
3103 this.keylist
.push(String(key
));
3105 this.vallist
= this.vallist
|| [];
3106 this.vallist
.push(dom
.elem(val
) ? val
: String(val
!= null ? val
: key
));
3110 render: function(option_index
, section_id
, in_table
) {
3111 return Promise
.resolve(this.cfgvalue(section_id
))
3112 .then(this.renderWidget
.bind(this, section_id
, option_index
))
3113 .then(this.renderFrame
.bind(this, section_id
, in_table
, option_index
));
3117 renderFrame: function(section_id
, in_table
, option_index
, nodes
) {
3118 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
3119 depend_list
= this.transformDepList(section_id
),
3123 var title
= this.stripTags(this.title
).trim();
3124 optionEl
= E('div', {
3125 'class': 'td cbi-value-field',
3126 'data-title': (title
!= '') ? title
: null,
3127 'data-description': this.stripTags(this.description
).trim(),
3128 'data-name': this.option
,
3129 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3131 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3132 'data-index': option_index
,
3133 'data-depends': depend_list
,
3134 'data-field': this.cbid(section_id
)
3138 optionEl
= E('div', {
3139 'class': 'cbi-value',
3140 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3141 'data-index': option_index
,
3142 'data-depends': depend_list
,
3143 'data-field': this.cbid(section_id
),
3144 'data-name': this.option
,
3145 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3148 if (this.last_child
)
3149 optionEl
.classList
.add('cbi-value-last');
3151 if (typeof(this.title
) === 'string' && this.title
!== '') {
3152 optionEl
.appendChild(E('label', {
3153 'class': 'cbi-value-title',
3154 'for': 'widget.cbid.%s.%s.%s'.format(config_name
, section_id
, this.option
),
3155 'click': function(ev
) {
3156 var node
= ev
.currentTarget
,
3157 elem
= node
.nextElementSibling
.querySelector('#' + node
.getAttribute('for')) || node
.nextElementSibling
.querySelector('[data-widget-id="' + node
.getAttribute('for') + '"]');
3165 this.titleref
? E('a', {
3166 'class': 'cbi-title-ref',
3167 'href': this.titleref
,
3168 'title': this.titledesc
|| _('Go to relevant configuration page')
3169 }, this.title
) : this.title
));
3171 optionEl
.appendChild(E('div', { 'class': 'cbi-value-field' }));
3176 (optionEl
.lastChild
|| optionEl
).appendChild(nodes
);
3178 if (!in_table
&& typeof(this.description
) === 'string' && this.description
!== '')
3179 dom
.append(optionEl
.lastChild
|| optionEl
,
3180 E('div', { 'class': 'cbi-value-description' }, this.description
));
3182 if (depend_list
&& depend_list
.length
)
3183 optionEl
.classList
.add('hidden');
3185 optionEl
.addEventListener('widget-change',
3186 L
.bind(this.map
.checkDepends
, this.map
));
3188 dom
.bindClassInstance(optionEl
, this);
3194 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3195 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3196 choices
= this.transformChoices(),
3200 var placeholder
= (this.optional
|| this.rmempty
)
3201 ? E('em', _('unspecified')) : _('-- Please choose --');
3203 widget
= new ui
.Combobox(Array
.isArray(value
) ? value
.join(' ') : value
, choices
, {
3204 id
: this.cbid(section_id
),
3206 optional
: this.optional
|| this.rmempty
,
3207 datatype
: this.datatype
,
3208 select_placeholder
: this.placeholder
|| placeholder
,
3209 validate
: L
.bind(this.validate
, this, section_id
),
3210 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3214 widget
= new ui
.Textfield(Array
.isArray(value
) ? value
.join(' ') : value
, {
3215 id
: this.cbid(section_id
),
3216 password
: this.password
,
3217 optional
: this.optional
|| this.rmempty
,
3218 datatype
: this.datatype
,
3219 placeholder
: this.placeholder
,
3220 validate
: L
.bind(this.validate
, this, section_id
),
3221 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3225 return widget
.render();
3230 * @class DynamicList
3231 * @memberof LuCI.form
3232 * @augments LuCI.form.Value
3236 * The `DynamicList` class represents a multi value widget allowing the user
3237 * to enter multiple unique values, optionally selected from a set of
3238 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3240 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3241 * The configuration form this section is added to. It is automatically passed
3242 * by [option()]{@link LuCI.form.AbstractSection#option} or
3243 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3244 * option to the section.
3246 * @param {LuCI.form.AbstractSection} section
3247 * The configuration section this option is added to. It is automatically passed
3248 * by [option()]{@link LuCI.form.AbstractSection#option} or
3249 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3250 * option to the section.
3252 * @param {string} option
3253 * The name of the UCI option to map.
3255 * @param {string} [title]
3256 * The title caption of the option element.
3258 * @param {string} [description]
3259 * The description text of the option element.
3261 var CBIDynamicList
= CBIValue
.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3262 __name__
: 'CBI.DynamicList',
3265 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3266 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3267 choices
= this.transformChoices(),
3268 items
= L
.toArray(value
);
3270 var widget
= new ui
.DynamicList(items
, choices
, {
3271 id
: this.cbid(section_id
),
3273 optional
: this.optional
|| this.rmempty
,
3274 datatype
: this.datatype
,
3275 placeholder
: this.placeholder
,
3276 validate
: L
.bind(this.validate
, this, section_id
),
3277 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3280 return widget
.render();
3286 * @memberof LuCI.form
3287 * @augments LuCI.form.Value
3291 * The `ListValue` class implements a simple static HTML select element
3292 * allowing the user to chose a single value from a set of predefined choices.
3293 * It builds upon the {@link LuCI.ui.Select} widget.
3295 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3296 * The configuration form this section is added to. It is automatically passed
3297 * by [option()]{@link LuCI.form.AbstractSection#option} or
3298 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3299 * option to the section.
3301 * @param {LuCI.form.AbstractSection} section
3302 * The configuration section this option is added to. It is automatically passed
3303 * by [option()]{@link LuCI.form.AbstractSection#option} or
3304 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3305 * option to the section.
3307 * @param {string} option
3308 * The name of the UCI option to map.
3310 * @param {string} [title]
3311 * The title caption of the option element.
3313 * @param {string} [description]
3314 * The description text of the option element.
3316 var CBIListValue
= CBIValue
.extend(/** @lends LuCI.form.ListValue.prototype */ {
3317 __name__
: 'CBI.ListValue',
3319 __init__: function() {
3320 this.super('__init__', arguments
);
3321 this.widget
= 'select';
3322 this.orientation
= 'horizontal';
3327 * Set the size attribute of the underlying HTML select element.
3329 * @name LuCI.form.ListValue.prototype#size
3335 * Set the type of the underlying form controls.
3337 * May be one of `select` or `radio`. If set to `select`, an HTML
3338 * select element is rendered, otherwise a collection of `radio`
3341 * @name LuCI.form.ListValue.prototype#widget
3347 * Set the orientation of the underlying radio or checkbox elements.
3349 * May be one of `horizontal` or `vertical`. Only applies to non-select
3352 * @name LuCI.form.ListValue.prototype#orientation
3354 * @default horizontal
3358 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3359 var choices
= this.transformChoices();
3360 var widget
= new ui
.Select((cfgvalue
!= null) ? cfgvalue
: this.default, choices
, {
3361 id
: this.cbid(section_id
),
3364 widget
: this.widget
,
3365 optional
: this.optional
,
3366 orientation
: this.orientation
,
3367 placeholder
: this.placeholder
,
3368 validate
: L
.bind(this.validate
, this, section_id
),
3369 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3372 return widget
.render();
3378 * @memberof LuCI.form
3379 * @augments LuCI.form.Value
3383 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3384 * implement a simple checkbox element.
3386 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3387 * The configuration form this section is added to. It is automatically passed
3388 * by [option()]{@link LuCI.form.AbstractSection#option} or
3389 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3390 * option to the section.
3392 * @param {LuCI.form.AbstractSection} section
3393 * The configuration section this option is added to. It is automatically passed
3394 * by [option()]{@link LuCI.form.AbstractSection#option} or
3395 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3396 * option to the section.
3398 * @param {string} option
3399 * The name of the UCI option to map.
3401 * @param {string} [title]
3402 * The title caption of the option element.
3404 * @param {string} [description]
3405 * The description text of the option element.
3407 var CBIFlagValue
= CBIValue
.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3408 __name__
: 'CBI.FlagValue',
3410 __init__: function() {
3411 this.super('__init__', arguments
);
3414 this.disabled
= '0';
3415 this.default = this.disabled
;
3419 * Sets the input value to use for the checkbox checked state.
3421 * @name LuCI.form.FlagValue.prototype#enabled
3427 * Sets the input value to use for the checkbox unchecked state.
3429 * @name LuCI.form.FlagValue.prototype#disabled
3435 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3436 var widget
= new ui
.Checkbox((cfgvalue
!= null) ? cfgvalue
: this.default, {
3437 id
: this.cbid(section_id
),
3438 value_enabled
: this.enabled
,
3439 value_disabled
: this.disabled
,
3440 validate
: L
.bind(this.validate
, this, section_id
),
3441 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3444 return widget
.render();
3448 * Query the checked state of the underlying checkbox widget and return
3449 * either the `enabled` or the `disabled` property value, depending on
3450 * the checked state.
3454 formvalue: function(section_id
) {
3455 var elem
= this.getUIElement(section_id
),
3456 checked
= elem
? elem
.isChecked() : false;
3457 return checked
? this.enabled
: this.disabled
;
3461 * Query the checked state of the underlying checkbox widget and return
3462 * either a localized `Yes` or `No` string, depending on the checked state.
3466 textvalue: function(section_id
) {
3467 var cval
= this.cfgvalue(section_id
);
3470 cval
= this.default;
3472 return (cval
== this.enabled
) ? _('Yes') : _('No');
3476 parse: function(section_id
) {
3477 if (this.isActive(section_id
)) {
3478 var fval
= this.formvalue(section_id
);
3480 if (!this.isValid(section_id
)) {
3481 var title
= this.stripTags(this.title
).trim();
3482 return Promise
.reject(new TypeError(_('Option "%s" contains an invalid input value.').format(title
|| this.option
)));
3485 if (fval
== this.default && (this.optional
|| this.rmempty
))
3486 return Promise
.resolve(this.remove(section_id
));
3488 return Promise
.resolve(this.write(section_id
, fval
));
3491 return Promise
.resolve(this.remove(section_id
));
3498 * @memberof LuCI.form
3499 * @augments LuCI.form.DynamicList
3503 * The `MultiValue` class is a modified variant of the `DynamicList` element
3504 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
3505 * select dropdown element.
3507 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3508 * The configuration form this section is added to. It is automatically passed
3509 * by [option()]{@link LuCI.form.AbstractSection#option} or
3510 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3511 * option to the section.
3513 * @param {LuCI.form.AbstractSection} section
3514 * The configuration section this option is added to. It is automatically passed
3515 * by [option()]{@link LuCI.form.AbstractSection#option} or
3516 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3517 * option to the section.
3519 * @param {string} option
3520 * The name of the UCI option to map.
3522 * @param {string} [title]
3523 * The title caption of the option element.
3525 * @param {string} [description]
3526 * The description text of the option element.
3528 var CBIMultiValue
= CBIDynamicList
.extend(/** @lends LuCI.form.MultiValue.prototype */ {
3529 __name__
: 'CBI.MultiValue',
3531 __init__: function() {
3532 this.super('__init__', arguments
);
3533 this.placeholder
= _('-- Please choose --');
3537 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
3538 * property of the underlying dropdown widget. If omitted, the value of
3539 * the `size` property is used or `3` when `size` is unspecified as well.
3541 * @name LuCI.form.MultiValue.prototype#display_size
3547 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
3548 * property of the underlying dropdown widget. If omitted, the value of
3549 * the `size` property is used or `-1` when `size` is unspecified as well.
3551 * @name LuCI.form.MultiValue.prototype#dropdown_size
3557 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3558 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3559 choices
= this.transformChoices();
3561 var widget
= new ui
.Dropdown(L
.toArray(value
), choices
, {
3562 id
: this.cbid(section_id
),
3565 optional
: this.optional
|| this.rmempty
,
3566 select_placeholder
: this.placeholder
,
3567 display_items
: this.display_size
|| this.size
|| 3,
3568 dropdown_items
: this.dropdown_size
|| this.size
|| -1,
3569 validate
: L
.bind(this.validate
, this, section_id
),
3570 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3573 return widget
.render();
3579 * @memberof LuCI.form
3580 * @augments LuCI.form.Value
3584 * The `TextValue` class implements a multi-line textarea input using
3585 * {@link LuCI.ui.Textarea}.
3587 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3588 * The configuration form this section is added to. It is automatically passed
3589 * by [option()]{@link LuCI.form.AbstractSection#option} or
3590 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3591 * option to the section.
3593 * @param {LuCI.form.AbstractSection} section
3594 * The configuration section this option is added to. It is automatically passed
3595 * by [option()]{@link LuCI.form.AbstractSection#option} or
3596 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3597 * option to the section.
3599 * @param {string} option
3600 * The name of the UCI option to map.
3602 * @param {string} [title]
3603 * The title caption of the option element.
3605 * @param {string} [description]
3606 * The description text of the option element.
3608 var CBITextValue
= CBIValue
.extend(/** @lends LuCI.form.TextValue.prototype */ {
3609 __name__
: 'CBI.TextValue',
3615 * Enforces the use of a monospace font for the textarea contents when set
3618 * @name LuCI.form.TextValue.prototype#monospace
3624 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
3625 * property of the underlying textarea widget.
3627 * @name LuCI.form.TextValue.prototype#cols
3633 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
3634 * property of the underlying textarea widget.
3636 * @name LuCI.form.TextValue.prototype#rows
3642 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
3643 * property of the underlying textarea widget.
3645 * @name LuCI.form.TextValue.prototype#wrap
3651 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3652 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default;
3654 var widget
= new ui
.Textarea(value
, {
3655 id
: this.cbid(section_id
),
3656 optional
: this.optional
|| this.rmempty
,
3657 placeholder
: this.placeholder
,
3658 monospace
: this.monospace
,
3662 validate
: L
.bind(this.validate
, this, section_id
),
3663 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3666 return widget
.render();
3672 * @memberof LuCI.form
3673 * @augments LuCI.form.Value
3677 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
3678 * renders the underlying UCI option or default value as readonly text.
3680 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3681 * The configuration form this section is added to. It is automatically passed
3682 * by [option()]{@link LuCI.form.AbstractSection#option} or
3683 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3684 * option to the section.
3686 * @param {LuCI.form.AbstractSection} section
3687 * The configuration section this option is added to. It is automatically passed
3688 * by [option()]{@link LuCI.form.AbstractSection#option} or
3689 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3690 * option to the section.
3692 * @param {string} option
3693 * The name of the UCI option to map.
3695 * @param {string} [title]
3696 * The title caption of the option element.
3698 * @param {string} [description]
3699 * The description text of the option element.
3701 var CBIDummyValue
= CBIValue
.extend(/** @lends LuCI.form.DummyValue.prototype */ {
3702 __name__
: 'CBI.DummyValue',
3705 * Set an URL which is opened when clicking on the dummy value text.
3707 * By setting this property, the dummy value text is wrapped in an `<a>`
3708 * element with the property value used as `href` attribute.
3710 * @name LuCI.form.DummyValue.prototype#href
3716 * Treat the UCI option value (or the `default` property value) as HTML.
3718 * By default, the value text is HTML escaped before being rendered as
3719 * text. In some cases it may be needed to actually interpret and render
3720 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
3722 * @name LuCI.form.DummyValue.prototype#rawhtml
3728 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3729 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3730 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
3731 outputEl
= E('div');
3733 if (this.href
&& !((this.readonly
!= null) ? this.readonly
: this.map
.readonly
))
3734 outputEl
.appendChild(E('a', { 'href': this.href
}));
3736 dom
.append(outputEl
.lastChild
|| outputEl
,
3737 this.rawhtml
? value
: [ value
]);
3746 remove: function() {},
3749 write: function() {}
3753 * @class ButtonValue
3754 * @memberof LuCI.form
3755 * @augments LuCI.form.Value
3759 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
3760 * renders the underlying UCI option or default value as readonly text.
3762 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3763 * The configuration form this section is added to. It is automatically passed
3764 * by [option()]{@link LuCI.form.AbstractSection#option} or
3765 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3766 * option to the section.
3768 * @param {LuCI.form.AbstractSection} section
3769 * The configuration section this option is added to. It is automatically passed
3770 * by [option()]{@link LuCI.form.AbstractSection#option} or
3771 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3772 * option to the section.
3774 * @param {string} option
3775 * The name of the UCI option to map.
3777 * @param {string} [title]
3778 * The title caption of the option element.
3780 * @param {string} [description]
3781 * The description text of the option element.
3783 var CBIButtonValue
= CBIValue
.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
3784 __name__
: 'CBI.ButtonValue',
3787 * Override the rendered button caption.
3789 * By default, the option title - which is passed as fourth argument to the
3790 * constructor - is used as caption for the button element. When setting
3791 * this property to a string, it is used as `String.format()` pattern with
3792 * the underlying UCI section name passed as first format argument. When
3793 * set to a function, it is invoked passing the section ID as sole argument
3794 * and the resulting return value is converted to a string before being
3795 * used as button caption.
3797 * The default is `null`, means the option title is used as caption.
3799 * @name LuCI.form.ButtonValue.prototype#inputtitle
3800 * @type string|function
3805 * Override the button style class.
3807 * By setting this property, a specific `cbi-button-*` CSS class can be
3808 * selected to influence the style of the resulting button.
3810 * Suitable values which are implemented by most themes are `positive`,
3811 * `negative` and `primary`.
3813 * The default is `null`, means a neutral button styling is used.
3815 * @name LuCI.form.ButtonValue.prototype#inputstyle
3821 * Override the button click action.
3823 * By default, the underlying UCI option (or default property) value is
3824 * copied into a hidden field tied to the button element and the save
3825 * action is triggered on the parent form element.
3827 * When this property is set to a function, it is invoked instead of
3828 * performing the default actions. The handler function will receive the
3829 * DOM click element as first and the underlying configuration section ID
3830 * as second argument.
3832 * @name LuCI.form.ButtonValue.prototype#onclick
3838 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3839 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3840 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
3841 outputEl
= E('div'),
3842 btn_title
= this.titleFn('inputtitle', section_id
) || this.titleFn('title', section_id
);
3844 if (value
!== false)
3845 dom
.content(outputEl
, [
3847 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle
|| 'button'),
3848 'click': ui
.createHandlerFn(this, function(section_id
, ev
) {
3850 return this.onclick(ev
, section_id
);
3852 ev
.currentTarget
.parentNode
.nextElementSibling
.value
= value
;
3853 return this.map
.save();
3855 'disabled': ((this.readonly
!= null) ? this.readonly
: this.map
.readonly
) || null
3859 dom
.content(outputEl
, ' - ');
3869 * @class HiddenValue
3870 * @memberof LuCI.form
3871 * @augments LuCI.form.Value
3875 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
3877 * Hidden value widgets used to be necessary in legacy code which actually
3878 * submitted the underlying HTML form the server. With client side handling of
3879 * forms, there are more efficient ways to store hidden state data.
3881 * Since this widget has no visible content, the title and description values
3882 * of this form element should be set to `null` as well to avoid a broken or
3883 * distorted form layout when rendering the option element.
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.
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.
3897 * @param {string} option
3898 * The name of the UCI option to map.
3900 * @param {string} [title]
3901 * The title caption of the option element.
3903 * @param {string} [description]
3904 * The description text of the option element.
3906 var CBIHiddenValue
= CBIValue
.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
3907 __name__
: 'CBI.HiddenValue',
3910 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3911 var widget
= new ui
.Hiddenfield((cfgvalue
!= null) ? cfgvalue
: this.default, {
3912 id
: this.cbid(section_id
)
3915 return widget
.render();
3921 * @memberof LuCI.form
3922 * @augments LuCI.form.Value
3926 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
3927 * offers the ability to browse, upload and select remote files.
3929 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3930 * The configuration form this section is added to. It is automatically passed
3931 * by [option()]{@link LuCI.form.AbstractSection#option} or
3932 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3933 * option to the section.
3935 * @param {LuCI.form.AbstractSection} section
3936 * The configuration section this option is added to. It is automatically passed
3937 * by [option()]{@link LuCI.form.AbstractSection#option} or
3938 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3939 * option to the section.
3941 * @param {string} option
3942 * The name of the UCI option to map.
3944 * @param {string} [title]
3945 * The title caption of the option element.
3947 * @param {string} [description]
3948 * The description text of the option element.
3950 var CBIFileUpload
= CBIValue
.extend(/** @lends LuCI.form.FileUpload.prototype */ {
3951 __name__
: 'CBI.FileSelect',
3953 __init__: function(/* ... */) {
3954 this.super('__init__', arguments
);
3956 this.show_hidden
= false;
3957 this.enable_upload
= true;
3958 this.enable_remove
= true;
3959 this.root_directory
= '/etc/luci-uploads';
3963 * Toggle display of hidden files.
3965 * Display hidden files when rendering the remote directory listing.
3966 * Note that this is merely a cosmetic feature, hidden files are always
3967 * included in received remote file listings.
3969 * The default is `false`, means hidden files are not displayed.
3971 * @name LuCI.form.FileUpload.prototype#show_hidden
3977 * Toggle file upload functionality.
3979 * When set to `true`, the underlying widget provides a button which lets
3980 * the user select and upload local files to the remote system.
3981 * Note that this is merely a cosmetic feature, remote upload access is
3982 * controlled by the session ACL rules.
3984 * The default is `true`, means file upload functionality is displayed.
3986 * @name LuCI.form.FileUpload.prototype#enable_upload
3992 * Toggle remote file delete functionality.
3994 * When set to `true`, the underlying widget provides a buttons which let
3995 * the user delete files from remote directories. Note that this is merely
3996 * a cosmetic feature, remote delete permissions are controlled by the
3997 * session ACL rules.
3999 * The default is `true`, means file removal buttons are displayed.
4001 * @name LuCI.form.FileUpload.prototype#enable_remove
4007 * Specify the root directory for file browsing.
4009 * This property defines the topmost directory the file browser widget may
4010 * navigate to, the UI will not allow browsing directories outside this
4011 * prefix. Note that this is merely a cosmetic feature, remote file access
4012 * and directory listing permissions are controlled by the session ACL
4015 * The default is `/etc/luci-uploads`.
4017 * @name LuCI.form.FileUpload.prototype#root_directory
4019 * @default /etc/luci-uploads
4023 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4024 var browserEl
= new ui
.FileUpload((cfgvalue
!= null) ? cfgvalue
: this.default, {
4025 id
: this.cbid(section_id
),
4026 name
: this.cbid(section_id
),
4027 show_hidden
: this.show_hidden
,
4028 enable_upload
: this.enable_upload
,
4029 enable_remove
: this.enable_remove
,
4030 root_directory
: this.root_directory
,
4031 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4034 return browserEl
.render();
4039 * @class SectionValue
4040 * @memberof LuCI.form
4041 * @augments LuCI.form.Value
4045 * The `SectionValue` widget embeds a form section element within an option
4046 * element container, allowing to nest form sections into other sections.
4048 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4049 * The configuration form this section is added to. It is automatically passed
4050 * by [option()]{@link LuCI.form.AbstractSection#option} or
4051 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4052 * option to the section.
4054 * @param {LuCI.form.AbstractSection} section
4055 * The configuration section this option is added to. It is automatically passed
4056 * by [option()]{@link LuCI.form.AbstractSection#option} or
4057 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4058 * option to the section.
4060 * @param {string} option
4061 * The internal name of the option element holding the section. Since a section
4062 * container element does not read or write any configuration itself, the name
4063 * is only used internally and does not need to relate to any underlying UCI
4066 * @param {LuCI.form.AbstractSection} subsection_class
4067 * The class to use for instantiating the nested section element. Note that
4068 * the class value itself is expected here, not a class instance obtained by
4069 * calling `new`. The given class argument must be a subclass of the
4070 * `AbstractSection` class.
4072 * @param {...*} [class_args]
4073 * All further arguments are passed as-is to the subclass constructor. Refer
4074 * to the corresponding class constructor documentations for details.
4076 var CBISectionValue
= CBIValue
.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4077 __name__
: 'CBI.ContainerValue',
4078 __init__: function(map
, section
, option
, cbiClass
/*, ... */) {
4079 this.super('__init__', [map
, section
, option
]);
4081 if (!CBIAbstractSection
.isSubclass(cbiClass
))
4082 throw 'Sub section must be a descendent of CBIAbstractSection';
4084 this.subsection
= cbiClass
.instantiate(this.varargs(arguments
, 4, this.map
));
4085 this.subsection
.parentoption
= this;
4089 * Access the embedded section instance.
4091 * This property holds a reference to the instantiated nested section.
4093 * @name LuCI.form.SectionValue.prototype#subsection
4094 * @type LuCI.form.AbstractSection
4099 load: function(section_id
) {
4100 return this.subsection
.load();
4104 parse: function(section_id
) {
4105 return this.subsection
.parse();
4109 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4110 return this.subsection
.render();
4114 checkDepends: function(section_id
) {
4115 this.subsection
.checkDepends();
4116 return CBIValue
.prototype.checkDepends
.apply(this, [ section_id
]);
4120 * Since the section container is not rendering an own widget,
4121 * its `value()` implementation is a no-op.
4125 value: function() {},
4128 * Since the section container is not tied to any UCI configuration,
4129 * its `write()` implementation is a no-op.
4133 write: function() {},
4136 * Since the section container is not tied to any UCI configuration,
4137 * its `remove()` implementation is a no-op.
4141 remove: function() {},
4144 * Since the section container is not tied to any UCI configuration,
4145 * its `cfgvalue()` implementation will always return `null`.
4150 cfgvalue: function() { return null },
4153 * Since the section container is not tied to any UCI configuration,
4154 * its `formvalue()` implementation will always return `null`.
4159 formvalue: function() { return null }
4168 * The LuCI form class provides high level abstractions for creating creating
4169 * UCI- or JSON backed configurations forms.
4171 * To import the class in views, use `'require form'`, to import it in
4172 * external JavaScript, use `L.require("form").then(...)`.
4174 * A typical form is created by first constructing a
4175 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4176 * by subsequently adding sections and options to it. Finally
4177 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4178 * assemble the HTML markup and insert it into the DOM.
4188 * m = new form.Map('example', 'Example form',
4189 * 'This is an example form mapping the contents of /etc/config/example');
4191 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4192 * 'This sections maps "config example first_section" of /etc/config/example');
4194 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4196 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4197 * o.value('choice1', 'The first choice');
4198 * o.value('choice2', 'The second choice');
4200 * m.render().then(function(node) {
4201 * document.body.appendChild(node);
4205 return baseclass
.extend(/** @lends LuCI.form.prototype */ {
4207 JSONMap
: CBIJSONMap
,
4208 AbstractSection
: CBIAbstractSection
,
4209 AbstractValue
: CBIAbstractValue
,
4211 TypedSection
: CBITypedSection
,
4212 TableSection
: CBITableSection
,
4213 GridSection
: CBIGridSection
,
4214 NamedSection
: CBINamedSection
,
4217 DynamicList
: CBIDynamicList
,
4218 ListValue
: CBIListValue
,
4220 MultiValue
: CBIMultiValue
,
4221 TextValue
: CBITextValue
,
4222 DummyValue
: CBIDummyValue
,
4223 Button
: CBIButtonValue
,
4224 HiddenValue
: CBIHiddenValue
,
4225 FileUpload
: CBIFileUpload
,
4226 SectionValue
: CBISectionValue