aaff4d0a1a05f2e8467b7043b1d854cd0c1fb7eb
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} element
208 * The form element to add.
210 append: function(obj
) {
211 this.children
.push(obj
);
215 * Parse this elements form input.
217 * The `parse()` function recursively walks the form element tree and
218 * triggers input value reading and validation for each encountered element.
220 * Elements which are hidden due to unsatisified dependencies are skipped.
222 * @returns {Promise<void>}
223 * Returns a promise resolving once this element's value and the values of
224 * all child elements have been parsed. The returned promise is rejected
225 * if any parsed values are not meeting the validation constraints of their
226 * respective elements.
229 var args
= arguments
;
230 this.children
.forEach(function(child
) {
231 child
.parse
.apply(child
, args
);
236 * Render the form element.
238 * The `render()` function recursively walks the form element tree and
239 * renders the markup for each element, returning the assembled DOM tree.
242 * @returns {Node|Promise<Node>}
243 * May return a DOM Node or a promise resolving to a DOM node containing
244 * the form element's markup, including the markup of any child elements.
247 L
.error('InternalError', 'Not implemented');
251 loadChildren: function(/* ... */) {
254 if (Array
.isArray(this.children
))
255 for (var i
= 0; i
< this.children
.length
; i
++)
256 if (!this.children
[i
].disable
)
257 tasks
.push(this.children
[i
].load
.apply(this.children
[i
], arguments
));
259 return Promise
.all(tasks
);
263 renderChildren: function(tab_name
/*, ... */) {
267 if (Array
.isArray(this.children
))
268 for (var i
= 0; i
< this.children
.length
; i
++)
269 if (tab_name
=== null || this.children
[i
].tab
=== tab_name
)
270 if (!this.children
[i
].disable
)
271 tasks
.push(this.children
[i
].render
.apply(
272 this.children
[i
], this.varargs(arguments
, 1, index
++)));
274 return Promise
.all(tasks
);
278 * Strip any HTML tags from the given input string.
280 * @param {string} input
281 * The input string to clean.
284 * The cleaned input string with HTML 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 * configuraton 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 conents.
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 dervied from
506 * `LuCI.form.AbstractSection`.
508 * @param {...string} classargs
509 * Additional arguments which are passed as-is to the contructor 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 unsatisified 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 failes. 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_or_id
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]
699 * The name of the UCI configuration the option instance is belonging 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 conents.
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 unsatisified 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 exeption 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 dervied from
1001 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
1003 * @param {...*} classargs
1004 * Additional arguments which are passed as-is to the contructor 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 * descendent 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 descendent 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 dervied from
1034 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
1036 * @param {...*} classargs
1037 * Additional arguments which are passed as-is to the contructor 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 * descendent 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 depedencies. 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 contraint to the option.
1544 * Dependency constraints allow making the presence of option elements
1545 * dependant 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 of 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>} optionname_or_depends
1624 * The name of the option to depend on or an object describing multiple
1625 * dependencies which must be satified (a logical "and" expression).
1627 * @param {string} optionvalue|RegExp
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 * If set to `true`, the user may add or remove instances from the form
2380 * section widget, otherwise only preexisting sections may be edited.
2381 * The default is `false`.
2383 * @name LuCI.form.TableSection.prototype#addremove
2389 * If set to `true`, mapped section instances are treated as anonymous
2390 * UCI sections, which means that section instance elements will be
2391 * rendered without title element and that no name is required when adding
2392 * new sections. The default is `false`.
2394 * @name LuCI.form.TableSection.prototype#anonymous
2400 * Override the caption used for the section add button at the bottom of
2401 * the section form element. If set to a string, it will be used as-is,
2402 * if set to a function, the function will be invoked and its return value
2403 * is used as caption, after converting it to a string. If this property
2404 * is not set, the default is `Add`.
2406 * @name LuCI.form.TableSection.prototype#addbtntitle
2407 * @type string|function
2412 * Override the per-section instance title caption shown in the first
2413 * column of the table unless `anonymous` is set to true. If set to a
2414 * string, it will be used as `String.format()` pattern with the name of
2415 * the underlying UCI section as first argument, if set to a function, the
2416 * function will be invoked with the section name as first argument and
2417 * its return value is used as caption, after converting it to a string.
2418 * If this property is not set, the default is the name of the underlying
2419 * UCI configuration section.
2421 * @name LuCI.form.TableSection.prototype#sectiontitle
2422 * @type string|function
2427 * Override the per-section instance modal popup title caption shown when
2428 * clicking the `More…` button in a section specifying `max_cols`. If set
2429 * to a string, it will be used as `String.format()` pattern with the name
2430 * of the underlying UCI section as first argument, if set to a function,
2431 * the function will be invoked with the section name as first argument and
2432 * its return value is used as caption, after converting it to a string.
2433 * If this property is not set, the default is the name of the underlying
2434 * UCI configuration section.
2436 * @name LuCI.form.TableSection.prototype#modaltitle
2437 * @type string|function
2442 * Override the UCI configuration name to read the section IDs from. By
2443 * default, the configuration name is inherited from the parent `Map`.
2444 * By setting this property, a deviating configuration may be specified.
2445 * The default is `null`, means inheriting from the parent form.
2447 * @name LuCI.form.TableSection.prototype#uciconfig
2453 * Specify a maximum amount of columns to display. By default, one table
2454 * column is rendered for each child option of the form section element.
2455 * When this option is set to a positive number, then no more columns than
2456 * the given amount are rendered. When the number of child options exceeds
2457 * the specified amount, a `More…` button is rendered in the last column,
2458 * opening a modal dialog presenting all options elements in `NamedSection`
2459 * style when clicked.
2461 * @name LuCI.form.TableSection.prototype#max_cols
2467 * If set to `true`, alternating `cbi-rowstyle-1` and `cbi-rowstyle-2` CSS
2468 * classes are added to the table row elements. Not all LuCI themes
2469 * implement these row style classes. The default is `false`.
2471 * @name LuCI.form.TableSection.prototype#rowcolors
2477 * Enables a per-section instance row `Edit` button which triggers a certain
2478 * action when clicked. If set to a string, the string value is used
2479 * as `String.format()` pattern with the name of the underlying UCI section
2480 * as first format argument. The result is then interpreted as URL which
2481 * LuCI will navigate to when the user clicks the edit button.
2483 * If set to a function, this function will be registered as click event
2484 * handler on the rendered edit button, receiving the section instance
2485 * name as first and the DOM click event as second argument.
2487 * @name LuCI.form.TableSection.prototype#extedit
2488 * @type string|function
2493 * If set to `true`, a sort button is added to the last column, allowing
2494 * the user to reorder the section instances mapped by the section form
2497 * @name LuCI.form.TableSection.prototype#sortable
2503 * If set to `true`, the header row with the options descriptions will
2504 * not be displayed. By default, descriptions row is automatically displayed
2505 * when at least one option has a description.
2507 * @name LuCI.form.TableSection.prototype#nodescriptions
2513 * The `TableSection` implementation does not support option tabbing, so
2514 * its implementation of `tab()` will always throw an exception when
2518 * @throws Throws an exception when invoked.
2521 throw 'Tabs are not supported by TableSection';
2525 renderContents: function(cfgsections
, nodes
) {
2526 var section_id
= null,
2527 config_name
= this.uciconfig
|| this.map
.config
,
2528 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2529 has_more
= max_cols
< this.children
.length
,
2530 drag_sort
= this.sortable
&& !('ontouchstart' in window
),
2531 touch_sort
= this.sortable
&& ('ontouchstart' in window
),
2532 sectionEl
= E('div', {
2533 'id': 'cbi-%s-%s'.format(config_name
, this.sectiontype
),
2534 'class': 'cbi-section cbi-tblsection',
2535 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2536 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2538 tableEl
= E('table', {
2539 'class': 'table cbi-section-table'
2542 if (this.title
!= null && this.title
!= '')
2543 sectionEl
.appendChild(E('h3', {}, this.title
));
2545 if (this.description
!= null && this.description
!= '')
2546 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2548 tableEl
.appendChild(this.renderHeaderRows(max_cols
));
2550 for (var i
= 0; i
< nodes
.length
; i
++) {
2551 var sectionname
= this.titleFn('sectiontitle', cfgsections
[i
]);
2553 if (sectionname
== null)
2554 sectionname
= cfgsections
[i
];
2556 var trEl
= E('tr', {
2557 'id': 'cbi-%s-%s'.format(config_name
, cfgsections
[i
]),
2558 'class': 'tr cbi-section-table-row',
2559 'data-sid': cfgsections
[i
],
2560 'draggable': (drag_sort
|| touch_sort
) ? true : null,
2561 'mousedown': drag_sort
? L
.bind(this.handleDragInit
, this) : null,
2562 'dragstart': drag_sort
? L
.bind(this.handleDragStart
, this) : null,
2563 'dragover': drag_sort
? L
.bind(this.handleDragOver
, this) : null,
2564 'dragenter': drag_sort
? L
.bind(this.handleDragEnter
, this) : null,
2565 'dragleave': drag_sort
? L
.bind(this.handleDragLeave
, this) : null,
2566 'dragend': drag_sort
? L
.bind(this.handleDragEnd
, this) : null,
2567 'drop': drag_sort
? L
.bind(this.handleDrop
, this) : null,
2568 'touchmove': touch_sort
? L
.bind(this.handleTouchMove
, this) : null,
2569 'touchend': touch_sort
? L
.bind(this.handleTouchEnd
, this) : null,
2570 'data-title': (sectionname
&& (!this.anonymous
|| this.sectiontitle
)) ? sectionname
: null,
2571 'data-section-id': cfgsections
[i
]
2574 if (this.extedit
|| this.rowcolors
)
2575 trEl
.classList
.add(!(tableEl
.childNodes
.length
% 2)
2576 ? 'cbi-rowstyle-1' : 'cbi-rowstyle-2');
2578 for (var j
= 0; j
< max_cols
&& nodes
[i
].firstChild
; j
++)
2579 trEl
.appendChild(nodes
[i
].firstChild
);
2581 trEl
.appendChild(this.renderRowActions(cfgsections
[i
], has_more
? _('More…') : null));
2582 tableEl
.appendChild(trEl
);
2585 if (nodes
.length
== 0)
2586 tableEl
.appendChild(E('tr', { 'class': 'tr cbi-section-table-row placeholder' },
2587 E('td', { 'class': 'td' }, this.renderSectionPlaceholder())));
2589 sectionEl
.appendChild(tableEl
);
2591 sectionEl
.appendChild(this.renderSectionAdd('cbi-tblsection-create'));
2593 dom
.bindClassInstance(sectionEl
, this);
2599 renderHeaderRows: function(max_cols
, has_action
) {
2600 var has_titles
= false,
2601 has_descriptions
= false,
2602 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2603 has_more
= max_cols
< this.children
.length
,
2604 anon_class
= (!this.anonymous
|| this.sectiontitle
) ? 'named' : 'anonymous',
2607 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2611 has_titles
= has_titles
|| !!opt
.title
;
2612 has_descriptions
= has_descriptions
|| !!opt
.description
;
2616 var trEl
= E('tr', {
2617 'class': 'tr cbi-section-table-titles ' + anon_class
,
2618 'data-title': (!this.anonymous
|| this.sectiontitle
) ? _('Name') : null,
2619 'click': this.sortable
? ui
.createHandlerFn(this, 'handleSort') : null
2622 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2626 trEl
.appendChild(E('th', {
2627 'class': 'th cbi-section-table-cell',
2628 'data-widget': opt
.__name__
,
2629 'data-sortable-row': this.sortable
? '' : null
2632 if (opt
.width
!= null)
2633 trEl
.lastElementChild
.style
.width
=
2634 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2637 trEl
.lastElementChild
.appendChild(E('a', {
2638 'href': opt
.titleref
,
2639 'class': 'cbi-title-ref',
2640 'title': this.titledesc
|| _('Go to relevant configuration page')
2643 dom
.content(trEl
.lastElementChild
, opt
.title
);
2646 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2647 trEl
.appendChild(E('th', {
2648 'class': 'th cbi-section-table-cell cbi-section-actions'
2651 trEls
.appendChild(trEl
);
2654 if (has_descriptions
&& !this.nodescriptions
) {
2655 var trEl
= E('tr', {
2656 'class': 'tr cbi-section-table-descr ' + anon_class
2659 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2663 trEl
.appendChild(E('th', {
2664 'class': 'th cbi-section-table-cell',
2665 'data-widget': opt
.__name__
2666 }, opt
.description
));
2668 if (opt
.width
!= null)
2669 trEl
.lastElementChild
.style
.width
=
2670 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2673 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2674 trEl
.appendChild(E('th', {
2675 'class': 'th cbi-section-table-cell cbi-section-actions'
2678 trEls
.appendChild(trEl
);
2685 renderRowActions: function(section_id
, more_label
) {
2686 var config_name
= this.uciconfig
|| this.map
.config
;
2688 if (!this.sortable
&& !this.extedit
&& !this.addremove
&& !more_label
)
2691 var tdEl
= E('td', {
2692 'class': 'td cbi-section-table-cell nowrap cbi-section-actions'
2695 if (this.sortable
) {
2696 dom
.append(tdEl
.lastElementChild
, [
2698 'title': _('Drag to reorder'),
2699 'class': 'cbi-button drag-handle center',
2700 'style': 'cursor:move',
2701 'disabled': this.map
.readonly
|| null
2709 if (typeof(this.extedit
) == 'function')
2710 evFn
= L
.bind(this.extedit
, this);
2711 else if (typeof(this.extedit
) == 'string')
2712 evFn
= L
.bind(function(sid
, ev
) {
2713 location
.href
= this.extedit
.format(sid
);
2714 }, this, section_id
);
2716 dom
.append(tdEl
.lastElementChild
,
2719 'class': 'cbi-button cbi-button-edit',
2726 dom
.append(tdEl
.lastElementChild
,
2728 'title': more_label
,
2729 'class': 'cbi-button cbi-button-edit',
2730 'click': ui
.createHandlerFn(this, 'renderMoreOptionsModal', section_id
)
2735 if (this.addremove
) {
2736 var btn_title
= this.titleFn('removebtntitle', section_id
);
2738 dom
.append(tdEl
.lastElementChild
,
2740 'title': btn_title
|| _('Delete'),
2741 'class': 'cbi-button cbi-button-remove',
2742 'click': ui
.createHandlerFn(this, 'handleRemove', section_id
),
2743 'disabled': this.map
.readonly
|| null
2744 }, [ btn_title
|| _('Delete') ])
2752 handleDragInit: function(ev
) {
2753 scope
.dragState
= { node
: ev
.target
};
2757 handleDragStart: function(ev
) {
2758 if (!scope
.dragState
|| !scope
.dragState
.node
.classList
.contains('drag-handle')) {
2759 scope
.dragState
= null;
2760 ev
.preventDefault();
2764 scope
.dragState
.node
= dom
.parent(scope
.dragState
.node
, '.tr');
2765 ev
.dataTransfer
.setData('text', 'drag');
2766 ev
.target
.style
.opacity
= 0.4;
2770 handleDragOver: function(ev
) {
2771 var n
= scope
.dragState
.targetNode
,
2772 r
= scope
.dragState
.rect
,
2773 t
= r
.top
+ r
.height
/ 2;
2775 if (ev
.clientY
<= t
) {
2776 n
.classList
.remove('drag-over-below');
2777 n
.classList
.add('drag-over-above');
2780 n
.classList
.remove('drag-over-above');
2781 n
.classList
.add('drag-over-below');
2784 ev
.dataTransfer
.dropEffect
= 'move';
2785 ev
.preventDefault();
2790 handleDragEnter: function(ev
) {
2791 scope
.dragState
.rect
= ev
.currentTarget
.getBoundingClientRect();
2792 scope
.dragState
.targetNode
= ev
.currentTarget
;
2796 handleDragLeave: function(ev
) {
2797 ev
.currentTarget
.classList
.remove('drag-over-above');
2798 ev
.currentTarget
.classList
.remove('drag-over-below');
2802 handleDragEnd: function(ev
) {
2805 n
.style
.opacity
= '';
2806 n
.classList
.add('flash');
2807 n
.parentNode
.querySelectorAll('.drag-over-above, .drag-over-below')
2808 .forEach(function(tr
) {
2809 tr
.classList
.remove('drag-over-above');
2810 tr
.classList
.remove('drag-over-below');
2815 handleDrop: function(ev
) {
2816 var s
= scope
.dragState
;
2818 if (s
.node
&& s
.targetNode
) {
2819 var config_name
= this.uciconfig
|| this.map
.config
,
2820 ref_node
= s
.targetNode
,
2823 if (ref_node
.classList
.contains('drag-over-below')) {
2824 ref_node
= ref_node
.nextElementSibling
;
2828 var sid1
= s
.node
.getAttribute('data-sid'),
2829 sid2
= s
.targetNode
.getAttribute('data-sid');
2831 s
.node
.parentNode
.insertBefore(s
.node
, ref_node
);
2832 this.map
.data
.move(config_name
, sid1
, sid2
, after
);
2835 scope
.dragState
= null;
2836 ev
.target
.style
.opacity
= '';
2837 ev
.stopPropagation();
2838 ev
.preventDefault();
2843 determineBackgroundColor: function(node
) {
2844 var r
= 255, g
= 255, b
= 255;
2847 var s
= window
.getComputedStyle(node
),
2848 c
= (s
.getPropertyValue('background-color') || '').replace(/ /g
, '');
2850 if (c
!= '' && c
!= 'transparent' && c
!= 'rgba(0,0,0,0)') {
2851 if (/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.test(c
)) {
2852 r
= parseInt(RegExp
.$1, 16);
2853 g
= parseInt(RegExp
.$2, 16);
2854 b
= parseInt(RegExp
.$3, 16);
2856 else if (/^rgba?\(([0-9]+),([0-9]+),([0-9]+)[,)]$/.test(c
)) {
2865 node
= node
.parentNode
;
2872 handleTouchMove: function(ev
) {
2873 if (!ev
.target
.classList
.contains('drag-handle'))
2876 var touchLoc
= ev
.targetTouches
[0],
2878 rowElem
= dom
.parent(rowBtn
, '.tr'),
2879 htmlElem
= document
.querySelector('html'),
2880 dragHandle
= document
.querySelector('.touchsort-element'),
2881 viewportHeight
= Math
.max(document
.documentElement
.clientHeight
, window
.innerHeight
|| 0);
2884 var rowRect
= rowElem
.getBoundingClientRect(),
2885 btnRect
= rowBtn
.getBoundingClientRect(),
2886 paddingLeft
= btnRect
.left
- rowRect
.left
,
2887 paddingRight
= rowRect
.right
- btnRect
.right
,
2888 colorBg
= this.determineBackgroundColor(rowElem
),
2889 colorFg
= (colorBg
[0] * 0.299 + colorBg
[1] * 0.587 + colorBg
[2] * 0.114) > 186 ? [ 0, 0, 0 ] : [ 255, 255, 255 ];
2891 dragHandle
= E('div', { 'class': 'touchsort-element' }, [
2892 E('strong', [ rowElem
.getAttribute('data-title') ]),
2893 rowBtn
.cloneNode(true)
2896 Object
.assign(dragHandle
.style
, {
2897 position
: 'absolute',
2898 boxShadow
: '0 0 3px rgba(%d, %d, %d, 1)'.format(colorFg
[0], colorFg
[1], colorFg
[2]),
2899 background
: 'rgba(%d, %d, %d, 0.8)'.format(colorBg
[0], colorBg
[1], colorBg
[2]),
2900 top
: rowRect
.top
+ 'px',
2901 left
: rowRect
.left
+ 'px',
2902 width
: rowRect
.width
+ 'px',
2903 height
: (rowBtn
.offsetHeight
+ 4) + 'px'
2906 Object
.assign(dragHandle
.firstElementChild
.style
, {
2907 position
: 'absolute',
2908 lineHeight
: dragHandle
.style
.height
,
2909 whiteSpace
: 'nowrap',
2911 textOverflow
: 'ellipsis',
2912 left
: (paddingRight
> paddingLeft
) ? '' : '5px',
2913 right
: (paddingRight
> paddingLeft
) ? '5px' : '',
2914 width
: (Math
.max(paddingLeft
, paddingRight
) - 10) + 'px'
2917 Object
.assign(dragHandle
.lastElementChild
.style
, {
2918 position
: 'absolute',
2920 left
: paddingLeft
+ 'px',
2921 width
: rowBtn
.offsetWidth
+ 'px'
2924 document
.body
.appendChild(dragHandle
);
2926 rowElem
.classList
.remove('flash');
2930 dragHandle
.style
.top
= (touchLoc
.pageY
- (parseInt(dragHandle
.style
.height
) / 2)) + 'px';
2932 rowElem
.parentNode
.querySelectorAll('[draggable]').forEach(function(tr
, i
, trs
) {
2933 var trRect
= tr
.getBoundingClientRect(),
2934 yTop
= trRect
.top
+ window
.scrollY
,
2935 yBottom
= trRect
.bottom
+ window
.scrollY
,
2936 yMiddle
= yTop
+ ((yBottom
- yTop
) / 2);
2938 tr
.classList
.remove('drag-over-above', 'drag-over-below');
2940 if ((i
== 0 || touchLoc
.pageY
>= yTop
) && touchLoc
.pageY
<= yMiddle
)
2941 tr
.classList
.add('drag-over-above');
2942 else if ((i
== (trs
.length
- 1) || touchLoc
.pageY
<= yBottom
) && touchLoc
.pageY
> yMiddle
)
2943 tr
.classList
.add('drag-over-below');
2946 /* prevent standard scrolling and scroll page when drag handle is
2947 * moved very close (~30px) to the viewport edge */
2949 ev
.preventDefault();
2951 if (touchLoc
.clientY
< 30)
2952 window
.requestAnimationFrame(function() { htmlElem
.scrollTop
-= 30 });
2953 else if (touchLoc
.clientY
> viewportHeight
- 30)
2954 window
.requestAnimationFrame(function() { htmlElem
.scrollTop
+= 30 });
2958 handleTouchEnd: function(ev
) {
2959 var rowElem
= dom
.parent(ev
.target
, '.tr'),
2960 htmlElem
= document
.querySelector('html'),
2961 dragHandle
= document
.querySelector('.touchsort-element'),
2962 targetElem
= rowElem
.parentNode
.querySelector('.drag-over-above, .drag-over-below'),
2963 viewportHeight
= Math
.max(document
.documentElement
.clientHeight
, window
.innerHeight
|| 0);
2969 var isBelow
= targetElem
.classList
.contains('drag-over-below');
2971 rowElem
.parentNode
.insertBefore(rowElem
, isBelow
? targetElem
.nextElementSibling
: targetElem
);
2974 this.uciconfig
|| this.map
.config
,
2975 rowElem
.getAttribute('data-sid'),
2976 targetElem
.getAttribute('data-sid'),
2979 window
.requestAnimationFrame(function() {
2980 var rowRect
= rowElem
.getBoundingClientRect();
2982 if (rowRect
.top
< 50)
2983 htmlElem
.scrollTop
= (htmlElem
.scrollTop
+ rowRect
.top
- 50);
2984 else if (rowRect
.bottom
> viewportHeight
- 50)
2985 htmlElem
.scrollTop
= (htmlElem
.scrollTop
+ viewportHeight
- 50 - rowRect
.height
);
2987 rowElem
.classList
.add('flash');
2990 targetElem
.classList
.remove('drag-over-above', 'drag-over-below');
2993 document
.body
.removeChild(dragHandle
);
2997 handleModalCancel: function(modalMap
, ev
) {
2998 var prevNode
= this.getPreviousModalMap(),
2999 resetTasks
= Promise
.resolve();
3002 var heading
= prevNode
.parentNode
.querySelector('h4'),
3003 prevMap
= dom
.findClassInstance(prevNode
);
3006 resetTasks
= resetTasks
3007 .then(L
.bind(prevMap
.load
, prevMap
))
3008 .then(L
.bind(prevMap
.reset
, prevMap
));
3010 prevMap
= prevMap
.parent
;
3013 prevNode
.classList
.add('flash');
3014 prevNode
.classList
.remove('hidden');
3015 prevNode
.parentNode
.removeChild(prevNode
.nextElementSibling
);
3017 heading
.removeChild(heading
.lastElementChild
);
3019 if (!this.getPreviousModalMap())
3021 .querySelector('div.right > button')
3022 .firstChild
.data
= _('Dismiss');
3032 handleModalSave: function(modalMap
, ev
) {
3033 var mapNode
= this.getActiveModalMap(),
3034 activeMap
= dom
.findClassInstance(mapNode
),
3035 saveTasks
= activeMap
.save(null, true);
3037 while (activeMap
.parent
) {
3038 activeMap
= activeMap
.parent
;
3039 saveTasks
= saveTasks
3040 .then(L
.bind(activeMap
.load
, activeMap
))
3041 .then(L
.bind(activeMap
.reset
, activeMap
));
3045 .then(L
.bind(this.handleModalCancel
, this, modalMap
, ev
, true))
3046 .catch(function() {});
3050 handleSort: function(ev
) {
3051 if (!ev
.target
.matches('th[data-sortable-row]'))
3055 descending
= (th
.getAttribute('data-sort-direction') == 'desc'),
3056 config_name
= this.uciconfig
|| this.map
.config
,
3060 ev
.currentTarget
.querySelectorAll('th').forEach(function(other_th
, i
) {
3061 if (other_th
!== th
)
3062 other_th
.removeAttribute('data-sort-direction');
3067 ev
.currentTarget
.parentNode
.querySelectorAll('tr.cbi-section-table-row').forEach(L
.bind(function(tr
, i
) {
3068 var sid
= tr
.getAttribute('data-sid'),
3069 opt
= tr
.childNodes
[index
].getAttribute('data-name'),
3070 val
= this.cfgvalue(sid
, opt
);
3072 tr
.querySelectorAll('.flash').forEach(function(n
) {
3073 n
.classList
.remove('flash')
3077 ui
.Table
.prototype.deriveSortKey((val
!= null) ? val
.trim() : ''),
3082 list
.sort(function(a
, b
) {
3084 ? -L
.naturalCompare(a
[0], b
[0])
3085 : L
.naturalCompare(a
[0], b
[0]);
3088 window
.requestAnimationFrame(L
.bind(function() {
3089 var ref_sid
, cur_sid
;
3091 for (var i
= 0; i
< list
.length
; i
++) {
3092 list
[i
][1].childNodes
[index
].classList
.add('flash');
3093 th
.parentNode
.parentNode
.appendChild(list
[i
][1]);
3095 cur_sid
= list
[i
][1].getAttribute('data-sid');
3098 this.map
.data
.move(config_name
, cur_sid
, ref_sid
, true);
3103 th
.setAttribute('data-sort-direction', descending
? 'asc' : 'desc');
3108 * Add further options to the per-section instanced modal popup.
3110 * This function may be overwritten by user code to perform additional
3111 * setup steps before displaying the more options modal which is useful to
3112 * e.g. query additional data or to inject further option elements.
3114 * The default implementation of this function does nothing.
3117 * @param {LuCI.form.NamedSection} modalSection
3118 * The `NamedSection` instance about to be rendered in the modal popup.
3120 * @param {string} section_id
3121 * The ID of the underlying UCI section the modal popup belongs to.
3124 * The DOM event emitted by clicking the `More…` button.
3126 * @returns {*|Promise<*>}
3127 * Return values of this function are ignored but if a promise is returned,
3128 * it is run to completion before the rendering is continued, allowing
3129 * custom logic to perform asynchroneous work before the modal dialog
3132 addModalOptions: function(modalSection
, section_id
, ev
) {
3137 getActiveModalMap: function() {
3138 return document
.querySelector('body.modal-overlay-active > #modal_overlay > .modal.cbi-modal > .cbi-map:not(.hidden)');
3142 getPreviousModalMap: function() {
3143 var mapNode
= this.getActiveModalMap(),
3144 prevNode
= mapNode
? mapNode
.previousElementSibling
: null;
3146 return (prevNode
&& prevNode
.matches('.cbi-map.hidden')) ? prevNode
: null;
3150 cloneOptions: function(src_section
, dest_section
) {
3151 for (var i
= 0; i
< src_section
.children
.length
; i
++) {
3152 var o1
= src_section
.children
[i
];
3154 if (o1
.modalonly
=== false && src_section
=== this)
3159 if (o1
.subsection
) {
3160 o2
= dest_section
.option(o1
.constructor, o1
.option
, o1
.subsection
.constructor, o1
.subsection
.sectiontype
, o1
.subsection
.title
, o1
.subsection
.description
);
3162 for (var k
in o1
.subsection
) {
3163 if (!o1
.subsection
.hasOwnProperty(k
))
3169 case 'parentoption':
3173 o2
.subsection
[k
] = o1
.subsection
[k
];
3177 this.cloneOptions(o1
.subsection
, o2
.subsection
);
3180 o2
= dest_section
.option(o1
.constructor, o1
.option
, o1
.title
, o1
.description
);
3184 if (!o1
.hasOwnProperty(k
))
3204 renderMoreOptionsModal: function(section_id
, ev
) {
3205 var parent
= this.map
,
3206 sref
= parent
.data
.get(parent
.config
, section_id
),
3207 mapNode
= this.getActiveModalMap(),
3208 activeMap
= mapNode
? dom
.findClassInstance(mapNode
) : null,
3209 stackedMap
= activeMap
&& (activeMap
.parent
!== parent
|| activeMap
.section
!== section_id
);
3211 return (stackedMap
? activeMap
.save(null, true) : Promise
.resolve()).then(L
.bind(function() {
3212 section_id
= sref
['.name'];
3216 if (parent
instanceof CBIJSONMap
) {
3217 m
= new CBIJSONMap(null, null, null);
3218 m
.data
= parent
.data
;
3221 m
= new CBIMap(parent
.config
, null, null);
3224 var s
= m
.section(CBINamedSection
, section_id
, this.sectiontype
);
3227 m
.section
= section_id
;
3228 m
.readonly
= parent
.readonly
;
3231 s
.tab_names
= this.tab_names
;
3233 this.cloneOptions(this, s
);
3235 return Promise
.resolve(this.addModalOptions(s
, section_id
, ev
)).then(function() {
3237 }).then(L
.bind(function(nodes
) {
3238 var title
= parent
.title
,
3241 if ((name
= this.titleFn('modaltitle', section_id
)) != null)
3243 else if ((name
= this.titleFn('sectiontitle', section_id
)) != null)
3244 title
= '%s - %s'.format(parent
.title
, name
);
3245 else if (!this.anonymous
)
3246 title
= '%s - %s'.format(parent
.title
, section_id
);
3250 .querySelector('h4')
3251 .appendChild(E('span', title
? ' » ' + title
: ''));
3254 .querySelector('div.right > button')
3255 .firstChild
.data
= _('Back');
3257 mapNode
.classList
.add('hidden');
3258 mapNode
.parentNode
.insertBefore(nodes
, mapNode
.nextElementSibling
);
3260 nodes
.classList
.add('flash');
3263 ui
.showModal(title
, [
3265 E('div', { 'class': 'right' }, [
3267 'class': 'cbi-button',
3268 'click': ui
.createHandlerFn(this, 'handleModalCancel', m
)
3269 }, [ _('Dismiss') ]), ' ',
3271 'class': 'cbi-button cbi-button-positive important',
3272 'click': ui
.createHandlerFn(this, 'handleModalSave', m
),
3273 'disabled': m
.readonly
|| null
3279 }, this)).catch(L
.error
);
3284 * @class GridSection
3285 * @memberof LuCI.form
3286 * @augments LuCI.form.TableSection
3290 * The `GridSection` class maps all or - if `filter()` is overwritten - a
3291 * subset of the underlying UCI configuration sections of a given type.
3293 * A grid section functions similar to a {@link LuCI.form.TableSection} but
3294 * supports tabbing in the modal overlay. Option elements added with
3295 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
3296 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
3297 * are displayed in the modal popup.
3299 * Another important difference is that the table cells show a readonly text
3300 * preview of the corresponding option elements by default, unless the child
3301 * option element is explicitely made writable by setting the `editable`
3302 * property to `true`.
3304 * Additionally, the grid section honours a `modalonly` property of child
3305 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
3306 * documentation for details.
3308 * Layout wise, a grid section looks mostly identical to table sections.
3310 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3311 * The configuration form this section is added to. It is automatically passed
3312 * by [section()]{@link LuCI.form.Map#section}.
3314 * @param {string} section_type
3315 * The type of the UCI section to map.
3317 * @param {string} [title]
3318 * The title caption of the form section element.
3320 * @param {string} [description]
3321 * The description text of the form section element.
3323 var CBIGridSection
= CBITableSection
.extend(/** @lends LuCI.form.GridSection.prototype */ {
3325 * Add an option tab to the section.
3327 * The modal option elements of a grid section may be divided into multiple
3328 * tabs to provide a better overview to the user.
3330 * Before options can be moved into a tab pane, the corresponding tab
3331 * has to be defined first, which is done by calling this function.
3333 * Note that tabs are only effective in modal popups, options added with
3334 * `option()` will not be assigned to a specific tab and are rendered in
3335 * the table view only.
3337 * @param {string} name
3338 * The name of the tab to register. It may be freely chosen and just serves
3339 * as an identifier to differentiate tabs.
3341 * @param {string} title
3342 * The human readable caption of the tab.
3344 * @param {string} [description]
3345 * An additional description text for the corresponding tab pane. It is
3346 * displayed as text paragraph below the tab but before the tab pane
3347 * contents. If omitted, no description will be rendered.
3350 * Throws an exeption if a tab with the same `name` already exists.
3352 tab: function(name
, title
, description
) {
3353 CBIAbstractSection
.prototype.tab
.call(this, name
, title
, description
);
3357 handleAdd: function(ev
, name
) {
3358 var config_name
= this.uciconfig
|| this.map
.config
,
3359 section_id
= this.map
.data
.add(config_name
, this.sectiontype
, name
),
3360 mapNode
= this.getPreviousModalMap(),
3361 prevMap
= mapNode
? dom
.findClassInstance(mapNode
) : this.map
;
3363 prevMap
.addedSection
= section_id
;
3365 return this.renderMoreOptionsModal(section_id
);
3369 handleModalSave: function(/* ... */) {
3370 var mapNode
= this.getPreviousModalMap(),
3371 prevMap
= mapNode
? dom
.findClassInstance(mapNode
) : this.map
;
3373 return this.super('handleModalSave', arguments
);
3377 handleModalCancel: function(modalMap
, ev
, isSaving
) {
3378 var config_name
= this.uciconfig
|| this.map
.config
,
3379 mapNode
= this.getPreviousModalMap(),
3380 prevMap
= mapNode
? dom
.findClassInstance(mapNode
) : this.map
;
3382 if (prevMap
.addedSection
!= null && !isSaving
)
3383 this.map
.data
.remove(config_name
, prevMap
.addedSection
);
3385 delete prevMap
.addedSection
;
3387 return this.super('handleModalCancel', arguments
);
3391 renderUCISection: function(section_id
) {
3392 return this.renderOptions(null, section_id
);
3396 renderChildren: function(tab_name
, section_id
, in_table
) {
3397 var tasks
= [], index
= 0;
3399 for (var i
= 0, opt
; (opt
= this.children
[i
]) != null; i
++) {
3400 if (opt
.disable
|| opt
.modalonly
)
3404 tasks
.push(opt
.render(index
++, section_id
, in_table
));
3406 tasks
.push(this.renderTextValue(section_id
, opt
));
3409 return Promise
.all(tasks
);
3413 renderTextValue: function(section_id
, opt
) {
3414 var title
= this.stripTags(opt
.title
).trim(),
3415 descr
= this.stripTags(opt
.description
).trim(),
3416 value
= opt
.textvalue(section_id
);
3419 'class': 'td cbi-value-field',
3420 'data-title': (title
!= '') ? title
: null,
3421 'data-description': (descr
!= '') ? descr
: null,
3422 'data-name': opt
.option
,
3423 'data-widget': 'CBI.DummyValue'
3424 }, (value
!= null) ? value
: E('em', _('none')));
3428 renderHeaderRows: function(section_id
) {
3429 return this.super('renderHeaderRows', [ NaN
, true ]);
3433 renderRowActions: function(section_id
) {
3434 return this.super('renderRowActions', [ section_id
, _('Edit') ]);
3439 var section_ids
= this.cfgsections(),
3442 if (Array
.isArray(this.children
)) {
3443 for (var i
= 0; i
< section_ids
.length
; i
++) {
3444 for (var j
= 0; j
< this.children
.length
; j
++) {
3445 if (!this.children
[j
].editable
|| this.children
[j
].modalonly
)
3448 tasks
.push(this.children
[j
].parse(section_ids
[i
]));
3453 return Promise
.all(tasks
);
3458 * @class NamedSection
3459 * @memberof LuCI.form
3460 * @augments LuCI.form.AbstractSection
3464 * The `NamedSection` class maps exactly one UCI section instance which is
3465 * specified when constructing the class instance.
3467 * Layout and functionality wise, a named section is essentially a
3468 * `TypedSection` which allows exactly one section node.
3470 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3471 * The configuration form this section is added to. It is automatically passed
3472 * by [section()]{@link LuCI.form.Map#section}.
3474 * @param {string} section_id
3475 * The name (ID) of the UCI section to map.
3477 * @param {string} section_type
3478 * The type of the UCI section to map.
3480 * @param {string} [title]
3481 * The title caption of the form section element.
3483 * @param {string} [description]
3484 * The description text of the form section element.
3486 var CBINamedSection
= CBIAbstractSection
.extend(/** @lends LuCI.form.NamedSection.prototype */ {
3487 __name__
: 'CBI.NamedSection',
3488 __init__: function(map
, section_id
/*, ... */) {
3489 this.super('__init__', this.varargs(arguments
, 2, map
));
3491 this.section
= section_id
;
3495 * If set to `true`, the user may remove or recreate the sole mapped
3496 * configuration instance from the form section widget, otherwise only a
3497 * preexisting section may be edited. The default is `false`.
3499 * @name LuCI.form.NamedSection.prototype#addremove
3505 * Override the UCI configuration name to read the section IDs from. By
3506 * default, the configuration name is inherited from the parent `Map`.
3507 * By setting this property, a deviating configuration may be specified.
3508 * The default is `null`, means inheriting from the parent form.
3510 * @name LuCI.form.NamedSection.prototype#uciconfig
3516 * The `NamedSection` class overwrites the generic `cfgsections()`
3517 * implementation to return a one-element array containing the mapped
3518 * section ID as sole element. User code should not normally change this.
3520 * @returns {string[]}
3521 * Returns a one-element array containing the mapped section ID.
3523 cfgsections: function() {
3524 return [ this.section
];
3528 handleAdd: function(ev
) {
3529 var section_id
= this.section
,
3530 config_name
= this.uciconfig
|| this.map
.config
;
3532 this.map
.data
.add(config_name
, this.sectiontype
, section_id
);
3533 return this.map
.save(null, true);
3537 handleRemove: function(ev
) {
3538 var section_id
= this.section
,
3539 config_name
= this.uciconfig
|| this.map
.config
;
3541 this.map
.data
.remove(config_name
, section_id
);
3542 return this.map
.save(null, true);
3546 renderContents: function(data
) {
3547 var ucidata
= data
[0], nodes
= data
[1],
3548 section_id
= this.section
,
3549 config_name
= this.uciconfig
|| this.map
.config
,
3550 sectionEl
= E('div', {
3551 'id': ucidata
? null : 'cbi-%s-%s'.format(config_name
, section_id
),
3552 'class': 'cbi-section',
3553 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
3554 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
3557 if (typeof(this.title
) === 'string' && this.title
!== '')
3558 sectionEl
.appendChild(E('h3', {}, this.title
));
3560 if (typeof(this.description
) === 'string' && this.description
!== '')
3561 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
3564 if (this.addremove
) {
3565 sectionEl
.appendChild(
3566 E('div', { 'class': 'cbi-section-remove right' },
3568 'class': 'cbi-button',
3569 'click': ui
.createHandlerFn(this, 'handleRemove'),
3570 'disabled': this.map
.readonly
|| null
3571 }, [ _('Delete') ])));
3574 sectionEl
.appendChild(E('div', {
3575 'id': 'cbi-%s-%s'.format(config_name
, section_id
),
3577 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3578 'data-section-id': section_id
3581 else if (this.addremove
) {
3582 sectionEl
.appendChild(
3584 'class': 'cbi-button cbi-button-add',
3585 'click': ui
.createHandlerFn(this, 'handleAdd'),
3586 'disabled': this.map
.readonly
|| null
3590 dom
.bindClassInstance(sectionEl
, this);
3596 render: function() {
3597 var config_name
= this.uciconfig
|| this.map
.config
,
3598 section_id
= this.section
;
3600 return Promise
.all([
3601 this.map
.data
.get(config_name
, section_id
),
3602 this.renderUCISection(section_id
)
3603 ]).then(this.renderContents
.bind(this));
3609 * @memberof LuCI.form
3610 * @augments LuCI.form.AbstractValue
3614 * The `Value` class represents a simple one-line form input using the
3615 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3616 * {@link LuCI.ui.Combobox} class as underlying widget.
3618 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3619 * The configuration form this section is added to. It is automatically passed
3620 * by [option()]{@link LuCI.form.AbstractSection#option} or
3621 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3622 * option to the section.
3624 * @param {LuCI.form.AbstractSection} section
3625 * The configuration section this option is added to. It is automatically passed
3626 * by [option()]{@link LuCI.form.AbstractSection#option} or
3627 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3628 * option to the section.
3630 * @param {string} option
3631 * The name of the UCI option to map.
3633 * @param {string} [title]
3634 * The title caption of the option element.
3636 * @param {string} [description]
3637 * The description text of the option element.
3639 var CBIValue
= CBIAbstractValue
.extend(/** @lends LuCI.form.Value.prototype */ {
3640 __name__
: 'CBI.Value',
3643 * If set to `true`, the field is rendered as password input, otherwise
3644 * as plain text input.
3646 * @name LuCI.form.Value.prototype#password
3652 * Set a placeholder string to use when the input field is empty.
3654 * @name LuCI.form.Value.prototype#placeholder
3660 * Add a predefined choice to the form option. By adding one or more
3661 * choices, the plain text input field is turned into a combobox widget
3662 * which prompts the user to select a predefined choice, or to enter a
3665 * @param {string} key
3666 * The choice value to add.
3668 * @param {Node|string} value
3669 * The caption for the choice value. May be a DOM node, a document fragment
3670 * or a plain text string. If omitted, the `key` value is used as caption.
3672 value: function(key
, val
) {
3673 this.keylist
= this.keylist
|| [];
3674 this.keylist
.push(String(key
));
3676 this.vallist
= this.vallist
|| [];
3677 this.vallist
.push(dom
.elem(val
) ? val
: String(val
!= null ? val
: key
));
3681 render: function(option_index
, section_id
, in_table
) {
3682 return Promise
.resolve(this.cfgvalue(section_id
))
3683 .then(this.renderWidget
.bind(this, section_id
, option_index
))
3684 .then(this.renderFrame
.bind(this, section_id
, in_table
, option_index
));
3688 handleValueChange: function(section_id
, state
, ev
) {
3689 if (typeof(this.onchange
) != 'function')
3692 var value
= this.formvalue(section_id
);
3694 if (isEqual(value
, state
.previousValue
))
3697 state
.previousValue
= value
;
3698 this.onchange
.call(this, ev
, section_id
, value
);
3702 renderFrame: function(section_id
, in_table
, option_index
, nodes
) {
3703 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
3704 depend_list
= this.transformDepList(section_id
),
3708 var title
= this.stripTags(this.title
).trim();
3709 optionEl
= E('td', {
3710 'class': 'td cbi-value-field',
3711 'data-title': (title
!= '') ? title
: null,
3712 'data-description': this.stripTags(this.description
).trim(),
3713 'data-name': this.option
,
3714 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3716 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3717 'data-index': option_index
,
3718 'data-depends': depend_list
,
3719 'data-field': this.cbid(section_id
)
3723 optionEl
= E('div', {
3724 'class': 'cbi-value',
3725 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3726 'data-index': option_index
,
3727 'data-depends': depend_list
,
3728 'data-field': this.cbid(section_id
),
3729 'data-name': this.option
,
3730 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3733 if (this.last_child
)
3734 optionEl
.classList
.add('cbi-value-last');
3736 if (typeof(this.title
) === 'string' && this.title
!== '') {
3737 optionEl
.appendChild(E('label', {
3738 'class': 'cbi-value-title',
3739 'for': 'widget.cbid.%s.%s.%s'.format(config_name
, section_id
, this.option
),
3740 'click': function(ev
) {
3741 var node
= ev
.currentTarget
,
3742 elem
= node
.nextElementSibling
.querySelector('#' + node
.getAttribute('for')) || node
.nextElementSibling
.querySelector('[data-widget-id="' + node
.getAttribute('for') + '"]');
3750 this.titleref
? E('a', {
3751 'class': 'cbi-title-ref',
3752 'href': this.titleref
,
3753 'title': this.titledesc
|| _('Go to relevant configuration page')
3754 }, this.title
) : this.title
));
3756 optionEl
.appendChild(E('div', { 'class': 'cbi-value-field' }));
3761 (optionEl
.lastChild
|| optionEl
).appendChild(nodes
);
3763 if (!in_table
&& typeof(this.description
) === 'string' && this.description
!== '')
3764 dom
.append(optionEl
.lastChild
|| optionEl
,
3765 E('div', { 'class': 'cbi-value-description' }, this.description
.trim()));
3767 if (depend_list
&& depend_list
.length
)
3768 optionEl
.classList
.add('hidden');
3770 optionEl
.addEventListener('widget-change',
3771 L
.bind(this.map
.checkDepends
, this.map
));
3773 optionEl
.addEventListener('widget-change',
3774 L
.bind(this.handleValueChange
, this, section_id
, {}));
3776 dom
.bindClassInstance(optionEl
, this);
3782 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3783 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3784 choices
= this.transformChoices(),
3788 var placeholder
= (this.optional
|| this.rmempty
)
3789 ? E('em', _('unspecified')) : _('-- Please choose --');
3791 widget
= new ui
.Combobox(Array
.isArray(value
) ? value
.join(' ') : value
, choices
, {
3792 id
: this.cbid(section_id
),
3794 optional
: this.optional
|| this.rmempty
,
3795 datatype
: this.datatype
,
3796 select_placeholder
: this.placeholder
|| placeholder
,
3797 validate
: L
.bind(this.validate
, this, section_id
),
3798 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3802 widget
= new ui
.Textfield(Array
.isArray(value
) ? value
.join(' ') : value
, {
3803 id
: this.cbid(section_id
),
3804 password
: this.password
,
3805 optional
: this.optional
|| this.rmempty
,
3806 datatype
: this.datatype
,
3807 placeholder
: this.placeholder
,
3808 validate
: L
.bind(this.validate
, this, section_id
),
3809 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3813 return widget
.render();
3818 * @class DynamicList
3819 * @memberof LuCI.form
3820 * @augments LuCI.form.Value
3824 * The `DynamicList` class represents a multi value widget allowing the user
3825 * to enter multiple unique values, optionally selected from a set of
3826 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3828 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3829 * The configuration form this section is added to. It is automatically passed
3830 * by [option()]{@link LuCI.form.AbstractSection#option} or
3831 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3832 * option to the section.
3834 * @param {LuCI.form.AbstractSection} section
3835 * The configuration section this option is added to. It is automatically passed
3836 * by [option()]{@link LuCI.form.AbstractSection#option} or
3837 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3838 * option to the section.
3840 * @param {string} option
3841 * The name of the UCI option to map.
3843 * @param {string} [title]
3844 * The title caption of the option element.
3846 * @param {string} [description]
3847 * The description text of the option element.
3849 var CBIDynamicList
= CBIValue
.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3850 __name__
: 'CBI.DynamicList',
3853 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3854 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3855 choices
= this.transformChoices(),
3856 items
= L
.toArray(value
);
3858 var widget
= new ui
.DynamicList(items
, choices
, {
3859 id
: this.cbid(section_id
),
3861 optional
: this.optional
|| this.rmempty
,
3862 datatype
: this.datatype
,
3863 placeholder
: this.placeholder
,
3864 validate
: L
.bind(this.validate
, this, section_id
),
3865 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3868 return widget
.render();
3874 * @memberof LuCI.form
3875 * @augments LuCI.form.Value
3879 * The `ListValue` class implements a simple static HTML select element
3880 * allowing the user to chose a single value from a set of predefined choices.
3881 * It builds upon the {@link LuCI.ui.Select} widget.
3883 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3884 * The configuration form this section is added to. It is automatically passed
3885 * by [option()]{@link LuCI.form.AbstractSection#option} or
3886 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3887 * option to the section.
3889 * @param {LuCI.form.AbstractSection} section
3890 * The configuration section this option is added to. It is automatically passed
3891 * by [option()]{@link LuCI.form.AbstractSection#option} or
3892 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3893 * option to the section.
3895 * @param {string} option
3896 * The name of the UCI option to map.
3898 * @param {string} [title]
3899 * The title caption of the option element.
3901 * @param {string} [description]
3902 * The description text of the option element.
3904 var CBIListValue
= CBIValue
.extend(/** @lends LuCI.form.ListValue.prototype */ {
3905 __name__
: 'CBI.ListValue',
3907 __init__: function() {
3908 this.super('__init__', arguments
);
3909 this.widget
= 'select';
3910 this.orientation
= 'horizontal';
3915 * Set the size attribute of the underlying HTML select element.
3917 * @name LuCI.form.ListValue.prototype#size
3923 * Set the type of the underlying form controls.
3925 * May be one of `select` or `radio`. If set to `select`, an HTML
3926 * select element is rendered, otherwise a collection of `radio`
3929 * @name LuCI.form.ListValue.prototype#widget
3935 * Set the orientation of the underlying radio or checkbox elements.
3937 * May be one of `horizontal` or `vertical`. Only applies to non-select
3940 * @name LuCI.form.ListValue.prototype#orientation
3942 * @default horizontal
3946 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3947 var choices
= this.transformChoices();
3948 var widget
= new ui
.Select((cfgvalue
!= null) ? cfgvalue
: this.default, choices
, {
3949 id
: this.cbid(section_id
),
3952 widget
: this.widget
,
3953 optional
: this.optional
,
3954 orientation
: this.orientation
,
3955 placeholder
: this.placeholder
,
3956 validate
: L
.bind(this.validate
, this, section_id
),
3957 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3960 return widget
.render();
3966 * @memberof LuCI.form
3967 * @augments LuCI.form.Value
3971 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3972 * implement a simple checkbox element.
3974 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3975 * The configuration form this section is added to. It is automatically passed
3976 * by [option()]{@link LuCI.form.AbstractSection#option} or
3977 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3978 * option to the section.
3980 * @param {LuCI.form.AbstractSection} section
3981 * The configuration section this option is added to. It is automatically passed
3982 * by [option()]{@link LuCI.form.AbstractSection#option} or
3983 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3984 * option to the section.
3986 * @param {string} option
3987 * The name of the UCI option to map.
3989 * @param {string} [title]
3990 * The title caption of the option element.
3992 * @param {string} [description]
3993 * The description text of the option element.
3995 var CBIFlagValue
= CBIValue
.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3996 __name__
: 'CBI.FlagValue',
3998 __init__: function() {
3999 this.super('__init__', arguments
);
4002 this.disabled
= '0';
4003 this.default = this.disabled
;
4007 * Sets the input value to use for the checkbox checked state.
4009 * @name LuCI.form.FlagValue.prototype#enabled
4015 * Sets the input value to use for the checkbox unchecked state.
4017 * @name LuCI.form.FlagValue.prototype#disabled
4023 * Set a tooltip for the flag option.
4025 * If set to a string, it will be used as-is as a tooltip.
4027 * If set to a function, the function will be invoked and the return
4028 * value will be shown as a tooltip. If the return value of the function
4029 * is `null` no tooltip will be set.
4031 * @name LuCI.form.TypedSection.prototype#tooltip
4032 * @type string|function
4037 * Set a tooltip icon.
4039 * If set, this icon will be shown for the default one.
4040 * This could also be a png icon from the resources directory.
4042 * @name LuCI.form.TypedSection.prototype#tooltipicon
4048 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4051 if (typeof(this.tooltip
) == 'function')
4052 tooltip
= this.tooltip
.apply(this, [section_id
]);
4053 else if (typeof(this.tooltip
) == 'string')
4054 tooltip
= (arguments
.length
> 1) ? ''.format
.apply(this.tooltip
, this.varargs(arguments
, 1)) : this.tooltip
;
4056 var widget
= new ui
.Checkbox((cfgvalue
!= null) ? cfgvalue
: this.default, {
4057 id
: this.cbid(section_id
),
4058 value_enabled
: this.enabled
,
4059 value_disabled
: this.disabled
,
4060 validate
: L
.bind(this.validate
, this, section_id
),
4062 tooltipicon
: this.tooltipicon
,
4063 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4066 return widget
.render();
4070 * Query the checked state of the underlying checkbox widget and return
4071 * either the `enabled` or the `disabled` property value, depending on
4072 * the checked state.
4076 formvalue: function(section_id
) {
4077 var elem
= this.getUIElement(section_id
),
4078 checked
= elem
? elem
.isChecked() : false;
4079 return checked
? this.enabled
: this.disabled
;
4083 * Query the checked state of the underlying checkbox widget and return
4084 * either a localized `Yes` or `No` string, depending on the checked state.
4088 textvalue: function(section_id
) {
4089 var cval
= this.cfgvalue(section_id
);
4092 cval
= this.default;
4094 return (cval
== this.enabled
) ? _('Yes') : _('No');
4098 parse: function(section_id
) {
4099 if (this.isActive(section_id
)) {
4100 var fval
= this.formvalue(section_id
);
4102 if (!this.isValid(section_id
)) {
4103 var title
= this.stripTags(this.title
).trim();
4104 var error
= this.getValidationError(section_id
);
4105 return Promise
.reject(new TypeError(
4106 _('Option "%s" contains an invalid input value.').format(title
|| this.option
) + ' ' + error
));
4109 if (fval
== this.default && (this.optional
|| this.rmempty
))
4110 return Promise
.resolve(this.remove(section_id
));
4112 return Promise
.resolve(this.write(section_id
, fval
));
4114 else if (!this.retain
) {
4115 return Promise
.resolve(this.remove(section_id
));
4122 * @memberof LuCI.form
4123 * @augments LuCI.form.DynamicList
4127 * The `MultiValue` class is a modified variant of the `DynamicList` element
4128 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
4129 * select dropdown element.
4131 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4132 * The configuration form this section is added to. It is automatically passed
4133 * by [option()]{@link LuCI.form.AbstractSection#option} or
4134 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4135 * option to the section.
4137 * @param {LuCI.form.AbstractSection} section
4138 * The configuration section this option is added to. It is automatically passed
4139 * by [option()]{@link LuCI.form.AbstractSection#option} or
4140 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4141 * option to the section.
4143 * @param {string} option
4144 * The name of the UCI option to map.
4146 * @param {string} [title]
4147 * The title caption of the option element.
4149 * @param {string} [description]
4150 * The description text of the option element.
4152 var CBIMultiValue
= CBIDynamicList
.extend(/** @lends LuCI.form.MultiValue.prototype */ {
4153 __name__
: 'CBI.MultiValue',
4155 __init__: function() {
4156 this.super('__init__', arguments
);
4157 this.placeholder
= _('-- Please choose --');
4161 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
4162 * property of the underlying dropdown widget. If omitted, the value of
4163 * the `size` property is used or `3` when `size` is unspecified as well.
4165 * @name LuCI.form.MultiValue.prototype#display_size
4171 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
4172 * property of the underlying dropdown widget. If omitted, the value of
4173 * the `size` property is used or `-1` when `size` is unspecified as well.
4175 * @name LuCI.form.MultiValue.prototype#dropdown_size
4181 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4182 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
4183 choices
= this.transformChoices();
4185 var widget
= new ui
.Dropdown(L
.toArray(value
), choices
, {
4186 id
: this.cbid(section_id
),
4189 optional
: this.optional
|| this.rmempty
,
4190 select_placeholder
: this.placeholder
,
4191 display_items
: this.display_size
|| this.size
|| 3,
4192 dropdown_items
: this.dropdown_size
|| this.size
|| -1,
4193 validate
: L
.bind(this.validate
, this, section_id
),
4194 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4197 return widget
.render();
4203 * @memberof LuCI.form
4204 * @augments LuCI.form.Value
4208 * The `TextValue` class implements a multi-line textarea input using
4209 * {@link LuCI.ui.Textarea}.
4211 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4212 * The configuration form this section is added to. It is automatically passed
4213 * by [option()]{@link LuCI.form.AbstractSection#option} or
4214 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4215 * option to the section.
4217 * @param {LuCI.form.AbstractSection} section
4218 * The configuration section this option is added to. It is automatically passed
4219 * by [option()]{@link LuCI.form.AbstractSection#option} or
4220 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4221 * option to the section.
4223 * @param {string} option
4224 * The name of the UCI option to map.
4226 * @param {string} [title]
4227 * The title caption of the option element.
4229 * @param {string} [description]
4230 * The description text of the option element.
4232 var CBITextValue
= CBIValue
.extend(/** @lends LuCI.form.TextValue.prototype */ {
4233 __name__
: 'CBI.TextValue',
4239 * Enforces the use of a monospace font for the textarea contents when set
4242 * @name LuCI.form.TextValue.prototype#monospace
4248 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
4249 * property of the underlying textarea widget.
4251 * @name LuCI.form.TextValue.prototype#cols
4257 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
4258 * property of the underlying textarea widget.
4260 * @name LuCI.form.TextValue.prototype#rows
4266 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
4267 * property of the underlying textarea widget.
4269 * @name LuCI.form.TextValue.prototype#wrap
4275 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4276 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default;
4278 var widget
= new ui
.Textarea(value
, {
4279 id
: this.cbid(section_id
),
4280 optional
: this.optional
|| this.rmempty
,
4281 placeholder
: this.placeholder
,
4282 monospace
: this.monospace
,
4286 validate
: L
.bind(this.validate
, this, section_id
),
4287 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4290 return widget
.render();
4296 * @memberof LuCI.form
4297 * @augments LuCI.form.Value
4301 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4302 * renders the underlying UCI option or default value as readonly text.
4304 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4305 * The configuration form this section is added to. It is automatically passed
4306 * by [option()]{@link LuCI.form.AbstractSection#option} or
4307 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4308 * option to the section.
4310 * @param {LuCI.form.AbstractSection} section
4311 * The configuration section this option is added to. It is automatically passed
4312 * by [option()]{@link LuCI.form.AbstractSection#option} or
4313 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4314 * option to the section.
4316 * @param {string} option
4317 * The name of the UCI option to map.
4319 * @param {string} [title]
4320 * The title caption of the option element.
4322 * @param {string} [description]
4323 * The description text of the option element.
4325 var CBIDummyValue
= CBIValue
.extend(/** @lends LuCI.form.DummyValue.prototype */ {
4326 __name__
: 'CBI.DummyValue',
4329 * Set a URL which is opened when clicking on the dummy value text.
4331 * By setting this property, the dummy value text is wrapped in an `<a>`
4332 * element with the property value used as `href` attribute.
4334 * @name LuCI.form.DummyValue.prototype#href
4340 * Treat the UCI option value (or the `default` property value) as HTML.
4342 * By default, the value text is HTML escaped before being rendered as
4343 * text. In some cases it may be needed to actually interpret and render
4344 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
4346 * @name LuCI.form.DummyValue.prototype#rawhtml
4352 * Render the UCI option value as hidden using the HTML display: none style property.
4354 * By default, the value is displayed
4356 * @name LuCI.form.DummyValue.prototype#hidden
4362 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4363 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
4364 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
4365 outputEl
= E('div', { 'style': this.hidden
? 'display:none' : null });
4367 if (this.href
&& !((this.readonly
!= null) ? this.readonly
: this.map
.readonly
))
4368 outputEl
.appendChild(E('a', { 'href': this.href
}));
4370 dom
.append(outputEl
.lastChild
|| outputEl
,
4371 this.rawhtml
? value
: [ value
]);
4380 remove: function() {},
4383 write: function() {}
4387 * @class ButtonValue
4388 * @memberof LuCI.form
4389 * @augments LuCI.form.Value
4393 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4394 * renders the underlying UCI option or default value as readonly text.
4396 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4397 * The configuration form this section is added to. It is automatically passed
4398 * by [option()]{@link LuCI.form.AbstractSection#option} or
4399 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4400 * option to the section.
4402 * @param {LuCI.form.AbstractSection} section
4403 * The configuration section this option is added to. It is automatically passed
4404 * by [option()]{@link LuCI.form.AbstractSection#option} or
4405 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4406 * option to the section.
4408 * @param {string} option
4409 * The name of the UCI option to map.
4411 * @param {string} [title]
4412 * The title caption of the option element.
4414 * @param {string} [description]
4415 * The description text of the option element.
4417 var CBIButtonValue
= CBIValue
.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
4418 __name__
: 'CBI.ButtonValue',
4421 * Override the rendered button caption.
4423 * By default, the option title - which is passed as fourth argument to the
4424 * constructor - is used as caption for the button element. When setting
4425 * this property to a string, it is used as `String.format()` pattern with
4426 * the underlying UCI section name passed as first format argument. When
4427 * set to a function, it is invoked passing the section ID as sole argument
4428 * and the resulting return value is converted to a string before being
4429 * used as button caption.
4431 * The default is `null`, means the option title is used as caption.
4433 * @name LuCI.form.ButtonValue.prototype#inputtitle
4434 * @type string|function
4439 * Override the button style class.
4441 * By setting this property, a specific `cbi-button-*` CSS class can be
4442 * selected to influence the style of the resulting button.
4444 * Suitable values which are implemented by most themes are `positive`,
4445 * `negative` and `primary`.
4447 * The default is `null`, means a neutral button styling is used.
4449 * @name LuCI.form.ButtonValue.prototype#inputstyle
4455 * Override the button click action.
4457 * By default, the underlying UCI option (or default property) value is
4458 * copied into a hidden field tied to the button element and the save
4459 * action is triggered on the parent form element.
4461 * When this property is set to a function, it is invoked instead of
4462 * performing the default actions. The handler function will receive the
4463 * DOM click element as first and the underlying configuration section ID
4464 * as second argument.
4466 * @name LuCI.form.ButtonValue.prototype#onclick
4472 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4473 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
4474 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
4475 outputEl
= E('div'),
4476 btn_title
= this.titleFn('inputtitle', section_id
) || this.titleFn('title', section_id
);
4478 if (value
!== false)
4479 dom
.content(outputEl
, [
4481 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle
|| 'button'),
4482 'click': ui
.createHandlerFn(this, function(section_id
, ev
) {
4484 return this.onclick(ev
, section_id
);
4486 ev
.currentTarget
.parentNode
.nextElementSibling
.value
= value
;
4487 return this.map
.save();
4489 'disabled': ((this.readonly
!= null) ? this.readonly
: this.map
.readonly
) || null
4493 dom
.content(outputEl
, ' - ');
4503 * @class HiddenValue
4504 * @memberof LuCI.form
4505 * @augments LuCI.form.Value
4509 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
4511 * Hidden value widgets used to be necessary in legacy code which actually
4512 * submitted the underlying HTML form the server. With client side handling of
4513 * forms, there are more efficient ways to store hidden state data.
4515 * Since this widget has no visible content, the title and description values
4516 * of this form element should be set to `null` as well to avoid a broken or
4517 * distorted form layout when rendering the option element.
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 CBIHiddenValue
= CBIValue
.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
4541 __name__
: 'CBI.HiddenValue',
4544 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4545 var widget
= new ui
.Hiddenfield((cfgvalue
!= null) ? cfgvalue
: this.default, {
4546 id
: this.cbid(section_id
)
4549 return widget
.render();
4555 * @memberof LuCI.form
4556 * @augments LuCI.form.Value
4560 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
4561 * offers the ability to browse, upload and select remote files.
4563 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4564 * The configuration form this section is added to. It is automatically passed
4565 * by [option()]{@link LuCI.form.AbstractSection#option} or
4566 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4567 * option to the section.
4569 * @param {LuCI.form.AbstractSection} section
4570 * The configuration section this option is added to. It is automatically passed
4571 * by [option()]{@link LuCI.form.AbstractSection#option} or
4572 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4573 * option to the section.
4575 * @param {string} option
4576 * The name of the UCI option to map.
4578 * @param {string} [title]
4579 * The title caption of the option element.
4581 * @param {string} [description]
4582 * The description text of the option element.
4584 var CBIFileUpload
= CBIValue
.extend(/** @lends LuCI.form.FileUpload.prototype */ {
4585 __name__
: 'CBI.FileSelect',
4587 __init__: function(/* ... */) {
4588 this.super('__init__', arguments
);
4590 this.show_hidden
= false;
4591 this.enable_upload
= true;
4592 this.enable_remove
= true;
4593 this.root_directory
= '/etc/luci-uploads';
4597 * Toggle display of hidden files.
4599 * Display hidden files when rendering the remote directory listing.
4600 * Note that this is merely a cosmetic feature, hidden files are always
4601 * included in received remote file listings.
4603 * The default is `false`, means hidden files are not displayed.
4605 * @name LuCI.form.FileUpload.prototype#show_hidden
4611 * Toggle file upload functionality.
4613 * When set to `true`, the underlying widget provides a button which lets
4614 * the user select and upload local files to the remote system.
4615 * Note that this is merely a cosmetic feature, remote upload access is
4616 * controlled by the session ACL rules.
4618 * The default is `true`, means file upload functionality is displayed.
4620 * @name LuCI.form.FileUpload.prototype#enable_upload
4626 * Toggle remote file delete functionality.
4628 * When set to `true`, the underlying widget provides a buttons which let
4629 * the user delete files from remote directories. Note that this is merely
4630 * a cosmetic feature, remote delete permissions are controlled by the
4631 * session ACL rules.
4633 * The default is `true`, means file removal buttons are displayed.
4635 * @name LuCI.form.FileUpload.prototype#enable_remove
4641 * Specify the root directory for file browsing.
4643 * This property defines the topmost directory the file browser widget may
4644 * navigate to, the UI will not allow browsing directories outside this
4645 * prefix. Note that this is merely a cosmetic feature, remote file access
4646 * and directory listing permissions are controlled by the session ACL
4649 * The default is `/etc/luci-uploads`.
4651 * @name LuCI.form.FileUpload.prototype#root_directory
4653 * @default /etc/luci-uploads
4657 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4658 var browserEl
= new ui
.FileUpload((cfgvalue
!= null) ? cfgvalue
: this.default, {
4659 id
: this.cbid(section_id
),
4660 name
: this.cbid(section_id
),
4661 show_hidden
: this.show_hidden
,
4662 enable_upload
: this.enable_upload
,
4663 enable_remove
: this.enable_remove
,
4664 root_directory
: this.root_directory
,
4665 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4668 return browserEl
.render();
4673 * @class SectionValue
4674 * @memberof LuCI.form
4675 * @augments LuCI.form.Value
4679 * The `SectionValue` widget embeds a form section element within an option
4680 * element container, allowing to nest form sections into other sections.
4682 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4683 * The configuration form this section is added to. It is automatically passed
4684 * by [option()]{@link LuCI.form.AbstractSection#option} or
4685 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4686 * option to the section.
4688 * @param {LuCI.form.AbstractSection} section
4689 * The configuration section this option is added to. It is automatically passed
4690 * by [option()]{@link LuCI.form.AbstractSection#option} or
4691 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4692 * option to the section.
4694 * @param {string} option
4695 * The internal name of the option element holding the section. Since a section
4696 * container element does not read or write any configuration itself, the name
4697 * is only used internally and does not need to relate to any underlying UCI
4700 * @param {LuCI.form.AbstractSection} subsection_class
4701 * The class to use for instantiating the nested section element. Note that
4702 * the class value itself is expected here, not a class instance obtained by
4703 * calling `new`. The given class argument must be a subclass of the
4704 * `AbstractSection` class.
4706 * @param {...*} [class_args]
4707 * All further arguments are passed as-is to the subclass constructor. Refer
4708 * to the corresponding class constructor documentations for details.
4710 var CBISectionValue
= CBIValue
.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4711 __name__
: 'CBI.ContainerValue',
4712 __init__: function(map
, section
, option
, cbiClass
/*, ... */) {
4713 this.super('__init__', [map
, section
, option
]);
4715 if (!CBIAbstractSection
.isSubclass(cbiClass
))
4716 throw 'Sub section must be a descendent of CBIAbstractSection';
4718 this.subsection
= cbiClass
.instantiate(this.varargs(arguments
, 4, this.map
));
4719 this.subsection
.parentoption
= this;
4723 * Access the embedded section instance.
4725 * This property holds a reference to the instantiated nested section.
4727 * @name LuCI.form.SectionValue.prototype#subsection
4728 * @type LuCI.form.AbstractSection
4733 load: function(section_id
) {
4734 return this.subsection
.load(section_id
);
4738 parse: function(section_id
) {
4739 return this.subsection
.parse(section_id
);
4743 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4744 return this.subsection
.render(section_id
);
4748 checkDepends: function(section_id
) {
4749 this.subsection
.checkDepends(section_id
);
4750 return CBIValue
.prototype.checkDepends
.apply(this, [ section_id
]);
4754 * Since the section container is not rendering an own widget,
4755 * its `value()` implementation is a no-op.
4759 value: function() {},
4762 * Since the section container is not tied to any UCI configuration,
4763 * its `write()` implementation is a no-op.
4767 write: function() {},
4770 * Since the section container is not tied to any UCI configuration,
4771 * its `remove()` implementation is a no-op.
4775 remove: function() {},
4778 * Since the section container is not tied to any UCI configuration,
4779 * its `cfgvalue()` implementation will always return `null`.
4784 cfgvalue: function() { return null },
4787 * Since the section container is not tied to any UCI configuration,
4788 * its `formvalue()` implementation will always return `null`.
4793 formvalue: function() { return null }
4802 * The LuCI form class provides high level abstractions for creating creating
4803 * UCI- or JSON backed configurations forms.
4805 * To import the class in views, use `'require form'`, to import it in
4806 * external JavaScript, use `L.require("form").then(...)`.
4808 * A typical form is created by first constructing a
4809 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4810 * by subsequently adding sections and options to it. Finally
4811 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4812 * assemble the HTML markup and insert it into the DOM.
4822 * m = new form.Map('example', 'Example form',
4823 * 'This is an example form mapping the contents of /etc/config/example');
4825 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4826 * 'This sections maps "config example first_section" of /etc/config/example');
4828 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4830 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4831 * o.value('choice1', 'The first choice');
4832 * o.value('choice2', 'The second choice');
4834 * m.render().then(function(node) {
4835 * document.body.appendChild(node);
4839 return baseclass
.extend(/** @lends LuCI.form.prototype */ {
4841 JSONMap
: CBIJSONMap
,
4842 AbstractSection
: CBIAbstractSection
,
4843 AbstractValue
: CBIAbstractValue
,
4845 TypedSection
: CBITypedSection
,
4846 TableSection
: CBITableSection
,
4847 GridSection
: CBIGridSection
,
4848 NamedSection
: CBINamedSection
,
4851 DynamicList
: CBIDynamicList
,
4852 ListValue
: CBIListValue
,
4854 MultiValue
: CBIMultiValue
,
4855 TextValue
: CBITextValue
,
4856 DummyValue
: CBIDummyValue
,
4857 Button
: CBIButtonValue
,
4858 HiddenValue
: CBIHiddenValue
,
4859 FileUpload
: CBIFileUpload
,
4860 SectionValue
: CBISectionValue