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');
1787 triggerValidation: function(section_id
) {
1788 var elem
= this.getUIElement(section_id
);
1789 return elem
? elem
.triggerValidation() : true;
1793 * Parse the option element input.
1795 * The function is invoked when the `parse()` method has been invoked on
1796 * the parent form and triggers input value reading and validation.
1798 * @param {string} section_id
1799 * The configuration section ID
1801 * @returns {Promise<void>}
1802 * Returns a promise resolving once the input value has been read and
1803 * validated or rejecting in case the input value does not meet the
1804 * validation constraints.
1806 parse: function(section_id
) {
1807 var active
= this.isActive(section_id
),
1808 cval
= this.cfgvalue(section_id
),
1809 fval
= active
? this.formvalue(section_id
) : null;
1811 if (active
&& !this.isValid(section_id
)) {
1812 var title
= this.stripTags(this.title
).trim();
1813 return Promise
.reject(new TypeError(_('Option "%s" contains an invalid input value.').format(title
|| this.option
)));
1816 if (fval
!= '' && fval
!= null) {
1817 if (this.forcewrite
|| !isEqual(cval
, fval
))
1818 return Promise
.resolve(this.write(section_id
, fval
));
1821 if (!active
|| this.rmempty
|| this.optional
) {
1822 return Promise
.resolve(this.remove(section_id
));
1824 else if (!isEqual(cval
, fval
)) {
1825 var title
= this.stripTags(this.title
).trim();
1826 return Promise
.reject(new TypeError(_('Option "%s" must not be empty.').format(title
|| this.option
)));
1830 return Promise
.resolve();
1834 * Write the current input value into the configuration.
1836 * This function is invoked upon saving the parent form when the option
1837 * element is valid and when its input value has been changed compared to
1838 * the initial value returned by
1839 * [cfgvalue()]{@link LuCI.form.AbstractValue#cfgvalue}.
1841 * The default implementation simply sets the given input value in the
1842 * UCI configuration (or the associated JavaScript object property in
1843 * case of `JSONMap` forms). It may be overwritten by user code to
1844 * implement alternative save logic, e.g. to transform the input value
1845 * before it is written.
1847 * @param {string} section_id
1848 * The configuration section ID
1850 * @param {string|string[]} formvalue
1851 * The input value to write.
1853 write: function(section_id
, formvalue
) {
1854 return this.map
.data
.set(
1855 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1856 this.ucisection
|| section_id
,
1857 this.ucioption
|| this.option
,
1862 * Remove the corresponding value from the configuration.
1864 * This function is invoked upon saving the parent form when the option
1865 * element has been hidden due to unsatisfied dependencies or when the
1866 * user cleared the input value and the option is marked optional.
1868 * The default implementation simply removes the associated option from the
1869 * UCI configuration (or the associated JavaScript object property in
1870 * case of `JSONMap` forms). It may be overwritten by user code to
1871 * implement alternative removal logic, e.g. to retain the original value.
1873 * @param {string} section_id
1874 * The configuration section ID
1876 remove: function(section_id
) {
1877 return this.map
.data
.unset(
1878 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1879 this.ucisection
|| section_id
,
1880 this.ucioption
|| this.option
);
1885 * @class TypedSection
1886 * @memberof LuCI.form
1887 * @augments LuCI.form.AbstractSection
1891 * The `TypedSection` class maps all or - if `filter()` is overwritten - a
1892 * subset of the underlying UCI configuration sections of a given type.
1894 * Layout wise, the configuration section instances mapped by the section
1895 * element (sometimes referred to as "section nodes") are stacked beneath
1896 * each other in a single column, with an optional section remove button next
1897 * to each section node and a section add button at the end, depending on the
1898 * value of the `addremove` property.
1900 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
1901 * The configuration form this section is added to. It is automatically passed
1902 * by [section()]{@link LuCI.form.Map#section}.
1904 * @param {string} section_type
1905 * The type of the UCI section to map.
1907 * @param {string} [title]
1908 * The title caption of the form section element.
1910 * @param {string} [description]
1911 * The description text of the form section element.
1913 var CBITypedSection
= CBIAbstractSection
.extend(/** @lends LuCI.form.TypedSection.prototype */ {
1914 __name__
: 'CBI.TypedSection',
1917 * If set to `true`, the user may add or remove instances from the form
1918 * section widget, otherwise only preexisting sections may be edited.
1919 * The default is `false`.
1921 * @name LuCI.form.TypedSection.prototype#addremove
1927 * If set to `true`, mapped section instances are treated as anonymous
1928 * UCI sections, which means that section instance elements will be
1929 * rendered without title element and that no name is required when adding
1930 * new sections. The default is `false`.
1932 * @name LuCI.form.TypedSection.prototype#anonymous
1938 * When set to `true`, instead of rendering section instances one below
1939 * another, treat each instance as separate tab pane and render a tab menu
1940 * at the top of the form section element, allowing the user to switch
1941 * among instances. The default is `false`.
1943 * @name LuCI.form.TypedSection.prototype#tabbed
1949 * Override the caption used for the section add button at the bottom of
1950 * the section form element. If set to a string, it will be used as-is,
1951 * if set to a function, the function will be invoked and its return value
1952 * is used as caption, after converting it to a string. If this property
1953 * is not set, the default is `Add`.
1955 * @name LuCI.form.TypedSection.prototype#addbtntitle
1956 * @type string|function
1961 * Override the UCI configuration name to read the section IDs from. By
1962 * default, the configuration name is inherited from the parent `Map`.
1963 * By setting this property, a deviating configuration may be specified.
1964 * The default is `null`, means inheriting from the parent form.
1966 * @name LuCI.form.TypedSection.prototype#uciconfig
1972 cfgsections: function() {
1973 return this.map
.data
.sections(this.uciconfig
|| this.map
.config
, this.sectiontype
)
1974 .map(function(s
) { return s
['.name'] })
1975 .filter(L
.bind(this.filter
, this));
1979 handleAdd: function(ev
, name
) {
1980 var config_name
= this.uciconfig
|| this.map
.config
;
1982 this.map
.data
.add(config_name
, this.sectiontype
, name
);
1983 return this.map
.save(null, true);
1987 handleRemove: function(section_id
, ev
) {
1988 var config_name
= this.uciconfig
|| this.map
.config
;
1990 this.map
.data
.remove(config_name
, section_id
);
1991 return this.map
.save(null, true);
1995 renderSectionAdd: function(extra_class
) {
1996 if (!this.addremove
)
1999 var createEl
= E('div', { 'class': 'cbi-section-create' }),
2000 config_name
= this.uciconfig
|| this.map
.config
,
2001 btn_title
= this.titleFn('addbtntitle');
2003 if (extra_class
!= null)
2004 createEl
.classList
.add(extra_class
);
2006 if (this.anonymous
) {
2007 createEl
.appendChild(E('button', {
2008 'class': 'cbi-button cbi-button-add',
2009 'title': btn_title
|| _('Add'),
2010 'click': ui
.createHandlerFn(this, 'handleAdd'),
2011 'disabled': this.map
.readonly
|| null
2012 }, [ btn_title
|| _('Add') ]));
2015 var nameEl
= E('input', {
2017 'class': 'cbi-section-create-name',
2018 'disabled': this.map
.readonly
|| null
2021 dom
.append(createEl
, [
2022 E('div', {}, nameEl
),
2024 'class': 'cbi-button cbi-button-add',
2026 'value': btn_title
|| _('Add'),
2027 'title': btn_title
|| _('Add'),
2028 'click': ui
.createHandlerFn(this, function(ev
) {
2029 if (nameEl
.classList
.contains('cbi-input-invalid'))
2032 return this.handleAdd(ev
, nameEl
.value
);
2034 'disabled': this.map
.readonly
|| null
2038 ui
.addValidator(nameEl
, 'uciname', true, 'blur', 'keyup');
2045 renderSectionPlaceholder: function() {
2047 E('em', _('This section contains no values yet')),
2053 renderContents: function(cfgsections
, nodes
) {
2054 var section_id
= null,
2055 config_name
= this.uciconfig
|| this.map
.config
,
2056 sectionEl
= E('div', {
2057 'id': 'cbi-%s-%s'.format(config_name
, this.sectiontype
),
2058 'class': 'cbi-section',
2059 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2060 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2063 if (this.title
!= null && this.title
!= '')
2064 sectionEl
.appendChild(E('legend', {}, this.title
));
2066 if (this.description
!= null && this.description
!= '')
2067 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2069 for (var i
= 0; i
< nodes
.length
; i
++) {
2070 if (this.addremove
) {
2071 sectionEl
.appendChild(
2072 E('div', { 'class': 'cbi-section-remove right' },
2074 'class': 'cbi-button',
2075 'name': 'cbi.rts.%s.%s'.format(config_name
, cfgsections
[i
]),
2076 'data-section-id': cfgsections
[i
],
2077 'click': ui
.createHandlerFn(this, 'handleRemove', cfgsections
[i
]),
2078 'disabled': this.map
.readonly
|| null
2079 }, [ _('Delete') ])));
2082 if (!this.anonymous
)
2083 sectionEl
.appendChild(E('h3', cfgsections
[i
].toUpperCase()));
2085 sectionEl
.appendChild(E('div', {
2086 'id': 'cbi-%s-%s'.format(config_name
, cfgsections
[i
]),
2088 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
2089 'data-section-id': cfgsections
[i
]
2093 if (nodes
.length
== 0)
2094 sectionEl
.appendChild(this.renderSectionPlaceholder());
2096 sectionEl
.appendChild(this.renderSectionAdd());
2098 dom
.bindClassInstance(sectionEl
, this);
2104 render: function() {
2105 var cfgsections
= this.cfgsections(),
2108 for (var i
= 0; i
< cfgsections
.length
; i
++)
2109 renderTasks
.push(this.renderUCISection(cfgsections
[i
]));
2111 return Promise
.all(renderTasks
).then(this.renderContents
.bind(this, cfgsections
));
2116 * @class TableSection
2117 * @memberof LuCI.form
2118 * @augments LuCI.form.TypedSection
2122 * The `TableSection` class maps all or - if `filter()` is overwritten - a
2123 * subset of the underlying UCI configuration sections of a given type.
2125 * Layout wise, the configuration section instances mapped by the section
2126 * element (sometimes referred to as "section nodes") are rendered as rows
2127 * within an HTML table element, with an optional section remove button in the
2128 * last column and a section add button below the table, depending on the
2129 * value of the `addremove` property.
2131 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2132 * The configuration form this section is added to. It is automatically passed
2133 * by [section()]{@link LuCI.form.Map#section}.
2135 * @param {string} section_type
2136 * The type of the UCI section to map.
2138 * @param {string} [title]
2139 * The title caption of the form section element.
2141 * @param {string} [description]
2142 * The description text of the form section element.
2144 var CBITableSection
= CBITypedSection
.extend(/** @lends LuCI.form.TableSection.prototype */ {
2145 __name__
: 'CBI.TableSection',
2148 * If set to `true`, the user may add or remove instances from the form
2149 * section widget, otherwise only preexisting sections may be edited.
2150 * The default is `false`.
2152 * @name LuCI.form.TableSection.prototype#addremove
2158 * If set to `true`, mapped section instances are treated as anonymous
2159 * UCI sections, which means that section instance elements will be
2160 * rendered without title element and that no name is required when adding
2161 * new sections. The default is `false`.
2163 * @name LuCI.form.TableSection.prototype#anonymous
2169 * Override the caption used for the section add button at the bottom of
2170 * the section form element. If set to a string, it will be used as-is,
2171 * if set to a function, the function will be invoked and its return value
2172 * is used as caption, after converting it to a string. If this property
2173 * is not set, the default is `Add`.
2175 * @name LuCI.form.TableSection.prototype#addbtntitle
2176 * @type string|function
2181 * Override the per-section instance title caption shown in the first
2182 * column of the table unless `anonymous` is set to true. If set to a
2183 * string, it will be used as `String.format()` pattern with the name of
2184 * the underlying UCI section as first argument, if set to a function, the
2185 * function will be invoked with the section name as first argument and
2186 * its return value is used as caption, after converting it to a string.
2187 * If this property is not set, the default is the name of the underlying
2188 * UCI configuration section.
2190 * @name LuCI.form.TableSection.prototype#sectiontitle
2191 * @type string|function
2196 * Override the per-section instance modal popup title caption shown when
2197 * clicking the `More…` button in a section specifying `max_cols`. If set
2198 * to a string, it will be used as `String.format()` pattern with the name
2199 * of the underlying UCI section as first argument, if set to a function,
2200 * the function will be invoked with the section name as first argument and
2201 * its return value is used as caption, after converting it to a string.
2202 * If this property is not set, the default is the name of the underlying
2203 * UCI configuration section.
2205 * @name LuCI.form.TableSection.prototype#modaltitle
2206 * @type string|function
2211 * Override the UCI configuration name to read the section IDs from. By
2212 * default, the configuration name is inherited from the parent `Map`.
2213 * By setting this property, a deviating configuration may be specified.
2214 * The default is `null`, means inheriting from the parent form.
2216 * @name LuCI.form.TableSection.prototype#uciconfig
2222 * Specify a maximum amount of columns to display. By default, one table
2223 * column is rendered for each child option of the form section element.
2224 * When this option is set to a positive number, then no more columns than
2225 * the given amount are rendered. When the number of child options exceeds
2226 * the specified amount, a `More…` button is rendered in the last column,
2227 * opening a modal dialog presenting all options elements in `NamedSection`
2228 * style when clicked.
2230 * @name LuCI.form.TableSection.prototype#max_cols
2236 * If set to `true`, alternating `cbi-rowstyle-1` and `cbi-rowstyle-2` CSS
2237 * classes are added to the table row elements. Not all LuCI themes
2238 * implement these row style classes. The default is `false`.
2240 * @name LuCI.form.TableSection.prototype#rowcolors
2246 * Enables a per-section instance row `Edit` button which triggers a certain
2247 * action when clicked. If set to a string, the string value is used
2248 * as `String.format()` pattern with the name of the underlying UCI section
2249 * as first format argument. The result is then interpreted as URL which
2250 * LuCI will navigate to when the user clicks the edit button.
2252 * If set to a function, this function will be registered as click event
2253 * handler on the rendered edit button, receiving the section instance
2254 * name as first and the DOM click event as second argument.
2256 * @name LuCI.form.TableSection.prototype#extedit
2257 * @type string|function
2262 * If set to `true`, a sort button is added to the last column, allowing
2263 * the user to reorder the section instances mapped by the section form
2266 * @name LuCI.form.TableSection.prototype#sortable
2272 * If set to `true`, the header row with the options descriptions will
2273 * not be displayed. By default, descriptions row is automatically displayed
2274 * when at least one option has a description.
2276 * @name LuCI.form.TableSection.prototype#nodescriptions
2282 * The `TableSection` implementation does not support option tabbing, so
2283 * its implementation of `tab()` will always throw an exception when
2287 * @throws Throws an exception when invoked.
2290 throw 'Tabs are not supported by TableSection';
2294 renderContents: function(cfgsections
, nodes
) {
2295 var section_id
= null,
2296 config_name
= this.uciconfig
|| this.map
.config
,
2297 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2298 has_more
= max_cols
< this.children
.length
,
2299 sectionEl
= E('div', {
2300 'id': 'cbi-%s-%s'.format(config_name
, this.sectiontype
),
2301 'class': 'cbi-section cbi-tblsection',
2302 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2303 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2305 tableEl
= E('div', {
2306 'class': 'table cbi-section-table'
2309 if (this.title
!= null && this.title
!= '')
2310 sectionEl
.appendChild(E('h3', {}, this.title
));
2312 if (this.description
!= null && this.description
!= '')
2313 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2315 tableEl
.appendChild(this.renderHeaderRows(max_cols
));
2317 for (var i
= 0; i
< nodes
.length
; i
++) {
2318 var sectionname
= this.titleFn('sectiontitle', cfgsections
[i
]);
2320 if (sectionname
== null)
2321 sectionname
= cfgsections
[i
];
2323 var trEl
= E('div', {
2324 'id': 'cbi-%s-%s'.format(config_name
, cfgsections
[i
]),
2325 'class': 'tr cbi-section-table-row',
2326 'data-sid': cfgsections
[i
],
2327 'draggable': this.sortable
? true : null,
2328 'mousedown': this.sortable
? L
.bind(this.handleDragInit
, this) : null,
2329 'dragstart': this.sortable
? L
.bind(this.handleDragStart
, this) : null,
2330 'dragover': this.sortable
? L
.bind(this.handleDragOver
, this) : null,
2331 'dragenter': this.sortable
? L
.bind(this.handleDragEnter
, this) : null,
2332 'dragleave': this.sortable
? L
.bind(this.handleDragLeave
, this) : null,
2333 'dragend': this.sortable
? L
.bind(this.handleDragEnd
, this) : null,
2334 'drop': this.sortable
? L
.bind(this.handleDrop
, this) : null,
2335 'data-title': (sectionname
&& (!this.anonymous
|| this.sectiontitle
)) ? sectionname
: null,
2336 'data-section-id': cfgsections
[i
]
2339 if (this.extedit
|| this.rowcolors
)
2340 trEl
.classList
.add(!(tableEl
.childNodes
.length
% 2)
2341 ? 'cbi-rowstyle-1' : 'cbi-rowstyle-2');
2343 for (var j
= 0; j
< max_cols
&& nodes
[i
].firstChild
; j
++)
2344 trEl
.appendChild(nodes
[i
].firstChild
);
2346 trEl
.appendChild(this.renderRowActions(cfgsections
[i
], has_more
? _('More…') : null));
2347 tableEl
.appendChild(trEl
);
2350 if (nodes
.length
== 0)
2351 tableEl
.appendChild(E('div', { 'class': 'tr cbi-section-table-row placeholder' },
2352 E('div', { 'class': 'td' },
2353 E('em', {}, _('This section contains no values yet')))));
2355 sectionEl
.appendChild(tableEl
);
2357 sectionEl
.appendChild(this.renderSectionAdd('cbi-tblsection-create'));
2359 dom
.bindClassInstance(sectionEl
, this);
2365 renderHeaderRows: function(max_cols
, has_action
) {
2366 var has_titles
= false,
2367 has_descriptions
= false,
2368 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2369 has_more
= max_cols
< this.children
.length
,
2370 anon_class
= (!this.anonymous
|| this.sectiontitle
) ? 'named' : 'anonymous',
2373 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2377 has_titles
= has_titles
|| !!opt
.title
;
2378 has_descriptions
= has_descriptions
|| !!opt
.description
;
2382 var trEl
= E('div', {
2383 'class': 'tr cbi-section-table-titles ' + anon_class
,
2384 'data-title': (!this.anonymous
|| this.sectiontitle
) ? _('Name') : null
2387 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2391 trEl
.appendChild(E('div', {
2392 'class': 'th cbi-section-table-cell',
2393 'data-widget': opt
.__name__
2396 if (opt
.width
!= null)
2397 trEl
.lastElementChild
.style
.width
=
2398 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2401 trEl
.lastElementChild
.appendChild(E('a', {
2402 'href': opt
.titleref
,
2403 'class': 'cbi-title-ref',
2404 'title': this.titledesc
|| _('Go to relevant configuration page')
2407 dom
.content(trEl
.lastElementChild
, opt
.title
);
2410 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2411 trEl
.appendChild(E('div', {
2412 'class': 'th cbi-section-table-cell cbi-section-actions'
2415 trEls
.appendChild(trEl
);
2418 if (has_descriptions
&& !this.nodescriptions
) {
2419 var trEl
= E('div', {
2420 'class': 'tr cbi-section-table-descr ' + anon_class
2423 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2427 trEl
.appendChild(E('div', {
2428 'class': 'th cbi-section-table-cell',
2429 'data-widget': opt
.__name__
2430 }, opt
.description
));
2432 if (opt
.width
!= null)
2433 trEl
.lastElementChild
.style
.width
=
2434 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2437 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2438 trEl
.appendChild(E('div', {
2439 'class': 'th cbi-section-table-cell cbi-section-actions'
2442 trEls
.appendChild(trEl
);
2449 renderRowActions: function(section_id
, more_label
) {
2450 var config_name
= this.uciconfig
|| this.map
.config
;
2452 if (!this.sortable
&& !this.extedit
&& !this.addremove
&& !more_label
)
2455 var tdEl
= E('div', {
2456 'class': 'td cbi-section-table-cell nowrap cbi-section-actions'
2459 if (this.sortable
) {
2460 dom
.append(tdEl
.lastElementChild
, [
2462 'title': _('Drag to reorder'),
2463 'class': 'btn cbi-button drag-handle center',
2464 'style': 'cursor:move',
2465 'disabled': this.map
.readonly
|| null
2473 if (typeof(this.extedit
) == 'function')
2474 evFn
= L
.bind(this.extedit
, this);
2475 else if (typeof(this.extedit
) == 'string')
2476 evFn
= L
.bind(function(sid
, ev
) {
2477 location
.href
= this.extedit
.format(sid
);
2478 }, this, section_id
);
2480 dom
.append(tdEl
.lastElementChild
,
2483 'class': 'cbi-button cbi-button-edit',
2490 dom
.append(tdEl
.lastElementChild
,
2492 'title': more_label
,
2493 'class': 'cbi-button cbi-button-edit',
2494 'click': ui
.createHandlerFn(this, 'renderMoreOptionsModal', section_id
)
2499 if (this.addremove
) {
2500 var btn_title
= this.titleFn('removebtntitle', section_id
);
2502 dom
.append(tdEl
.lastElementChild
,
2504 'title': btn_title
|| _('Delete'),
2505 'class': 'cbi-button cbi-button-remove',
2506 'click': ui
.createHandlerFn(this, 'handleRemove', section_id
),
2507 'disabled': this.map
.readonly
|| null
2508 }, [ btn_title
|| _('Delete') ])
2516 handleDragInit: function(ev
) {
2517 scope
.dragState
= { node
: ev
.target
};
2521 handleDragStart: function(ev
) {
2522 if (!scope
.dragState
|| !scope
.dragState
.node
.classList
.contains('drag-handle')) {
2523 scope
.dragState
= null;
2524 ev
.preventDefault();
2528 scope
.dragState
.node
= dom
.parent(scope
.dragState
.node
, '.tr');
2529 ev
.dataTransfer
.setData('text', 'drag');
2530 ev
.target
.style
.opacity
= 0.4;
2534 handleDragOver: function(ev
) {
2535 var n
= scope
.dragState
.targetNode
,
2536 r
= scope
.dragState
.rect
,
2537 t
= r
.top
+ r
.height
/ 2;
2539 if (ev
.clientY
<= t
) {
2540 n
.classList
.remove('drag-over-below');
2541 n
.classList
.add('drag-over-above');
2544 n
.classList
.remove('drag-over-above');
2545 n
.classList
.add('drag-over-below');
2548 ev
.dataTransfer
.dropEffect
= 'move';
2549 ev
.preventDefault();
2554 handleDragEnter: function(ev
) {
2555 scope
.dragState
.rect
= ev
.currentTarget
.getBoundingClientRect();
2556 scope
.dragState
.targetNode
= ev
.currentTarget
;
2560 handleDragLeave: function(ev
) {
2561 ev
.currentTarget
.classList
.remove('drag-over-above');
2562 ev
.currentTarget
.classList
.remove('drag-over-below');
2566 handleDragEnd: function(ev
) {
2569 n
.style
.opacity
= '';
2570 n
.classList
.add('flash');
2571 n
.parentNode
.querySelectorAll('.drag-over-above, .drag-over-below')
2572 .forEach(function(tr
) {
2573 tr
.classList
.remove('drag-over-above');
2574 tr
.classList
.remove('drag-over-below');
2579 handleDrop: function(ev
) {
2580 var s
= scope
.dragState
;
2582 if (s
.node
&& s
.targetNode
) {
2583 var config_name
= this.uciconfig
|| this.map
.config
,
2584 ref_node
= s
.targetNode
,
2587 if (ref_node
.classList
.contains('drag-over-below')) {
2588 ref_node
= ref_node
.nextElementSibling
;
2592 var sid1
= s
.node
.getAttribute('data-sid'),
2593 sid2
= s
.targetNode
.getAttribute('data-sid');
2595 s
.node
.parentNode
.insertBefore(s
.node
, ref_node
);
2596 this.map
.data
.move(config_name
, sid1
, sid2
, after
);
2599 scope
.dragState
= null;
2600 ev
.target
.style
.opacity
= '';
2601 ev
.stopPropagation();
2602 ev
.preventDefault();
2607 handleModalCancel: function(modalMap
, ev
) {
2608 return Promise
.resolve(ui
.hideModal());
2612 handleModalSave: function(modalMap
, ev
) {
2613 return modalMap
.save()
2614 .then(L
.bind(this.map
.load
, this.map
))
2615 .then(L
.bind(this.map
.reset
, this.map
))
2617 .catch(function() {});
2621 * Add further options to the per-section instanced modal popup.
2623 * This function may be overwritten by user code to perform additional
2624 * setup steps before displaying the more options modal which is useful to
2625 * e.g. query additional data or to inject further option elements.
2627 * The default implementation of this function does nothing.
2630 * @param {LuCI.form.NamedSection} modalSection
2631 * The `NamedSection` instance about to be rendered in the modal popup.
2633 * @param {string} section_id
2634 * The ID of the underlying UCI section the modal popup belongs to.
2637 * The DOM event emitted by clicking the `More…` button.
2639 * @returns {*|Promise<*>}
2640 * Return values of this function are ignored but if a promise is returned,
2641 * it is run to completion before the rendering is continued, allowing
2642 * custom logic to perform asynchroneous work before the modal dialog
2645 addModalOptions: function(modalSection
, section_id
, ev
) {
2650 renderMoreOptionsModal: function(section_id
, ev
) {
2651 var parent
= this.map
,
2652 title
= parent
.title
,
2654 m
= new CBIMap(this.map
.config
, null, null),
2655 s
= m
.section(CBINamedSection
, section_id
, this.sectiontype
);
2658 m
.readonly
= parent
.readonly
;
2661 s
.tab_names
= this.tab_names
;
2663 if ((name
= this.titleFn('modaltitle', section_id
)) != null)
2665 else if ((name
= this.titleFn('sectiontitle', section_id
)) != null)
2666 title
= '%s - %s'.format(parent
.title
, name
);
2667 else if (!this.anonymous
)
2668 title
= '%s - %s'.format(parent
.title
, section_id
);
2670 for (var i
= 0; i
< this.children
.length
; i
++) {
2671 var o1
= this.children
[i
];
2673 if (o1
.modalonly
=== false)
2676 var o2
= s
.option(o1
.constructor, o1
.option
, o1
.title
, o1
.description
);
2679 if (!o1
.hasOwnProperty(k
))
2696 return Promise
.resolve(this.addModalOptions(s
, section_id
, ev
)).then(L
.bind(m
.render
, m
)).then(L
.bind(function(nodes
) {
2697 ui
.showModal(title
, [
2699 E('div', { 'class': 'right' }, [
2702 'click': ui
.createHandlerFn(this, 'handleModalCancel', m
)
2703 }, [ _('Dismiss') ]), ' ',
2705 'class': 'cbi-button cbi-button-positive important',
2706 'click': ui
.createHandlerFn(this, 'handleModalSave', m
),
2707 'disabled': m
.readonly
|| null
2711 }, this)).catch(L
.error
);
2716 * @class GridSection
2717 * @memberof LuCI.form
2718 * @augments LuCI.form.TableSection
2722 * The `GridSection` class maps all or - if `filter()` is overwritten - a
2723 * subset of the underlying UCI configuration sections of a given type.
2725 * A grid section functions similar to a {@link LuCI.form.TableSection} but
2726 * supports tabbing in the modal overlay. Option elements added with
2727 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
2728 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
2729 * are displayed in the modal popup.
2731 * Another important difference is that the table cells show a readonly text
2732 * preview of the corresponding option elements by default, unless the child
2733 * option element is explicitely made writable by setting the `editable`
2734 * property to `true`.
2736 * Additionally, the grid section honours a `modalonly` property of child
2737 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
2738 * documentation for details.
2740 * Layout wise, a grid section looks mostly identical to table sections.
2742 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2743 * The configuration form this section is added to. It is automatically passed
2744 * by [section()]{@link LuCI.form.Map#section}.
2746 * @param {string} section_type
2747 * The type of the UCI section to map.
2749 * @param {string} [title]
2750 * The title caption of the form section element.
2752 * @param {string} [description]
2753 * The description text of the form section element.
2755 var CBIGridSection
= CBITableSection
.extend(/** @lends LuCI.form.GridSection.prototype */ {
2757 * Add an option tab to the section.
2759 * The modal option elements of a grid section may be divided into multiple
2760 * tabs to provide a better overview to the user.
2762 * Before options can be moved into a tab pane, the corresponding tab
2763 * has to be defined first, which is done by calling this function.
2765 * Note that tabs are only effective in modal popups, options added with
2766 * `option()` will not be assigned to a specific tab and are rendered in
2767 * the table view only.
2769 * @param {string} name
2770 * The name of the tab to register. It may be freely chosen and just serves
2771 * as an identifier to differentiate tabs.
2773 * @param {string} title
2774 * The human readable caption of the tab.
2776 * @param {string} [description]
2777 * An additional description text for the corresponding tab pane. It is
2778 * displayed as text paragraph below the tab but before the tab pane
2779 * contents. If omitted, no description will be rendered.
2782 * Throws an exeption if a tab with the same `name` already exists.
2784 tab: function(name
, title
, description
) {
2785 CBIAbstractSection
.prototype.tab
.call(this, name
, title
, description
);
2789 handleAdd: function(ev
, name
) {
2790 var config_name
= this.uciconfig
|| this.map
.config
,
2791 section_id
= this.map
.data
.add(config_name
, this.sectiontype
, name
);
2793 this.addedSection
= section_id
;
2794 return this.renderMoreOptionsModal(section_id
);
2798 handleModalSave: function(/* ... */) {
2799 return this.super('handleModalSave', arguments
)
2800 .then(L
.bind(function() { this.addedSection
= null }, this));
2804 handleModalCancel: function(/* ... */) {
2805 var config_name
= this.uciconfig
|| this.map
.config
;
2807 if (this.addedSection
!= null) {
2808 this.map
.data
.remove(config_name
, this.addedSection
);
2809 this.addedSection
= null;
2812 return this.super('handleModalCancel', arguments
);
2816 renderUCISection: function(section_id
) {
2817 return this.renderOptions(null, section_id
);
2821 renderChildren: function(tab_name
, section_id
, in_table
) {
2822 var tasks
= [], index
= 0;
2824 for (var i
= 0, opt
; (opt
= this.children
[i
]) != null; i
++) {
2825 if (opt
.disable
|| opt
.modalonly
)
2829 tasks
.push(opt
.render(index
++, section_id
, in_table
));
2831 tasks
.push(this.renderTextValue(section_id
, opt
));
2834 return Promise
.all(tasks
);
2838 renderTextValue: function(section_id
, opt
) {
2839 var title
= this.stripTags(opt
.title
).trim(),
2840 descr
= this.stripTags(opt
.description
).trim(),
2841 value
= opt
.textvalue(section_id
);
2844 'class': 'td cbi-value-field',
2845 'data-title': (title
!= '') ? title
: null,
2846 'data-description': (descr
!= '') ? descr
: null,
2847 'data-name': opt
.option
,
2848 'data-widget': opt
.typename
|| opt
.__name__
2849 }, (value
!= null) ? value
: E('em', _('none')));
2853 renderHeaderRows: function(section_id
) {
2854 return this.super('renderHeaderRows', [ NaN
, true ]);
2858 renderRowActions: function(section_id
) {
2859 return this.super('renderRowActions', [ section_id
, _('Edit') ]);
2864 var section_ids
= this.cfgsections(),
2867 if (Array
.isArray(this.children
)) {
2868 for (var i
= 0; i
< section_ids
.length
; i
++) {
2869 for (var j
= 0; j
< this.children
.length
; j
++) {
2870 if (!this.children
[j
].editable
|| this.children
[j
].modalonly
)
2873 tasks
.push(this.children
[j
].parse(section_ids
[i
]));
2878 return Promise
.all(tasks
);
2883 * @class NamedSection
2884 * @memberof LuCI.form
2885 * @augments LuCI.form.AbstractSection
2889 * The `NamedSection` class maps exactly one UCI section instance which is
2890 * specified when constructing the class instance.
2892 * Layout and functionality wise, a named section is essentially a
2893 * `TypedSection` which allows exactly one section node.
2895 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2896 * The configuration form this section is added to. It is automatically passed
2897 * by [section()]{@link LuCI.form.Map#section}.
2899 * @param {string} section_id
2900 * The name (ID) of the UCI section to map.
2902 * @param {string} section_type
2903 * The type of the UCI section to map.
2905 * @param {string} [title]
2906 * The title caption of the form section element.
2908 * @param {string} [description]
2909 * The description text of the form section element.
2911 var CBINamedSection
= CBIAbstractSection
.extend(/** @lends LuCI.form.NamedSection.prototype */ {
2912 __name__
: 'CBI.NamedSection',
2913 __init__: function(map
, section_id
/*, ... */) {
2914 this.super('__init__', this.varargs(arguments
, 2, map
));
2916 this.section
= section_id
;
2920 * If set to `true`, the user may remove or recreate the sole mapped
2921 * configuration instance from the form section widget, otherwise only a
2922 * preexisting section may be edited. The default is `false`.
2924 * @name LuCI.form.NamedSection.prototype#addremove
2930 * Override the UCI configuration name to read the section IDs from. By
2931 * default, the configuration name is inherited from the parent `Map`.
2932 * By setting this property, a deviating configuration may be specified.
2933 * The default is `null`, means inheriting from the parent form.
2935 * @name LuCI.form.NamedSection.prototype#uciconfig
2941 * The `NamedSection` class overwrites the generic `cfgsections()`
2942 * implementation to return a one-element array containing the mapped
2943 * section ID as sole element. User code should not normally change this.
2945 * @returns {string[]}
2946 * Returns a one-element array containing the mapped section ID.
2948 cfgsections: function() {
2949 return [ this.section
];
2953 handleAdd: function(ev
) {
2954 var section_id
= this.section
,
2955 config_name
= this.uciconfig
|| this.map
.config
;
2957 this.map
.data
.add(config_name
, this.sectiontype
, section_id
);
2958 return this.map
.save(null, true);
2962 handleRemove: function(ev
) {
2963 var section_id
= this.section
,
2964 config_name
= this.uciconfig
|| this.map
.config
;
2966 this.map
.data
.remove(config_name
, section_id
);
2967 return this.map
.save(null, true);
2971 renderContents: function(data
) {
2972 var ucidata
= data
[0], nodes
= data
[1],
2973 section_id
= this.section
,
2974 config_name
= this.uciconfig
|| this.map
.config
,
2975 sectionEl
= E('div', {
2976 'id': ucidata
? null : 'cbi-%s-%s'.format(config_name
, section_id
),
2977 'class': 'cbi-section',
2978 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2979 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2982 if (typeof(this.title
) === 'string' && this.title
!== '')
2983 sectionEl
.appendChild(E('legend', {}, this.title
));
2985 if (typeof(this.description
) === 'string' && this.description
!== '')
2986 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2989 if (this.addremove
) {
2990 sectionEl
.appendChild(
2991 E('div', { 'class': 'cbi-section-remove right' },
2993 'class': 'cbi-button',
2994 'click': ui
.createHandlerFn(this, 'handleRemove'),
2995 'disabled': this.map
.readonly
|| null
2996 }, [ _('Delete') ])));
2999 sectionEl
.appendChild(E('div', {
3000 'id': 'cbi-%s-%s'.format(config_name
, section_id
),
3002 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3003 'data-section-id': section_id
3006 else if (this.addremove
) {
3007 sectionEl
.appendChild(
3009 'class': 'cbi-button cbi-button-add',
3010 'click': ui
.createHandlerFn(this, 'handleAdd'),
3011 'disabled': this.map
.readonly
|| null
3015 dom
.bindClassInstance(sectionEl
, this);
3021 render: function() {
3022 var config_name
= this.uciconfig
|| this.map
.config
,
3023 section_id
= this.section
;
3025 return Promise
.all([
3026 this.map
.data
.get(config_name
, section_id
),
3027 this.renderUCISection(section_id
)
3028 ]).then(this.renderContents
.bind(this));
3034 * @memberof LuCI.form
3035 * @augments LuCI.form.AbstractValue
3039 * The `Value` class represents a simple one-line form input using the
3040 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3041 * {@link LuCI.ui.Combobox} class as underlying widget.
3043 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3044 * The configuration form this section is added to. It is automatically passed
3045 * by [option()]{@link LuCI.form.AbstractSection#option} or
3046 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3047 * option to the section.
3049 * @param {LuCI.form.AbstractSection} section
3050 * The configuration section this option is added to. It is automatically passed
3051 * by [option()]{@link LuCI.form.AbstractSection#option} or
3052 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3053 * option to the section.
3055 * @param {string} option
3056 * The name of the UCI option to map.
3058 * @param {string} [title]
3059 * The title caption of the option element.
3061 * @param {string} [description]
3062 * The description text of the option element.
3064 var CBIValue
= CBIAbstractValue
.extend(/** @lends LuCI.form.Value.prototype */ {
3065 __name__
: 'CBI.Value',
3068 * If set to `true`, the field is rendered as password input, otherwise
3069 * as plain text input.
3071 * @name LuCI.form.Value.prototype#password
3077 * Set a placeholder string to use when the input field is empty.
3079 * @name LuCI.form.Value.prototype#placeholder
3085 * Add a predefined choice to the form option. By adding one or more
3086 * choices, the plain text input field is turned into a combobox widget
3087 * which prompts the user to select a predefined choice, or to enter a
3090 * @param {string} key
3091 * The choice value to add.
3093 * @param {Node|string} value
3094 * The caption for the choice value. May be a DOM node, a document fragment
3095 * or a plain text string. If omitted, the `key` value is used as caption.
3097 value: function(key
, val
) {
3098 this.keylist
= this.keylist
|| [];
3099 this.keylist
.push(String(key
));
3101 this.vallist
= this.vallist
|| [];
3102 this.vallist
.push(dom
.elem(val
) ? val
: String(val
!= null ? val
: key
));
3106 render: function(option_index
, section_id
, in_table
) {
3107 return Promise
.resolve(this.cfgvalue(section_id
))
3108 .then(this.renderWidget
.bind(this, section_id
, option_index
))
3109 .then(this.renderFrame
.bind(this, section_id
, in_table
, option_index
));
3113 renderFrame: function(section_id
, in_table
, option_index
, nodes
) {
3114 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
3115 depend_list
= this.transformDepList(section_id
),
3119 var title
= this.stripTags(this.title
).trim();
3120 optionEl
= E('div', {
3121 'class': 'td cbi-value-field',
3122 'data-title': (title
!= '') ? title
: null,
3123 'data-description': this.stripTags(this.description
).trim(),
3124 'data-name': this.option
,
3125 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3127 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3128 'data-index': option_index
,
3129 'data-depends': depend_list
,
3130 'data-field': this.cbid(section_id
)
3134 optionEl
= E('div', {
3135 'class': 'cbi-value',
3136 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3137 'data-index': option_index
,
3138 'data-depends': depend_list
,
3139 'data-field': this.cbid(section_id
),
3140 'data-name': this.option
,
3141 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3144 if (this.last_child
)
3145 optionEl
.classList
.add('cbi-value-last');
3147 if (typeof(this.title
) === 'string' && this.title
!== '') {
3148 optionEl
.appendChild(E('label', {
3149 'class': 'cbi-value-title',
3150 'for': 'widget.cbid.%s.%s.%s'.format(config_name
, section_id
, this.option
),
3151 'click': function(ev
) {
3152 var node
= ev
.currentTarget
,
3153 elem
= node
.nextElementSibling
.querySelector('#' + node
.getAttribute('for')) || node
.nextElementSibling
.querySelector('[data-widget-id="' + node
.getAttribute('for') + '"]');
3161 this.titleref
? E('a', {
3162 'class': 'cbi-title-ref',
3163 'href': this.titleref
,
3164 'title': this.titledesc
|| _('Go to relevant configuration page')
3165 }, this.title
) : this.title
));
3167 optionEl
.appendChild(E('div', { 'class': 'cbi-value-field' }));
3172 (optionEl
.lastChild
|| optionEl
).appendChild(nodes
);
3174 if (!in_table
&& typeof(this.description
) === 'string' && this.description
!== '')
3175 dom
.append(optionEl
.lastChild
|| optionEl
,
3176 E('div', { 'class': 'cbi-value-description' }, this.description
));
3178 if (depend_list
&& depend_list
.length
)
3179 optionEl
.classList
.add('hidden');
3181 optionEl
.addEventListener('widget-change',
3182 L
.bind(this.map
.checkDepends
, this.map
));
3184 dom
.bindClassInstance(optionEl
, this);
3190 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3191 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3192 choices
= this.transformChoices(),
3196 var placeholder
= (this.optional
|| this.rmempty
)
3197 ? E('em', _('unspecified')) : _('-- Please choose --');
3199 widget
= new ui
.Combobox(Array
.isArray(value
) ? value
.join(' ') : value
, choices
, {
3200 id
: this.cbid(section_id
),
3202 optional
: this.optional
|| this.rmempty
,
3203 datatype
: this.datatype
,
3204 select_placeholder
: this.placeholder
|| placeholder
,
3205 validate
: L
.bind(this.validate
, this, section_id
),
3206 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3210 widget
= new ui
.Textfield(Array
.isArray(value
) ? value
.join(' ') : value
, {
3211 id
: this.cbid(section_id
),
3212 password
: this.password
,
3213 optional
: this.optional
|| this.rmempty
,
3214 datatype
: this.datatype
,
3215 placeholder
: this.placeholder
,
3216 validate
: L
.bind(this.validate
, this, section_id
),
3217 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3221 return widget
.render();
3226 * @class DynamicList
3227 * @memberof LuCI.form
3228 * @augments LuCI.form.Value
3232 * The `DynamicList` class represents a multi value widget allowing the user
3233 * to enter multiple unique values, optionally selected from a set of
3234 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3236 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3237 * The configuration form this section is added to. It is automatically passed
3238 * by [option()]{@link LuCI.form.AbstractSection#option} or
3239 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3240 * option to the section.
3242 * @param {LuCI.form.AbstractSection} section
3243 * The configuration section this option is added to. It is automatically passed
3244 * by [option()]{@link LuCI.form.AbstractSection#option} or
3245 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3246 * option to the section.
3248 * @param {string} option
3249 * The name of the UCI option to map.
3251 * @param {string} [title]
3252 * The title caption of the option element.
3254 * @param {string} [description]
3255 * The description text of the option element.
3257 var CBIDynamicList
= CBIValue
.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3258 __name__
: 'CBI.DynamicList',
3261 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3262 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3263 choices
= this.transformChoices(),
3264 items
= L
.toArray(value
);
3266 var widget
= new ui
.DynamicList(items
, choices
, {
3267 id
: this.cbid(section_id
),
3269 optional
: this.optional
|| this.rmempty
,
3270 datatype
: this.datatype
,
3271 placeholder
: this.placeholder
,
3272 validate
: L
.bind(this.validate
, this, section_id
),
3273 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3276 return widget
.render();
3282 * @memberof LuCI.form
3283 * @augments LuCI.form.Value
3287 * The `ListValue` class implements a simple static HTML select element
3288 * allowing the user to chose a single value from a set of predefined choices.
3289 * It builds upon the {@link LuCI.ui.Select} widget.
3291 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3292 * The configuration form this section is added to. It is automatically passed
3293 * by [option()]{@link LuCI.form.AbstractSection#option} or
3294 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3295 * option to the section.
3297 * @param {LuCI.form.AbstractSection} section
3298 * The configuration section this option is added to. It is automatically passed
3299 * by [option()]{@link LuCI.form.AbstractSection#option} or
3300 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3301 * option to the section.
3303 * @param {string} option
3304 * The name of the UCI option to map.
3306 * @param {string} [title]
3307 * The title caption of the option element.
3309 * @param {string} [description]
3310 * The description text of the option element.
3312 var CBIListValue
= CBIValue
.extend(/** @lends LuCI.form.ListValue.prototype */ {
3313 __name__
: 'CBI.ListValue',
3315 __init__: function() {
3316 this.super('__init__', arguments
);
3317 this.widget
= 'select';
3318 this.orientation
= 'horizontal';
3323 * Set the size attribute of the underlying HTML select element.
3325 * @name LuCI.form.ListValue.prototype#size
3331 * Set the type of the underlying form controls.
3333 * May be one of `select` or `radio`. If set to `select`, an HTML
3334 * select element is rendered, otherwise a collection of `radio`
3337 * @name LuCI.form.ListValue.prototype#widget
3343 * Set the orientation of the underlying radio or checkbox elements.
3345 * May be one of `horizontal` or `vertical`. Only applies to non-select
3348 * @name LuCI.form.ListValue.prototype#orientation
3350 * @default horizontal
3354 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3355 var choices
= this.transformChoices();
3356 var widget
= new ui
.Select((cfgvalue
!= null) ? cfgvalue
: this.default, choices
, {
3357 id
: this.cbid(section_id
),
3360 widget
: this.widget
,
3361 optional
: this.optional
,
3362 orientation
: this.orientation
,
3363 placeholder
: this.placeholder
,
3364 validate
: L
.bind(this.validate
, this, section_id
),
3365 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3368 return widget
.render();
3374 * @memberof LuCI.form
3375 * @augments LuCI.form.Value
3379 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3380 * implement a simple checkbox element.
3382 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3383 * The configuration form this section is added to. It is automatically passed
3384 * by [option()]{@link LuCI.form.AbstractSection#option} or
3385 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3386 * option to the section.
3388 * @param {LuCI.form.AbstractSection} section
3389 * The configuration section this option is added to. It is automatically passed
3390 * by [option()]{@link LuCI.form.AbstractSection#option} or
3391 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3392 * option to the section.
3394 * @param {string} option
3395 * The name of the UCI option to map.
3397 * @param {string} [title]
3398 * The title caption of the option element.
3400 * @param {string} [description]
3401 * The description text of the option element.
3403 var CBIFlagValue
= CBIValue
.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3404 __name__
: 'CBI.FlagValue',
3406 __init__: function() {
3407 this.super('__init__', arguments
);
3410 this.disabled
= '0';
3411 this.default = this.disabled
;
3415 * Sets the input value to use for the checkbox checked state.
3417 * @name LuCI.form.FlagValue.prototype#enabled
3423 * Sets the input value to use for the checkbox unchecked state.
3425 * @name LuCI.form.FlagValue.prototype#disabled
3431 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3432 var widget
= new ui
.Checkbox((cfgvalue
!= null) ? cfgvalue
: this.default, {
3433 id
: this.cbid(section_id
),
3434 value_enabled
: this.enabled
,
3435 value_disabled
: this.disabled
,
3436 validate
: L
.bind(this.validate
, this, section_id
),
3437 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3440 return widget
.render();
3444 * Query the checked state of the underlying checkbox widget and return
3445 * either the `enabled` or the `disabled` property value, depending on
3446 * the checked state.
3450 formvalue: function(section_id
) {
3451 var elem
= this.getUIElement(section_id
),
3452 checked
= elem
? elem
.isChecked() : false;
3453 return checked
? this.enabled
: this.disabled
;
3457 * Query the checked state of the underlying checkbox widget and return
3458 * either a localized `Yes` or `No` string, depending on the checked state.
3462 textvalue: function(section_id
) {
3463 var cval
= this.cfgvalue(section_id
);
3466 cval
= this.default;
3468 return (cval
== this.enabled
) ? _('Yes') : _('No');
3472 parse: function(section_id
) {
3473 if (this.isActive(section_id
)) {
3474 var fval
= this.formvalue(section_id
);
3476 if (!this.isValid(section_id
)) {
3477 var title
= this.stripTags(this.title
).trim();
3478 return Promise
.reject(new TypeError(_('Option "%s" contains an invalid input value.').format(title
|| this.option
)));
3481 if (fval
== this.default && (this.optional
|| this.rmempty
))
3482 return Promise
.resolve(this.remove(section_id
));
3484 return Promise
.resolve(this.write(section_id
, fval
));
3487 return Promise
.resolve(this.remove(section_id
));
3494 * @memberof LuCI.form
3495 * @augments LuCI.form.DynamicList
3499 * The `MultiValue` class is a modified variant of the `DynamicList` element
3500 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
3501 * select dropdown element.
3503 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3504 * The configuration form this section is added to. It is automatically passed
3505 * by [option()]{@link LuCI.form.AbstractSection#option} or
3506 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3507 * option to the section.
3509 * @param {LuCI.form.AbstractSection} section
3510 * The configuration section this option is added to. It is automatically passed
3511 * by [option()]{@link LuCI.form.AbstractSection#option} or
3512 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3513 * option to the section.
3515 * @param {string} option
3516 * The name of the UCI option to map.
3518 * @param {string} [title]
3519 * The title caption of the option element.
3521 * @param {string} [description]
3522 * The description text of the option element.
3524 var CBIMultiValue
= CBIDynamicList
.extend(/** @lends LuCI.form.MultiValue.prototype */ {
3525 __name__
: 'CBI.MultiValue',
3527 __init__: function() {
3528 this.super('__init__', arguments
);
3529 this.placeholder
= _('-- Please choose --');
3533 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
3534 * property of the underlying dropdown widget. If omitted, the value of
3535 * the `size` property is used or `3` when `size` is unspecified as well.
3537 * @name LuCI.form.MultiValue.prototype#display_size
3543 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
3544 * property of the underlying dropdown widget. If omitted, the value of
3545 * the `size` property is used or `-1` when `size` is unspecified as well.
3547 * @name LuCI.form.MultiValue.prototype#dropdown_size
3553 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3554 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3555 choices
= this.transformChoices();
3557 var widget
= new ui
.Dropdown(L
.toArray(value
), choices
, {
3558 id
: this.cbid(section_id
),
3561 optional
: this.optional
|| this.rmempty
,
3562 select_placeholder
: this.placeholder
,
3563 display_items
: this.display_size
|| this.size
|| 3,
3564 dropdown_items
: this.dropdown_size
|| this.size
|| -1,
3565 validate
: L
.bind(this.validate
, this, section_id
),
3566 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3569 return widget
.render();
3575 * @memberof LuCI.form
3576 * @augments LuCI.form.Value
3580 * The `TextValue` class implements a multi-line textarea input using
3581 * {@link LuCI.ui.Textarea}.
3583 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3584 * The configuration form this section is added to. It is automatically passed
3585 * by [option()]{@link LuCI.form.AbstractSection#option} or
3586 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3587 * option to the section.
3589 * @param {LuCI.form.AbstractSection} section
3590 * The configuration section this option is added to. It is automatically passed
3591 * by [option()]{@link LuCI.form.AbstractSection#option} or
3592 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3593 * option to the section.
3595 * @param {string} option
3596 * The name of the UCI option to map.
3598 * @param {string} [title]
3599 * The title caption of the option element.
3601 * @param {string} [description]
3602 * The description text of the option element.
3604 var CBITextValue
= CBIValue
.extend(/** @lends LuCI.form.TextValue.prototype */ {
3605 __name__
: 'CBI.TextValue',
3611 * Enforces the use of a monospace font for the textarea contents when set
3614 * @name LuCI.form.TextValue.prototype#monospace
3620 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
3621 * property of the underlying textarea widget.
3623 * @name LuCI.form.TextValue.prototype#cols
3629 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
3630 * property of the underlying textarea widget.
3632 * @name LuCI.form.TextValue.prototype#rows
3638 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
3639 * property of the underlying textarea widget.
3641 * @name LuCI.form.TextValue.prototype#wrap
3647 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3648 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default;
3650 var widget
= new ui
.Textarea(value
, {
3651 id
: this.cbid(section_id
),
3652 optional
: this.optional
|| this.rmempty
,
3653 placeholder
: this.placeholder
,
3654 monospace
: this.monospace
,
3658 validate
: L
.bind(this.validate
, this, section_id
),
3659 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3662 return widget
.render();
3668 * @memberof LuCI.form
3669 * @augments LuCI.form.Value
3673 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
3674 * renders the underlying UCI option or default value as readonly text.
3676 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3677 * The configuration form this section is added to. It is automatically passed
3678 * by [option()]{@link LuCI.form.AbstractSection#option} or
3679 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3680 * option to the section.
3682 * @param {LuCI.form.AbstractSection} section
3683 * The configuration section this option is added to. It is automatically passed
3684 * by [option()]{@link LuCI.form.AbstractSection#option} or
3685 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3686 * option to the section.
3688 * @param {string} option
3689 * The name of the UCI option to map.
3691 * @param {string} [title]
3692 * The title caption of the option element.
3694 * @param {string} [description]
3695 * The description text of the option element.
3697 var CBIDummyValue
= CBIValue
.extend(/** @lends LuCI.form.DummyValue.prototype */ {
3698 __name__
: 'CBI.DummyValue',
3701 * Set an URL which is opened when clicking on the dummy value text.
3703 * By setting this property, the dummy value text is wrapped in an `<a>`
3704 * element with the property value used as `href` attribute.
3706 * @name LuCI.form.DummyValue.prototype#href
3712 * Treat the UCI option value (or the `default` property value) as HTML.
3714 * By default, the value text is HTML escaped before being rendered as
3715 * text. In some cases it may be needed to actually interpret and render
3716 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
3718 * @name LuCI.form.DummyValue.prototype#rawhtml
3724 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3725 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3726 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
3727 outputEl
= E('div');
3729 if (this.href
&& !((this.readonly
!= null) ? this.readonly
: this.map
.readonly
))
3730 outputEl
.appendChild(E('a', { 'href': this.href
}));
3732 dom
.append(outputEl
.lastChild
|| outputEl
,
3733 this.rawhtml
? value
: [ value
]);
3742 remove: function() {},
3745 write: function() {}
3749 * @class ButtonValue
3750 * @memberof LuCI.form
3751 * @augments LuCI.form.Value
3755 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
3756 * renders the underlying UCI option or default value as readonly text.
3758 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3759 * The configuration form this section is added to. It is automatically passed
3760 * by [option()]{@link LuCI.form.AbstractSection#option} or
3761 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3762 * option to the section.
3764 * @param {LuCI.form.AbstractSection} section
3765 * The configuration section this option is added to. It is automatically passed
3766 * by [option()]{@link LuCI.form.AbstractSection#option} or
3767 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3768 * option to the section.
3770 * @param {string} option
3771 * The name of the UCI option to map.
3773 * @param {string} [title]
3774 * The title caption of the option element.
3776 * @param {string} [description]
3777 * The description text of the option element.
3779 var CBIButtonValue
= CBIValue
.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
3780 __name__
: 'CBI.ButtonValue',
3783 * Override the rendered button caption.
3785 * By default, the option title - which is passed as fourth argument to the
3786 * constructor - is used as caption for the button element. When setting
3787 * this property to a string, it is used as `String.format()` pattern with
3788 * the underlying UCI section name passed as first format argument. When
3789 * set to a function, it is invoked passing the section ID as sole argument
3790 * and the resulting return value is converted to a string before being
3791 * used as button caption.
3793 * The default is `null`, means the option title is used as caption.
3795 * @name LuCI.form.ButtonValue.prototype#inputtitle
3796 * @type string|function
3801 * Override the button style class.
3803 * By setting this property, a specific `cbi-button-*` CSS class can be
3804 * selected to influence the style of the resulting button.
3806 * Suitable values which are implemented by most themes are `positive`,
3807 * `negative` and `primary`.
3809 * The default is `null`, means a neutral button styling is used.
3811 * @name LuCI.form.ButtonValue.prototype#inputstyle
3817 * Override the button click action.
3819 * By default, the underlying UCI option (or default property) value is
3820 * copied into a hidden field tied to the button element and the save
3821 * action is triggered on the parent form element.
3823 * When this property is set to a function, it is invoked instead of
3824 * performing the default actions. The handler function will receive the
3825 * DOM click element as first and the underlying configuration section ID
3826 * as second argument.
3828 * @name LuCI.form.ButtonValue.prototype#onclick
3834 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3835 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3836 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
3837 outputEl
= E('div'),
3838 btn_title
= this.titleFn('inputtitle', section_id
) || this.titleFn('title', section_id
);
3840 if (value
!== false)
3841 dom
.content(outputEl
, [
3843 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle
|| 'button'),
3844 'click': ui
.createHandlerFn(this, function(section_id
, ev
) {
3846 return this.onclick(ev
, section_id
);
3848 ev
.currentTarget
.parentNode
.nextElementSibling
.value
= value
;
3849 return this.map
.save();
3851 'disabled': ((this.readonly
!= null) ? this.readonly
: this.map
.readonly
) || null
3855 dom
.content(outputEl
, ' - ');
3865 * @class HiddenValue
3866 * @memberof LuCI.form
3867 * @augments LuCI.form.Value
3871 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
3873 * Hidden value widgets used to be necessary in legacy code which actually
3874 * submitted the underlying HTML form the server. With client side handling of
3875 * forms, there are more efficient ways to store hidden state data.
3877 * Since this widget has no visible content, the title and description values
3878 * of this form element should be set to `null` as well to avoid a broken or
3879 * distorted form layout when rendering the option element.
3881 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3882 * The configuration form this section is added to. It is automatically passed
3883 * by [option()]{@link LuCI.form.AbstractSection#option} or
3884 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3885 * option to the section.
3887 * @param {LuCI.form.AbstractSection} section
3888 * The configuration section this option is added to. It is automatically passed
3889 * by [option()]{@link LuCI.form.AbstractSection#option} or
3890 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3891 * option to the section.
3893 * @param {string} option
3894 * The name of the UCI option to map.
3896 * @param {string} [title]
3897 * The title caption of the option element.
3899 * @param {string} [description]
3900 * The description text of the option element.
3902 var CBIHiddenValue
= CBIValue
.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
3903 __name__
: 'CBI.HiddenValue',
3906 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3907 var widget
= new ui
.Hiddenfield((cfgvalue
!= null) ? cfgvalue
: this.default, {
3908 id
: this.cbid(section_id
)
3911 return widget
.render();
3917 * @memberof LuCI.form
3918 * @augments LuCI.form.Value
3922 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
3923 * offers the ability to browse, upload and select remote files.
3925 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3926 * The configuration form this section is added to. It is automatically passed
3927 * by [option()]{@link LuCI.form.AbstractSection#option} or
3928 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3929 * option to the section.
3931 * @param {LuCI.form.AbstractSection} section
3932 * The configuration section this option is added to. It is automatically passed
3933 * by [option()]{@link LuCI.form.AbstractSection#option} or
3934 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3935 * option to the section.
3937 * @param {string} option
3938 * The name of the UCI option to map.
3940 * @param {string} [title]
3941 * The title caption of the option element.
3943 * @param {string} [description]
3944 * The description text of the option element.
3946 var CBIFileUpload
= CBIValue
.extend(/** @lends LuCI.form.FileUpload.prototype */ {
3947 __name__
: 'CBI.FileSelect',
3949 __init__: function(/* ... */) {
3950 this.super('__init__', arguments
);
3952 this.show_hidden
= false;
3953 this.enable_upload
= true;
3954 this.enable_remove
= true;
3955 this.root_directory
= '/etc/luci-uploads';
3959 * Toggle display of hidden files.
3961 * Display hidden files when rendering the remote directory listing.
3962 * Note that this is merely a cosmetic feature, hidden files are always
3963 * included in received remote file listings.
3965 * The default is `false`, means hidden files are not displayed.
3967 * @name LuCI.form.FileUpload.prototype#show_hidden
3973 * Toggle file upload functionality.
3975 * When set to `true`, the underlying widget provides a button which lets
3976 * the user select and upload local files to the remote system.
3977 * Note that this is merely a cosmetic feature, remote upload access is
3978 * controlled by the session ACL rules.
3980 * The default is `true`, means file upload functionality is displayed.
3982 * @name LuCI.form.FileUpload.prototype#enable_upload
3988 * Toggle remote file delete functionality.
3990 * When set to `true`, the underlying widget provides a buttons which let
3991 * the user delete files from remote directories. Note that this is merely
3992 * a cosmetic feature, remote delete permissions are controlled by the
3993 * session ACL rules.
3995 * The default is `true`, means file removal buttons are displayed.
3997 * @name LuCI.form.FileUpload.prototype#enable_remove
4003 * Specify the root directory for file browsing.
4005 * This property defines the topmost directory the file browser widget may
4006 * navigate to, the UI will not allow browsing directories outside this
4007 * prefix. Note that this is merely a cosmetic feature, remote file access
4008 * and directory listing permissions are controlled by the session ACL
4011 * The default is `/etc/luci-uploads`.
4013 * @name LuCI.form.FileUpload.prototype#root_directory
4015 * @default /etc/luci-uploads
4019 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4020 var browserEl
= new ui
.FileUpload((cfgvalue
!= null) ? cfgvalue
: this.default, {
4021 id
: this.cbid(section_id
),
4022 name
: this.cbid(section_id
),
4023 show_hidden
: this.show_hidden
,
4024 enable_upload
: this.enable_upload
,
4025 enable_remove
: this.enable_remove
,
4026 root_directory
: this.root_directory
,
4027 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4030 return browserEl
.render();
4035 * @class SectionValue
4036 * @memberof LuCI.form
4037 * @augments LuCI.form.Value
4041 * The `SectionValue` widget embeds a form section element within an option
4042 * element container, allowing to nest form sections into other sections.
4044 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4045 * The configuration form this section is added to. It is automatically passed
4046 * by [option()]{@link LuCI.form.AbstractSection#option} or
4047 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4048 * option to the section.
4050 * @param {LuCI.form.AbstractSection} section
4051 * The configuration section this option is added to. It is automatically passed
4052 * by [option()]{@link LuCI.form.AbstractSection#option} or
4053 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4054 * option to the section.
4056 * @param {string} option
4057 * The internal name of the option element holding the section. Since a section
4058 * container element does not read or write any configuration itself, the name
4059 * is only used internally and does not need to relate to any underlying UCI
4062 * @param {LuCI.form.AbstractSection} subsection_class
4063 * The class to use for instantiating the nested section element. Note that
4064 * the class value itself is expected here, not a class instance obtained by
4065 * calling `new`. The given class argument must be a subclass of the
4066 * `AbstractSection` class.
4068 * @param {...*} [class_args]
4069 * All further arguments are passed as-is to the subclass constructor. Refer
4070 * to the corresponding class constructor documentations for details.
4072 var CBISectionValue
= CBIValue
.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4073 __name__
: 'CBI.ContainerValue',
4074 __init__: function(map
, section
, option
, cbiClass
/*, ... */) {
4075 this.super('__init__', [map
, section
, option
]);
4077 if (!CBIAbstractSection
.isSubclass(cbiClass
))
4078 throw 'Sub section must be a descendent of CBIAbstractSection';
4080 this.subsection
= cbiClass
.instantiate(this.varargs(arguments
, 4, this.map
));
4081 this.subsection
.parentoption
= this;
4085 * Access the embedded section instance.
4087 * This property holds a reference to the instantiated nested section.
4089 * @name LuCI.form.SectionValue.prototype#subsection
4090 * @type LuCI.form.AbstractSection
4095 load: function(section_id
) {
4096 return this.subsection
.load();
4100 parse: function(section_id
) {
4101 return this.subsection
.parse();
4105 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4106 return this.subsection
.render();
4110 checkDepends: function(section_id
) {
4111 this.subsection
.checkDepends();
4112 return CBIValue
.prototype.checkDepends
.apply(this, [ section_id
]);
4116 * Since the section container is not rendering an own widget,
4117 * its `value()` implementation is a no-op.
4121 value: function() {},
4124 * Since the section container is not tied to any UCI configuration,
4125 * its `write()` implementation is a no-op.
4129 write: function() {},
4132 * Since the section container is not tied to any UCI configuration,
4133 * its `remove()` implementation is a no-op.
4137 remove: function() {},
4140 * Since the section container is not tied to any UCI configuration,
4141 * its `cfgvalue()` implementation will always return `null`.
4146 cfgvalue: function() { return null },
4149 * Since the section container is not tied to any UCI configuration,
4150 * its `formvalue()` implementation will always return `null`.
4155 formvalue: function() { return null }
4164 * The LuCI form class provides high level abstractions for creating creating
4165 * UCI- or JSON backed configurations forms.
4167 * To import the class in views, use `'require form'`, to import it in
4168 * external JavaScript, use `L.require("form").then(...)`.
4170 * A typical form is created by first constructing a
4171 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4172 * by subsequently adding sections and options to it. Finally
4173 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4174 * assemble the HTML markup and insert it into the DOM.
4184 * m = new form.Map('example', 'Example form',
4185 * 'This is an example form mapping the contents of /etc/config/example');
4187 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4188 * 'This sections maps "config example first_section" of /etc/config/example');
4190 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4192 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4193 * o.value('choice1', 'The first choice');
4194 * o.value('choice2', 'The second choice');
4196 * m.render().then(function(node) {
4197 * document.body.appendChild(node);
4201 return baseclass
.extend(/** @lends LuCI.form.prototype */ {
4203 JSONMap
: CBIJSONMap
,
4204 AbstractSection
: CBIAbstractSection
,
4205 AbstractValue
: CBIAbstractValue
,
4207 TypedSection
: CBITypedSection
,
4208 TableSection
: CBITableSection
,
4209 GridSection
: CBIGridSection
,
4210 NamedSection
: CBINamedSection
,
4213 DynamicList
: CBIDynamicList
,
4214 ListValue
: CBIListValue
,
4216 MultiValue
: CBIMultiValue
,
4217 TextValue
: CBITextValue
,
4218 DummyValue
: CBIDummyValue
,
4219 Button
: CBIButtonValue
,
4220 HiddenValue
: CBIHiddenValue
,
4221 FileUpload
: CBIFileUpload
,
4222 SectionValue
: CBISectionValue