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 (Array
.isArray(data
[sectiontype
])) {
31 for (var i
= 0, index
= 0; i
< data
[sectiontype
].length
; i
++) {
32 var item
= data
[sectiontype
][i
],
35 if (!L
.isObject(item
))
38 if (typeof(item
['.name']) == 'string') {
43 name
= sectiontype
+ num_sections
;
47 if (!this.data
.hasOwnProperty(name
))
48 section_ids
.push(name
);
50 this.data
[name
] = Object
.assign(item
, {
51 '.index': num_sections
++,
52 '.anonymous': anonymous
,
58 else if (L
.isObject(data
[sectiontype
])) {
59 this.data
[sectiontype
] = Object
.assign(data
[sectiontype
], {
65 section_ids
.push(sectiontype
);
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
);
77 return L
.naturalCompare(a
, b
);
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} obj
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 unsatisfied 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.
281 * The input string to clean.
284 * The cleaned input string with HTML tags removed.
286 stripTags: function(s
) {
287 if (typeof(s
) == 'string' && !s
.match(/[<>]/))
290 var x
= dom
.elem(s
) ? s
: dom
.parse('<div>' + s
+ '</div>');
292 x
.querySelectorAll('br').forEach(function(br
) {
293 x
.replaceChild(document
.createTextNode('\n'), br
);
296 return (x
.textContent
|| x
.innerText
|| '').replace(/([ \t]*\n)+/g, '\n');
300 * Format the given named property as title string.
302 * This function looks up the given named property and formats its value
303 * suitable for use as element caption or description string. It also
304 * strips any HTML tags from the result.
306 * If the property value is a string, it is passed to `String.format()`
307 * along with any additional parameters passed to `titleFn()`.
309 * If the property value is a function, it is invoked with any additional
310 * `titleFn()` parameters as arguments and the obtained return value is
311 * converted to a string.
313 * In all other cases, `null` is returned.
315 * @param {string} property
316 * The name of the element property to use.
318 * @param {...*} fmt_args
319 * Extra values to format the title string with.
321 * @returns {string|null}
322 * The formatted title string or `null` if the property did not exist or
323 * was neither a string nor a function.
325 titleFn: function(attr
/*, ... */) {
328 if (typeof(this[attr
]) == 'function')
329 s
= this[attr
].apply(this, this.varargs(arguments
, 1));
330 else if (typeof(this[attr
]) == 'string')
331 s
= (arguments
.length
> 1) ? ''.format
.apply(this[attr
], this.varargs(arguments
, 1)) : this[attr
];
334 s
= this.stripTags(String(s
)).trim();
336 if (s
== null || s
== '')
345 * @memberof LuCI.form
346 * @augments LuCI.form.AbstractElement
350 * The `Map` class represents one complete form. A form usually maps one UCI
351 * configuration file and is divided into multiple sections containing multiple
354 * It serves as main entry point into the `LuCI.form` for typical view code.
356 * @param {string} config
357 * The UCI configuration to map. It is automatically loaded along when the
358 * resulting map instance.
360 * @param {string} [title]
361 * The title caption of the form. A form title is usually rendered as separate
362 * headline element before the actual form contents. If omitted, the
363 * corresponding headline element will not be rendered.
365 * @param {string} [description]
366 * The description text of the form which is usually rendered as text
367 * paragraph below the form title and before the actual form contents.
368 * If omitted, the corresponding paragraph element will not be rendered.
370 var CBIMap
= CBIAbstractElement
.extend(/** @lends LuCI.form.Map.prototype */ {
371 __init__: function(config
/*, ... */) {
372 this.super('__init__', this.varargs(arguments
, 1));
374 this.config
= config
;
375 this.parsechain
= [ config
];
380 * Toggle readonly state of the form.
382 * If set to `true`, the Map instance is marked readonly and any form
383 * option elements added to it will inherit the readonly state.
385 * If left unset, the Map will test the access permission of the primary
386 * uci configuration upon loading and mark the form readonly if no write
387 * permissions are granted.
389 * @name LuCI.form.Map.prototype#readonly
394 * Find all DOM nodes within this Map which match the given search
395 * parameters. This function is essentially a convenience wrapper around
396 * `querySelectorAll()`.
398 * This function is sensitive to the amount of arguments passed to it;
399 * if only one argument is specified, it is used as selector-expression
400 * as-is. When two arguments are passed, the first argument is treated
401 * as attribute name, the second one as attribute value to match.
403 * As an example, `map.findElements('input')` would find all `<input>`
404 * nodes while `map.findElements('type', 'text')` would find any DOM node
405 * with a `type="text"` attribute.
407 * @param {string} selector_or_attrname
408 * If invoked with only one parameter, this argument is a
409 * `querySelectorAll()` compatible selector expression. If invoked with
410 * two parameters, this argument is the attribute name to filter for.
412 * @param {string} [attrvalue]
413 * In case the function is invoked with two parameters, this argument
414 * specifies the attribute value to match.
416 * @throws {InternalError}
417 * Throws an `InternalError` if more than two function parameters are
420 * @returns {NodeList}
421 * Returns a (possibly empty) DOM `NodeList` containing the found DOM nodes.
423 findElements: function(/* ... */) {
426 if (arguments
.length
== 1)
428 else if (arguments
.length
== 2)
429 q
= '[%s="%s"]'.format(arguments
[0], arguments
[1]);
431 L
.error('InternalError', 'Expecting one or two arguments to findElements()');
433 return this.root
.querySelectorAll(q
);
437 * Find the first DOM node within this Map which matches the given search
438 * parameters. This function is essentially a convenience wrapper around
439 * `findElements()` which only returns the first found node.
441 * This function is sensitive to the amount of arguments passed to it;
442 * if only one argument is specified, it is used as selector-expression
443 * as-is. When two arguments are passed, the first argument is treated
444 * as attribute name, the second one as attribute value to match.
446 * As an example, `map.findElement('input')` would find the first `<input>`
447 * node while `map.findElement('type', 'text')` would find the first DOM
448 * node with a `type="text"` attribute.
450 * @param {string} selector_or_attrname
451 * If invoked with only one parameter, this argument is a `querySelector()`
452 * compatible selector expression. If invoked with two parameters, this
453 * argument is the attribute name to filter for.
455 * @param {string} [attrvalue]
456 * In case the function is invoked with two parameters, this argument
457 * specifies the attribute value to match.
459 * @throws {InternalError}
460 * Throws an `InternalError` if more than two function parameters are
463 * @returns {Node|null}
464 * Returns the first found DOM node or `null` if no element matched.
466 findElement: function(/* ... */) {
467 var res
= this.findElements
.apply(this, arguments
);
468 return res
.length
? res
[0] : null;
472 * Tie another UCI configuration to the map.
474 * By default, a map instance will only load the UCI configuration file
475 * specified in the constructor but sometimes access to values from
476 * further configuration files is required. This function allows for such
477 * use cases by registering further UCI configuration files which are
480 * @param {string} config
481 * The additional UCI configuration file to tie to the map. If the given
482 * config already is in the list of required files, it will be ignored.
484 chain: function(config
) {
485 if (this.parsechain
.indexOf(config
) == -1)
486 this.parsechain
.push(config
);
490 * Add a configuration section to the map.
492 * LuCI forms follow the structure of the underlying UCI configurations,
493 * means that a map, which represents a single UCI configuration, is
494 * divided into multiple sections which in turn contain an arbitrary
497 * While UCI itself only knows two kinds of sections - named and anonymous
498 * ones - the form class offers various flavors of form section elements
499 * to present configuration sections in different ways. Refer to the
500 * documentation of the different section classes for details.
502 * @param {LuCI.form.AbstractSection} sectionclass
503 * The section class to use for rendering the configuration section.
504 * Note that this value must be the class itself, not a class instance
505 * obtained from calling `new`. It must also be a class derived from
506 * `LuCI.form.AbstractSection`.
508 * @param {...string} classargs
509 * Additional arguments which are passed as-is to the constructor of the
510 * given section class. Refer to the class specific constructor
511 * documentation for details.
513 * @returns {LuCI.form.AbstractSection}
514 * Returns the instantiated section class instance.
516 section: function(cbiClass
/*, ... */) {
517 if (!CBIAbstractSection
.isSubclass(cbiClass
))
518 L
.error('TypeError', 'Class must be a descendent of CBIAbstractSection');
520 var obj
= cbiClass
.instantiate(this.varargs(arguments
, 1, this));
526 * Load the configuration covered by this map.
528 * The `load()` function first loads all referenced UCI configurations,
529 * then it recursively walks the form element tree and invokes the
530 * load function of each child element.
532 * @returns {Promise<void>}
533 * Returns a promise resolving once the entire form completed loading all
534 * data. The promise may reject with an error if any configuration failed
535 * to load or if any of the child elements load functions rejected with
539 var doCheckACL
= (!(this instanceof CBIJSONMap
) && this.readonly
== null),
540 loadTasks
= [ doCheckACL
? callSessionAccess('uci', this.config
, 'write') : true ],
541 configs
= this.parsechain
|| [ this.config
];
543 loadTasks
.push
.apply(loadTasks
, configs
.map(L
.bind(function(config
, i
) {
544 return i
? L
.resolveDefault(this.data
.load(config
)) : this.data
.load(config
);
547 return Promise
.all(loadTasks
).then(L
.bind(function(res
) {
548 if (res
[0] === false)
549 this.readonly
= true;
551 return this.loadChildren();
556 * Parse the form input values.
558 * The `parse()` function recursively walks the form element tree and
559 * triggers input value reading and validation for each child element.
561 * Elements which are hidden due to unsatisfied dependencies are skipped.
563 * @returns {Promise<void>}
564 * Returns a promise resolving once the entire form completed parsing all
565 * input values. The returned promise is rejected if any parsed values are
566 * not meeting the validation constraints of their respective elements.
571 if (Array
.isArray(this.children
))
572 for (var i
= 0; i
< this.children
.length
; i
++)
573 tasks
.push(this.children
[i
].parse());
575 return Promise
.all(tasks
);
579 * Save the form input values.
581 * This function parses the current form, saves the resulting UCI changes,
582 * reloads the UCI configuration data and redraws the form elements.
584 * @param {function} [cb]
585 * An optional callback function that is invoked after the form is parsed
586 * but before the changed UCI data is saved. This is useful to perform
587 * additional data manipulation steps before saving the changes.
589 * @param {boolean} [silent=false]
590 * If set to `true`, trigger an alert message to the user in case saving
591 * the form data failures. Otherwise fail silently.
593 * @returns {Promise<void>}
594 * Returns a promise resolving once the entire save operation is complete.
595 * The returned promise is rejected if any step of the save operation
598 save: function(cb
, silent
) {
603 .then(this.data
.save
.bind(this.data
))
604 .then(this.load
.bind(this))
607 ui
.showModal(_('Save error'), [
608 E('p', {}, [ _('An error occurred while saving the form:') ]),
609 E('p', {}, [ E('em', { 'style': 'white-space:pre-wrap' }, [ e
.message
]) ]),
610 E('div', { 'class': 'right' }, [
611 E('button', { 'class': 'cbi-button', 'click': ui
.hideModal
}, [ _('Dismiss') ])
616 return Promise
.reject(e
);
617 }).then(this.renderContents
.bind(this));
621 * Reset the form by re-rendering its contents. This will revert all
622 * unsaved user inputs to their initial form state.
624 * @returns {Promise<Node>}
625 * Returns a promise resolving to the toplevel form DOM node once the
626 * re-rendering is complete.
629 return this.renderContents();
633 * Render the form markup.
635 * @returns {Promise<Node>}
636 * Returns a promise resolving to the toplevel form DOM node once the
637 * rendering is complete.
640 return this.load().then(this.renderContents
.bind(this));
644 renderContents: function() {
645 var mapEl
= this.root
|| (this.root
= E('div', {
646 'id': 'cbi-%s'.format(this.config
),
648 'cbi-dependency-check': L
.bind(this.checkDepends
, this)
651 dom
.bindClassInstance(mapEl
, this);
653 return this.renderChildren(null).then(L
.bind(function(nodes
) {
654 var initialRender
= !mapEl
.firstChild
;
656 dom
.content(mapEl
, null);
658 if (this.title
!= null && this.title
!= '')
659 mapEl
.appendChild(E('h2', { 'name': 'content' }, this.title
));
661 if (this.description
!= null && this.description
!= '')
662 mapEl
.appendChild(E('div', { 'class': 'cbi-map-descr' }, this.description
));
665 dom
.append(mapEl
, E('div', { 'class': 'cbi-map-tabbed' }, nodes
));
667 dom
.append(mapEl
, nodes
);
669 if (!initialRender
) {
670 mapEl
.classList
.remove('flash');
672 window
.setTimeout(function() {
673 mapEl
.classList
.add('flash');
679 var tabGroups
= mapEl
.querySelectorAll('.cbi-map-tabbed, .cbi-section-node-tabbed');
681 for (var i
= 0; i
< tabGroups
.length
; i
++)
682 ui
.tabs
.initTabGroup(tabGroups
[i
].childNodes
);
689 * Find a form option element instance.
691 * @param {string} name
692 * The name or the full ID of the option element to look up.
694 * @param {string} [section_id]
695 * The ID of the UCI section containing the option to look up. May be
696 * omitted if a full ID is passed as first argument.
698 * @param {string} [config_name]
699 * The name of the UCI configuration the option instance belongs to.
700 * Defaults to the main UCI configuration of the map if omitted.
702 * @returns {Array<LuCI.form.AbstractValue,string>|null}
703 * Returns a two-element array containing the form option instance as
704 * first item and the corresponding UCI section ID as second item.
705 * Returns `null` if the option could not be found.
707 lookupOption: function(name
, section_id
, config_name
) {
708 var id
, elem
, sid
, inst
;
710 if (name
.indexOf('.') > -1)
711 id
= 'cbid.%s'.format(name
);
713 id
= 'cbid.%s.%s.%s'.format(config_name
|| this.config
, section_id
, name
);
715 elem
= this.findElement('data-field', id
);
716 sid
= elem
? id
.split(/\./)[2] : null;
717 inst
= elem
? dom
.findClassInstance(elem
) : null;
719 return (inst
instanceof CBIAbstractValue
) ? [ inst
, sid
] : null;
723 checkDepends: function(ev
, n
) {
726 for (var i
= 0, s
= this.children
[0]; (s
= this.children
[i
]) != null; i
++)
727 if (s
.checkDepends(ev
, n
))
730 if (changed
&& (n
|| 0) < 10)
731 this.checkDepends(ev
, (n
|| 10) + 1);
733 ui
.tabs
.updateTabs(ev
, this.root
);
737 isDependencySatisfied: function(depends
, config_name
, section_id
) {
740 if (!Array
.isArray(depends
) || !depends
.length
)
743 for (var i
= 0; i
< depends
.length
; i
++) {
745 reverse
= depends
[i
]['!reverse'],
746 contains
= depends
[i
]['!contains'];
748 for (var dep
in depends
[i
]) {
749 if (dep
== '!reverse' || dep
== '!contains') {
752 else if (dep
== '!default') {
757 var res
= this.lookupOption(dep
, section_id
, config_name
),
758 val
= (res
&& res
[0].isActive(res
[1])) ? res
[0].formvalue(res
[1]) : null;
761 ? isContained(val
, depends
[i
][dep
])
762 : isEqual(val
, depends
[i
][dep
]);
764 istat
= (istat
&& equal
);
777 * @constructor JSONMap
778 * @memberof LuCI.form
779 * @augments LuCI.form.Map
783 * A `JSONMap` class functions similar to [LuCI.form.Map]{@link LuCI.form.Map}
784 * but uses a multidimensional JavaScript object instead of UCI configuration
787 * @param {Object<string, Object<string, *>|Array<Object<string, *>>>} data
788 * The JavaScript object to use as data source. Internally, the object is
789 * converted into an UCI-like format. Its toplevel keys are treated like UCI
790 * section types while the object or array-of-object values are treated as
793 * @param {string} [title]
794 * The title caption of the form. A form title is usually rendered as separate
795 * headline element before the actual form contents. If omitted, the
796 * corresponding headline element will not be rendered.
798 * @param {string} [description]
799 * The description text of the form which is usually rendered as text
800 * paragraph below the form title and before the actual form contents.
801 * If omitted, the corresponding paragraph element will not be rendered.
803 var CBIJSONMap
= CBIMap
.extend(/** @lends LuCI.form.JSONMap.prototype */ {
804 __init__: function(data
/*, ... */) {
805 this.super('__init__', this.varargs(arguments
, 1, 'json'));
807 this.config
= 'json';
808 this.parsechain
= [ 'json' ];
809 this.data
= new CBIJSONConfig(data
);
814 * @class AbstractSection
815 * @memberof LuCI.form
816 * @augments LuCI.form.AbstractElement
820 * The `AbstractSection` class serves as abstract base for the different form
821 * section styles implemented by `LuCI.form`. It provides the common logic for
822 * enumerating underlying configuration section instances, for registering
823 * form options and for handling tabs to segment child options.
825 * This class is private and not directly accessible by user code.
827 var CBIAbstractSection
= CBIAbstractElement
.extend(/** @lends LuCI.form.AbstractSection.prototype */ {
828 __init__: function(map
, sectionType
/*, ... */) {
829 this.super('__init__', this.varargs(arguments
, 2));
831 this.sectiontype
= sectionType
;
833 this.config
= map
.config
;
835 this.optional
= true;
836 this.addremove
= false;
837 this.dynamic
= false;
841 * Access the parent option container instance.
843 * In case this section is nested within an option element container,
844 * this property will hold a reference to the parent option instance.
846 * If this section is not nested, the property is `null`.
848 * @name LuCI.form.AbstractSection.prototype#parentoption
849 * @type LuCI.form.AbstractValue
854 * Enumerate the UCI section IDs covered by this form section element.
857 * @throws {InternalError}
858 * Throws an `InternalError` exception if the function is not implemented.
860 * @returns {string[]}
861 * Returns an array of UCI section IDs covered by this form element.
862 * The sections will be rendered in the same order as the returned array.
864 cfgsections: function() {
865 L
.error('InternalError', 'Not implemented');
869 * Filter UCI section IDs to render.
871 * The filter function is invoked for each UCI section ID of a given type
872 * and controls whether the given UCI section is rendered or ignored by
873 * the form section element.
875 * The default implementation always returns `true`. User code or
876 * classes extending `AbstractSection` may overwrite this function with
877 * custom implementations.
880 * @param {string} section_id
881 * The UCI section ID to test.
884 * Returns `true` when the given UCI section ID should be handled and
885 * `false` when it should be ignored.
887 filter: function(section_id
) {
892 * Load the configuration covered by this section.
894 * The `load()` function recursively walks the section element tree and
895 * invokes the load function of each child option element.
897 * @returns {Promise<void>}
898 * Returns a promise resolving once the values of all child elements have
899 * been loaded. The promise may reject with an error if any of the child
900 * elements load functions rejected with an error.
903 var section_ids
= this.cfgsections(),
906 if (Array
.isArray(this.children
))
907 for (var i
= 0; i
< section_ids
.length
; i
++)
908 tasks
.push(this.loadChildren(section_ids
[i
])
909 .then(Function
.prototype.bind
.call(function(section_id
, set_values
) {
910 for (var i
= 0; i
< set_values
.length
; i
++)
911 this.children
[i
].cfgvalue(section_id
, set_values
[i
]);
912 }, this, section_ids
[i
])));
914 return Promise
.all(tasks
);
918 * Parse this sections form input.
920 * The `parse()` function recursively walks the section element tree and
921 * triggers input value reading and validation for each encountered child
924 * Options which are hidden due to unsatisfied dependencies are skipped.
926 * @returns {Promise<void>}
927 * Returns a promise resolving once the values of all child elements have
928 * been parsed. The returned promise is rejected if any parsed values are
929 * not meeting the validation constraints of their respective elements.
932 var section_ids
= this.cfgsections(),
935 if (Array
.isArray(this.children
))
936 for (var i
= 0; i
< section_ids
.length
; i
++)
937 for (var j
= 0; j
< this.children
.length
; j
++)
938 tasks
.push(this.children
[j
].parse(section_ids
[i
]));
940 return Promise
.all(tasks
);
944 * Add an option tab to the section.
946 * The child option elements of a section may be divided into multiple
947 * tabs to provide a better overview to the user.
949 * Before options can be moved into a tab pane, the corresponding tab
950 * has to be defined first, which is done by calling this function.
952 * Note that once tabs are defined, user code must use the `taboption()`
953 * method to add options to specific tabs. Option elements added by
954 * `option()` will not be assigned to any tab and not be rendered in this
957 * @param {string} name
958 * The name of the tab to register. It may be freely chosen and just serves
959 * as an identifier to differentiate tabs.
961 * @param {string} title
962 * The human readable caption of the tab.
964 * @param {string} [description]
965 * An additional description text for the corresponding tab pane. It is
966 * displayed as text paragraph below the tab but before the tab pane
967 * contents. If omitted, no description will be rendered.
970 * Throws an exception if a tab with the same `name` already exists.
972 tab: function(name
, title
, description
) {
973 if (this.tabs
&& this.tabs
[name
])
974 throw 'Tab already declared';
979 description
: description
,
983 this.tabs
= this.tabs
|| [];
984 this.tabs
.push(entry
);
985 this.tabs
[name
] = entry
;
987 this.tab_names
= this.tab_names
|| [];
988 this.tab_names
.push(name
);
992 * Add a configuration option widget to the section.
994 * Note that [taboption()]{@link LuCI.form.AbstractSection#taboption}
995 * should be used instead if this form section element uses tabs.
997 * @param {LuCI.form.AbstractValue} optionclass
998 * The option class to use for rendering the configuration option. Note
999 * that this value must be the class itself, not a class instance obtained
1000 * from calling `new`. It must also be a class derived from
1001 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
1003 * @param {...*} classargs
1004 * Additional arguments which are passed as-is to the constructor of the
1005 * given option class. Refer to the class specific constructor
1006 * documentation for details.
1008 * @throws {TypeError}
1009 * Throws a `TypeError` exception in case the passed class value is not a
1010 * descendant of `AbstractValue`.
1012 * @returns {LuCI.form.AbstractValue}
1013 * Returns the instantiated option class instance.
1015 option: function(cbiClass
/*, ... */) {
1016 if (!CBIAbstractValue
.isSubclass(cbiClass
))
1017 throw L
.error('TypeError', 'Class must be a descendant of CBIAbstractValue');
1019 var obj
= cbiClass
.instantiate(this.varargs(arguments
, 1, this.map
, this));
1025 * Add a configuration option widget to a tab of the section.
1027 * @param {string} tabName
1028 * The name of the section tab to add the option element to.
1030 * @param {LuCI.form.AbstractValue} optionclass
1031 * The option class to use for rendering the configuration option. Note
1032 * that this value must be the class itself, not a class instance obtained
1033 * from calling `new`. It must also be a class derived from
1034 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
1036 * @param {...*} classargs
1037 * Additional arguments which are passed as-is to the constructor of the
1038 * given option class. Refer to the class specific constructor
1039 * documentation for details.
1041 * @throws {ReferenceError}
1042 * Throws a `ReferenceError` exception when the given tab name does not
1045 * @throws {TypeError}
1046 * Throws a `TypeError` exception in case the passed class value is not a
1047 * descendant of `AbstractValue`.
1049 * @returns {LuCI.form.AbstractValue}
1050 * Returns the instantiated option class instance.
1052 taboption: function(tabName
/*, ... */) {
1053 if (!this.tabs
|| !this.tabs
[tabName
])
1054 throw L
.error('ReferenceError', 'Associated tab not declared');
1056 var obj
= this.option
.apply(this, this.varargs(arguments
, 1));
1058 this.tabs
[tabName
].children
.push(obj
);
1063 * Query underlying option configuration values.
1065 * This function is sensitive to the amount of arguments passed to it;
1066 * if only one argument is specified, the configuration values of all
1067 * options within this section are returned as dictionary.
1069 * If both the section ID and an option name are supplied, this function
1070 * returns the configuration value of the specified option only.
1072 * @param {string} section_id
1073 * The configuration section ID
1075 * @param {string} [option]
1076 * The name of the option to query
1078 * @returns {null|string|string[]|Object<string, null|string|string[]>}
1079 * Returns either a dictionary of option names and their corresponding
1080 * configuration values or just a single configuration value, depending
1081 * on the amount of passed arguments.
1083 cfgvalue: function(section_id
, option
) {
1084 var rv
= (arguments
.length
== 1) ? {} : null;
1086 for (var i
= 0, o
; (o
= this.children
[i
]) != null; i
++)
1088 rv
[o
.option
] = o
.cfgvalue(section_id
);
1089 else if (o
.option
== option
)
1090 return o
.cfgvalue(section_id
);
1096 * Query underlying option widget input values.
1098 * This function is sensitive to the amount of arguments passed to it;
1099 * if only one argument is specified, the widget input values of all
1100 * options within this section are returned as dictionary.
1102 * If both the section ID and an option name are supplied, this function
1103 * returns the widget input value of the specified option only.
1105 * @param {string} section_id
1106 * The configuration section ID
1108 * @param {string} [option]
1109 * The name of the option to query
1111 * @returns {null|string|string[]|Object<string, null|string|string[]>}
1112 * Returns either a dictionary of option names and their corresponding
1113 * widget input values or just a single widget input value, depending
1114 * on the amount of passed arguments.
1116 formvalue: function(section_id
, option
) {
1117 var rv
= (arguments
.length
== 1) ? {} : null;
1119 for (var i
= 0, o
; (o
= this.children
[i
]) != null; i
++) {
1120 var func
= this.map
.root
? this.children
[i
].formvalue
: this.children
[i
].cfgvalue
;
1123 rv
[o
.option
] = func
.call(o
, section_id
);
1124 else if (o
.option
== option
)
1125 return func
.call(o
, section_id
);
1132 * Obtain underlying option LuCI.ui widget instances.
1134 * This function is sensitive to the amount of arguments passed to it;
1135 * if only one argument is specified, the LuCI.ui widget instances of all
1136 * options within this section are returned as dictionary.
1138 * If both the section ID and an option name are supplied, this function
1139 * returns the LuCI.ui widget instance value of the specified option only.
1141 * @param {string} section_id
1142 * The configuration section ID
1144 * @param {string} [option]
1145 * The name of the option to query
1147 * @returns {null|LuCI.ui.AbstractElement|Object<string, null|LuCI.ui.AbstractElement>}
1148 * Returns either a dictionary of option names and their corresponding
1149 * widget input values or just a single widget input value, depending
1150 * on the amount of passed arguments.
1152 getUIElement: function(section_id
, option
) {
1153 var rv
= (arguments
.length
== 1) ? {} : null;
1155 for (var i
= 0, o
; (o
= this.children
[i
]) != null; i
++)
1157 rv
[o
.option
] = o
.getUIElement(section_id
);
1158 else if (o
.option
== option
)
1159 return o
.getUIElement(section_id
);
1165 * Obtain underlying option objects.
1167 * This function is sensitive to the amount of arguments passed to it;
1168 * if no option name is specified, all options within this section are
1169 * returned as dictionary.
1171 * If an option name is supplied, this function returns the matching
1172 * LuCI.form.AbstractValue instance only.
1174 * @param {string} [option]
1175 * The name of the option object to obtain
1177 * @returns {null|LuCI.form.AbstractValue|Object<string, LuCI.form.AbstractValue>}
1178 * Returns either a dictionary of option names and their corresponding
1179 * option instance objects or just a single object instance value,
1180 * depending on the amount of passed arguments.
1182 getOption: function(option
) {
1183 var rv
= (arguments
.length
== 0) ? {} : null;
1185 for (var i
= 0, o
; (o
= this.children
[i
]) != null; i
++)
1188 else if (o
.option
== option
)
1195 renderUCISection: function(section_id
) {
1196 var renderTasks
= [];
1199 return this.renderOptions(null, section_id
);
1201 for (var i
= 0; i
< this.tab_names
.length
; i
++)
1202 renderTasks
.push(this.renderOptions(this.tab_names
[i
], section_id
));
1204 return Promise
.all(renderTasks
)
1205 .then(this.renderTabContainers
.bind(this, section_id
));
1209 renderTabContainers: function(section_id
, nodes
) {
1210 var config_name
= this.uciconfig
|| this.map
.config
,
1211 containerEls
= E([]);
1213 for (var i
= 0; i
< nodes
.length
; i
++) {
1214 var tab_name
= this.tab_names
[i
],
1215 tab_data
= this.tabs
[tab_name
],
1216 containerEl
= E('div', {
1217 'id': 'container.%s.%s.%s'.format(config_name
, section_id
, tab_name
),
1218 'data-tab': tab_name
,
1219 'data-tab-title': tab_data
.title
,
1220 'data-tab-active': tab_name
=== this.selected_tab
1223 if (tab_data
.description
!= null && tab_data
.description
!= '')
1224 containerEl
.appendChild(
1225 E('div', { 'class': 'cbi-tab-descr' }, tab_data
.description
));
1227 containerEl
.appendChild(nodes
[i
]);
1228 containerEls
.appendChild(containerEl
);
1231 return containerEls
;
1235 renderOptions: function(tab_name
, section_id
) {
1236 var in_table
= (this instanceof CBITableSection
);
1237 return this.renderChildren(tab_name
, section_id
, in_table
).then(function(nodes
) {
1238 var optionEls
= E([]);
1239 for (var i
= 0; i
< nodes
.length
; i
++)
1240 optionEls
.appendChild(nodes
[i
]);
1246 checkDepends: function(ev
, n
) {
1247 var changed
= false,
1248 sids
= this.cfgsections();
1250 for (var i
= 0, sid
= sids
[0]; (sid
= sids
[i
]) != null; i
++) {
1251 for (var j
= 0, o
= this.children
[0]; (o
= this.children
[j
]) != null; j
++) {
1252 var isActive
= o
.isActive(sid
),
1253 isSatisified
= o
.checkDepends(sid
);
1255 if (isActive
!= isSatisified
) {
1256 o
.setActive(sid
, !isActive
);
1257 isActive
= !isActive
;
1262 o
.triggerValidation(sid
);
1271 var isEqual = function(x
, y
) {
1272 if (typeof(y
) == 'object' && y
instanceof RegExp
)
1273 return (x
== null) ? false : y
.test(x
);
1275 if (x
!= null && y
!= null && typeof(x
) != typeof(y
))
1278 if ((x
== null && y
!= null) || (x
!= null && y
== null))
1281 if (Array
.isArray(x
)) {
1282 if (x
.length
!= y
.length
)
1285 for (var i
= 0; i
< x
.length
; i
++)
1286 if (!isEqual(x
[i
], y
[i
]))
1289 else if (typeof(x
) == 'object') {
1291 if (x
.hasOwnProperty(k
) && !y
.hasOwnProperty(k
))
1294 if (!isEqual(x
[k
], y
[k
]))
1299 if (y
.hasOwnProperty(k
) && !x
.hasOwnProperty(k
))
1309 var isContained = function(x
, y
) {
1310 if (Array
.isArray(x
)) {
1311 for (var i
= 0; i
< x
.length
; i
++)
1315 else if (L
.isObject(x
)) {
1316 if (x
.hasOwnProperty(y
) && x
[y
] != null)
1319 else if (typeof(x
) == 'string') {
1320 return (x
.indexOf(y
) > -1);
1327 * @class AbstractValue
1328 * @memberof LuCI.form
1329 * @augments LuCI.form.AbstractElement
1333 * The `AbstractValue` class serves as abstract base for the different form
1334 * option styles implemented by `LuCI.form`. It provides the common logic for
1335 * handling option input values, for dependencies among options and for
1336 * validation constraints that should be applied to entered values.
1338 * This class is private and not directly accessible by user code.
1340 var CBIAbstractValue
= CBIAbstractElement
.extend(/** @lends LuCI.form.AbstractValue.prototype */ {
1341 __init__: function(map
, section
, option
/*, ... */) {
1342 this.super('__init__', this.varargs(arguments
, 3));
1344 this.section
= section
;
1345 this.option
= option
;
1347 this.config
= map
.config
;
1351 this.rmempty
= true;
1352 this.default = null;
1354 this.optional
= false;
1355 this.retain
= false;
1359 * If set to `false`, the underlying option value is retained upon saving
1360 * the form when the option element is disabled due to unsatisfied
1361 * dependency constraints.
1363 * @name LuCI.form.AbstractValue.prototype#rmempty
1369 * If set to `true`, the underlying ui input widget is allowed to be empty,
1370 * otherwise the option element is marked invalid when no value is entered
1371 * or selected by the user.
1373 * @name LuCI.form.AbstractValue.prototype#optional
1379 * If set to `true`, the underlying ui input widget value is not cleared
1380 * from the configuration on unsatisfied dependencies. The default behavior
1381 * is to remove the values of all options whose dependencies are not
1384 * @name LuCI.form.AbstractValue.prototype#retain
1390 * Sets a default value to use when the underlying UCI option is not set.
1392 * @name LuCI.form.AbstractValue.prototype#default
1398 * Specifies a datatype constraint expression to validate input values
1399 * against. Refer to {@link LuCI.validation} for details on the format.
1401 * If the user entered input does not match the datatype validation, the
1402 * option element is marked as invalid.
1404 * @name LuCI.form.AbstractValue.prototype#datatype
1410 * Specifies a custom validation function to test the user input for
1411 * validity. The validation function must return `true` to accept the
1412 * value. Any other return value type is converted to a string and
1413 * displayed to the user as validation error message.
1415 * If the user entered input does not pass the validation function, the
1416 * option element is marked as invalid.
1418 * @name LuCI.form.AbstractValue.prototype#validate
1424 * Override the UCI configuration name to read the option value from.
1426 * By default, the configuration name is inherited from the parent Map.
1427 * By setting this property, a deviating configuration may be specified.
1429 * The default is null, means inheriting from the parent form.
1431 * @name LuCI.form.AbstractValue.prototype#uciconfig
1437 * Override the UCI section name to read the option value from.
1439 * By default, the section ID is inherited from the parent section element.
1440 * By setting this property, a deviating section may be specified.
1442 * The default is null, means inheriting from the parent section.
1444 * @name LuCI.form.AbstractValue.prototype#ucisection
1450 * Override the UCI option name to read the value from.
1452 * By default, the elements name, which is passed as third argument to
1453 * the constructor, is used as UCI option name. By setting this property,
1454 * a deviating UCI option may be specified.
1456 * The default is null, means using the option element name.
1458 * @name LuCI.form.AbstractValue.prototype#ucioption
1464 * Mark grid section option element as editable.
1466 * Options which are displayed in the table portion of a `GridSection`
1467 * instance are rendered as readonly text by default. By setting the
1468 * `editable` property of a child option element to `true`, that element
1469 * is rendered as full input widget within its cell instead of a text only
1472 * This property has no effect on options that are not children of grid
1475 * @name LuCI.form.AbstractValue.prototype#editable
1481 * Move grid section option element into the table, the modal popup or both.
1483 * If this property is `null` (the default), the option element is
1484 * displayed in both the table preview area and the per-section instance
1485 * modal popup of a grid section. When it is set to `false` the option
1486 * is only shown in the table but not the modal popup. When set to `true`,
1487 * the option is only visible in the modal popup but not the table.
1489 * This property has no effect on options that are not children of grid
1492 * @name LuCI.form.AbstractValue.prototype#modalonly
1498 * Make option element readonly.
1500 * This property defaults to the readonly state of the parent form element.
1501 * When set to `true`, the underlying widget is rendered in disabled state,
1502 * means its contents cannot be changed and the widget cannot be interacted
1505 * @name LuCI.form.AbstractValue.prototype#readonly
1511 * Override the cell width of a table or grid section child option.
1513 * If the property is set to a numeric value, it is treated as pixel width
1514 * which is set on the containing cell element of the option, essentially
1515 * forcing a certain column width. When the property is set to a string
1516 * value, it is applied as-is to the CSS `width` property.
1518 * This property has no effect on options that are not children of grid or
1519 * table section elements.
1521 * @name LuCI.form.AbstractValue.prototype#width
1522 * @type number|string
1527 * Register a custom value change handler.
1529 * If this property is set to a function value, the function is invoked
1530 * whenever the value of the underlying UI input element is changing.
1532 * The invoked handler function will receive the DOM click element as
1533 * first and the underlying configuration section ID as well as the input
1534 * value as second and third argument respectively.
1536 * @name LuCI.form.AbstractValue.prototype#onchange
1542 * Add a dependency constraint to the option.
1544 * Dependency constraints allow making the presence of option elements
1545 * dependent on the current values of certain other options within the
1546 * same form. An option element with unsatisfied dependencies will be
1547 * hidden from the view and its current value is omitted when saving.
1549 * Multiple constraints (that is, multiple calls to `depends()`) are
1550 * treated as alternatives, forming a logical "or" expression.
1552 * By passing an object of name => value pairs as first argument, it is
1553 * possible to depend on multiple options simultaneously, allowing to form
1554 * a logical "and" expression.
1556 * Option names may be given in "dot notation" which allows to reference
1557 * option elements outside the current form section. If a name without
1558 * dot is specified, it refers to an option within the same configuration
1559 * section. If specified as <code>configname.sectionid.optionname</code>,
1560 * options anywhere within the same form may be specified.
1562 * The object notation also allows for a number of special keys which are
1563 * not treated as option names but as modifiers to influence the dependency
1564 * constraint evaluation. The associated value of these special "tag" keys
1565 * is ignored. The recognized tags are:
1569 * <code>!reverse</code><br>
1570 * Invert the dependency, instead of requiring another option to be
1571 * equal to the dependency value, that option should <em>not</em> be
1575 * <code>!contains</code><br>
1576 * Instead of requiring an exact match, the dependency is considered
1577 * satisfied when the dependency value is contained within the option
1581 * <code>!default</code><br>
1582 * The dependency is always satisfied
1590 * <code>opt.depends("foo", "test")</code><br>
1591 * Require the value of `foo` to be `test`.
1594 * <code>opt.depends({ foo: "test" })</code><br>
1595 * Equivalent to the previous example.
1598 * <code>opt.depends({ foo: /test/ })</code><br>
1599 * Require the value of `foo` to match the regular expression `/test/`.
1602 * <code>opt.depends({ foo: "test", bar: "qrx" })</code><br>
1603 * Require the value of `foo` to be `test` and the value of `bar` to be
1607 * <code>opt.depends({ foo: "test" })<br>
1608 * opt.depends({ bar: "qrx" })</code><br>
1609 * Require either <code>foo</code> to be set to <code>test</code>,
1610 * <em>or</em> the <code>bar</code> option to be <code>qrx</code>.
1613 * <code>opt.depends("test.section1.foo", "bar")</code><br>
1614 * Require the "foo" form option within the "section1" section to be
1618 * <code>opt.depends({ foo: "test", "!contains": true })</code><br>
1619 * Require the "foo" option value to contain the substring "test".
1623 * @param {string|Object<string, string|RegExp>} field
1624 * The name of the option to depend on or an object describing multiple
1625 * dependencies which must be satisfied (a logical "and" expression).
1627 * @param {string|RegExp} value
1628 * When invoked with a plain option name as first argument, this parameter
1629 * specifies the expected value. In case an object is passed as first
1630 * argument, this parameter is ignored.
1632 depends: function(field
, value
) {
1635 if (typeof(field
) === 'string')
1636 deps
= {}, deps
[field
] = value
;
1640 this.deps
.push(deps
);
1644 transformDepList: function(section_id
, deplist
) {
1645 var list
= deplist
|| this.deps
,
1648 if (Array
.isArray(list
)) {
1649 for (var i
= 0; i
< list
.length
; i
++) {
1652 for (var k
in list
[i
]) {
1653 if (list
[i
].hasOwnProperty(k
)) {
1654 if (k
.charAt(0) === '!')
1655 dep
[k
] = list
[i
][k
];
1656 else if (k
.indexOf('.') !== -1)
1657 dep
['cbid.%s'.format(k
)] = list
[i
][k
];
1659 dep
['cbid.%s.%s.%s'.format(
1660 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1661 this.ucisection
|| section_id
,
1667 for (var k
in dep
) {
1668 if (dep
.hasOwnProperty(k
)) {
1680 transformChoices: function() {
1681 if (!Array
.isArray(this.keylist
) || this.keylist
.length
== 0)
1686 for (var i
= 0; i
< this.keylist
.length
; i
++)
1687 choices
[this.keylist
[i
]] = this.vallist
[i
];
1693 checkDepends: function(section_id
) {
1694 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1695 active
= this.map
.isDependencySatisfied(this.deps
, config_name
, section_id
);
1698 this.updateDefaultValue(section_id
);
1704 updateDefaultValue: function(section_id
) {
1705 if (!L
.isObject(this.defaults
))
1708 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1709 cfgvalue
= L
.toArray(this.cfgvalue(section_id
))[0],
1710 default_defval
= null, satisified_defval
= null;
1712 for (var value
in this.defaults
) {
1713 if (!this.defaults
[value
] || this.defaults
[value
].length
== 0) {
1714 default_defval
= value
;
1717 else if (this.map
.isDependencySatisfied(this.defaults
[value
], config_name
, section_id
)) {
1718 satisified_defval
= value
;
1723 if (satisified_defval
== null)
1724 satisified_defval
= default_defval
;
1726 var node
= this.map
.findElement('id', this.cbid(section_id
));
1727 if (node
&& node
.getAttribute('data-changed') != 'true' && satisified_defval
!= null && cfgvalue
== null)
1728 dom
.callClassMethod(node
, 'setValue', satisified_defval
);
1730 this.default = satisified_defval
;
1734 * Obtain the internal ID ("cbid") of the element instance.
1736 * Since each form section element may map multiple underlying
1737 * configuration sections, the configuration section ID is required to
1738 * form a fully qualified ID pointing to the specific element instance
1739 * within the given specific section.
1741 * @param {string} section_id
1742 * The configuration section ID
1744 * @throws {TypeError}
1745 * Throws a `TypeError` exception when no `section_id` was specified.
1748 * Returns the element ID.
1750 cbid: function(section_id
) {
1751 if (section_id
== null)
1752 L
.error('TypeError', 'Section ID required');
1754 return 'cbid.%s.%s.%s'.format(
1755 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1756 section_id
, this.option
);
1760 * Load the underlying configuration value.
1762 * The default implementation of this method reads and returns the
1763 * underlying UCI option value (or the related JavaScript property for
1764 * `JSONMap` instances). It may be overwritten by user code to load data
1765 * from nonstandard sources.
1767 * @param {string} section_id
1768 * The configuration section ID
1770 * @throws {TypeError}
1771 * Throws a `TypeError` exception when no `section_id` was specified.
1773 * @returns {*|Promise<*>}
1774 * Returns the configuration value to initialize the option element with.
1775 * The return value of this function is filtered through `Promise.resolve()`
1776 * so it may return promises if overridden by user code.
1778 load: function(section_id
) {
1779 if (section_id
== null)
1780 L
.error('TypeError', 'Section ID required');
1782 return this.map
.data
.get(
1783 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1784 this.ucisection
|| section_id
,
1785 this.ucioption
|| this.option
);
1789 * Obtain the underlying `LuCI.ui` element instance.
1791 * @param {string} section_id
1792 * The configuration section ID
1794 * @throws {TypeError}
1795 * Throws a `TypeError` exception when no `section_id` was specified.
1797 * @return {LuCI.ui.AbstractElement|null}
1798 * Returns the `LuCI.ui` element instance or `null` in case the form
1799 * option implementation does not use `LuCI.ui` widgets.
1801 getUIElement: function(section_id
) {
1802 var node
= this.map
.findElement('id', this.cbid(section_id
)),
1803 inst
= node
? dom
.findClassInstance(node
) : null;
1804 return (inst
instanceof ui
.AbstractElement
) ? inst
: null;
1808 * Query the underlying configuration value.
1810 * The default implementation of this method returns the cached return
1811 * value of [load()]{@link LuCI.form.AbstractValue#load}. It may be
1812 * overwritten by user code to obtain the configuration value in a
1815 * @param {string} section_id
1816 * The configuration section ID
1818 * @throws {TypeError}
1819 * Throws a `TypeError` exception when no `section_id` was specified.
1822 * Returns the configuration value.
1824 cfgvalue: function(section_id
, set_value
) {
1825 if (section_id
== null)
1826 L
.error('TypeError', 'Section ID required');
1828 if (arguments
.length
== 2) {
1829 this.data
= this.data
|| {};
1830 this.data
[section_id
] = set_value
;
1833 return this.data
? this.data
[section_id
] : null;
1837 * Query the current form input value.
1839 * The default implementation of this method returns the current input
1840 * value of the underlying [LuCI.ui]{@link LuCI.ui.AbstractElement} widget.
1841 * It may be overwritten by user code to handle input values differently.
1843 * @param {string} section_id
1844 * The configuration section ID
1846 * @throws {TypeError}
1847 * Throws a `TypeError` exception when no `section_id` was specified.
1850 * Returns the current input value.
1852 formvalue: function(section_id
) {
1853 var elem
= this.getUIElement(section_id
);
1854 return elem
? elem
.getValue() : null;
1858 * Obtain a textual input representation.
1860 * The default implementation of this method returns the HTML escaped
1861 * current input value of the underlying
1862 * [LuCI.ui]{@link LuCI.ui.AbstractElement} widget. User code or specific
1863 * option element implementations may overwrite this function to apply a
1864 * different logic, e.g. to return `Yes` or `No` depending on the checked
1865 * state of checkbox elements.
1867 * @param {string} section_id
1868 * The configuration section ID
1870 * @throws {TypeError}
1871 * Throws a `TypeError` exception when no `section_id` was specified.
1874 * Returns the text representation of the current input value.
1876 textvalue: function(section_id
) {
1877 var cval
= this.cfgvalue(section_id
);
1880 cval
= this.default;
1882 if (Array
.isArray(cval
))
1883 cval
= cval
.join(' ');
1885 return (cval
!= null) ? '%h'.format(cval
) : null;
1889 * Apply custom validation logic.
1891 * This method is invoked whenever incremental validation is performed on
1892 * the user input, e.g. on keyup or blur events.
1894 * The default implementation of this method does nothing and always
1895 * returns `true`. User code may overwrite this method to provide
1896 * additional validation logic which is not covered by data type
1900 * @param {string} section_id
1901 * The configuration section ID
1904 * The value to validate
1907 * The method shall return `true` to accept the given value. Any other
1908 * return value is treated as failure, converted to a string and displayed
1909 * as error message to the user.
1911 validate: function(section_id
, value
) {
1916 * Test whether the input value is currently valid.
1918 * @param {string} section_id
1919 * The configuration section ID
1921 * @returns {boolean}
1922 * Returns `true` if the input value currently is valid, otherwise it
1925 isValid: function(section_id
) {
1926 var elem
= this.getUIElement(section_id
);
1927 return elem
? elem
.isValid() : true;
1931 * Returns the current validation error for this input.
1933 * @param {string} section_id
1934 * The configuration section ID
1937 * The validation error at this time
1939 getValidationError: function (section_id
) {
1940 var elem
= this.getUIElement(section_id
);
1941 return elem
? elem
.getValidationError() : '';
1945 * Test whether the option element is currently active.
1947 * An element is active when it is not hidden due to unsatisfied dependency
1950 * @param {string} section_id
1951 * The configuration section ID
1953 * @returns {boolean}
1954 * Returns `true` if the option element currently is active, otherwise it
1957 isActive: function(section_id
) {
1958 var field
= this.map
.findElement('data-field', this.cbid(section_id
));
1959 return (field
!= null && !field
.classList
.contains('hidden'));
1963 setActive: function(section_id
, active
) {
1964 var field
= this.map
.findElement('data-field', this.cbid(section_id
));
1966 if (field
&& field
.classList
.contains('hidden') == active
) {
1967 field
.classList
[active
? 'remove' : 'add']('hidden');
1969 if (dom
.matches(field
.parentNode
, '.td.cbi-value-field'))
1970 field
.parentNode
.classList
[active
? 'remove' : 'add']('inactive');
1979 triggerValidation: function(section_id
) {
1980 var elem
= this.getUIElement(section_id
);
1981 return elem
? elem
.triggerValidation() : true;
1985 * Parse the option element input.
1987 * The function is invoked when the `parse()` method has been invoked on
1988 * the parent form and triggers input value reading and validation.
1990 * @param {string} section_id
1991 * The configuration section ID
1993 * @returns {Promise<void>}
1994 * Returns a promise resolving once the input value has been read and
1995 * validated or rejecting in case the input value does not meet the
1996 * validation constraints.
1998 parse: function(section_id
) {
1999 var active
= this.isActive(section_id
);
2001 if (active
&& !this.isValid(section_id
)) {
2002 var title
= this.stripTags(this.title
).trim(),
2003 error
= this.getValidationError(section_id
);
2005 return Promise
.reject(new TypeError(
2006 _('Option "%s" contains an invalid input value.').format(title
|| this.option
) + ' ' + error
));
2010 var cval
= this.cfgvalue(section_id
),
2011 fval
= this.formvalue(section_id
);
2013 if (fval
== null || fval
== '') {
2014 if (this.rmempty
|| this.optional
) {
2015 return Promise
.resolve(this.remove(section_id
));
2018 var title
= this.stripTags(this.title
).trim();
2020 return Promise
.reject(new TypeError(
2021 _('Option "%s" must not be empty.').format(title
|| this.option
)));
2024 else if (this.forcewrite
|| !isEqual(cval
, fval
)) {
2025 return Promise
.resolve(this.write(section_id
, fval
));
2028 else if (!this.retain
) {
2029 return Promise
.resolve(this.remove(section_id
));
2032 return Promise
.resolve();
2036 * Write the current input value into the configuration.
2038 * This function is invoked upon saving the parent form when the option
2039 * element is valid and when its input value has been changed compared to
2040 * the initial value returned by
2041 * [cfgvalue()]{@link LuCI.form.AbstractValue#cfgvalue}.
2043 * The default implementation simply sets the given input value in the
2044 * UCI configuration (or the associated JavaScript object property in
2045 * case of `JSONMap` forms). It may be overwritten by user code to
2046 * implement alternative save logic, e.g. to transform the input value
2047 * before it is written.
2049 * @param {string} section_id
2050 * The configuration section ID
2052 * @param {string|string[]} formvalue
2053 * The input value to write.
2055 write: function(section_id
, formvalue
) {
2056 return this.map
.data
.set(
2057 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
2058 this.ucisection
|| section_id
,
2059 this.ucioption
|| this.option
,
2064 * Remove the corresponding value from the configuration.
2066 * This function is invoked upon saving the parent form when the option
2067 * element has been hidden due to unsatisfied dependencies or when the
2068 * user cleared the input value and the option is marked optional.
2070 * The default implementation simply removes the associated option from the
2071 * UCI configuration (or the associated JavaScript object property in
2072 * case of `JSONMap` forms). It may be overwritten by user code to
2073 * implement alternative removal logic, e.g. to retain the original value.
2075 * @param {string} section_id
2076 * The configuration section ID
2078 remove: function(section_id
) {
2079 var this_cfg
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
2080 this_sid
= this.ucisection
|| section_id
,
2081 this_opt
= this.ucioption
|| this.option
;
2083 for (var i
= 0; i
< this.section
.children
.length
; i
++) {
2084 var sibling
= this.section
.children
[i
];
2086 if (sibling
=== this || sibling
.ucioption
== null)
2089 var sibling_cfg
= sibling
.uciconfig
|| sibling
.section
.uciconfig
|| sibling
.map
.config
,
2090 sibling_sid
= sibling
.ucisection
|| section_id
,
2091 sibling_opt
= sibling
.ucioption
|| sibling
.option
;
2093 if (this_cfg
!= sibling_cfg
|| this_sid
!= sibling_sid
|| this_opt
!= sibling_opt
)
2096 if (!sibling
.isActive(section_id
))
2099 /* found another active option aliasing the same uci option name,
2100 * so we can't remove the value */
2104 this.map
.data
.unset(this_cfg
, this_sid
, this_opt
);
2109 * @class TypedSection
2110 * @memberof LuCI.form
2111 * @augments LuCI.form.AbstractSection
2115 * The `TypedSection` class maps all or - if `filter()` is overwritten - a
2116 * subset of the underlying UCI configuration sections of a given type.
2118 * Layout wise, the configuration section instances mapped by the section
2119 * element (sometimes referred to as "section nodes") are stacked beneath
2120 * each other in a single column, with an optional section remove button next
2121 * to each section node and a section add button at the end, depending on the
2122 * value of the `addremove` property.
2124 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2125 * The configuration form this section is added to. It is automatically passed
2126 * by [section()]{@link LuCI.form.Map#section}.
2128 * @param {string} section_type
2129 * The type of the UCI section to map.
2131 * @param {string} [title]
2132 * The title caption of the form section element.
2134 * @param {string} [description]
2135 * The description text of the form section element.
2137 var CBITypedSection
= CBIAbstractSection
.extend(/** @lends LuCI.form.TypedSection.prototype */ {
2138 __name__
: 'CBI.TypedSection',
2141 * If set to `true`, the user may add or remove instances from the form
2142 * section widget, otherwise only preexisting sections may be edited.
2143 * The default is `false`.
2145 * @name LuCI.form.TypedSection.prototype#addremove
2151 * If set to `true`, mapped section instances are treated as anonymous
2152 * UCI sections, which means that section instance elements will be
2153 * rendered without title element and that no name is required when adding
2154 * new sections. The default is `false`.
2156 * @name LuCI.form.TypedSection.prototype#anonymous
2162 * When set to `true`, instead of rendering section instances one below
2163 * another, treat each instance as separate tab pane and render a tab menu
2164 * at the top of the form section element, allowing the user to switch
2165 * among instances. The default is `false`.
2167 * @name LuCI.form.TypedSection.prototype#tabbed
2173 * Override the caption used for the section add button at the bottom of
2174 * the section form element. If set to a string, it will be used as-is,
2175 * if set to a function, the function will be invoked and its return value
2176 * is used as caption, after converting it to a string. If this property
2177 * is not set, the default is `Add`.
2179 * @name LuCI.form.TypedSection.prototype#addbtntitle
2180 * @type string|function
2185 * Override the UCI configuration name to read the section IDs from. By
2186 * default, the configuration name is inherited from the parent `Map`.
2187 * By setting this property, a deviating configuration may be specified.
2188 * The default is `null`, means inheriting from the parent form.
2190 * @name LuCI.form.TypedSection.prototype#uciconfig
2196 cfgsections: function() {
2197 return this.map
.data
.sections(this.uciconfig
|| this.map
.config
, this.sectiontype
)
2198 .map(function(s
) { return s
['.name'] })
2199 .filter(L
.bind(this.filter
, this));
2203 handleAdd: function(ev
, name
) {
2204 var config_name
= this.uciconfig
|| this.map
.config
;
2206 this.map
.data
.add(config_name
, this.sectiontype
, name
);
2207 return this.map
.save(null, true);
2211 handleRemove: function(section_id
, ev
) {
2212 var config_name
= this.uciconfig
|| this.map
.config
;
2214 this.map
.data
.remove(config_name
, section_id
);
2215 return this.map
.save(null, true);
2219 renderSectionAdd: function(extra_class
) {
2220 if (!this.addremove
)
2223 var createEl
= E('div', { 'class': 'cbi-section-create' }),
2224 config_name
= this.uciconfig
|| this.map
.config
,
2225 btn_title
= this.titleFn('addbtntitle');
2227 if (extra_class
!= null)
2228 createEl
.classList
.add(extra_class
);
2230 if (this.anonymous
) {
2231 createEl
.appendChild(E('button', {
2232 'class': 'cbi-button cbi-button-add',
2233 'title': btn_title
|| _('Add'),
2234 'click': ui
.createHandlerFn(this, 'handleAdd'),
2235 'disabled': this.map
.readonly
|| null
2236 }, [ btn_title
|| _('Add') ]));
2239 var nameEl
= E('input', {
2241 'class': 'cbi-section-create-name',
2242 'disabled': this.map
.readonly
|| null
2245 dom
.append(createEl
, [
2246 E('div', {}, nameEl
),
2248 'class': 'cbi-button cbi-button-add',
2249 'title': btn_title
|| _('Add'),
2250 'click': ui
.createHandlerFn(this, function(ev
) {
2251 if (nameEl
.classList
.contains('cbi-input-invalid'))
2254 return this.handleAdd(ev
, nameEl
.value
);
2256 'disabled': this.map
.readonly
|| true
2257 }, [ btn_title
|| _('Add') ])
2260 if (this.map
.readonly
!== true) {
2261 ui
.addValidator(nameEl
, 'uciname', true, function(v
) {
2262 var button
= createEl
.querySelector('.cbi-section-create > .cbi-button-add');
2264 button
.disabled
= null;
2268 button
.disabled
= true;
2269 return _('Expecting: %s').format(_('non-empty value'));
2271 }, 'blur', 'keyup');
2279 renderSectionPlaceholder: function() {
2280 return E('em', _('This section contains no values yet'));
2284 renderContents: function(cfgsections
, nodes
) {
2285 var section_id
= null,
2286 config_name
= this.uciconfig
|| this.map
.config
,
2287 sectionEl
= E('div', {
2288 'id': 'cbi-%s-%s'.format(config_name
, this.sectiontype
),
2289 'class': 'cbi-section',
2290 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2291 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2294 if (this.title
!= null && this.title
!= '')
2295 sectionEl
.appendChild(E('h3', {}, this.title
));
2297 if (this.description
!= null && this.description
!= '')
2298 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2300 for (var i
= 0; i
< nodes
.length
; i
++) {
2301 if (this.addremove
) {
2302 sectionEl
.appendChild(
2303 E('div', { 'class': 'cbi-section-remove right' },
2305 'class': 'cbi-button',
2306 'name': 'cbi.rts.%s.%s'.format(config_name
, cfgsections
[i
]),
2307 'data-section-id': cfgsections
[i
],
2308 'click': ui
.createHandlerFn(this, 'handleRemove', cfgsections
[i
]),
2309 'disabled': this.map
.readonly
|| null
2310 }, [ _('Delete') ])));
2313 if (!this.anonymous
)
2314 sectionEl
.appendChild(E('h3', cfgsections
[i
].toUpperCase()));
2316 sectionEl
.appendChild(E('div', {
2317 'id': 'cbi-%s-%s'.format(config_name
, cfgsections
[i
]),
2319 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
2320 'data-section-id': cfgsections
[i
]
2324 if (nodes
.length
== 0)
2325 sectionEl
.appendChild(this.renderSectionPlaceholder());
2327 sectionEl
.appendChild(this.renderSectionAdd());
2329 dom
.bindClassInstance(sectionEl
, this);
2335 render: function() {
2336 var cfgsections
= this.cfgsections(),
2339 for (var i
= 0; i
< cfgsections
.length
; i
++)
2340 renderTasks
.push(this.renderUCISection(cfgsections
[i
]));
2342 return Promise
.all(renderTasks
).then(this.renderContents
.bind(this, cfgsections
));
2347 * @class TableSection
2348 * @memberof LuCI.form
2349 * @augments LuCI.form.TypedSection
2353 * The `TableSection` class maps all or - if `filter()` is overwritten - a
2354 * subset of the underlying UCI configuration sections of a given type.
2356 * Layout wise, the configuration section instances mapped by the section
2357 * element (sometimes referred to as "section nodes") are rendered as rows
2358 * within an HTML table element, with an optional section remove button in the
2359 * last column and a section add button below the table, depending on the
2360 * value of the `addremove` property.
2362 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2363 * The configuration form this section is added to. It is automatically passed
2364 * by [section()]{@link LuCI.form.Map#section}.
2366 * @param {string} section_type
2367 * The type of the UCI section to map.
2369 * @param {string} [title]
2370 * The title caption of the form section element.
2372 * @param {string} [description]
2373 * The description text of the form section element.
2375 var CBITableSection
= CBITypedSection
.extend(/** @lends LuCI.form.TableSection.prototype */ {
2376 __name__
: 'CBI.TableSection',
2379 * Override the per-section instance title caption shown in the first
2380 * column of the table unless `anonymous` is set to true. If set to a
2381 * string, it will be used as `String.format()` pattern with the name of
2382 * the underlying UCI section as first argument, if set to a function, the
2383 * function will be invoked with the section name as first argument and
2384 * its return value is used as caption, after converting it to a string.
2385 * If this property is not set, the default is the name of the underlying
2386 * UCI configuration section.
2388 * @name LuCI.form.TableSection.prototype#sectiontitle
2389 * @type string|function
2394 * Override the per-section instance modal popup title caption shown when
2395 * clicking the `More…` button in a section specifying `max_cols`. If set
2396 * to a string, it will be used as `String.format()` pattern with the name
2397 * of the underlying UCI section as first argument, if set to a function,
2398 * the function will be invoked with the section name as first argument and
2399 * its return value is used as caption, after converting it to a string.
2400 * If this property is not set, the default is the name of the underlying
2401 * UCI configuration section.
2403 * @name LuCI.form.TableSection.prototype#modaltitle
2404 * @type string|function
2409 * Specify a maximum amount of columns to display. By default, one table
2410 * column is rendered for each child option of the form section element.
2411 * When this option is set to a positive number, then no more columns than
2412 * the given amount are rendered. When the number of child options exceeds
2413 * the specified amount, a `More…` button is rendered in the last column,
2414 * opening a modal dialog presenting all options elements in `NamedSection`
2415 * style when clicked.
2417 * @name LuCI.form.TableSection.prototype#max_cols
2423 * If set to `true`, alternating `cbi-rowstyle-1` and `cbi-rowstyle-2` CSS
2424 * classes are added to the table row elements. Not all LuCI themes
2425 * implement these row style classes. The default is `false`.
2427 * @name LuCI.form.TableSection.prototype#rowcolors
2433 * Enables a per-section instance row `Edit` button which triggers a certain
2434 * action when clicked. If set to a string, the string value is used
2435 * as `String.format()` pattern with the name of the underlying UCI section
2436 * as first format argument. The result is then interpreted as URL which
2437 * LuCI will navigate to when the user clicks the edit button.
2439 * If set to a function, this function will be registered as click event
2440 * handler on the rendered edit button, receiving the section instance
2441 * name as first and the DOM click event as second argument.
2443 * @name LuCI.form.TableSection.prototype#extedit
2444 * @type string|function
2449 * If set to `true`, a sort button is added to the last column, allowing
2450 * the user to reorder the section instances mapped by the section form
2453 * @name LuCI.form.TableSection.prototype#sortable
2459 * If set to `true`, the header row with the options descriptions will
2460 * not be displayed. By default, descriptions row is automatically displayed
2461 * when at least one option has a description.
2463 * @name LuCI.form.TableSection.prototype#nodescriptions
2469 * The `TableSection` implementation does not support option tabbing, so
2470 * its implementation of `tab()` will always throw an exception when
2474 * @throws Throws an exception when invoked.
2477 throw 'Tabs are not supported by TableSection';
2481 renderContents: function(cfgsections
, nodes
) {
2482 var section_id
= null,
2483 config_name
= this.uciconfig
|| this.map
.config
,
2484 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2485 has_more
= max_cols
< this.children
.length
,
2486 drag_sort
= this.sortable
&& !('ontouchstart' in window
),
2487 touch_sort
= this.sortable
&& ('ontouchstart' in window
),
2488 sectionEl
= E('div', {
2489 'id': 'cbi-%s-%s'.format(config_name
, this.sectiontype
),
2490 'class': 'cbi-section cbi-tblsection',
2491 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2492 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2494 tableEl
= E('table', {
2495 'class': 'table cbi-section-table'
2498 if (this.title
!= null && this.title
!= '')
2499 sectionEl
.appendChild(E('h3', {}, this.title
));
2501 if (this.description
!= null && this.description
!= '')
2502 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2504 tableEl
.appendChild(this.renderHeaderRows(max_cols
));
2506 for (var i
= 0; i
< nodes
.length
; i
++) {
2507 var sectionname
= this.titleFn('sectiontitle', cfgsections
[i
]);
2509 if (sectionname
== null)
2510 sectionname
= cfgsections
[i
];
2512 var trEl
= E('tr', {
2513 'id': 'cbi-%s-%s'.format(config_name
, cfgsections
[i
]),
2514 'class': 'tr cbi-section-table-row',
2515 'data-sid': cfgsections
[i
],
2516 'draggable': (drag_sort
|| touch_sort
) ? true : null,
2517 'mousedown': drag_sort
? L
.bind(this.handleDragInit
, this) : null,
2518 'dragstart': drag_sort
? L
.bind(this.handleDragStart
, this) : null,
2519 'dragover': drag_sort
? L
.bind(this.handleDragOver
, this) : null,
2520 'dragenter': drag_sort
? L
.bind(this.handleDragEnter
, this) : null,
2521 'dragleave': drag_sort
? L
.bind(this.handleDragLeave
, this) : null,
2522 'dragend': drag_sort
? L
.bind(this.handleDragEnd
, this) : null,
2523 'drop': drag_sort
? L
.bind(this.handleDrop
, this) : null,
2524 'touchmove': touch_sort
? L
.bind(this.handleTouchMove
, this) : null,
2525 'touchend': touch_sort
? L
.bind(this.handleTouchEnd
, this) : null,
2526 'data-title': (sectionname
&& (!this.anonymous
|| this.sectiontitle
)) ? sectionname
: null,
2527 'data-section-id': cfgsections
[i
]
2530 if (this.extedit
|| this.rowcolors
)
2531 trEl
.classList
.add(!(tableEl
.childNodes
.length
% 2)
2532 ? 'cbi-rowstyle-1' : 'cbi-rowstyle-2');
2534 for (var j
= 0; j
< max_cols
&& nodes
[i
].firstChild
; j
++)
2535 trEl
.appendChild(nodes
[i
].firstChild
);
2537 trEl
.appendChild(this.renderRowActions(cfgsections
[i
], has_more
? _('More…') : null));
2538 tableEl
.appendChild(trEl
);
2541 if (nodes
.length
== 0)
2542 tableEl
.appendChild(E('tr', { 'class': 'tr cbi-section-table-row placeholder' },
2543 E('td', { 'class': 'td' }, this.renderSectionPlaceholder())));
2545 sectionEl
.appendChild(tableEl
);
2547 sectionEl
.appendChild(this.renderSectionAdd('cbi-tblsection-create'));
2549 dom
.bindClassInstance(sectionEl
, this);
2555 renderHeaderRows: function(max_cols
, has_action
) {
2556 var has_titles
= false,
2557 has_descriptions
= false,
2558 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2559 has_more
= max_cols
< this.children
.length
,
2560 anon_class
= (!this.anonymous
|| this.sectiontitle
) ? 'named' : 'anonymous',
2563 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2567 has_titles
= has_titles
|| !!opt
.title
;
2568 has_descriptions
= has_descriptions
|| !!opt
.description
;
2572 var trEl
= E('tr', {
2573 'class': 'tr cbi-section-table-titles ' + anon_class
,
2574 'data-title': (!this.anonymous
|| this.sectiontitle
) ? _('Name') : null,
2575 'click': this.sortable
? ui
.createHandlerFn(this, 'handleSort') : null
2578 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2582 trEl
.appendChild(E('th', {
2583 'class': 'th cbi-section-table-cell',
2584 'data-widget': opt
.__name__
,
2585 'data-sortable-row': this.sortable
? '' : null
2588 if (opt
.width
!= null)
2589 trEl
.lastElementChild
.style
.width
=
2590 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2593 trEl
.lastElementChild
.appendChild(E('a', {
2594 'href': opt
.titleref
,
2595 'class': 'cbi-title-ref',
2596 'title': this.titledesc
|| _('Go to relevant configuration page')
2599 dom
.content(trEl
.lastElementChild
, opt
.title
);
2602 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2603 trEl
.appendChild(E('th', {
2604 'class': 'th cbi-section-table-cell cbi-section-actions'
2607 trEls
.appendChild(trEl
);
2610 if (has_descriptions
&& !this.nodescriptions
) {
2611 var trEl
= E('tr', {
2612 'class': 'tr cbi-section-table-descr ' + anon_class
2615 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2619 trEl
.appendChild(E('th', {
2620 'class': 'th cbi-section-table-cell',
2621 'data-widget': opt
.__name__
2622 }, opt
.description
));
2624 if (opt
.width
!= null)
2625 trEl
.lastElementChild
.style
.width
=
2626 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2629 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2630 trEl
.appendChild(E('th', {
2631 'class': 'th cbi-section-table-cell cbi-section-actions'
2634 trEls
.appendChild(trEl
);
2641 renderRowActions: function(section_id
, more_label
) {
2642 var config_name
= this.uciconfig
|| this.map
.config
;
2644 if (!this.sortable
&& !this.extedit
&& !this.addremove
&& !more_label
)
2647 var tdEl
= E('td', {
2648 'class': 'td cbi-section-table-cell nowrap cbi-section-actions'
2651 if (this.sortable
) {
2652 dom
.append(tdEl
.lastElementChild
, [
2654 'title': _('Drag to reorder'),
2655 'class': 'cbi-button drag-handle center',
2656 'style': 'cursor:move',
2657 'disabled': this.map
.readonly
|| null
2665 if (typeof(this.extedit
) == 'function')
2666 evFn
= L
.bind(this.extedit
, this);
2667 else if (typeof(this.extedit
) == 'string')
2668 evFn
= L
.bind(function(sid
, ev
) {
2669 location
.href
= this.extedit
.format(sid
);
2670 }, this, section_id
);
2672 dom
.append(tdEl
.lastElementChild
,
2675 'class': 'cbi-button cbi-button-edit',
2682 dom
.append(tdEl
.lastElementChild
,
2684 'title': more_label
,
2685 'class': 'cbi-button cbi-button-edit',
2686 'click': ui
.createHandlerFn(this, 'renderMoreOptionsModal', section_id
)
2691 if (this.addremove
) {
2692 var btn_title
= this.titleFn('removebtntitle', section_id
);
2694 dom
.append(tdEl
.lastElementChild
,
2696 'title': btn_title
|| _('Delete'),
2697 'class': 'cbi-button cbi-button-remove',
2698 'click': ui
.createHandlerFn(this, 'handleRemove', section_id
),
2699 'disabled': this.map
.readonly
|| null
2700 }, [ btn_title
|| _('Delete') ])
2708 handleDragInit: function(ev
) {
2709 scope
.dragState
= { node
: ev
.target
};
2713 handleDragStart: function(ev
) {
2714 if (!scope
.dragState
|| !scope
.dragState
.node
.classList
.contains('drag-handle')) {
2715 scope
.dragState
= null;
2716 ev
.preventDefault();
2720 scope
.dragState
.node
= dom
.parent(scope
.dragState
.node
, '.tr');
2721 ev
.dataTransfer
.setData('text', 'drag');
2722 ev
.target
.style
.opacity
= 0.4;
2726 handleDragOver: function(ev
) {
2727 var n
= scope
.dragState
.targetNode
,
2728 r
= scope
.dragState
.rect
,
2729 t
= r
.top
+ r
.height
/ 2;
2731 if (ev
.clientY
<= t
) {
2732 n
.classList
.remove('drag-over-below');
2733 n
.classList
.add('drag-over-above');
2736 n
.classList
.remove('drag-over-above');
2737 n
.classList
.add('drag-over-below');
2740 ev
.dataTransfer
.dropEffect
= 'move';
2741 ev
.preventDefault();
2746 handleDragEnter: function(ev
) {
2747 scope
.dragState
.rect
= ev
.currentTarget
.getBoundingClientRect();
2748 scope
.dragState
.targetNode
= ev
.currentTarget
;
2752 handleDragLeave: function(ev
) {
2753 ev
.currentTarget
.classList
.remove('drag-over-above');
2754 ev
.currentTarget
.classList
.remove('drag-over-below');
2758 handleDragEnd: function(ev
) {
2761 n
.style
.opacity
= '';
2762 n
.classList
.add('flash');
2763 n
.parentNode
.querySelectorAll('.drag-over-above, .drag-over-below')
2764 .forEach(function(tr
) {
2765 tr
.classList
.remove('drag-over-above');
2766 tr
.classList
.remove('drag-over-below');
2771 handleDrop: function(ev
) {
2772 var s
= scope
.dragState
;
2774 if (s
.node
&& s
.targetNode
) {
2775 var config_name
= this.uciconfig
|| this.map
.config
,
2776 ref_node
= s
.targetNode
,
2779 if (ref_node
.classList
.contains('drag-over-below')) {
2780 ref_node
= ref_node
.nextElementSibling
;
2784 var sid1
= s
.node
.getAttribute('data-sid'),
2785 sid2
= s
.targetNode
.getAttribute('data-sid');
2787 s
.node
.parentNode
.insertBefore(s
.node
, ref_node
);
2788 this.map
.data
.move(config_name
, sid1
, sid2
, after
);
2791 scope
.dragState
= null;
2792 ev
.target
.style
.opacity
= '';
2793 ev
.stopPropagation();
2794 ev
.preventDefault();
2799 determineBackgroundColor: function(node
) {
2800 var r
= 255, g
= 255, b
= 255;
2803 var s
= window
.getComputedStyle(node
),
2804 c
= (s
.getPropertyValue('background-color') || '').replace(/ /g
, '');
2806 if (c
!= '' && c
!= 'transparent' && c
!= 'rgba(0,0,0,0)') {
2807 if (/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.test(c
)) {
2808 r
= parseInt(RegExp
.$1, 16);
2809 g
= parseInt(RegExp
.$2, 16);
2810 b
= parseInt(RegExp
.$3, 16);
2812 else if (/^rgba?\(([0-9]+),([0-9]+),([0-9]+)[,)]$/.test(c
)) {
2821 node
= node
.parentNode
;
2828 handleTouchMove: function(ev
) {
2829 if (!ev
.target
.classList
.contains('drag-handle'))
2832 var touchLoc
= ev
.targetTouches
[0],
2834 rowElem
= dom
.parent(rowBtn
, '.tr'),
2835 htmlElem
= document
.querySelector('html'),
2836 dragHandle
= document
.querySelector('.touchsort-element'),
2837 viewportHeight
= Math
.max(document
.documentElement
.clientHeight
, window
.innerHeight
|| 0);
2840 var rowRect
= rowElem
.getBoundingClientRect(),
2841 btnRect
= rowBtn
.getBoundingClientRect(),
2842 paddingLeft
= btnRect
.left
- rowRect
.left
,
2843 paddingRight
= rowRect
.right
- btnRect
.right
,
2844 colorBg
= this.determineBackgroundColor(rowElem
),
2845 colorFg
= (colorBg
[0] * 0.299 + colorBg
[1] * 0.587 + colorBg
[2] * 0.114) > 186 ? [ 0, 0, 0 ] : [ 255, 255, 255 ];
2847 dragHandle
= E('div', { 'class': 'touchsort-element' }, [
2848 E('strong', [ rowElem
.getAttribute('data-title') ]),
2849 rowBtn
.cloneNode(true)
2852 Object
.assign(dragHandle
.style
, {
2853 position
: 'absolute',
2854 boxShadow
: '0 0 3px rgba(%d, %d, %d, 1)'.format(colorFg
[0], colorFg
[1], colorFg
[2]),
2855 background
: 'rgba(%d, %d, %d, 0.8)'.format(colorBg
[0], colorBg
[1], colorBg
[2]),
2856 top
: rowRect
.top
+ 'px',
2857 left
: rowRect
.left
+ 'px',
2858 width
: rowRect
.width
+ 'px',
2859 height
: (rowBtn
.offsetHeight
+ 4) + 'px'
2862 Object
.assign(dragHandle
.firstElementChild
.style
, {
2863 position
: 'absolute',
2864 lineHeight
: dragHandle
.style
.height
,
2865 whiteSpace
: 'nowrap',
2867 textOverflow
: 'ellipsis',
2868 left
: (paddingRight
> paddingLeft
) ? '' : '5px',
2869 right
: (paddingRight
> paddingLeft
) ? '5px' : '',
2870 width
: (Math
.max(paddingLeft
, paddingRight
) - 10) + 'px'
2873 Object
.assign(dragHandle
.lastElementChild
.style
, {
2874 position
: 'absolute',
2876 left
: paddingLeft
+ 'px',
2877 width
: rowBtn
.offsetWidth
+ 'px'
2880 document
.body
.appendChild(dragHandle
);
2882 rowElem
.classList
.remove('flash');
2886 dragHandle
.style
.top
= (touchLoc
.pageY
- (parseInt(dragHandle
.style
.height
) / 2)) + 'px';
2888 rowElem
.parentNode
.querySelectorAll('[draggable]').forEach(function(tr
, i
, trs
) {
2889 var trRect
= tr
.getBoundingClientRect(),
2890 yTop
= trRect
.top
+ window
.scrollY
,
2891 yBottom
= trRect
.bottom
+ window
.scrollY
,
2892 yMiddle
= yTop
+ ((yBottom
- yTop
) / 2);
2894 tr
.classList
.remove('drag-over-above', 'drag-over-below');
2896 if ((i
== 0 || touchLoc
.pageY
>= yTop
) && touchLoc
.pageY
<= yMiddle
)
2897 tr
.classList
.add('drag-over-above');
2898 else if ((i
== (trs
.length
- 1) || touchLoc
.pageY
<= yBottom
) && touchLoc
.pageY
> yMiddle
)
2899 tr
.classList
.add('drag-over-below');
2902 /* prevent standard scrolling and scroll page when drag handle is
2903 * moved very close (~30px) to the viewport edge */
2905 ev
.preventDefault();
2907 if (touchLoc
.clientY
< 30)
2908 window
.requestAnimationFrame(function() { htmlElem
.scrollTop
-= 30 });
2909 else if (touchLoc
.clientY
> viewportHeight
- 30)
2910 window
.requestAnimationFrame(function() { htmlElem
.scrollTop
+= 30 });
2914 handleTouchEnd: function(ev
) {
2915 var rowElem
= dom
.parent(ev
.target
, '.tr'),
2916 htmlElem
= document
.querySelector('html'),
2917 dragHandle
= document
.querySelector('.touchsort-element'),
2918 targetElem
= rowElem
.parentNode
.querySelector('.drag-over-above, .drag-over-below'),
2919 viewportHeight
= Math
.max(document
.documentElement
.clientHeight
, window
.innerHeight
|| 0);
2925 var isBelow
= targetElem
.classList
.contains('drag-over-below');
2927 rowElem
.parentNode
.insertBefore(rowElem
, isBelow
? targetElem
.nextElementSibling
: targetElem
);
2930 this.uciconfig
|| this.map
.config
,
2931 rowElem
.getAttribute('data-sid'),
2932 targetElem
.getAttribute('data-sid'),
2935 window
.requestAnimationFrame(function() {
2936 var rowRect
= rowElem
.getBoundingClientRect();
2938 if (rowRect
.top
< 50)
2939 htmlElem
.scrollTop
= (htmlElem
.scrollTop
+ rowRect
.top
- 50);
2940 else if (rowRect
.bottom
> viewportHeight
- 50)
2941 htmlElem
.scrollTop
= (htmlElem
.scrollTop
+ viewportHeight
- 50 - rowRect
.height
);
2943 rowElem
.classList
.add('flash');
2946 targetElem
.classList
.remove('drag-over-above', 'drag-over-below');
2949 document
.body
.removeChild(dragHandle
);
2953 handleModalCancel: function(modalMap
, ev
) {
2954 var prevNode
= this.getPreviousModalMap(),
2955 resetTasks
= Promise
.resolve();
2958 var heading
= prevNode
.parentNode
.querySelector('h4'),
2959 prevMap
= dom
.findClassInstance(prevNode
);
2962 resetTasks
= resetTasks
2963 .then(L
.bind(prevMap
.load
, prevMap
))
2964 .then(L
.bind(prevMap
.reset
, prevMap
));
2966 prevMap
= prevMap
.parent
;
2969 prevNode
.classList
.add('flash');
2970 prevNode
.classList
.remove('hidden');
2971 prevNode
.parentNode
.removeChild(prevNode
.nextElementSibling
);
2973 heading
.removeChild(heading
.lastElementChild
);
2975 if (!this.getPreviousModalMap())
2977 .querySelector('div.right > button')
2978 .firstChild
.data
= _('Dismiss');
2988 handleModalSave: function(modalMap
, ev
) {
2989 var mapNode
= this.getActiveModalMap(),
2990 activeMap
= dom
.findClassInstance(mapNode
),
2991 saveTasks
= activeMap
.save(null, true);
2993 while (activeMap
.parent
) {
2994 activeMap
= activeMap
.parent
;
2995 saveTasks
= saveTasks
2996 .then(L
.bind(activeMap
.load
, activeMap
))
2997 .then(L
.bind(activeMap
.reset
, activeMap
));
3001 .then(L
.bind(this.handleModalCancel
, this, modalMap
, ev
, true))
3002 .catch(function() {});
3006 handleSort: function(ev
) {
3007 if (!ev
.target
.matches('th[data-sortable-row]'))
3011 descending
= (th
.getAttribute('data-sort-direction') == 'desc'),
3012 config_name
= this.uciconfig
|| this.map
.config
,
3016 ev
.currentTarget
.querySelectorAll('th').forEach(function(other_th
, i
) {
3017 if (other_th
!== th
)
3018 other_th
.removeAttribute('data-sort-direction');
3023 ev
.currentTarget
.parentNode
.querySelectorAll('tr.cbi-section-table-row').forEach(L
.bind(function(tr
, i
) {
3024 var sid
= tr
.getAttribute('data-sid'),
3025 opt
= tr
.childNodes
[index
].getAttribute('data-name'),
3026 val
= this.cfgvalue(sid
, opt
);
3028 tr
.querySelectorAll('.flash').forEach(function(n
) {
3029 n
.classList
.remove('flash')
3033 ui
.Table
.prototype.deriveSortKey((val
!= null) ? val
.trim() : ''),
3038 list
.sort(function(a
, b
) {
3040 ? -L
.naturalCompare(a
[0], b
[0])
3041 : L
.naturalCompare(a
[0], b
[0]);
3044 window
.requestAnimationFrame(L
.bind(function() {
3045 var ref_sid
, cur_sid
;
3047 for (var i
= 0; i
< list
.length
; i
++) {
3048 list
[i
][1].childNodes
[index
].classList
.add('flash');
3049 th
.parentNode
.parentNode
.appendChild(list
[i
][1]);
3051 cur_sid
= list
[i
][1].getAttribute('data-sid');
3054 this.map
.data
.move(config_name
, cur_sid
, ref_sid
, true);
3059 th
.setAttribute('data-sort-direction', descending
? 'asc' : 'desc');
3064 * Add further options to the per-section instanced modal popup.
3066 * This function may be overwritten by user code to perform additional
3067 * setup steps before displaying the more options modal which is useful to
3068 * e.g. query additional data or to inject further option elements.
3070 * The default implementation of this function does nothing.
3073 * @param {LuCI.form.NamedSection} modalSection
3074 * The `NamedSection` instance about to be rendered in the modal popup.
3076 * @param {string} section_id
3077 * The ID of the underlying UCI section the modal popup belongs to.
3080 * The DOM event emitted by clicking the `More…` button.
3082 * @returns {*|Promise<*>}
3083 * Return values of this function are ignored but if a promise is returned,
3084 * it is run to completion before the rendering is continued, allowing
3085 * custom logic to perform asynchronous work before the modal dialog
3088 addModalOptions: function(modalSection
, section_id
, ev
) {
3093 getActiveModalMap: function() {
3094 return document
.querySelector('body.modal-overlay-active > #modal_overlay > .modal.cbi-modal > .cbi-map:not(.hidden)');
3098 getPreviousModalMap: function() {
3099 var mapNode
= this.getActiveModalMap(),
3100 prevNode
= mapNode
? mapNode
.previousElementSibling
: null;
3102 return (prevNode
&& prevNode
.matches('.cbi-map.hidden')) ? prevNode
: null;
3106 cloneOptions: function(src_section
, dest_section
) {
3107 for (var i
= 0; i
< src_section
.children
.length
; i
++) {
3108 var o1
= src_section
.children
[i
];
3110 if (o1
.modalonly
=== false && src_section
=== this)
3115 if (o1
.subsection
) {
3116 o2
= dest_section
.option(o1
.constructor, o1
.option
, o1
.subsection
.constructor, o1
.subsection
.sectiontype
, o1
.subsection
.title
, o1
.subsection
.description
);
3118 for (var k
in o1
.subsection
) {
3119 if (!o1
.subsection
.hasOwnProperty(k
))
3125 case 'parentoption':
3129 o2
.subsection
[k
] = o1
.subsection
[k
];
3133 this.cloneOptions(o1
.subsection
, o2
.subsection
);
3136 o2
= dest_section
.option(o1
.constructor, o1
.option
, o1
.title
, o1
.description
);
3140 if (!o1
.hasOwnProperty(k
))
3160 renderMoreOptionsModal: function(section_id
, ev
) {
3161 var parent
= this.map
,
3162 sref
= parent
.data
.get(parent
.config
, section_id
),
3163 mapNode
= this.getActiveModalMap(),
3164 activeMap
= mapNode
? dom
.findClassInstance(mapNode
) : null,
3165 stackedMap
= activeMap
&& (activeMap
.parent
!== parent
|| activeMap
.section
!== section_id
);
3167 return (stackedMap
? activeMap
.save(null, true) : Promise
.resolve()).then(L
.bind(function() {
3168 section_id
= sref
['.name'];
3172 if (parent
instanceof CBIJSONMap
) {
3173 m
= new CBIJSONMap(null, null, null);
3174 m
.data
= parent
.data
;
3177 m
= new CBIMap(parent
.config
, null, null);
3180 var s
= m
.section(CBINamedSection
, section_id
, this.sectiontype
);
3183 m
.section
= section_id
;
3184 m
.readonly
= parent
.readonly
;
3187 s
.tab_names
= this.tab_names
;
3189 this.cloneOptions(this, s
);
3191 return Promise
.resolve(this.addModalOptions(s
, section_id
, ev
)).then(function() {
3193 }).then(L
.bind(function(nodes
) {
3194 var title
= parent
.title
,
3197 if ((name
= this.titleFn('modaltitle', section_id
)) != null)
3199 else if ((name
= this.titleFn('sectiontitle', section_id
)) != null)
3200 title
= '%s - %s'.format(parent
.title
, name
);
3201 else if (!this.anonymous
)
3202 title
= '%s - %s'.format(parent
.title
, section_id
);
3206 .querySelector('h4')
3207 .appendChild(E('span', title
? ' » ' + title
: ''));
3210 .querySelector('div.right > button')
3211 .firstChild
.data
= _('Back');
3213 mapNode
.classList
.add('hidden');
3214 mapNode
.parentNode
.insertBefore(nodes
, mapNode
.nextElementSibling
);
3216 nodes
.classList
.add('flash');
3219 ui
.showModal(title
, [
3221 E('div', { 'class': 'right' }, [
3223 'class': 'cbi-button',
3224 'click': ui
.createHandlerFn(this, 'handleModalCancel', m
)
3225 }, [ _('Dismiss') ]), ' ',
3227 'class': 'cbi-button cbi-button-positive important',
3228 'click': ui
.createHandlerFn(this, 'handleModalSave', m
),
3229 'disabled': m
.readonly
|| null
3235 }, this)).catch(L
.error
);
3240 * @class GridSection
3241 * @memberof LuCI.form
3242 * @augments LuCI.form.TableSection
3246 * The `GridSection` class maps all or - if `filter()` is overwritten - a
3247 * subset of the underlying UCI configuration sections of a given type.
3249 * A grid section functions similar to a {@link LuCI.form.TableSection} but
3250 * supports tabbing in the modal overlay. Option elements added with
3251 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
3252 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
3253 * are displayed in the modal popup.
3255 * Another important difference is that the table cells show a readonly text
3256 * preview of the corresponding option elements by default, unless the child
3257 * option element is explicitly made writable by setting the `editable`
3258 * property to `true`.
3260 * Additionally, the grid section honours a `modalonly` property of child
3261 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
3262 * documentation for details.
3264 * Layout wise, a grid section looks mostly identical to table sections.
3266 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3267 * The configuration form this section is added to. It is automatically passed
3268 * by [section()]{@link LuCI.form.Map#section}.
3270 * @param {string} section_type
3271 * The type of the UCI section to map.
3273 * @param {string} [title]
3274 * The title caption of the form section element.
3276 * @param {string} [description]
3277 * The description text of the form section element.
3279 var CBIGridSection
= CBITableSection
.extend(/** @lends LuCI.form.GridSection.prototype */ {
3281 * Add an option tab to the section.
3283 * The modal option elements of a grid section may be divided into multiple
3284 * tabs to provide a better overview to the user.
3286 * Before options can be moved into a tab pane, the corresponding tab
3287 * has to be defined first, which is done by calling this function.
3289 * Note that tabs are only effective in modal popups, options added with
3290 * `option()` will not be assigned to a specific tab and are rendered in
3291 * the table view only.
3293 * @param {string} name
3294 * The name of the tab to register. It may be freely chosen and just serves
3295 * as an identifier to differentiate tabs.
3297 * @param {string} title
3298 * The human readable caption of the tab.
3300 * @param {string} [description]
3301 * An additional description text for the corresponding tab pane. It is
3302 * displayed as text paragraph below the tab but before the tab pane
3303 * contents. If omitted, no description will be rendered.
3306 * Throws an exception if a tab with the same `name` already exists.
3308 tab: function(name
, title
, description
) {
3309 CBIAbstractSection
.prototype.tab
.call(this, name
, title
, description
);
3313 handleAdd: function(ev
, name
) {
3314 var config_name
= this.uciconfig
|| this.map
.config
,
3315 section_id
= this.map
.data
.add(config_name
, this.sectiontype
, name
),
3316 mapNode
= this.getPreviousModalMap(),
3317 prevMap
= mapNode
? dom
.findClassInstance(mapNode
) : this.map
;
3319 prevMap
.addedSection
= section_id
;
3321 return this.renderMoreOptionsModal(section_id
);
3325 handleModalSave: function(/* ... */) {
3326 var mapNode
= this.getPreviousModalMap(),
3327 prevMap
= mapNode
? dom
.findClassInstance(mapNode
) : this.map
;
3329 return this.super('handleModalSave', arguments
);
3333 handleModalCancel: function(modalMap
, ev
, isSaving
) {
3334 var config_name
= this.uciconfig
|| this.map
.config
,
3335 mapNode
= this.getPreviousModalMap(),
3336 prevMap
= mapNode
? dom
.findClassInstance(mapNode
) : this.map
;
3338 if (prevMap
.addedSection
!= null && !isSaving
)
3339 this.map
.data
.remove(config_name
, prevMap
.addedSection
);
3341 delete prevMap
.addedSection
;
3343 return this.super('handleModalCancel', arguments
);
3347 renderUCISection: function(section_id
) {
3348 return this.renderOptions(null, section_id
);
3352 renderChildren: function(tab_name
, section_id
, in_table
) {
3353 var tasks
= [], index
= 0;
3355 for (var i
= 0, opt
; (opt
= this.children
[i
]) != null; i
++) {
3356 if (opt
.disable
|| opt
.modalonly
)
3360 tasks
.push(opt
.render(index
++, section_id
, in_table
));
3362 tasks
.push(this.renderTextValue(section_id
, opt
));
3365 return Promise
.all(tasks
);
3369 renderTextValue: function(section_id
, opt
) {
3370 var title
= this.stripTags(opt
.title
).trim(),
3371 descr
= this.stripTags(opt
.description
).trim(),
3372 value
= opt
.textvalue(section_id
);
3375 'class': 'td cbi-value-field',
3376 'data-title': (title
!= '') ? title
: null,
3377 'data-description': (descr
!= '') ? descr
: null,
3378 'data-name': opt
.option
,
3379 'data-widget': 'CBI.DummyValue'
3380 }, (value
!= null) ? value
: E('em', _('none')));
3384 renderHeaderRows: function(section_id
) {
3385 return this.super('renderHeaderRows', [ NaN
, true ]);
3389 renderRowActions: function(section_id
) {
3390 return this.super('renderRowActions', [ section_id
, _('Edit') ]);
3395 var section_ids
= this.cfgsections(),
3398 if (Array
.isArray(this.children
)) {
3399 for (var i
= 0; i
< section_ids
.length
; i
++) {
3400 for (var j
= 0; j
< this.children
.length
; j
++) {
3401 if (!this.children
[j
].editable
|| this.children
[j
].modalonly
)
3404 tasks
.push(this.children
[j
].parse(section_ids
[i
]));
3409 return Promise
.all(tasks
);
3414 * @class NamedSection
3415 * @memberof LuCI.form
3416 * @augments LuCI.form.AbstractSection
3420 * The `NamedSection` class maps exactly one UCI section instance which is
3421 * specified when constructing the class instance.
3423 * Layout and functionality wise, a named section is essentially a
3424 * `TypedSection` which allows exactly one section node.
3426 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3427 * The configuration form this section is added to. It is automatically passed
3428 * by [section()]{@link LuCI.form.Map#section}.
3430 * @param {string} section_id
3431 * The name (ID) of the UCI section to map.
3433 * @param {string} section_type
3434 * The type of the UCI section to map.
3436 * @param {string} [title]
3437 * The title caption of the form section element.
3439 * @param {string} [description]
3440 * The description text of the form section element.
3442 var CBINamedSection
= CBIAbstractSection
.extend(/** @lends LuCI.form.NamedSection.prototype */ {
3443 __name__
: 'CBI.NamedSection',
3444 __init__: function(map
, section_id
/*, ... */) {
3445 this.super('__init__', this.varargs(arguments
, 2, map
));
3447 this.section
= section_id
;
3451 * If set to `true`, the user may remove or recreate the sole mapped
3452 * configuration instance from the form section widget, otherwise only a
3453 * preexisting section may be edited. The default is `false`.
3455 * @name LuCI.form.NamedSection.prototype#addremove
3461 * Override the UCI configuration name to read the section IDs from. By
3462 * default, the configuration name is inherited from the parent `Map`.
3463 * By setting this property, a deviating configuration may be specified.
3464 * The default is `null`, means inheriting from the parent form.
3466 * @name LuCI.form.NamedSection.prototype#uciconfig
3472 * The `NamedSection` class overwrites the generic `cfgsections()`
3473 * implementation to return a one-element array containing the mapped
3474 * section ID as sole element. User code should not normally change this.
3476 * @returns {string[]}
3477 * Returns a one-element array containing the mapped section ID.
3479 cfgsections: function() {
3480 return [ this.section
];
3484 handleAdd: function(ev
) {
3485 var section_id
= this.section
,
3486 config_name
= this.uciconfig
|| this.map
.config
;
3488 this.map
.data
.add(config_name
, this.sectiontype
, section_id
);
3489 return this.map
.save(null, true);
3493 handleRemove: function(ev
) {
3494 var section_id
= this.section
,
3495 config_name
= this.uciconfig
|| this.map
.config
;
3497 this.map
.data
.remove(config_name
, section_id
);
3498 return this.map
.save(null, true);
3502 renderContents: function(data
) {
3503 var ucidata
= data
[0], nodes
= data
[1],
3504 section_id
= this.section
,
3505 config_name
= this.uciconfig
|| this.map
.config
,
3506 sectionEl
= E('div', {
3507 'id': ucidata
? null : 'cbi-%s-%s'.format(config_name
, section_id
),
3508 'class': 'cbi-section',
3509 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
3510 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
3513 if (typeof(this.title
) === 'string' && this.title
!== '')
3514 sectionEl
.appendChild(E('h3', {}, this.title
));
3516 if (typeof(this.description
) === 'string' && this.description
!== '')
3517 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
3520 if (this.addremove
) {
3521 sectionEl
.appendChild(
3522 E('div', { 'class': 'cbi-section-remove right' },
3524 'class': 'cbi-button',
3525 'click': ui
.createHandlerFn(this, 'handleRemove'),
3526 'disabled': this.map
.readonly
|| null
3527 }, [ _('Delete') ])));
3530 sectionEl
.appendChild(E('div', {
3531 'id': 'cbi-%s-%s'.format(config_name
, section_id
),
3533 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3534 'data-section-id': section_id
3537 else if (this.addremove
) {
3538 sectionEl
.appendChild(
3540 'class': 'cbi-button cbi-button-add',
3541 'click': ui
.createHandlerFn(this, 'handleAdd'),
3542 'disabled': this.map
.readonly
|| null
3546 dom
.bindClassInstance(sectionEl
, this);
3552 render: function() {
3553 var config_name
= this.uciconfig
|| this.map
.config
,
3554 section_id
= this.section
;
3556 return Promise
.all([
3557 this.map
.data
.get(config_name
, section_id
),
3558 this.renderUCISection(section_id
)
3559 ]).then(this.renderContents
.bind(this));
3565 * @memberof LuCI.form
3566 * @augments LuCI.form.AbstractValue
3570 * The `Value` class represents a simple one-line form input using the
3571 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3572 * {@link LuCI.ui.Combobox} class as underlying widget.
3574 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3575 * The configuration form this section is added to. It is automatically passed
3576 * by [option()]{@link LuCI.form.AbstractSection#option} or
3577 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3578 * option to the section.
3580 * @param {LuCI.form.AbstractSection} section
3581 * The configuration section this option is added to. It is automatically passed
3582 * by [option()]{@link LuCI.form.AbstractSection#option} or
3583 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3584 * option to the section.
3586 * @param {string} option
3587 * The name of the UCI option to map.
3589 * @param {string} [title]
3590 * The title caption of the option element.
3592 * @param {string} [description]
3593 * The description text of the option element.
3595 var CBIValue
= CBIAbstractValue
.extend(/** @lends LuCI.form.Value.prototype */ {
3596 __name__
: 'CBI.Value',
3599 * If set to `true`, the field is rendered as password input, otherwise
3600 * as plain text input.
3602 * @name LuCI.form.Value.prototype#password
3608 * Set a placeholder string to use when the input field is empty.
3610 * @name LuCI.form.Value.prototype#placeholder
3616 * Add a predefined choice to the form option. By adding one or more
3617 * choices, the plain text input field is turned into a combobox widget
3618 * which prompts the user to select a predefined choice, or to enter a
3621 * @param {string} key
3622 * The choice value to add.
3624 * @param {Node|string} val
3625 * The caption for the choice value. May be a DOM node, a document fragment
3626 * or a plain text string. If omitted, the `key` value is used as caption.
3628 value: function(key
, val
) {
3629 this.keylist
= this.keylist
|| [];
3630 this.keylist
.push(String(key
));
3632 this.vallist
= this.vallist
|| [];
3633 this.vallist
.push(dom
.elem(val
) ? val
: String(val
!= null ? val
: key
));
3637 render: function(option_index
, section_id
, in_table
) {
3638 return Promise
.resolve(this.cfgvalue(section_id
))
3639 .then(this.renderWidget
.bind(this, section_id
, option_index
))
3640 .then(this.renderFrame
.bind(this, section_id
, in_table
, option_index
));
3644 handleValueChange: function(section_id
, state
, ev
) {
3645 if (typeof(this.onchange
) != 'function')
3648 var value
= this.formvalue(section_id
);
3650 if (isEqual(value
, state
.previousValue
))
3653 state
.previousValue
= value
;
3654 this.onchange
.call(this, ev
, section_id
, value
);
3658 renderFrame: function(section_id
, in_table
, option_index
, nodes
) {
3659 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
3660 depend_list
= this.transformDepList(section_id
),
3664 var title
= this.stripTags(this.title
).trim();
3665 optionEl
= E('td', {
3666 'class': 'td cbi-value-field',
3667 'data-title': (title
!= '') ? title
: null,
3668 'data-description': this.stripTags(this.description
).trim(),
3669 'data-name': this.option
,
3670 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3672 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3673 'data-index': option_index
,
3674 'data-depends': depend_list
,
3675 'data-field': this.cbid(section_id
)
3679 optionEl
= E('div', {
3680 'class': 'cbi-value',
3681 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3682 'data-index': option_index
,
3683 'data-depends': depend_list
,
3684 'data-field': this.cbid(section_id
),
3685 'data-name': this.option
,
3686 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3689 if (this.last_child
)
3690 optionEl
.classList
.add('cbi-value-last');
3692 if (typeof(this.title
) === 'string' && this.title
!== '') {
3693 optionEl
.appendChild(E('label', {
3694 'class': 'cbi-value-title',
3695 'for': 'widget.cbid.%s.%s.%s'.format(config_name
, section_id
, this.option
),
3696 'click': function(ev
) {
3697 var node
= ev
.currentTarget
,
3698 elem
= node
.nextElementSibling
.querySelector('#' + node
.getAttribute('for')) || node
.nextElementSibling
.querySelector('[data-widget-id="' + node
.getAttribute('for') + '"]');
3706 this.titleref
? E('a', {
3707 'class': 'cbi-title-ref',
3708 'href': this.titleref
,
3709 'title': this.titledesc
|| _('Go to relevant configuration page')
3710 }, this.title
) : this.title
));
3712 optionEl
.appendChild(E('div', { 'class': 'cbi-value-field' }));
3717 (optionEl
.lastChild
|| optionEl
).appendChild(nodes
);
3719 if (!in_table
&& typeof(this.description
) === 'string' && this.description
!== '')
3720 dom
.append(optionEl
.lastChild
|| optionEl
,
3721 E('div', { 'class': 'cbi-value-description' }, this.description
.trim()));
3723 if (depend_list
&& depend_list
.length
)
3724 optionEl
.classList
.add('hidden');
3726 optionEl
.addEventListener('widget-change',
3727 L
.bind(this.map
.checkDepends
, this.map
));
3729 optionEl
.addEventListener('widget-change',
3730 L
.bind(this.handleValueChange
, this, section_id
, {}));
3732 dom
.bindClassInstance(optionEl
, this);
3738 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3739 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3740 choices
= this.transformChoices(),
3744 var placeholder
= (this.optional
|| this.rmempty
)
3745 ? E('em', _('unspecified')) : _('-- Please choose --');
3747 widget
= new ui
.Combobox(Array
.isArray(value
) ? value
.join(' ') : value
, choices
, {
3748 id
: this.cbid(section_id
),
3750 optional
: this.optional
|| this.rmempty
,
3751 datatype
: this.datatype
,
3752 select_placeholder
: this.placeholder
|| placeholder
,
3753 validate
: L
.bind(this.validate
, this, section_id
),
3754 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3758 widget
= new ui
.Textfield(Array
.isArray(value
) ? value
.join(' ') : value
, {
3759 id
: this.cbid(section_id
),
3760 password
: this.password
,
3761 optional
: this.optional
|| this.rmempty
,
3762 datatype
: this.datatype
,
3763 placeholder
: this.placeholder
,
3764 validate
: L
.bind(this.validate
, this, section_id
),
3765 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3769 return widget
.render();
3774 * @class DynamicList
3775 * @memberof LuCI.form
3776 * @augments LuCI.form.Value
3780 * The `DynamicList` class represents a multi value widget allowing the user
3781 * to enter multiple unique values, optionally selected from a set of
3782 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3784 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3785 * The configuration form this section is added to. It is automatically passed
3786 * by [option()]{@link LuCI.form.AbstractSection#option} or
3787 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3788 * option to the section.
3790 * @param {LuCI.form.AbstractSection} section
3791 * The configuration section this option is added to. It is automatically passed
3792 * by [option()]{@link LuCI.form.AbstractSection#option} or
3793 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3794 * option to the section.
3796 * @param {string} option
3797 * The name of the UCI option to map.
3799 * @param {string} [title]
3800 * The title caption of the option element.
3802 * @param {string} [description]
3803 * The description text of the option element.
3805 var CBIDynamicList
= CBIValue
.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3806 __name__
: 'CBI.DynamicList',
3809 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3810 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3811 choices
= this.transformChoices(),
3812 items
= L
.toArray(value
);
3814 var widget
= new ui
.DynamicList(items
, choices
, {
3815 id
: this.cbid(section_id
),
3817 optional
: this.optional
|| this.rmempty
,
3818 datatype
: this.datatype
,
3819 placeholder
: this.placeholder
,
3820 validate
: L
.bind(this.validate
, this, section_id
),
3821 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3824 return widget
.render();
3830 * @memberof LuCI.form
3831 * @augments LuCI.form.Value
3835 * The `ListValue` class implements a simple static HTML select element
3836 * allowing the user to choose a single value from a set of predefined choices.
3837 * It builds upon the {@link LuCI.ui.Select} widget.
3839 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3840 * The configuration form this section is added to. It is automatically passed
3841 * by [option()]{@link LuCI.form.AbstractSection#option} or
3842 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3843 * option to the section.
3845 * @param {LuCI.form.AbstractSection} section
3846 * The configuration section this option is added to. It is automatically passed
3847 * by [option()]{@link LuCI.form.AbstractSection#option} or
3848 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3849 * option to the section.
3851 * @param {string} option
3852 * The name of the UCI option to map.
3854 * @param {string} [title]
3855 * The title caption of the option element.
3857 * @param {string} [description]
3858 * The description text of the option element.
3860 var CBIListValue
= CBIValue
.extend(/** @lends LuCI.form.ListValue.prototype */ {
3861 __name__
: 'CBI.ListValue',
3863 __init__: function() {
3864 this.super('__init__', arguments
);
3865 this.widget
= 'select';
3866 this.orientation
= 'horizontal';
3871 * Set the size attribute of the underlying HTML select element.
3873 * @name LuCI.form.ListValue.prototype#size
3879 * Set the type of the underlying form controls.
3881 * May be one of `select` or `radio`. If set to `select`, an HTML
3882 * select element is rendered, otherwise a collection of `radio`
3885 * @name LuCI.form.ListValue.prototype#widget
3891 * Set the orientation of the underlying radio or checkbox elements.
3893 * May be one of `horizontal` or `vertical`. Only applies to non-select
3896 * @name LuCI.form.ListValue.prototype#orientation
3898 * @default horizontal
3902 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3903 var choices
= this.transformChoices();
3904 var widget
= new ui
.Select((cfgvalue
!= null) ? cfgvalue
: this.default, choices
, {
3905 id
: this.cbid(section_id
),
3908 widget
: this.widget
,
3909 optional
: this.optional
,
3910 orientation
: this.orientation
,
3911 placeholder
: this.placeholder
,
3912 validate
: L
.bind(this.validate
, this, section_id
),
3913 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3916 return widget
.render();
3922 * @memberof LuCI.form
3923 * @augments LuCI.form.Value
3927 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3928 * implement a simple checkbox element.
3930 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3931 * The configuration form this section is added to. It is automatically passed
3932 * by [option()]{@link LuCI.form.AbstractSection#option} or
3933 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3934 * option to the section.
3936 * @param {LuCI.form.AbstractSection} section
3937 * The configuration section this option is added to. It is automatically passed
3938 * by [option()]{@link LuCI.form.AbstractSection#option} or
3939 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3940 * option to the section.
3942 * @param {string} option
3943 * The name of the UCI option to map.
3945 * @param {string} [title]
3946 * The title caption of the option element.
3948 * @param {string} [description]
3949 * The description text of the option element.
3951 var CBIFlagValue
= CBIValue
.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3952 __name__
: 'CBI.FlagValue',
3954 __init__: function() {
3955 this.super('__init__', arguments
);
3958 this.disabled
= '0';
3959 this.default = this.disabled
;
3963 * Sets the input value to use for the checkbox checked state.
3965 * @name LuCI.form.FlagValue.prototype#enabled
3971 * Sets the input value to use for the checkbox unchecked state.
3973 * @name LuCI.form.FlagValue.prototype#disabled
3979 * Set a tooltip for the flag option.
3981 * If set to a string, it will be used as-is as a tooltip.
3983 * If set to a function, the function will be invoked and the return
3984 * value will be shown as a tooltip. If the return value of the function
3985 * is `null` no tooltip will be set.
3987 * @name LuCI.form.FlagValue.prototype#tooltip
3988 * @type string|function
3993 * Set a tooltip icon for the flag option.
3995 * If set, this icon will be shown for the default one.
3996 * This could also be a png icon from the resources directory.
3998 * @name LuCI.form.FlagValue.prototype#tooltipicon
4004 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4007 if (typeof(this.tooltip
) == 'function')
4008 tooltip
= this.tooltip
.apply(this, [section_id
]);
4009 else if (typeof(this.tooltip
) == 'string')
4010 tooltip
= (arguments
.length
> 1) ? ''.format
.apply(this.tooltip
, this.varargs(arguments
, 1)) : this.tooltip
;
4012 var widget
= new ui
.Checkbox((cfgvalue
!= null) ? cfgvalue
: this.default, {
4013 id
: this.cbid(section_id
),
4014 value_enabled
: this.enabled
,
4015 value_disabled
: this.disabled
,
4016 validate
: L
.bind(this.validate
, this, section_id
),
4018 tooltipicon
: this.tooltipicon
,
4019 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4022 return widget
.render();
4026 * Query the checked state of the underlying checkbox widget and return
4027 * either the `enabled` or the `disabled` property value, depending on
4028 * the checked state.
4032 formvalue: function(section_id
) {
4033 var elem
= this.getUIElement(section_id
),
4034 checked
= elem
? elem
.isChecked() : false;
4035 return checked
? this.enabled
: this.disabled
;
4039 * Query the checked state of the underlying checkbox widget and return
4040 * either a localized `Yes` or `No` string, depending on the checked state.
4044 textvalue: function(section_id
) {
4045 var cval
= this.cfgvalue(section_id
);
4048 cval
= this.default;
4050 return (cval
== this.enabled
) ? _('Yes') : _('No');
4054 parse: function(section_id
) {
4055 if (this.isActive(section_id
)) {
4056 var fval
= this.formvalue(section_id
);
4058 if (!this.isValid(section_id
)) {
4059 var title
= this.stripTags(this.title
).trim();
4060 var error
= this.getValidationError(section_id
);
4061 return Promise
.reject(new TypeError(
4062 _('Option "%s" contains an invalid input value.').format(title
|| this.option
) + ' ' + error
));
4065 if (fval
== this.default && (this.optional
|| this.rmempty
))
4066 return Promise
.resolve(this.remove(section_id
));
4068 return Promise
.resolve(this.write(section_id
, fval
));
4070 else if (!this.retain
) {
4071 return Promise
.resolve(this.remove(section_id
));
4078 * @memberof LuCI.form
4079 * @augments LuCI.form.DynamicList
4083 * The `MultiValue` class is a modified variant of the `DynamicList` element
4084 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
4085 * select dropdown element.
4087 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4088 * The configuration form this section is added to. It is automatically passed
4089 * by [option()]{@link LuCI.form.AbstractSection#option} or
4090 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4091 * option to the section.
4093 * @param {LuCI.form.AbstractSection} section
4094 * The configuration section this option is added to. It is automatically passed
4095 * by [option()]{@link LuCI.form.AbstractSection#option} or
4096 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4097 * option to the section.
4099 * @param {string} option
4100 * The name of the UCI option to map.
4102 * @param {string} [title]
4103 * The title caption of the option element.
4105 * @param {string} [description]
4106 * The description text of the option element.
4108 var CBIMultiValue
= CBIDynamicList
.extend(/** @lends LuCI.form.MultiValue.prototype */ {
4109 __name__
: 'CBI.MultiValue',
4111 __init__: function() {
4112 this.super('__init__', arguments
);
4113 this.placeholder
= _('-- Please choose --');
4117 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
4118 * property of the underlying dropdown widget. If omitted, the value of
4119 * the `size` property is used or `3` when `size` is unspecified as well.
4121 * @name LuCI.form.MultiValue.prototype#display_size
4127 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
4128 * property of the underlying dropdown widget. If omitted, the value of
4129 * the `size` property is used or `-1` when `size` is unspecified as well.
4131 * @name LuCI.form.MultiValue.prototype#dropdown_size
4137 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4138 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
4139 choices
= this.transformChoices();
4141 var widget
= new ui
.Dropdown(L
.toArray(value
), choices
, {
4142 id
: this.cbid(section_id
),
4145 optional
: this.optional
|| this.rmempty
,
4146 select_placeholder
: this.placeholder
,
4147 display_items
: this.display_size
|| this.size
|| 3,
4148 dropdown_items
: this.dropdown_size
|| this.size
|| -1,
4149 validate
: L
.bind(this.validate
, this, section_id
),
4150 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4153 return widget
.render();
4159 * @memberof LuCI.form
4160 * @augments LuCI.form.Value
4164 * The `TextValue` class implements a multi-line textarea input using
4165 * {@link LuCI.ui.Textarea}.
4167 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4168 * The configuration form this section is added to. It is automatically passed
4169 * by [option()]{@link LuCI.form.AbstractSection#option} or
4170 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4171 * option to the section.
4173 * @param {LuCI.form.AbstractSection} section
4174 * The configuration section this option is added to. It is automatically passed
4175 * by [option()]{@link LuCI.form.AbstractSection#option} or
4176 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4177 * option to the section.
4179 * @param {string} option
4180 * The name of the UCI option to map.
4182 * @param {string} [title]
4183 * The title caption of the option element.
4185 * @param {string} [description]
4186 * The description text of the option element.
4188 var CBITextValue
= CBIValue
.extend(/** @lends LuCI.form.TextValue.prototype */ {
4189 __name__
: 'CBI.TextValue',
4195 * Enforces the use of a monospace font for the textarea contents when set
4198 * @name LuCI.form.TextValue.prototype#monospace
4204 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
4205 * property of the underlying textarea widget.
4207 * @name LuCI.form.TextValue.prototype#cols
4213 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
4214 * property of the underlying textarea widget.
4216 * @name LuCI.form.TextValue.prototype#rows
4222 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
4223 * property of the underlying textarea widget.
4225 * @name LuCI.form.TextValue.prototype#wrap
4231 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4232 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default;
4234 var widget
= new ui
.Textarea(value
, {
4235 id
: this.cbid(section_id
),
4236 optional
: this.optional
|| this.rmempty
,
4237 placeholder
: this.placeholder
,
4238 monospace
: this.monospace
,
4242 validate
: L
.bind(this.validate
, this, section_id
),
4243 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4246 return widget
.render();
4252 * @memberof LuCI.form
4253 * @augments LuCI.form.Value
4257 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4258 * renders the underlying UCI option or default value as readonly text.
4260 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4261 * The configuration form this section is added to. It is automatically passed
4262 * by [option()]{@link LuCI.form.AbstractSection#option} or
4263 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4264 * option to the section.
4266 * @param {LuCI.form.AbstractSection} section
4267 * The configuration section this option is added to. It is automatically passed
4268 * by [option()]{@link LuCI.form.AbstractSection#option} or
4269 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4270 * option to the section.
4272 * @param {string} option
4273 * The name of the UCI option to map.
4275 * @param {string} [title]
4276 * The title caption of the option element.
4278 * @param {string} [description]
4279 * The description text of the option element.
4281 var CBIDummyValue
= CBIValue
.extend(/** @lends LuCI.form.DummyValue.prototype */ {
4282 __name__
: 'CBI.DummyValue',
4285 * Set a URL which is opened when clicking on the dummy value text.
4287 * By setting this property, the dummy value text is wrapped in an `<a>`
4288 * element with the property value used as `href` attribute.
4290 * @name LuCI.form.DummyValue.prototype#href
4296 * Treat the UCI option value (or the `default` property value) as HTML.
4298 * By default, the value text is HTML escaped before being rendered as
4299 * text. In some cases it may be needed to actually interpret and render
4300 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
4302 * @name LuCI.form.DummyValue.prototype#rawhtml
4308 * Render the UCI option value as hidden using the HTML display: none style property.
4310 * By default, the value is displayed
4312 * @name LuCI.form.DummyValue.prototype#hidden
4318 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4319 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
4320 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
4321 outputEl
= E('div', { 'style': this.hidden
? 'display:none' : null });
4323 if (this.href
&& !((this.readonly
!= null) ? this.readonly
: this.map
.readonly
))
4324 outputEl
.appendChild(E('a', { 'href': this.href
}));
4326 dom
.append(outputEl
.lastChild
|| outputEl
,
4327 this.rawhtml
? value
: [ value
]);
4336 remove: function() {},
4339 write: function() {}
4343 * @class ButtonValue
4344 * @memberof LuCI.form
4345 * @augments LuCI.form.Value
4349 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4350 * renders the underlying UCI option or default value as readonly text.
4352 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4353 * The configuration form this section is added to. It is automatically passed
4354 * by [option()]{@link LuCI.form.AbstractSection#option} or
4355 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4356 * option to the section.
4358 * @param {LuCI.form.AbstractSection} section
4359 * The configuration section this option is added to. It is automatically passed
4360 * by [option()]{@link LuCI.form.AbstractSection#option} or
4361 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4362 * option to the section.
4364 * @param {string} option
4365 * The name of the UCI option to map.
4367 * @param {string} [title]
4368 * The title caption of the option element.
4370 * @param {string} [description]
4371 * The description text of the option element.
4373 var CBIButtonValue
= CBIValue
.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
4374 __name__
: 'CBI.ButtonValue',
4377 * Override the rendered button caption.
4379 * By default, the option title - which is passed as fourth argument to the
4380 * constructor - is used as caption for the button element. When setting
4381 * this property to a string, it is used as `String.format()` pattern with
4382 * the underlying UCI section name passed as first format argument. When
4383 * set to a function, it is invoked passing the section ID as sole argument
4384 * and the resulting return value is converted to a string before being
4385 * used as button caption.
4387 * The default is `null`, means the option title is used as caption.
4389 * @name LuCI.form.ButtonValue.prototype#inputtitle
4390 * @type string|function
4395 * Override the button style class.
4397 * By setting this property, a specific `cbi-button-*` CSS class can be
4398 * selected to influence the style of the resulting button.
4400 * Suitable values which are implemented by most themes are `positive`,
4401 * `negative` and `primary`.
4403 * The default is `null`, means a neutral button styling is used.
4405 * @name LuCI.form.ButtonValue.prototype#inputstyle
4411 * Override the button click action.
4413 * By default, the underlying UCI option (or default property) value is
4414 * copied into a hidden field tied to the button element and the save
4415 * action is triggered on the parent form element.
4417 * When this property is set to a function, it is invoked instead of
4418 * performing the default actions. The handler function will receive the
4419 * DOM click element as first and the underlying configuration section ID
4420 * as second argument.
4422 * @name LuCI.form.ButtonValue.prototype#onclick
4428 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4429 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
4430 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
4431 outputEl
= E('div'),
4432 btn_title
= this.titleFn('inputtitle', section_id
) || this.titleFn('title', section_id
);
4434 if (value
!== false)
4435 dom
.content(outputEl
, [
4437 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle
|| 'button'),
4438 'click': ui
.createHandlerFn(this, function(section_id
, ev
) {
4440 return this.onclick(ev
, section_id
);
4442 ev
.currentTarget
.parentNode
.nextElementSibling
.value
= value
;
4443 return this.map
.save();
4445 'disabled': ((this.readonly
!= null) ? this.readonly
: this.map
.readonly
) || null
4449 dom
.content(outputEl
, ' - ');
4459 * @class HiddenValue
4460 * @memberof LuCI.form
4461 * @augments LuCI.form.Value
4465 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
4467 * Hidden value widgets used to be necessary in legacy code which actually
4468 * submitted the underlying HTML form the server. With client side handling of
4469 * forms, there are more efficient ways to store hidden state data.
4471 * Since this widget has no visible content, the title and description values
4472 * of this form element should be set to `null` as well to avoid a broken or
4473 * distorted form layout when rendering the option element.
4475 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4476 * The configuration form this section is added to. It is automatically passed
4477 * by [option()]{@link LuCI.form.AbstractSection#option} or
4478 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4479 * option to the section.
4481 * @param {LuCI.form.AbstractSection} section
4482 * The configuration section this option is added to. It is automatically passed
4483 * by [option()]{@link LuCI.form.AbstractSection#option} or
4484 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4485 * option to the section.
4487 * @param {string} option
4488 * The name of the UCI option to map.
4490 * @param {string} [title]
4491 * The title caption of the option element.
4493 * @param {string} [description]
4494 * The description text of the option element.
4496 var CBIHiddenValue
= CBIValue
.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
4497 __name__
: 'CBI.HiddenValue',
4500 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4501 var widget
= new ui
.Hiddenfield((cfgvalue
!= null) ? cfgvalue
: this.default, {
4502 id
: this.cbid(section_id
)
4505 return widget
.render();
4511 * @memberof LuCI.form
4512 * @augments LuCI.form.Value
4516 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
4517 * offers the ability to browse, upload and select remote files.
4519 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4520 * The configuration form this section is added to. It is automatically passed
4521 * by [option()]{@link LuCI.form.AbstractSection#option} or
4522 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4523 * option to the section.
4525 * @param {LuCI.form.AbstractSection} section
4526 * The configuration section this option is added to. It is automatically passed
4527 * by [option()]{@link LuCI.form.AbstractSection#option} or
4528 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4529 * option to the section.
4531 * @param {string} option
4532 * The name of the UCI option to map.
4534 * @param {string} [title]
4535 * The title caption of the option element.
4537 * @param {string} [description]
4538 * The description text of the option element.
4540 var CBIFileUpload
= CBIValue
.extend(/** @lends LuCI.form.FileUpload.prototype */ {
4541 __name__
: 'CBI.FileSelect',
4543 __init__: function(/* ... */) {
4544 this.super('__init__', arguments
);
4546 this.show_hidden
= false;
4547 this.enable_upload
= true;
4548 this.enable_remove
= true;
4549 this.root_directory
= '/etc/luci-uploads';
4553 * Toggle display of hidden files.
4555 * Display hidden files when rendering the remote directory listing.
4556 * Note that this is merely a cosmetic feature, hidden files are always
4557 * included in received remote file listings.
4559 * The default is `false`, means hidden files are not displayed.
4561 * @name LuCI.form.FileUpload.prototype#show_hidden
4567 * Toggle file upload functionality.
4569 * When set to `true`, the underlying widget provides a button which lets
4570 * the user select and upload local files to the remote system.
4571 * Note that this is merely a cosmetic feature, remote upload access is
4572 * controlled by the session ACL rules.
4574 * The default is `true`, means file upload functionality is displayed.
4576 * @name LuCI.form.FileUpload.prototype#enable_upload
4582 * Toggle remote file delete functionality.
4584 * When set to `true`, the underlying widget provides a buttons which let
4585 * the user delete files from remote directories. Note that this is merely
4586 * a cosmetic feature, remote delete permissions are controlled by the
4587 * session ACL rules.
4589 * The default is `true`, means file removal buttons are displayed.
4591 * @name LuCI.form.FileUpload.prototype#enable_remove
4597 * Specify the root directory for file browsing.
4599 * This property defines the topmost directory the file browser widget may
4600 * navigate to, the UI will not allow browsing directories outside this
4601 * prefix. Note that this is merely a cosmetic feature, remote file access
4602 * and directory listing permissions are controlled by the session ACL
4605 * The default is `/etc/luci-uploads`.
4607 * @name LuCI.form.FileUpload.prototype#root_directory
4609 * @default /etc/luci-uploads
4613 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4614 var browserEl
= new ui
.FileUpload((cfgvalue
!= null) ? cfgvalue
: this.default, {
4615 id
: this.cbid(section_id
),
4616 name
: this.cbid(section_id
),
4617 show_hidden
: this.show_hidden
,
4618 enable_upload
: this.enable_upload
,
4619 enable_remove
: this.enable_remove
,
4620 root_directory
: this.root_directory
,
4621 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4624 return browserEl
.render();
4629 * @class SectionValue
4630 * @memberof LuCI.form
4631 * @augments LuCI.form.Value
4635 * The `SectionValue` widget embeds a form section element within an option
4636 * element container, allowing to nest form sections into other sections.
4638 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4639 * The configuration form this section is added to. It is automatically passed
4640 * by [option()]{@link LuCI.form.AbstractSection#option} or
4641 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4642 * option to the section.
4644 * @param {LuCI.form.AbstractSection} section
4645 * The configuration section this option is added to. It is automatically passed
4646 * by [option()]{@link LuCI.form.AbstractSection#option} or
4647 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4648 * option to the section.
4650 * @param {string} option
4651 * The internal name of the option element holding the section. Since a section
4652 * container element does not read or write any configuration itself, the name
4653 * is only used internally and does not need to relate to any underlying UCI
4656 * @param {LuCI.form.AbstractSection} subsection_class
4657 * The class to use for instantiating the nested section element. Note that
4658 * the class value itself is expected here, not a class instance obtained by
4659 * calling `new`. The given class argument must be a subclass of the
4660 * `AbstractSection` class.
4662 * @param {...*} [class_args]
4663 * All further arguments are passed as-is to the subclass constructor. Refer
4664 * to the corresponding class constructor documentations for details.
4666 var CBISectionValue
= CBIValue
.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4667 __name__
: 'CBI.ContainerValue',
4668 __init__: function(map
, section
, option
, cbiClass
/*, ... */) {
4669 this.super('__init__', [map
, section
, option
]);
4671 if (!CBIAbstractSection
.isSubclass(cbiClass
))
4672 throw 'Sub section must be a descendent of CBIAbstractSection';
4674 this.subsection
= cbiClass
.instantiate(this.varargs(arguments
, 4, this.map
));
4675 this.subsection
.parentoption
= this;
4679 * Access the embedded section instance.
4681 * This property holds a reference to the instantiated nested section.
4683 * @name LuCI.form.SectionValue.prototype#subsection
4684 * @type LuCI.form.AbstractSection
4689 load: function(section_id
) {
4690 return this.subsection
.load(section_id
);
4694 parse: function(section_id
) {
4695 return this.subsection
.parse(section_id
);
4699 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4700 return this.subsection
.render(section_id
);
4704 checkDepends: function(section_id
) {
4705 this.subsection
.checkDepends(section_id
);
4706 return CBIValue
.prototype.checkDepends
.apply(this, [ section_id
]);
4710 * Since the section container is not rendering an own widget,
4711 * its `value()` implementation is a no-op.
4715 value: function() {},
4718 * Since the section container is not tied to any UCI configuration,
4719 * its `write()` implementation is a no-op.
4723 write: function() {},
4726 * Since the section container is not tied to any UCI configuration,
4727 * its `remove()` implementation is a no-op.
4731 remove: function() {},
4734 * Since the section container is not tied to any UCI configuration,
4735 * its `cfgvalue()` implementation will always return `null`.
4740 cfgvalue: function() { return null },
4743 * Since the section container is not tied to any UCI configuration,
4744 * its `formvalue()` implementation will always return `null`.
4749 formvalue: function() { return null }
4758 * The LuCI form class provides high level abstractions for creating
4759 * UCI- or JSON backed configurations forms.
4761 * To import the class in views, use `'require form'`, to import it in
4762 * external JavaScript, use `L.require("form").then(...)`.
4764 * A typical form is created by first constructing a
4765 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4766 * by subsequently adding sections and options to it. Finally
4767 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4768 * assemble the HTML markup and insert it into the DOM.
4778 * m = new form.Map('example', 'Example form',
4779 * 'This is an example form mapping the contents of /etc/config/example');
4781 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4782 * 'This sections maps "config example first_section" of /etc/config/example');
4784 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4786 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4787 * o.value('choice1', 'The first choice');
4788 * o.value('choice2', 'The second choice');
4790 * m.render().then(function(node) {
4791 * document.body.appendChild(node);
4795 return baseclass
.extend(/** @lends LuCI.form.prototype */ {
4797 JSONMap
: CBIJSONMap
,
4798 AbstractSection
: CBIAbstractSection
,
4799 AbstractValue
: CBIAbstractValue
,
4801 TypedSection
: CBITypedSection
,
4802 TableSection
: CBITableSection
,
4803 GridSection
: CBIGridSection
,
4804 NamedSection
: CBINamedSection
,
4807 DynamicList
: CBIDynamicList
,
4808 ListValue
: CBIListValue
,
4810 MultiValue
: CBIMultiValue
,
4811 TextValue
: CBITextValue
,
4812 DummyValue
: CBIDummyValue
,
4813 Button
: CBIButtonValue
,
4814 HiddenValue
: CBIHiddenValue
,
4815 FileUpload
: CBIFileUpload
,
4816 SectionValue
: CBISectionValue