6786d3d2345e87fb73c41e689f4123ed0f0ba66f
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
);
80 for (var i
= 0; i
< section_ids
.length
; i
++)
81 this.data
[section_ids
[i
]]['.index'] = i
;
85 return Promise
.resolve(this.data
);
89 return Promise
.resolve();
92 get: function(config
, section
, option
) {
97 return this.data
[section
];
99 if (!this.data
.hasOwnProperty(section
))
102 var value
= this.data
[section
][option
];
104 if (Array
.isArray(value
))
108 return String(value
);
113 set: function(config
, section
, option
, value
) {
114 if (section
== null || option
== null || option
.charAt(0) == '.')
117 if (!this.data
.hasOwnProperty(section
))
121 delete this.data
[section
][option
];
122 else if (Array
.isArray(value
))
123 this.data
[section
][option
] = value
;
125 this.data
[section
][option
] = String(value
);
128 unset: function(config
, section
, option
) {
129 return this.set(config
, section
, option
, null);
132 sections: function(config
, sectiontype
, callback
) {
135 for (var section_id
in this.data
)
136 if (sectiontype
== null || this.data
[section_id
]['.type'] == sectiontype
)
137 rv
.push(this.data
[section_id
]);
139 rv
.sort(function(a
, b
) { return a
['.index'] - b
['.index'] });
141 if (typeof(callback
) == 'function')
142 for (var i
= 0; i
< rv
.length
; i
++)
143 callback
.call(this, rv
[i
], rv
[i
]['.name']);
148 add: function(config
, sectiontype
, sectionname
) {
149 var num_sections_type
= 0, next_index
= 0;
151 for (var name
in this.data
) {
152 num_sections_type
+= (this.data
[name
]['.type'] == sectiontype
);
153 next_index
= Math
.max(next_index
, this.data
[name
]['.index']);
156 var section_id
= sectionname
|| sectiontype
+ num_sections_type
;
158 if (!this.data
.hasOwnProperty(section_id
)) {
159 this.data
[section_id
] = {
161 '.type': sectiontype
,
162 '.anonymous': (sectionname
== null),
163 '.index': next_index
+ 1
170 remove: function(config
, section
) {
171 if (this.data
.hasOwnProperty(section
))
172 delete this.data
[section
];
175 resolveSID: function(config
, section_id
) {
179 move: function(config
, section_id1
, section_id2
, after
) {
180 return uci
.move.apply(this, [config
, section_id1
, section_id2
, after
]);
185 * @class AbstractElement
186 * @memberof LuCI.form
190 * The `AbstractElement` class serves as abstract base for the different form
191 * elements implemented by `LuCI.form`. It provides the common logic for
192 * loading and rendering values, for nesting elements and for defining common
195 * This class is private and not directly accessible by user code.
197 var CBIAbstractElement
= baseclass
.extend(/** @lends LuCI.form.AbstractElement.prototype */ {
198 __init__: function(title
, description
) {
199 this.title
= title
|| '';
200 this.description
= description
|| '';
205 * Add another form element as children to this element.
207 * @param {AbstractElement} element
208 * The form element to add.
210 append: function(obj
) {
211 this.children
.push(obj
);
215 * Parse this elements form input.
217 * The `parse()` function recursively walks the form element tree and
218 * triggers input value reading and validation for each encountered element.
220 * Elements which are hidden due to unsatisified dependencies are skipped.
222 * @returns {Promise<void>}
223 * Returns a promise resolving once this element's value and the values of
224 * all child elements have been parsed. The returned promise is rejected
225 * if any parsed values are not meeting the validation constraints of their
226 * respective elements.
229 var args
= arguments
;
230 this.children
.forEach(function(child
) {
231 child
.parse
.apply(child
, args
);
236 * Render the form element.
238 * The `render()` function recursively walks the form element tree and
239 * renders the markup for each element, returning the assembled DOM tree.
242 * @returns {Node|Promise<Node>}
243 * May return a DOM Node or a promise resolving to a DOM node containing
244 * the form element's markup, including the markup of any child elements.
247 L
.error('InternalError', 'Not implemented');
251 loadChildren: function(/* ... */) {
254 if (Array
.isArray(this.children
))
255 for (var i
= 0; i
< this.children
.length
; i
++)
256 if (!this.children
[i
].disable
)
257 tasks
.push(this.children
[i
].load
.apply(this.children
[i
], arguments
));
259 return Promise
.all(tasks
);
263 renderChildren: function(tab_name
/*, ... */) {
267 if (Array
.isArray(this.children
))
268 for (var i
= 0; i
< this.children
.length
; i
++)
269 if (tab_name
=== null || this.children
[i
].tab
=== tab_name
)
270 if (!this.children
[i
].disable
)
271 tasks
.push(this.children
[i
].render
.apply(
272 this.children
[i
], this.varargs(arguments
, 1, index
++)));
274 return Promise
.all(tasks
);
278 * Strip any HTML tags from the given input string.
280 * @param {string} input
281 * The input string to clean.
284 * The cleaned input string with HTML removes removed.
286 stripTags: function(s
) {
287 if (typeof(s
) == 'string' && !s
.match(/[<>]/))
290 var x
= dom
.parse('<div>' + s
+ '</div>');
292 return x
.textContent
|| x
.innerText
|| '';
296 * Format the given named property as title string.
298 * This function looks up the given named property and formats its value
299 * suitable for use as element caption or description string. It also
300 * strips any HTML tags from the result.
302 * If the property value is a string, it is passed to `String.format()`
303 * along with any additional parameters passed to `titleFn()`.
305 * If the property value is a function, it is invoked with any additional
306 * `titleFn()` parameters as arguments and the obtained return value is
307 * converted to a string.
309 * In all other cases, `null` is returned.
311 * @param {string} property
312 * The name of the element property to use.
314 * @param {...*} fmt_args
315 * Extra values to format the title string with.
317 * @returns {string|null}
318 * The formatted title string or `null` if the property did not exist or
319 * was neither a string nor a function.
321 titleFn: function(attr
/*, ... */) {
324 if (typeof(this[attr
]) == 'function')
325 s
= this[attr
].apply(this, this.varargs(arguments
, 1));
326 else if (typeof(this[attr
]) == 'string')
327 s
= (arguments
.length
> 1) ? ''.format
.apply(this[attr
], this.varargs(arguments
, 1)) : this[attr
];
330 s
= this.stripTags(String(s
)).trim();
332 if (s
== null || s
== '')
341 * @memberof LuCI.form
342 * @augments LuCI.form.AbstractElement
346 * The `Map` class represents one complete form. A form usually maps one UCI
347 * configuraton file and is divided into multiple sections containing multiple
350 * It serves as main entry point into the `LuCI.form` for typical view code.
352 * @param {string} config
353 * The UCI configuration to map. It is automatically loaded along when the
354 * resulting map instance.
356 * @param {string} [title]
357 * The title caption of the form. A form title is usually rendered as separate
358 * headline element before the actual form contents. If omitted, the
359 * corresponding headline element will not be rendered.
361 * @param {string} [description]
362 * The description text of the form which is usually rendered as text
363 * paragraph below the form title and before the actual form conents.
364 * If omitted, the corresponding paragraph element will not be rendered.
366 var CBIMap
= CBIAbstractElement
.extend(/** @lends LuCI.form.Map.prototype */ {
367 __init__: function(config
/*, ... */) {
368 this.super('__init__', this.varargs(arguments
, 1));
370 this.config
= config
;
371 this.parsechain
= [ config
];
376 * Toggle readonly state of the form.
378 * If set to `true`, the Map instance is marked readonly and any form
379 * option elements added to it will inherit the readonly state.
381 * If left unset, the Map will test the access permission of the primary
382 * uci configuration upon loading and mark the form readonly if no write
383 * permissions are granted.
385 * @name LuCI.form.Map.prototype#readonly
390 * Find all DOM nodes within this Map which match the given search
391 * parameters. This function is essentially a convenience wrapper around
392 * `querySelectorAll()`.
394 * This function is sensitive to the amount of arguments passed to it;
395 * if only one argument is specified, it is used as selector-expression
396 * as-is. When two arguments are passed, the first argument is treated
397 * as attribute name, the second one as attribute value to match.
399 * As an example, `map.findElements('input')` would find all `<input>`
400 * nodes while `map.findElements('type', 'text')` would find any DOM node
401 * with a `type="text"` attribute.
403 * @param {string} selector_or_attrname
404 * If invoked with only one parameter, this argument is a
405 * `querySelectorAll()` compatible selector expression. If invoked with
406 * two parameters, this argument is the attribute name to filter for.
408 * @param {string} [attrvalue]
409 * In case the function is invoked with two parameters, this argument
410 * specifies the attribute value to match.
412 * @throws {InternalError}
413 * Throws an `InternalError` if more than two function parameters are
416 * @returns {NodeList}
417 * Returns a (possibly empty) DOM `NodeList` containing the found DOM nodes.
419 findElements: function(/* ... */) {
422 if (arguments
.length
== 1)
424 else if (arguments
.length
== 2)
425 q
= '[%s="%s"]'.format(arguments
[0], arguments
[1]);
427 L
.error('InternalError', 'Expecting one or two arguments to findElements()');
429 return this.root
.querySelectorAll(q
);
433 * Find the first DOM node within this Map which matches the given search
434 * parameters. This function is essentially a convenience wrapper around
435 * `findElements()` which only returns the first found node.
437 * This function is sensitive to the amount of arguments passed to it;
438 * if only one argument is specified, it is used as selector-expression
439 * as-is. When two arguments are passed, the first argument is treated
440 * as attribute name, the second one as attribute value to match.
442 * As an example, `map.findElement('input')` would find the first `<input>`
443 * node while `map.findElement('type', 'text')` would find the first DOM
444 * node with a `type="text"` attribute.
446 * @param {string} selector_or_attrname
447 * If invoked with only one parameter, this argument is a `querySelector()`
448 * compatible selector expression. If invoked with two parameters, this
449 * argument is the attribute name to filter for.
451 * @param {string} [attrvalue]
452 * In case the function is invoked with two parameters, this argument
453 * specifies the attribute value to match.
455 * @throws {InternalError}
456 * Throws an `InternalError` if more than two function parameters are
459 * @returns {Node|null}
460 * Returns the first found DOM node or `null` if no element matched.
462 findElement: function(/* ... */) {
463 var res
= this.findElements
.apply(this, arguments
);
464 return res
.length
? res
[0] : null;
468 * Tie another UCI configuration to the map.
470 * By default, a map instance will only load the UCI configuration file
471 * specified in the constructor but sometimes access to values from
472 * further configuration files is required. This function allows for such
473 * use cases by registering further UCI configuration files which are
476 * @param {string} config
477 * The additional UCI configuration file to tie to the map. If the given
478 * config already is in the list of required files, it will be ignored.
480 chain: function(config
) {
481 if (this.parsechain
.indexOf(config
) == -1)
482 this.parsechain
.push(config
);
486 * Add a configuration section to the map.
488 * LuCI forms follow the structure of the underlying UCI configurations,
489 * means that a map, which represents a single UCI configuration, is
490 * divided into multiple sections which in turn contain an arbitrary
493 * While UCI itself only knows two kinds of sections - named and anonymous
494 * ones - the form class offers various flavors of form section elements
495 * to present configuration sections in different ways. Refer to the
496 * documentation of the different section classes for details.
498 * @param {LuCI.form.AbstractSection} sectionclass
499 * The section class to use for rendering the configuration section.
500 * Note that this value must be the class itself, not a class instance
501 * obtained from calling `new`. It must also be a class dervied from
502 * `LuCI.form.AbstractSection`.
504 * @param {...string} classargs
505 * Additional arguments which are passed as-is to the contructor of the
506 * given section class. Refer to the class specific constructor
507 * documentation for details.
509 * @returns {LuCI.form.AbstractSection}
510 * Returns the instantiated section class instance.
512 section: function(cbiClass
/*, ... */) {
513 if (!CBIAbstractSection
.isSubclass(cbiClass
))
514 L
.error('TypeError', 'Class must be a descendent of CBIAbstractSection');
516 var obj
= cbiClass
.instantiate(this.varargs(arguments
, 1, this));
522 * Load the configuration covered by this map.
524 * The `load()` function first loads all referenced UCI configurations,
525 * then it recursively walks the form element tree and invokes the
526 * load function of each child element.
528 * @returns {Promise<void>}
529 * Returns a promise resolving once the entire form completed loading all
530 * data. The promise may reject with an error if any configuration failed
531 * to load or if any of the child elements load functions rejected with
535 var doCheckACL
= (!(this instanceof CBIJSONMap
) && this.readonly
== null),
536 loadTasks
= [ doCheckACL
? callSessionAccess('uci', this.config
, 'write') : true ],
537 configs
= this.parsechain
|| [ this.config
];
539 loadTasks
.push
.apply(loadTasks
, configs
.map(L
.bind(function(config
, i
) {
540 return i
? L
.resolveDefault(this.data
.load(config
)) : this.data
.load(config
);
543 return Promise
.all(loadTasks
).then(L
.bind(function(res
) {
544 if (res
[0] === false)
545 this.readonly
= true;
547 return this.loadChildren();
552 * Parse the form input values.
554 * The `parse()` function recursively walks the form element tree and
555 * triggers input value reading and validation for each child element.
557 * Elements which are hidden due to unsatisified dependencies are skipped.
559 * @returns {Promise<void>}
560 * Returns a promise resolving once the entire form completed parsing all
561 * input values. The returned promise is rejected if any parsed values are
562 * not meeting the validation constraints of their respective elements.
567 if (Array
.isArray(this.children
))
568 for (var i
= 0; i
< this.children
.length
; i
++)
569 tasks
.push(this.children
[i
].parse());
571 return Promise
.all(tasks
);
575 * Save the form input values.
577 * This function parses the current form, saves the resulting UCI changes,
578 * reloads the UCI configuration data and redraws the form elements.
580 * @param {function} [cb]
581 * An optional callback function that is invoked after the form is parsed
582 * but before the changed UCI data is saved. This is useful to perform
583 * additional data manipulation steps before saving the changes.
585 * @param {boolean} [silent=false]
586 * If set to `true`, trigger an alert message to the user in case saving
587 * the form data failes. Otherwise fail silently.
589 * @returns {Promise<void>}
590 * Returns a promise resolving once the entire save operation is complete.
591 * The returned promise is rejected if any step of the save operation
594 save: function(cb
, silent
) {
599 .then(this.data
.save
.bind(this.data
))
600 .then(this.load
.bind(this))
603 ui
.showModal(_('Save error'), [
604 E('p', {}, [ _('An error occurred while saving the form:') ]),
605 E('p', {}, [ E('em', { 'style': 'white-space:pre-wrap' }, [ e
.message
]) ]),
606 E('div', { 'class': 'right' }, [
607 E('button', { 'class': 'cbi-button', 'click': ui
.hideModal
}, [ _('Dismiss') ])
612 return Promise
.reject(e
);
613 }).then(this.renderContents
.bind(this));
617 * Reset the form by re-rendering its contents. This will revert all
618 * unsaved user inputs to their initial form state.
620 * @returns {Promise<Node>}
621 * Returns a promise resolving to the toplevel form DOM node once the
622 * re-rendering is complete.
625 return this.renderContents();
629 * Render the form markup.
631 * @returns {Promise<Node>}
632 * Returns a promise resolving to the toplevel form DOM node once the
633 * rendering is complete.
636 return this.load().then(this.renderContents
.bind(this));
640 renderContents: function() {
641 var mapEl
= this.root
|| (this.root
= E('div', {
642 'id': 'cbi-%s'.format(this.config
),
644 'cbi-dependency-check': L
.bind(this.checkDepends
, this)
647 dom
.bindClassInstance(mapEl
, this);
649 return this.renderChildren(null).then(L
.bind(function(nodes
) {
650 var initialRender
= !mapEl
.firstChild
;
652 dom
.content(mapEl
, null);
654 if (this.title
!= null && this.title
!= '')
655 mapEl
.appendChild(E('h2', { 'name': 'content' }, this.title
));
657 if (this.description
!= null && this.description
!= '')
658 mapEl
.appendChild(E('div', { 'class': 'cbi-map-descr' }, this.description
));
661 dom
.append(mapEl
, E('div', { 'class': 'cbi-map-tabbed' }, nodes
));
663 dom
.append(mapEl
, nodes
);
665 if (!initialRender
) {
666 mapEl
.classList
.remove('flash');
668 window
.setTimeout(function() {
669 mapEl
.classList
.add('flash');
675 var tabGroups
= mapEl
.querySelectorAll('.cbi-map-tabbed, .cbi-section-node-tabbed');
677 for (var i
= 0; i
< tabGroups
.length
; i
++)
678 ui
.tabs
.initTabGroup(tabGroups
[i
].childNodes
);
685 * Find a form option element instance.
687 * @param {string} name_or_id
688 * The name or the full ID of the option element to look up.
690 * @param {string} [section_id]
691 * The ID of the UCI section containing the option to look up. May be
692 * omitted if a full ID is passed as first argument.
694 * @param {string} [config]
695 * The name of the UCI configuration the option instance is belonging to.
696 * Defaults to the main UCI configuration of the map if omitted.
698 * @returns {Array<LuCI.form.AbstractValue,string>|null}
699 * Returns a two-element array containing the form option instance as
700 * first item and the corresponding UCI section ID as second item.
701 * Returns `null` if the option could not be found.
703 lookupOption: function(name
, section_id
, config_name
) {
704 var id
, elem
, sid
, inst
;
706 if (name
.indexOf('.') > -1)
707 id
= 'cbid.%s'.format(name
);
709 id
= 'cbid.%s.%s.%s'.format(config_name
|| this.config
, section_id
, name
);
711 elem
= this.findElement('data-field', id
);
712 sid
= elem
? id
.split(/\./)[2] : null;
713 inst
= elem
? dom
.findClassInstance(elem
) : null;
715 return (inst
instanceof CBIAbstractValue
) ? [ inst
, sid
] : null;
719 checkDepends: function(ev
, n
) {
722 for (var i
= 0, s
= this.children
[0]; (s
= this.children
[i
]) != null; i
++)
723 if (s
.checkDepends(ev
, n
))
726 if (changed
&& (n
|| 0) < 10)
727 this.checkDepends(ev
, (n
|| 10) + 1);
729 ui
.tabs
.updateTabs(ev
, this.root
);
733 isDependencySatisfied: function(depends
, config_name
, section_id
) {
736 if (!Array
.isArray(depends
) || !depends
.length
)
739 for (var i
= 0; i
< depends
.length
; i
++) {
741 reverse
= depends
[i
]['!reverse'],
742 contains
= depends
[i
]['!contains'];
744 for (var dep
in depends
[i
]) {
745 if (dep
== '!reverse' || dep
== '!contains') {
748 else if (dep
== '!default') {
753 var res
= this.lookupOption(dep
, section_id
, config_name
),
754 val
= (res
&& res
[0].isActive(res
[1])) ? res
[0].formvalue(res
[1]) : null;
757 ? isContained(val
, depends
[i
][dep
])
758 : isEqual(val
, depends
[i
][dep
]);
760 istat
= (istat
&& equal
);
773 * @constructor JSONMap
774 * @memberof LuCI.form
775 * @augments LuCI.form.Map
779 * A `JSONMap` class functions similar to [LuCI.form.Map]{@link LuCI.form.Map}
780 * but uses a multidimensional JavaScript object instead of UCI configuration
783 * @param {Object<string, Object<string, *>|Array<Object<string, *>>>} data
784 * The JavaScript object to use as data source. Internally, the object is
785 * converted into an UCI-like format. Its toplevel keys are treated like UCI
786 * section types while the object or array-of-object values are treated as
789 * @param {string} [title]
790 * The title caption of the form. A form title is usually rendered as separate
791 * headline element before the actual form contents. If omitted, the
792 * corresponding headline element will not be rendered.
794 * @param {string} [description]
795 * The description text of the form which is usually rendered as text
796 * paragraph below the form title and before the actual form conents.
797 * If omitted, the corresponding paragraph element will not be rendered.
799 var CBIJSONMap
= CBIMap
.extend(/** @lends LuCI.form.JSONMap.prototype */ {
800 __init__: function(data
/*, ... */) {
801 this.super('__init__', this.varargs(arguments
, 1, 'json'));
803 this.config
= 'json';
804 this.parsechain
= [ 'json' ];
805 this.data
= new CBIJSONConfig(data
);
810 * @class AbstractSection
811 * @memberof LuCI.form
812 * @augments LuCI.form.AbstractElement
816 * The `AbstractSection` class serves as abstract base for the different form
817 * section styles implemented by `LuCI.form`. It provides the common logic for
818 * enumerating underlying configuration section instances, for registering
819 * form options and for handling tabs to segment child options.
821 * This class is private and not directly accessible by user code.
823 var CBIAbstractSection
= CBIAbstractElement
.extend(/** @lends LuCI.form.AbstractSection.prototype */ {
824 __init__: function(map
, sectionType
/*, ... */) {
825 this.super('__init__', this.varargs(arguments
, 2));
827 this.sectiontype
= sectionType
;
829 this.config
= map
.config
;
831 this.optional
= true;
832 this.addremove
= false;
833 this.dynamic
= false;
837 * Access the parent option container instance.
839 * In case this section is nested within an option element container,
840 * this property will hold a reference to the parent option instance.
842 * If this section is not nested, the property is `null`.
844 * @name LuCI.form.AbstractSection.prototype#parentoption
845 * @type LuCI.form.AbstractValue
850 * Enumerate the UCI section IDs covered by this form section element.
853 * @throws {InternalError}
854 * Throws an `InternalError` exception if the function is not implemented.
856 * @returns {string[]}
857 * Returns an array of UCI section IDs covered by this form element.
858 * The sections will be rendered in the same order as the returned array.
860 cfgsections: function() {
861 L
.error('InternalError', 'Not implemented');
865 * Filter UCI section IDs to render.
867 * The filter function is invoked for each UCI section ID of a given type
868 * and controls whether the given UCI section is rendered or ignored by
869 * the form section element.
871 * The default implementation always returns `true`. User code or
872 * classes extending `AbstractSection` may overwrite this function with
873 * custom implementations.
876 * @param {string} section_id
877 * The UCI section ID to test.
880 * Returns `true` when the given UCI section ID should be handled and
881 * `false` when it should be ignored.
883 filter: function(section_id
) {
888 * Load the configuration covered by this section.
890 * The `load()` function recursively walks the section element tree and
891 * invokes the load function of each child option element.
893 * @returns {Promise<void>}
894 * Returns a promise resolving once the values of all child elements have
895 * been loaded. The promise may reject with an error if any of the child
896 * elements load functions rejected with an error.
899 var section_ids
= this.cfgsections(),
902 if (Array
.isArray(this.children
))
903 for (var i
= 0; i
< section_ids
.length
; i
++)
904 tasks
.push(this.loadChildren(section_ids
[i
])
905 .then(Function
.prototype.bind
.call(function(section_id
, set_values
) {
906 for (var i
= 0; i
< set_values
.length
; i
++)
907 this.children
[i
].cfgvalue(section_id
, set_values
[i
]);
908 }, this, section_ids
[i
])));
910 return Promise
.all(tasks
);
914 * Parse this sections form input.
916 * The `parse()` function recursively walks the section element tree and
917 * triggers input value reading and validation for each encountered child
920 * Options which are hidden due to unsatisified dependencies are skipped.
922 * @returns {Promise<void>}
923 * Returns a promise resolving once the values of all child elements have
924 * been parsed. The returned promise is rejected if any parsed values are
925 * not meeting the validation constraints of their respective elements.
928 var section_ids
= this.cfgsections(),
931 if (Array
.isArray(this.children
))
932 for (var i
= 0; i
< section_ids
.length
; i
++)
933 for (var j
= 0; j
< this.children
.length
; j
++)
934 tasks
.push(this.children
[j
].parse(section_ids
[i
]));
936 return Promise
.all(tasks
);
940 * Add an option tab to the section.
942 * The child option elements of a section may be divided into multiple
943 * tabs to provide a better overview to the user.
945 * Before options can be moved into a tab pane, the corresponding tab
946 * has to be defined first, which is done by calling this function.
948 * Note that once tabs are defined, user code must use the `taboption()`
949 * method to add options to specific tabs. Option elements added by
950 * `option()` will not be assigned to any tab and not be rendered in this
953 * @param {string} name
954 * The name of the tab to register. It may be freely chosen and just serves
955 * as an identifier to differentiate tabs.
957 * @param {string} title
958 * The human readable caption of the tab.
960 * @param {string} [description]
961 * An additional description text for the corresponding tab pane. It is
962 * displayed as text paragraph below the tab but before the tab pane
963 * contents. If omitted, no description will be rendered.
966 * Throws an exeption if a tab with the same `name` already exists.
968 tab: function(name
, title
, description
) {
969 if (this.tabs
&& this.tabs
[name
])
970 throw 'Tab already declared';
975 description
: description
,
979 this.tabs
= this.tabs
|| [];
980 this.tabs
.push(entry
);
981 this.tabs
[name
] = entry
;
983 this.tab_names
= this.tab_names
|| [];
984 this.tab_names
.push(name
);
988 * Add a configuration option widget to the section.
990 * Note that [taboption()]{@link LuCI.form.AbstractSection#taboption}
991 * should be used instead if this form section element uses tabs.
993 * @param {LuCI.form.AbstractValue} optionclass
994 * The option class to use for rendering the configuration option. Note
995 * that this value must be the class itself, not a class instance obtained
996 * from calling `new`. It must also be a class dervied from
997 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
999 * @param {...*} classargs
1000 * Additional arguments which are passed as-is to the contructor of the
1001 * given option class. Refer to the class specific constructor
1002 * documentation for details.
1004 * @throws {TypeError}
1005 * Throws a `TypeError` exception in case the passed class value is not a
1006 * descendent of `AbstractValue`.
1008 * @returns {LuCI.form.AbstractValue}
1009 * Returns the instantiated option class instance.
1011 option: function(cbiClass
/*, ... */) {
1012 if (!CBIAbstractValue
.isSubclass(cbiClass
))
1013 throw L
.error('TypeError', 'Class must be a descendent of CBIAbstractValue');
1015 var obj
= cbiClass
.instantiate(this.varargs(arguments
, 1, this.map
, this));
1021 * Add a configuration option widget to a tab of the section.
1023 * @param {string} tabname
1024 * The name of the section tab to add the option element to.
1026 * @param {LuCI.form.AbstractValue} optionclass
1027 * The option class to use for rendering the configuration option. Note
1028 * that this value must be the class itself, not a class instance obtained
1029 * from calling `new`. It must also be a class dervied from
1030 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
1032 * @param {...*} classargs
1033 * Additional arguments which are passed as-is to the contructor of the
1034 * given option class. Refer to the class specific constructor
1035 * documentation for details.
1037 * @throws {ReferenceError}
1038 * Throws a `ReferenceError` exception when the given tab name does not
1041 * @throws {TypeError}
1042 * Throws a `TypeError` exception in case the passed class value is not a
1043 * descendent of `AbstractValue`.
1045 * @returns {LuCI.form.AbstractValue}
1046 * Returns the instantiated option class instance.
1048 taboption: function(tabName
/*, ... */) {
1049 if (!this.tabs
|| !this.tabs
[tabName
])
1050 throw L
.error('ReferenceError', 'Associated tab not declared');
1052 var obj
= this.option
.apply(this, this.varargs(arguments
, 1));
1054 this.tabs
[tabName
].children
.push(obj
);
1059 * Query underlying option configuration values.
1061 * This function is sensitive to the amount of arguments passed to it;
1062 * if only one argument is specified, the configuration values of all
1063 * options within this section are returned as dictionary.
1065 * If both the section ID and an option name are supplied, this function
1066 * returns the configuration value of the specified option only.
1068 * @param {string} section_id
1069 * The configuration section ID
1071 * @param {string} [option]
1072 * The name of the option to query
1074 * @returns {null|string|string[]|Object<string, null|string|string[]>}
1075 * Returns either a dictionary of option names and their corresponding
1076 * configuration values or just a single configuration value, depending
1077 * on the amount of passed arguments.
1079 cfgvalue: function(section_id
, option
) {
1080 var rv
= (arguments
.length
== 1) ? {} : null;
1082 for (var i
= 0, o
; (o
= this.children
[i
]) != null; i
++)
1084 rv
[o
.option
] = o
.cfgvalue(section_id
);
1085 else if (o
.option
== option
)
1086 return o
.cfgvalue(section_id
);
1092 * Query underlying option widget input values.
1094 * This function is sensitive to the amount of arguments passed to it;
1095 * if only one argument is specified, the widget input values of all
1096 * options within this section are returned as dictionary.
1098 * If both the section ID and an option name are supplied, this function
1099 * returns the widget input value of the specified option only.
1101 * @param {string} section_id
1102 * The configuration section ID
1104 * @param {string} [option]
1105 * The name of the option to query
1107 * @returns {null|string|string[]|Object<string, null|string|string[]>}
1108 * Returns either a dictionary of option names and their corresponding
1109 * widget input values or just a single widget input value, depending
1110 * on the amount of passed arguments.
1112 formvalue: function(section_id
, option
) {
1113 var rv
= (arguments
.length
== 1) ? {} : null;
1115 for (var i
= 0, o
; (o
= this.children
[i
]) != null; i
++) {
1116 var func
= this.map
.root
? this.children
[i
].formvalue
: this.children
[i
].cfgvalue
;
1119 rv
[o
.option
] = func
.call(o
, section_id
);
1120 else if (o
.option
== option
)
1121 return func
.call(o
, section_id
);
1128 * Obtain underlying option LuCI.ui widget instances.
1130 * This function is sensitive to the amount of arguments passed to it;
1131 * if only one argument is specified, the LuCI.ui widget instances of all
1132 * options within this section are returned as dictionary.
1134 * If both the section ID and an option name are supplied, this function
1135 * returns the LuCI.ui widget instance value of the specified option only.
1137 * @param {string} section_id
1138 * The configuration section ID
1140 * @param {string} [option]
1141 * The name of the option to query
1143 * @returns {null|LuCI.ui.AbstractElement|Object<string, null|LuCI.ui.AbstractElement>}
1144 * Returns either a dictionary of option names and their corresponding
1145 * widget input values or just a single widget input value, depending
1146 * on the amount of passed arguments.
1148 getUIElement: function(section_id
, option
) {
1149 var rv
= (arguments
.length
== 1) ? {} : null;
1151 for (var i
= 0, o
; (o
= this.children
[i
]) != null; i
++)
1153 rv
[o
.option
] = o
.getUIElement(section_id
);
1154 else if (o
.option
== option
)
1155 return o
.getUIElement(section_id
);
1161 * Obtain underlying option objects.
1163 * This function is sensitive to the amount of arguments passed to it;
1164 * if no option name is specified, all options within this section are
1165 * returned as dictionary.
1167 * If an option name is supplied, this function returns the matching
1168 * LuCI.form.AbstractValue instance only.
1170 * @param {string} [option]
1171 * The name of the option object to obtain
1173 * @returns {null|LuCI.form.AbstractValue|Object<string, LuCI.form.AbstractValue>}
1174 * Returns either a dictionary of option names and their corresponding
1175 * option instance objects or just a single object instance value,
1176 * depending on the amount of passed arguments.
1178 getOption: function(option
) {
1179 var rv
= (arguments
.length
== 0) ? {} : null;
1181 for (var i
= 0, o
; (o
= this.children
[i
]) != null; i
++)
1184 else if (o
.option
== option
)
1191 renderUCISection: function(section_id
) {
1192 var renderTasks
= [];
1195 return this.renderOptions(null, section_id
);
1197 for (var i
= 0; i
< this.tab_names
.length
; i
++)
1198 renderTasks
.push(this.renderOptions(this.tab_names
[i
], section_id
));
1200 return Promise
.all(renderTasks
)
1201 .then(this.renderTabContainers
.bind(this, section_id
));
1205 renderTabContainers: function(section_id
, nodes
) {
1206 var config_name
= this.uciconfig
|| this.map
.config
,
1207 containerEls
= E([]);
1209 for (var i
= 0; i
< nodes
.length
; i
++) {
1210 var tab_name
= this.tab_names
[i
],
1211 tab_data
= this.tabs
[tab_name
],
1212 containerEl
= E('div', {
1213 'id': 'container.%s.%s.%s'.format(config_name
, section_id
, tab_name
),
1214 'data-tab': tab_name
,
1215 'data-tab-title': tab_data
.title
,
1216 'data-tab-active': tab_name
=== this.selected_tab
1219 if (tab_data
.description
!= null && tab_data
.description
!= '')
1220 containerEl
.appendChild(
1221 E('div', { 'class': 'cbi-tab-descr' }, tab_data
.description
));
1223 containerEl
.appendChild(nodes
[i
]);
1224 containerEls
.appendChild(containerEl
);
1227 return containerEls
;
1231 renderOptions: function(tab_name
, section_id
) {
1232 var in_table
= (this instanceof CBITableSection
);
1233 return this.renderChildren(tab_name
, section_id
, in_table
).then(function(nodes
) {
1234 var optionEls
= E([]);
1235 for (var i
= 0; i
< nodes
.length
; i
++)
1236 optionEls
.appendChild(nodes
[i
]);
1242 checkDepends: function(ev
, n
) {
1243 var changed
= false,
1244 sids
= this.cfgsections();
1246 for (var i
= 0, sid
= sids
[0]; (sid
= sids
[i
]) != null; i
++) {
1247 for (var j
= 0, o
= this.children
[0]; (o
= this.children
[j
]) != null; j
++) {
1248 var isActive
= o
.isActive(sid
),
1249 isSatisified
= o
.checkDepends(sid
);
1251 if (isActive
!= isSatisified
) {
1252 o
.setActive(sid
, !isActive
);
1253 isActive
= !isActive
;
1258 o
.triggerValidation(sid
);
1267 var isEqual = function(x
, y
) {
1268 if (typeof(y
) == 'object' && y
instanceof RegExp
)
1269 return (x
== null) ? false : y
.test(x
);
1271 if (x
!= null && y
!= null && typeof(x
) != typeof(y
))
1274 if ((x
== null && y
!= null) || (x
!= null && y
== null))
1277 if (Array
.isArray(x
)) {
1278 if (x
.length
!= y
.length
)
1281 for (var i
= 0; i
< x
.length
; i
++)
1282 if (!isEqual(x
[i
], y
[i
]))
1285 else if (typeof(x
) == 'object') {
1287 if (x
.hasOwnProperty(k
) && !y
.hasOwnProperty(k
))
1290 if (!isEqual(x
[k
], y
[k
]))
1295 if (y
.hasOwnProperty(k
) && !x
.hasOwnProperty(k
))
1305 var isContained = function(x
, y
) {
1306 if (Array
.isArray(x
)) {
1307 for (var i
= 0; i
< x
.length
; i
++)
1311 else if (L
.isObject(x
)) {
1312 if (x
.hasOwnProperty(y
) && x
[y
] != null)
1315 else if (typeof(x
) == 'string') {
1316 return (x
.indexOf(y
) > -1);
1323 * @class AbstractValue
1324 * @memberof LuCI.form
1325 * @augments LuCI.form.AbstractElement
1329 * The `AbstractValue` class serves as abstract base for the different form
1330 * option styles implemented by `LuCI.form`. It provides the common logic for
1331 * handling option input values, for dependencies among options and for
1332 * validation constraints that should be applied to entered values.
1334 * This class is private and not directly accessible by user code.
1336 var CBIAbstractValue
= CBIAbstractElement
.extend(/** @lends LuCI.form.AbstractValue.prototype */ {
1337 __init__: function(map
, section
, option
/*, ... */) {
1338 this.super('__init__', this.varargs(arguments
, 3));
1340 this.section
= section
;
1341 this.option
= option
;
1343 this.config
= map
.config
;
1347 this.rmempty
= true;
1348 this.default = null;
1350 this.optional
= false;
1351 this.retain
= false;
1355 * If set to `false`, the underlying option value is retained upon saving
1356 * the form when the option element is disabled due to unsatisfied
1357 * dependency constraints.
1359 * @name LuCI.form.AbstractValue.prototype#rmempty
1365 * If set to `true`, the underlying ui input widget is allowed to be empty,
1366 * otherwise the option element is marked invalid when no value is entered
1367 * or selected by the user.
1369 * @name LuCI.form.AbstractValue.prototype#optional
1375 * If set to `true`, the underlying ui input widget value is not cleared
1376 * from the configuration on unsatisfied depedencies. The default behavior
1377 * is to remove the values of all options whose dependencies are not
1380 * @name LuCI.form.AbstractValue.prototype#retain
1386 * Sets a default value to use when the underlying UCI option is not set.
1388 * @name LuCI.form.AbstractValue.prototype#default
1394 * Specifies a datatype constraint expression to validate input values
1395 * against. Refer to {@link LuCI.validation} for details on the format.
1397 * If the user entered input does not match the datatype validation, the
1398 * option element is marked as invalid.
1400 * @name LuCI.form.AbstractValue.prototype#datatype
1406 * Specifies a custom validation function to test the user input for
1407 * validity. The validation function must return `true` to accept the
1408 * value. Any other return value type is converted to a string and
1409 * displayed to the user as validation error message.
1411 * If the user entered input does not pass the validation function, the
1412 * option element is marked as invalid.
1414 * @name LuCI.form.AbstractValue.prototype#validate
1420 * Override the UCI configuration name to read the option value from.
1422 * By default, the configuration name is inherited from the parent Map.
1423 * By setting this property, a deviating configuration may be specified.
1425 * The default is null, means inheriting from the parent form.
1427 * @name LuCI.form.AbstractValue.prototype#uciconfig
1433 * Override the UCI section name to read the option value from.
1435 * By default, the section ID is inherited from the parent section element.
1436 * By setting this property, a deviating section may be specified.
1438 * The default is null, means inheriting from the parent section.
1440 * @name LuCI.form.AbstractValue.prototype#ucisection
1446 * Override the UCI option name to read the value from.
1448 * By default, the elements name, which is passed as third argument to
1449 * the constructor, is used as UCI option name. By setting this property,
1450 * a deviating UCI option may be specified.
1452 * The default is null, means using the option element name.
1454 * @name LuCI.form.AbstractValue.prototype#ucioption
1460 * Mark grid section option element as editable.
1462 * Options which are displayed in the table portion of a `GridSection`
1463 * instance are rendered as readonly text by default. By setting the
1464 * `editable` property of a child option element to `true`, that element
1465 * is rendered as full input widget within its cell instead of a text only
1468 * This property has no effect on options that are not children of grid
1471 * @name LuCI.form.AbstractValue.prototype#editable
1477 * Move grid section option element into the table, the modal popup or both.
1479 * If this property is `null` (the default), the option element is
1480 * displayed in both the table preview area and the per-section instance
1481 * modal popup of a grid section. When it is set to `false` the option
1482 * is only shown in the table but not the modal popup. When set to `true`,
1483 * the option is only visible in the modal popup but not the table.
1485 * This property has no effect on options that are not children of grid
1488 * @name LuCI.form.AbstractValue.prototype#modalonly
1494 * Make option element readonly.
1496 * This property defaults to the readonly state of the parent form element.
1497 * When set to `true`, the underlying widget is rendered in disabled state,
1498 * means its contents cannot be changed and the widget cannot be interacted
1501 * @name LuCI.form.AbstractValue.prototype#readonly
1507 * Override the cell width of a table or grid section child option.
1509 * If the property is set to a numeric value, it is treated as pixel width
1510 * which is set on the containing cell element of the option, essentially
1511 * forcing a certain column width. When the property is set to a string
1512 * value, it is applied as-is to the CSS `width` property.
1514 * This property has no effect on options that are not children of grid or
1515 * table section elements.
1517 * @name LuCI.form.AbstractValue.prototype#width
1518 * @type number|string
1523 * Register a custom value change handler.
1525 * If this property is set to a function value, the function is invoked
1526 * whenever the value of the underlying UI input element is changing.
1528 * The invoked handler function will receive the DOM click element as
1529 * first and the underlying configuration section ID as well as the input
1530 * value as second and third argument respectively.
1532 * @name LuCI.form.AbstractValue.prototype#onchange
1538 * Add a dependency contraint to the option.
1540 * Dependency constraints allow making the presence of option elements
1541 * dependant on the current values of certain other options within the
1542 * same form. An option element with unsatisfied dependencies will be
1543 * hidden from the view and its current value is omitted when saving.
1545 * Multiple constraints (that is, multiple calls to `depends()`) are
1546 * treated as alternatives, forming a logical "or" expression.
1548 * By passing an object of name => value pairs as first argument, it is
1549 * possible to depend on multiple options simultaneously, allowing to form
1550 * a logical "and" expression.
1552 * Option names may be given in "dot notation" which allows to reference
1553 * option elements outside of the current form section. If a name without
1554 * dot is specified, it refers to an option within the same configuration
1555 * section. If specified as <code>configname.sectionid.optionname</code>,
1556 * options anywhere within the same form may be specified.
1558 * The object notation also allows for a number of special keys which are
1559 * not treated as option names but as modifiers to influence the dependency
1560 * constraint evaluation. The associated value of these special "tag" keys
1561 * is ignored. The recognized tags are:
1565 * <code>!reverse</code><br>
1566 * Invert the dependency, instead of requiring another option to be
1567 * equal to the dependency value, that option should <em>not</em> be
1571 * <code>!contains</code><br>
1572 * Instead of requiring an exact match, the dependency is considered
1573 * satisfied when the dependency value is contained within the option
1577 * <code>!default</code><br>
1578 * The dependency is always satisfied
1586 * <code>opt.depends("foo", "test")</code><br>
1587 * Require the value of `foo` to be `test`.
1590 * <code>opt.depends({ foo: "test" })</code><br>
1591 * Equivalent to the previous example.
1594 * <code>opt.depends({ foo: /test/ })</code><br>
1595 * Require the value of `foo` to match the regular expression `/test/`.
1598 * <code>opt.depends({ foo: "test", bar: "qrx" })</code><br>
1599 * Require the value of `foo` to be `test` and the value of `bar` to be
1603 * <code>opt.depends({ foo: "test" })<br>
1604 * opt.depends({ bar: "qrx" })</code><br>
1605 * Require either <code>foo</code> to be set to <code>test</code>,
1606 * <em>or</em> the <code>bar</code> option to be <code>qrx</code>.
1609 * <code>opt.depends("test.section1.foo", "bar")</code><br>
1610 * Require the "foo" form option within the "section1" section to be
1614 * <code>opt.depends({ foo: "test", "!contains": true })</code><br>
1615 * Require the "foo" option value to contain the substring "test".
1619 * @param {string|Object<string, string|RegExp>} optionname_or_depends
1620 * The name of the option to depend on or an object describing multiple
1621 * dependencies which must be satified (a logical "and" expression).
1623 * @param {string} optionvalue|RegExp
1624 * When invoked with a plain option name as first argument, this parameter
1625 * specifies the expected value. In case an object is passed as first
1626 * argument, this parameter is ignored.
1628 depends: function(field
, value
) {
1631 if (typeof(field
) === 'string')
1632 deps
= {}, deps
[field
] = value
;
1636 this.deps
.push(deps
);
1640 transformDepList: function(section_id
, deplist
) {
1641 var list
= deplist
|| this.deps
,
1644 if (Array
.isArray(list
)) {
1645 for (var i
= 0; i
< list
.length
; i
++) {
1648 for (var k
in list
[i
]) {
1649 if (list
[i
].hasOwnProperty(k
)) {
1650 if (k
.charAt(0) === '!')
1651 dep
[k
] = list
[i
][k
];
1652 else if (k
.indexOf('.') !== -1)
1653 dep
['cbid.%s'.format(k
)] = list
[i
][k
];
1655 dep
['cbid.%s.%s.%s'.format(
1656 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1657 this.ucisection
|| section_id
,
1663 for (var k
in dep
) {
1664 if (dep
.hasOwnProperty(k
)) {
1676 transformChoices: function() {
1677 if (!Array
.isArray(this.keylist
) || this.keylist
.length
== 0)
1682 for (var i
= 0; i
< this.keylist
.length
; i
++)
1683 choices
[this.keylist
[i
]] = this.vallist
[i
];
1689 checkDepends: function(section_id
) {
1690 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1691 active
= this.map
.isDependencySatisfied(this.deps
, config_name
, section_id
);
1694 this.updateDefaultValue(section_id
);
1700 updateDefaultValue: function(section_id
) {
1701 if (!L
.isObject(this.defaults
))
1704 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1705 cfgvalue
= L
.toArray(this.cfgvalue(section_id
))[0],
1706 default_defval
= null, satisified_defval
= null;
1708 for (var value
in this.defaults
) {
1709 if (!this.defaults
[value
] || this.defaults
[value
].length
== 0) {
1710 default_defval
= value
;
1713 else if (this.map
.isDependencySatisfied(this.defaults
[value
], config_name
, section_id
)) {
1714 satisified_defval
= value
;
1719 if (satisified_defval
== null)
1720 satisified_defval
= default_defval
;
1722 var node
= this.map
.findElement('id', this.cbid(section_id
));
1723 if (node
&& node
.getAttribute('data-changed') != 'true' && satisified_defval
!= null && cfgvalue
== null)
1724 dom
.callClassMethod(node
, 'setValue', satisified_defval
);
1726 this.default = satisified_defval
;
1730 * Obtain the internal ID ("cbid") of the element instance.
1732 * Since each form section element may map multiple underlying
1733 * configuration sections, the configuration section ID is required to
1734 * form a fully qualified ID pointing to the specific element instance
1735 * within the given specific section.
1737 * @param {string} section_id
1738 * The configuration section ID
1740 * @throws {TypeError}
1741 * Throws a `TypeError` exception when no `section_id` was specified.
1744 * Returns the element ID.
1746 cbid: function(section_id
) {
1747 if (section_id
== null)
1748 L
.error('TypeError', 'Section ID required');
1750 return 'cbid.%s.%s.%s'.format(
1751 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1752 section_id
, this.option
);
1756 * Load the underlying configuration value.
1758 * The default implementation of this method reads and returns the
1759 * underlying UCI option value (or the related JavaScript property for
1760 * `JSONMap` instances). It may be overwritten by user code to load data
1761 * from nonstandard sources.
1763 * @param {string} section_id
1764 * The configuration section ID
1766 * @throws {TypeError}
1767 * Throws a `TypeError` exception when no `section_id` was specified.
1769 * @returns {*|Promise<*>}
1770 * Returns the configuration value to initialize the option element with.
1771 * The return value of this function is filtered through `Promise.resolve()`
1772 * so it may return promises if overridden by user code.
1774 load: function(section_id
) {
1775 if (section_id
== null)
1776 L
.error('TypeError', 'Section ID required');
1778 return this.map
.data
.get(
1779 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
1780 this.ucisection
|| section_id
,
1781 this.ucioption
|| this.option
);
1785 * Obtain the underlying `LuCI.ui` element instance.
1787 * @param {string} section_id
1788 * The configuration section ID
1790 * @throws {TypeError}
1791 * Throws a `TypeError` exception when no `section_id` was specified.
1793 * @return {LuCI.ui.AbstractElement|null}
1794 * Returns the `LuCI.ui` element instance or `null` in case the form
1795 * option implementation does not use `LuCI.ui` widgets.
1797 getUIElement: function(section_id
) {
1798 var node
= this.map
.findElement('id', this.cbid(section_id
)),
1799 inst
= node
? dom
.findClassInstance(node
) : null;
1800 return (inst
instanceof ui
.AbstractElement
) ? inst
: null;
1804 * Query the underlying configuration value.
1806 * The default implementation of this method returns the cached return
1807 * value of [load()]{@link LuCI.form.AbstractValue#load}. It may be
1808 * overwritten by user code to obtain the configuration value in a
1811 * @param {string} section_id
1812 * The configuration section ID
1814 * @throws {TypeError}
1815 * Throws a `TypeError` exception when no `section_id` was specified.
1818 * Returns the configuration value.
1820 cfgvalue: function(section_id
, set_value
) {
1821 if (section_id
== null)
1822 L
.error('TypeError', 'Section ID required');
1824 if (arguments
.length
== 2) {
1825 this.data
= this.data
|| {};
1826 this.data
[section_id
] = set_value
;
1829 return this.data
? this.data
[section_id
] : null;
1833 * Query the current form input value.
1835 * The default implementation of this method returns the current input
1836 * value of the underlying [LuCI.ui]{@link LuCI.ui.AbstractElement} widget.
1837 * It may be overwritten by user code to handle input values differently.
1839 * @param {string} section_id
1840 * The configuration section ID
1842 * @throws {TypeError}
1843 * Throws a `TypeError` exception when no `section_id` was specified.
1846 * Returns the current input value.
1848 formvalue: function(section_id
) {
1849 var elem
= this.getUIElement(section_id
);
1850 return elem
? elem
.getValue() : null;
1854 * Obtain a textual input representation.
1856 * The default implementation of this method returns the HTML escaped
1857 * current input value of the underlying
1858 * [LuCI.ui]{@link LuCI.ui.AbstractElement} widget. User code or specific
1859 * option element implementations may overwrite this function to apply a
1860 * different logic, e.g. to return `Yes` or `No` depending on the checked
1861 * state of checkbox elements.
1863 * @param {string} section_id
1864 * The configuration section ID
1866 * @throws {TypeError}
1867 * Throws a `TypeError` exception when no `section_id` was specified.
1870 * Returns the text representation of the current input value.
1872 textvalue: function(section_id
) {
1873 var cval
= this.cfgvalue(section_id
);
1876 cval
= this.default;
1878 if (Array
.isArray(cval
))
1879 cval
= cval
.join(' ');
1881 return (cval
!= null) ? '%h'.format(cval
) : null;
1885 * Apply custom validation logic.
1887 * This method is invoked whenever incremental validation is performed on
1888 * the user input, e.g. on keyup or blur events.
1890 * The default implementation of this method does nothing and always
1891 * returns `true`. User code may overwrite this method to provide
1892 * additional validation logic which is not covered by data type
1896 * @param {string} section_id
1897 * The configuration section ID
1900 * The value to validate
1903 * The method shall return `true` to accept the given value. Any other
1904 * return value is treated as failure, converted to a string and displayed
1905 * as error message to the user.
1907 validate: function(section_id
, value
) {
1912 * Test whether the input value is currently valid.
1914 * @param {string} section_id
1915 * The configuration section ID
1917 * @returns {boolean}
1918 * Returns `true` if the input value currently is valid, otherwise it
1921 isValid: function(section_id
) {
1922 var elem
= this.getUIElement(section_id
);
1923 return elem
? elem
.isValid() : true;
1927 * Returns the current validation error for this input.
1929 * @param {string} section_id
1930 * The configuration section ID
1933 * The validation error at this time
1935 getValidationError: function (section_id
) {
1936 var elem
= this.getUIElement(section_id
);
1937 return elem
? elem
.getValidationError() : '';
1941 * Test whether the option element is currently active.
1943 * An element is active when it is not hidden due to unsatisfied dependency
1946 * @param {string} section_id
1947 * The configuration section ID
1949 * @returns {boolean}
1950 * Returns `true` if the option element currently is active, otherwise it
1953 isActive: function(section_id
) {
1954 var field
= this.map
.findElement('data-field', this.cbid(section_id
));
1955 return (field
!= null && !field
.classList
.contains('hidden'));
1959 setActive: function(section_id
, active
) {
1960 var field
= this.map
.findElement('data-field', this.cbid(section_id
));
1962 if (field
&& field
.classList
.contains('hidden') == active
) {
1963 field
.classList
[active
? 'remove' : 'add']('hidden');
1965 if (dom
.matches(field
.parentNode
, '.td.cbi-value-field'))
1966 field
.parentNode
.classList
[active
? 'remove' : 'add']('inactive');
1975 triggerValidation: function(section_id
) {
1976 var elem
= this.getUIElement(section_id
);
1977 return elem
? elem
.triggerValidation() : true;
1981 * Parse the option element input.
1983 * The function is invoked when the `parse()` method has been invoked on
1984 * the parent form and triggers input value reading and validation.
1986 * @param {string} section_id
1987 * The configuration section ID
1989 * @returns {Promise<void>}
1990 * Returns a promise resolving once the input value has been read and
1991 * validated or rejecting in case the input value does not meet the
1992 * validation constraints.
1994 parse: function(section_id
) {
1995 var active
= this.isActive(section_id
);
1997 if (active
&& !this.isValid(section_id
)) {
1998 var title
= this.stripTags(this.title
).trim(),
1999 error
= this.getValidationError(section_id
);
2001 return Promise
.reject(new TypeError(
2002 _('Option "%s" contains an invalid input value.').format(title
|| this.option
) + ' ' + error
));
2006 var cval
= this.cfgvalue(section_id
),
2007 fval
= this.formvalue(section_id
);
2009 if (fval
== null || fval
== '') {
2010 if (this.rmempty
|| this.optional
) {
2011 return Promise
.resolve(this.remove(section_id
));
2014 var title
= this.stripTags(this.title
).trim();
2016 return Promise
.reject(new TypeError(
2017 _('Option "%s" must not be empty.').format(title
|| this.option
)));
2020 else if (this.forcewrite
|| !isEqual(cval
, fval
)) {
2021 return Promise
.resolve(this.write(section_id
, fval
));
2024 else if (!this.retain
) {
2025 return Promise
.resolve(this.remove(section_id
));
2028 return Promise
.resolve();
2032 * Write the current input value into the configuration.
2034 * This function is invoked upon saving the parent form when the option
2035 * element is valid and when its input value has been changed compared to
2036 * the initial value returned by
2037 * [cfgvalue()]{@link LuCI.form.AbstractValue#cfgvalue}.
2039 * The default implementation simply sets the given input value in the
2040 * UCI configuration (or the associated JavaScript object property in
2041 * case of `JSONMap` forms). It may be overwritten by user code to
2042 * implement alternative save logic, e.g. to transform the input value
2043 * before it is written.
2045 * @param {string} section_id
2046 * The configuration section ID
2048 * @param {string|string[]} formvalue
2049 * The input value to write.
2051 write: function(section_id
, formvalue
) {
2052 return this.map
.data
.set(
2053 this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
2054 this.ucisection
|| section_id
,
2055 this.ucioption
|| this.option
,
2060 * Remove the corresponding value from the configuration.
2062 * This function is invoked upon saving the parent form when the option
2063 * element has been hidden due to unsatisfied dependencies or when the
2064 * user cleared the input value and the option is marked optional.
2066 * The default implementation simply removes the associated option from the
2067 * UCI configuration (or the associated JavaScript object property in
2068 * case of `JSONMap` forms). It may be overwritten by user code to
2069 * implement alternative removal logic, e.g. to retain the original value.
2071 * @param {string} section_id
2072 * The configuration section ID
2074 remove: function(section_id
) {
2075 var this_cfg
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
2076 this_sid
= this.ucisection
|| section_id
,
2077 this_opt
= this.ucioption
|| this.option
;
2079 for (var i
= 0; i
< this.section
.children
.length
; i
++) {
2080 var sibling
= this.section
.children
[i
];
2082 if (sibling
=== this || sibling
.ucioption
== null)
2085 var sibling_cfg
= sibling
.uciconfig
|| sibling
.section
.uciconfig
|| sibling
.map
.config
,
2086 sibling_sid
= sibling
.ucisection
|| section_id
,
2087 sibling_opt
= sibling
.ucioption
|| sibling
.option
;
2089 if (this_cfg
!= sibling_cfg
|| this_sid
!= sibling_sid
|| this_opt
!= sibling_opt
)
2092 if (!sibling
.isActive(section_id
))
2095 /* found another active option aliasing the same uci option name,
2096 * so we can't remove the value */
2100 this.map
.data
.unset(this_cfg
, this_sid
, this_opt
);
2105 * @class TypedSection
2106 * @memberof LuCI.form
2107 * @augments LuCI.form.AbstractSection
2111 * The `TypedSection` class maps all or - if `filter()` is overwritten - a
2112 * subset of the underlying UCI configuration sections of a given type.
2114 * Layout wise, the configuration section instances mapped by the section
2115 * element (sometimes referred to as "section nodes") are stacked beneath
2116 * each other in a single column, with an optional section remove button next
2117 * to each section node and a section add button at the end, depending on the
2118 * value of the `addremove` property.
2120 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2121 * The configuration form this section is added to. It is automatically passed
2122 * by [section()]{@link LuCI.form.Map#section}.
2124 * @param {string} section_type
2125 * The type of the UCI section to map.
2127 * @param {string} [title]
2128 * The title caption of the form section element.
2130 * @param {string} [description]
2131 * The description text of the form section element.
2133 var CBITypedSection
= CBIAbstractSection
.extend(/** @lends LuCI.form.TypedSection.prototype */ {
2134 __name__
: 'CBI.TypedSection',
2137 * If set to `true`, the user may add or remove instances from the form
2138 * section widget, otherwise only preexisting sections may be edited.
2139 * The default is `false`.
2141 * @name LuCI.form.TypedSection.prototype#addremove
2147 * If set to `true`, mapped section instances are treated as anonymous
2148 * UCI sections, which means that section instance elements will be
2149 * rendered without title element and that no name is required when adding
2150 * new sections. The default is `false`.
2152 * @name LuCI.form.TypedSection.prototype#anonymous
2158 * When set to `true`, instead of rendering section instances one below
2159 * another, treat each instance as separate tab pane and render a tab menu
2160 * at the top of the form section element, allowing the user to switch
2161 * among instances. The default is `false`.
2163 * @name LuCI.form.TypedSection.prototype#tabbed
2169 * Override the caption used for the section add button at the bottom of
2170 * the section form element. If set to a string, it will be used as-is,
2171 * if set to a function, the function will be invoked and its return value
2172 * is used as caption, after converting it to a string. If this property
2173 * is not set, the default is `Add`.
2175 * @name LuCI.form.TypedSection.prototype#addbtntitle
2176 * @type string|function
2181 * Override the UCI configuration name to read the section IDs from. By
2182 * default, the configuration name is inherited from the parent `Map`.
2183 * By setting this property, a deviating configuration may be specified.
2184 * The default is `null`, means inheriting from the parent form.
2186 * @name LuCI.form.TypedSection.prototype#uciconfig
2192 cfgsections: function() {
2193 return this.map
.data
.sections(this.uciconfig
|| this.map
.config
, this.sectiontype
)
2194 .map(function(s
) { return s
['.name'] })
2195 .filter(L
.bind(this.filter
, this));
2199 handleAdd: function(ev
, name
) {
2200 var config_name
= this.uciconfig
|| this.map
.config
;
2202 this.map
.data
.add(config_name
, this.sectiontype
, name
);
2203 return this.map
.save(null, true);
2207 handleRemove: function(section_id
, ev
) {
2208 var config_name
= this.uciconfig
|| this.map
.config
;
2210 this.map
.data
.remove(config_name
, section_id
);
2211 return this.map
.save(null, true);
2215 renderSectionAdd: function(extra_class
) {
2216 if (!this.addremove
)
2219 var createEl
= E('div', { 'class': 'cbi-section-create' }),
2220 config_name
= this.uciconfig
|| this.map
.config
,
2221 btn_title
= this.titleFn('addbtntitle');
2223 if (extra_class
!= null)
2224 createEl
.classList
.add(extra_class
);
2226 if (this.anonymous
) {
2227 createEl
.appendChild(E('button', {
2228 'class': 'cbi-button cbi-button-add',
2229 'title': btn_title
|| _('Add'),
2230 'click': ui
.createHandlerFn(this, 'handleAdd'),
2231 'disabled': this.map
.readonly
|| null
2232 }, [ btn_title
|| _('Add') ]));
2235 var nameEl
= E('input', {
2237 'class': 'cbi-section-create-name',
2238 'disabled': this.map
.readonly
|| null
2241 dom
.append(createEl
, [
2242 E('div', {}, nameEl
),
2244 'class': 'cbi-button cbi-button-add',
2245 'title': btn_title
|| _('Add'),
2246 'click': ui
.createHandlerFn(this, function(ev
) {
2247 if (nameEl
.classList
.contains('cbi-input-invalid'))
2250 return this.handleAdd(ev
, nameEl
.value
);
2252 'disabled': this.map
.readonly
|| true
2253 }, [ btn_title
|| _('Add') ])
2256 if (this.map
.readonly
!== true) {
2257 ui
.addValidator(nameEl
, 'uciname', true, function(v
) {
2258 var button
= document
.querySelector('.cbi-section-create > .cbi-button-add');
2260 button
.disabled
= null;
2264 button
.disabled
= true;
2265 return _('Expecting: %s').format(_('non-empty value'));
2267 }, 'blur', 'keyup');
2275 renderSectionPlaceholder: function() {
2277 E('em', _('This section contains no values yet')),
2283 renderContents: function(cfgsections
, nodes
) {
2284 var section_id
= null,
2285 config_name
= this.uciconfig
|| this.map
.config
,
2286 sectionEl
= E('div', {
2287 'id': 'cbi-%s-%s'.format(config_name
, this.sectiontype
),
2288 'class': 'cbi-section',
2289 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2290 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2293 if (this.title
!= null && this.title
!= '')
2294 sectionEl
.appendChild(E('h3', {}, this.title
));
2296 if (this.description
!= null && this.description
!= '')
2297 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2299 for (var i
= 0; i
< nodes
.length
; i
++) {
2300 if (this.addremove
) {
2301 sectionEl
.appendChild(
2302 E('div', { 'class': 'cbi-section-remove right' },
2304 'class': 'cbi-button',
2305 'name': 'cbi.rts.%s.%s'.format(config_name
, cfgsections
[i
]),
2306 'data-section-id': cfgsections
[i
],
2307 'click': ui
.createHandlerFn(this, 'handleRemove', cfgsections
[i
]),
2308 'disabled': this.map
.readonly
|| null
2309 }, [ _('Delete') ])));
2312 if (!this.anonymous
)
2313 sectionEl
.appendChild(E('h3', cfgsections
[i
].toUpperCase()));
2315 sectionEl
.appendChild(E('div', {
2316 'id': 'cbi-%s-%s'.format(config_name
, cfgsections
[i
]),
2318 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
2319 'data-section-id': cfgsections
[i
]
2323 if (nodes
.length
== 0)
2324 sectionEl
.appendChild(this.renderSectionPlaceholder());
2326 sectionEl
.appendChild(this.renderSectionAdd());
2328 dom
.bindClassInstance(sectionEl
, this);
2334 render: function() {
2335 var cfgsections
= this.cfgsections(),
2338 for (var i
= 0; i
< cfgsections
.length
; i
++)
2339 renderTasks
.push(this.renderUCISection(cfgsections
[i
]));
2341 return Promise
.all(renderTasks
).then(this.renderContents
.bind(this, cfgsections
));
2346 * @class TableSection
2347 * @memberof LuCI.form
2348 * @augments LuCI.form.TypedSection
2352 * The `TableSection` class maps all or - if `filter()` is overwritten - a
2353 * subset of the underlying UCI configuration sections of a given type.
2355 * Layout wise, the configuration section instances mapped by the section
2356 * element (sometimes referred to as "section nodes") are rendered as rows
2357 * within an HTML table element, with an optional section remove button in the
2358 * last column and a section add button below the table, depending on the
2359 * value of the `addremove` property.
2361 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2362 * The configuration form this section is added to. It is automatically passed
2363 * by [section()]{@link LuCI.form.Map#section}.
2365 * @param {string} section_type
2366 * The type of the UCI section to map.
2368 * @param {string} [title]
2369 * The title caption of the form section element.
2371 * @param {string} [description]
2372 * The description text of the form section element.
2374 var CBITableSection
= CBITypedSection
.extend(/** @lends LuCI.form.TableSection.prototype */ {
2375 __name__
: 'CBI.TableSection',
2378 * If set to `true`, the user may add or remove instances from the form
2379 * section widget, otherwise only preexisting sections may be edited.
2380 * The default is `false`.
2382 * @name LuCI.form.TableSection.prototype#addremove
2388 * If set to `true`, mapped section instances are treated as anonymous
2389 * UCI sections, which means that section instance elements will be
2390 * rendered without title element and that no name is required when adding
2391 * new sections. The default is `false`.
2393 * @name LuCI.form.TableSection.prototype#anonymous
2399 * Override the caption used for the section add button at the bottom of
2400 * the section form element. If set to a string, it will be used as-is,
2401 * if set to a function, the function will be invoked and its return value
2402 * is used as caption, after converting it to a string. If this property
2403 * is not set, the default is `Add`.
2405 * @name LuCI.form.TableSection.prototype#addbtntitle
2406 * @type string|function
2411 * Override the per-section instance title caption shown in the first
2412 * column of the table unless `anonymous` is set to true. If set to a
2413 * string, it will be used as `String.format()` pattern with the name of
2414 * the underlying UCI section as first argument, if set to a function, the
2415 * function will be invoked with the section name as first argument and
2416 * its return value is used as caption, after converting it to a string.
2417 * If this property is not set, the default is the name of the underlying
2418 * UCI configuration section.
2420 * @name LuCI.form.TableSection.prototype#sectiontitle
2421 * @type string|function
2426 * Override the per-section instance modal popup title caption shown when
2427 * clicking the `More…` button in a section specifying `max_cols`. If set
2428 * to a string, it will be used as `String.format()` pattern with the name
2429 * of the underlying UCI section as first argument, if set to a function,
2430 * the function will be invoked with the section name as first argument and
2431 * its return value is used as caption, after converting it to a string.
2432 * If this property is not set, the default is the name of the underlying
2433 * UCI configuration section.
2435 * @name LuCI.form.TableSection.prototype#modaltitle
2436 * @type string|function
2441 * Override the UCI configuration name to read the section IDs from. By
2442 * default, the configuration name is inherited from the parent `Map`.
2443 * By setting this property, a deviating configuration may be specified.
2444 * The default is `null`, means inheriting from the parent form.
2446 * @name LuCI.form.TableSection.prototype#uciconfig
2452 * Specify a maximum amount of columns to display. By default, one table
2453 * column is rendered for each child option of the form section element.
2454 * When this option is set to a positive number, then no more columns than
2455 * the given amount are rendered. When the number of child options exceeds
2456 * the specified amount, a `More…` button is rendered in the last column,
2457 * opening a modal dialog presenting all options elements in `NamedSection`
2458 * style when clicked.
2460 * @name LuCI.form.TableSection.prototype#max_cols
2466 * If set to `true`, alternating `cbi-rowstyle-1` and `cbi-rowstyle-2` CSS
2467 * classes are added to the table row elements. Not all LuCI themes
2468 * implement these row style classes. The default is `false`.
2470 * @name LuCI.form.TableSection.prototype#rowcolors
2476 * Enables a per-section instance row `Edit` button which triggers a certain
2477 * action when clicked. If set to a string, the string value is used
2478 * as `String.format()` pattern with the name of the underlying UCI section
2479 * as first format argument. The result is then interpreted as URL which
2480 * LuCI will navigate to when the user clicks the edit button.
2482 * If set to a function, this function will be registered as click event
2483 * handler on the rendered edit button, receiving the section instance
2484 * name as first and the DOM click event as second argument.
2486 * @name LuCI.form.TableSection.prototype#extedit
2487 * @type string|function
2492 * If set to `true`, a sort button is added to the last column, allowing
2493 * the user to reorder the section instances mapped by the section form
2496 * @name LuCI.form.TableSection.prototype#sortable
2502 * If set to `true`, the header row with the options descriptions will
2503 * not be displayed. By default, descriptions row is automatically displayed
2504 * when at least one option has a description.
2506 * @name LuCI.form.TableSection.prototype#nodescriptions
2512 * The `TableSection` implementation does not support option tabbing, so
2513 * its implementation of `tab()` will always throw an exception when
2517 * @throws Throws an exception when invoked.
2520 throw 'Tabs are not supported by TableSection';
2524 renderContents: function(cfgsections
, nodes
) {
2525 var section_id
= null,
2526 config_name
= this.uciconfig
|| this.map
.config
,
2527 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2528 has_more
= max_cols
< this.children
.length
,
2529 drag_sort
= this.sortable
&& !('ontouchstart' in window
),
2530 touch_sort
= this.sortable
&& ('ontouchstart' in window
),
2531 sectionEl
= E('div', {
2532 'id': 'cbi-%s-%s'.format(config_name
, this.sectiontype
),
2533 'class': 'cbi-section cbi-tblsection',
2534 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
2535 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
2537 tableEl
= E('table', {
2538 'class': 'table cbi-section-table'
2541 if (this.title
!= null && this.title
!= '')
2542 sectionEl
.appendChild(E('h3', {}, this.title
));
2544 if (this.description
!= null && this.description
!= '')
2545 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
2547 tableEl
.appendChild(this.renderHeaderRows(max_cols
));
2549 for (var i
= 0; i
< nodes
.length
; i
++) {
2550 var sectionname
= this.titleFn('sectiontitle', cfgsections
[i
]);
2552 if (sectionname
== null)
2553 sectionname
= cfgsections
[i
];
2555 var trEl
= E('tr', {
2556 'id': 'cbi-%s-%s'.format(config_name
, cfgsections
[i
]),
2557 'class': 'tr cbi-section-table-row',
2558 'data-sid': cfgsections
[i
],
2559 'draggable': (drag_sort
|| touch_sort
) ? true : null,
2560 'mousedown': drag_sort
? L
.bind(this.handleDragInit
, this) : null,
2561 'dragstart': drag_sort
? L
.bind(this.handleDragStart
, this) : null,
2562 'dragover': drag_sort
? L
.bind(this.handleDragOver
, this) : null,
2563 'dragenter': drag_sort
? L
.bind(this.handleDragEnter
, this) : null,
2564 'dragleave': drag_sort
? L
.bind(this.handleDragLeave
, this) : null,
2565 'dragend': drag_sort
? L
.bind(this.handleDragEnd
, this) : null,
2566 'drop': drag_sort
? L
.bind(this.handleDrop
, this) : null,
2567 'touchmove': touch_sort
? L
.bind(this.handleTouchMove
, this) : null,
2568 'touchend': touch_sort
? L
.bind(this.handleTouchEnd
, this) : null,
2569 'data-title': (sectionname
&& (!this.anonymous
|| this.sectiontitle
)) ? sectionname
: null,
2570 'data-section-id': cfgsections
[i
]
2573 if (this.extedit
|| this.rowcolors
)
2574 trEl
.classList
.add(!(tableEl
.childNodes
.length
% 2)
2575 ? 'cbi-rowstyle-1' : 'cbi-rowstyle-2');
2577 for (var j
= 0; j
< max_cols
&& nodes
[i
].firstChild
; j
++)
2578 trEl
.appendChild(nodes
[i
].firstChild
);
2580 trEl
.appendChild(this.renderRowActions(cfgsections
[i
], has_more
? _('More…') : null));
2581 tableEl
.appendChild(trEl
);
2584 if (nodes
.length
== 0)
2585 tableEl
.appendChild(E('tr', { 'class': 'tr cbi-section-table-row placeholder' },
2586 E('td', { 'class': 'td' }, this.renderSectionPlaceholder())));
2588 sectionEl
.appendChild(tableEl
);
2590 sectionEl
.appendChild(this.renderSectionAdd('cbi-tblsection-create'));
2592 dom
.bindClassInstance(sectionEl
, this);
2598 renderHeaderRows: function(max_cols
, has_action
) {
2599 var has_titles
= false,
2600 has_descriptions
= false,
2601 max_cols
= isNaN(this.max_cols
) ? this.children
.length
: this.max_cols
,
2602 has_more
= max_cols
< this.children
.length
,
2603 anon_class
= (!this.anonymous
|| this.sectiontitle
) ? 'named' : 'anonymous',
2606 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2610 has_titles
= has_titles
|| !!opt
.title
;
2611 has_descriptions
= has_descriptions
|| !!opt
.description
;
2615 var trEl
= E('tr', {
2616 'class': 'tr cbi-section-table-titles ' + anon_class
,
2617 'data-title': (!this.anonymous
|| this.sectiontitle
) ? _('Name') : null,
2618 'click': this.sortable
? ui
.createHandlerFn(this, 'handleSort') : null
2621 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2625 trEl
.appendChild(E('th', {
2626 'class': 'th cbi-section-table-cell',
2627 'data-widget': opt
.__name__
,
2628 'data-sortable-row': this.sortable
? '' : null
2631 if (opt
.width
!= null)
2632 trEl
.lastElementChild
.style
.width
=
2633 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2636 trEl
.lastElementChild
.appendChild(E('a', {
2637 'href': opt
.titleref
,
2638 'class': 'cbi-title-ref',
2639 'title': this.titledesc
|| _('Go to relevant configuration page')
2642 dom
.content(trEl
.lastElementChild
, opt
.title
);
2645 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2646 trEl
.appendChild(E('th', {
2647 'class': 'th cbi-section-table-cell cbi-section-actions'
2650 trEls
.appendChild(trEl
);
2653 if (has_descriptions
&& !this.nodescriptions
) {
2654 var trEl
= E('tr', {
2655 'class': 'tr cbi-section-table-descr ' + anon_class
2658 for (var i
= 0, opt
; i
< max_cols
&& (opt
= this.children
[i
]) != null; i
++) {
2662 trEl
.appendChild(E('th', {
2663 'class': 'th cbi-section-table-cell',
2664 'data-widget': opt
.__name__
2665 }, opt
.description
));
2667 if (opt
.width
!= null)
2668 trEl
.lastElementChild
.style
.width
=
2669 (typeof(opt
.width
) == 'number') ? opt
.width
+'px' : opt
.width
;
2672 if (this.sortable
|| this.extedit
|| this.addremove
|| has_more
|| has_action
)
2673 trEl
.appendChild(E('th', {
2674 'class': 'th cbi-section-table-cell cbi-section-actions'
2677 trEls
.appendChild(trEl
);
2684 renderRowActions: function(section_id
, more_label
) {
2685 var config_name
= this.uciconfig
|| this.map
.config
;
2687 if (!this.sortable
&& !this.extedit
&& !this.addremove
&& !more_label
)
2690 var tdEl
= E('td', {
2691 'class': 'td cbi-section-table-cell nowrap cbi-section-actions'
2694 if (this.sortable
) {
2695 dom
.append(tdEl
.lastElementChild
, [
2697 'title': _('Drag to reorder'),
2698 'class': 'cbi-button drag-handle center',
2699 'style': 'cursor:move',
2700 'disabled': this.map
.readonly
|| null
2708 if (typeof(this.extedit
) == 'function')
2709 evFn
= L
.bind(this.extedit
, this);
2710 else if (typeof(this.extedit
) == 'string')
2711 evFn
= L
.bind(function(sid
, ev
) {
2712 location
.href
= this.extedit
.format(sid
);
2713 }, this, section_id
);
2715 dom
.append(tdEl
.lastElementChild
,
2718 'class': 'cbi-button cbi-button-edit',
2725 dom
.append(tdEl
.lastElementChild
,
2727 'title': more_label
,
2728 'class': 'cbi-button cbi-button-edit',
2729 'click': ui
.createHandlerFn(this, 'renderMoreOptionsModal', section_id
)
2734 if (this.addremove
) {
2735 var btn_title
= this.titleFn('removebtntitle', section_id
);
2737 dom
.append(tdEl
.lastElementChild
,
2739 'title': btn_title
|| _('Delete'),
2740 'class': 'cbi-button cbi-button-remove',
2741 'click': ui
.createHandlerFn(this, 'handleRemove', section_id
),
2742 'disabled': this.map
.readonly
|| null
2743 }, [ btn_title
|| _('Delete') ])
2751 handleDragInit: function(ev
) {
2752 scope
.dragState
= { node
: ev
.target
};
2756 handleDragStart: function(ev
) {
2757 if (!scope
.dragState
|| !scope
.dragState
.node
.classList
.contains('drag-handle')) {
2758 scope
.dragState
= null;
2759 ev
.preventDefault();
2763 scope
.dragState
.node
= dom
.parent(scope
.dragState
.node
, '.tr');
2764 ev
.dataTransfer
.setData('text', 'drag');
2765 ev
.target
.style
.opacity
= 0.4;
2769 handleDragOver: function(ev
) {
2770 var n
= scope
.dragState
.targetNode
,
2771 r
= scope
.dragState
.rect
,
2772 t
= r
.top
+ r
.height
/ 2;
2774 if (ev
.clientY
<= t
) {
2775 n
.classList
.remove('drag-over-below');
2776 n
.classList
.add('drag-over-above');
2779 n
.classList
.remove('drag-over-above');
2780 n
.classList
.add('drag-over-below');
2783 ev
.dataTransfer
.dropEffect
= 'move';
2784 ev
.preventDefault();
2789 handleDragEnter: function(ev
) {
2790 scope
.dragState
.rect
= ev
.currentTarget
.getBoundingClientRect();
2791 scope
.dragState
.targetNode
= ev
.currentTarget
;
2795 handleDragLeave: function(ev
) {
2796 ev
.currentTarget
.classList
.remove('drag-over-above');
2797 ev
.currentTarget
.classList
.remove('drag-over-below');
2801 handleDragEnd: function(ev
) {
2804 n
.style
.opacity
= '';
2805 n
.classList
.add('flash');
2806 n
.parentNode
.querySelectorAll('.drag-over-above, .drag-over-below')
2807 .forEach(function(tr
) {
2808 tr
.classList
.remove('drag-over-above');
2809 tr
.classList
.remove('drag-over-below');
2814 handleDrop: function(ev
) {
2815 var s
= scope
.dragState
;
2817 if (s
.node
&& s
.targetNode
) {
2818 var config_name
= this.uciconfig
|| this.map
.config
,
2819 ref_node
= s
.targetNode
,
2822 if (ref_node
.classList
.contains('drag-over-below')) {
2823 ref_node
= ref_node
.nextElementSibling
;
2827 var sid1
= s
.node
.getAttribute('data-sid'),
2828 sid2
= s
.targetNode
.getAttribute('data-sid');
2830 s
.node
.parentNode
.insertBefore(s
.node
, ref_node
);
2831 this.map
.data
.move(config_name
, sid1
, sid2
, after
);
2834 scope
.dragState
= null;
2835 ev
.target
.style
.opacity
= '';
2836 ev
.stopPropagation();
2837 ev
.preventDefault();
2842 determineBackgroundColor: function(node
) {
2843 var r
= 255, g
= 255, b
= 255;
2846 var s
= window
.getComputedStyle(node
),
2847 c
= (s
.getPropertyValue('background-color') || '').replace(/ /g
, '');
2849 if (c
!= '' && c
!= 'transparent' && c
!= 'rgba(0,0,0,0)') {
2850 if (/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.test(c
)) {
2851 r
= parseInt(RegExp
.$1, 16);
2852 g
= parseInt(RegExp
.$2, 16);
2853 b
= parseInt(RegExp
.$3, 16);
2855 else if (/^rgba?\(([0-9]+),([0-9]+),([0-9]+)[,)]$/.test(c
)) {
2864 node
= node
.parentNode
;
2871 handleTouchMove: function(ev
) {
2872 if (!ev
.target
.classList
.contains('drag-handle'))
2875 var touchLoc
= ev
.targetTouches
[0],
2877 rowElem
= dom
.parent(rowBtn
, '.tr'),
2878 htmlElem
= document
.querySelector('html'),
2879 dragHandle
= document
.querySelector('.touchsort-element'),
2880 viewportHeight
= Math
.max(document
.documentElement
.clientHeight
, window
.innerHeight
|| 0);
2883 var rowRect
= rowElem
.getBoundingClientRect(),
2884 btnRect
= rowBtn
.getBoundingClientRect(),
2885 paddingLeft
= btnRect
.left
- rowRect
.left
,
2886 paddingRight
= rowRect
.right
- btnRect
.right
,
2887 colorBg
= this.determineBackgroundColor(rowElem
),
2888 colorFg
= (colorBg
[0] * 0.299 + colorBg
[1] * 0.587 + colorBg
[2] * 0.114) > 186 ? [ 0, 0, 0 ] : [ 255, 255, 255 ];
2890 dragHandle
= E('div', { 'class': 'touchsort-element' }, [
2891 E('strong', [ rowElem
.getAttribute('data-title') ]),
2892 rowBtn
.cloneNode(true)
2895 Object
.assign(dragHandle
.style
, {
2896 position
: 'absolute',
2897 boxShadow
: '0 0 3px rgba(%d, %d, %d, 1)'.format(colorFg
[0], colorFg
[1], colorFg
[2]),
2898 background
: 'rgba(%d, %d, %d, 0.8)'.format(colorBg
[0], colorBg
[1], colorBg
[2]),
2899 top
: rowRect
.top
+ 'px',
2900 left
: rowRect
.left
+ 'px',
2901 width
: rowRect
.width
+ 'px',
2902 height
: (rowBtn
.offsetHeight
+ 4) + 'px'
2905 Object
.assign(dragHandle
.firstElementChild
.style
, {
2906 position
: 'absolute',
2907 lineHeight
: dragHandle
.style
.height
,
2908 whiteSpace
: 'nowrap',
2910 textOverflow
: 'ellipsis',
2911 left
: (paddingRight
> paddingLeft
) ? '' : '5px',
2912 right
: (paddingRight
> paddingLeft
) ? '5px' : '',
2913 width
: (Math
.max(paddingLeft
, paddingRight
) - 10) + 'px'
2916 Object
.assign(dragHandle
.lastElementChild
.style
, {
2917 position
: 'absolute',
2919 left
: paddingLeft
+ 'px',
2920 width
: rowBtn
.offsetWidth
+ 'px'
2923 document
.body
.appendChild(dragHandle
);
2925 rowElem
.classList
.remove('flash');
2929 dragHandle
.style
.top
= (touchLoc
.pageY
- (parseInt(dragHandle
.style
.height
) / 2)) + 'px';
2931 rowElem
.parentNode
.querySelectorAll('[draggable]').forEach(function(tr
, i
, trs
) {
2932 var trRect
= tr
.getBoundingClientRect(),
2933 yTop
= trRect
.top
+ window
.scrollY
,
2934 yBottom
= trRect
.bottom
+ window
.scrollY
,
2935 yMiddle
= yTop
+ ((yBottom
- yTop
) / 2);
2937 tr
.classList
.remove('drag-over-above', 'drag-over-below');
2939 if ((i
== 0 || touchLoc
.pageY
>= yTop
) && touchLoc
.pageY
<= yMiddle
)
2940 tr
.classList
.add('drag-over-above');
2941 else if ((i
== (trs
.length
- 1) || touchLoc
.pageY
<= yBottom
) && touchLoc
.pageY
> yMiddle
)
2942 tr
.classList
.add('drag-over-below');
2945 /* prevent standard scrolling and scroll page when drag handle is
2946 * moved very close (~30px) to the viewport edge */
2948 ev
.preventDefault();
2950 if (touchLoc
.clientY
< 30)
2951 window
.requestAnimationFrame(function() { htmlElem
.scrollTop
-= 30 });
2952 else if (touchLoc
.clientY
> viewportHeight
- 30)
2953 window
.requestAnimationFrame(function() { htmlElem
.scrollTop
+= 30 });
2957 handleTouchEnd: function(ev
) {
2958 var rowElem
= dom
.parent(ev
.target
, '.tr'),
2959 htmlElem
= document
.querySelector('html'),
2960 dragHandle
= document
.querySelector('.touchsort-element'),
2961 targetElem
= rowElem
.parentNode
.querySelector('.drag-over-above, .drag-over-below'),
2962 viewportHeight
= Math
.max(document
.documentElement
.clientHeight
, window
.innerHeight
|| 0);
2968 var isBelow
= targetElem
.classList
.contains('drag-over-below');
2970 rowElem
.parentNode
.insertBefore(rowElem
, isBelow
? targetElem
.nextElementSibling
: targetElem
);
2973 this.uciconfig
|| this.map
.config
,
2974 rowElem
.getAttribute('data-sid'),
2975 targetElem
.getAttribute('data-sid'),
2978 window
.requestAnimationFrame(function() {
2979 var rowRect
= rowElem
.getBoundingClientRect();
2981 if (rowRect
.top
< 50)
2982 htmlElem
.scrollTop
= (htmlElem
.scrollTop
+ rowRect
.top
- 50);
2983 else if (rowRect
.bottom
> viewportHeight
- 50)
2984 htmlElem
.scrollTop
= (htmlElem
.scrollTop
+ viewportHeight
- 50 - rowRect
.height
);
2986 rowElem
.classList
.add('flash');
2989 targetElem
.classList
.remove('drag-over-above', 'drag-over-below');
2992 document
.body
.removeChild(dragHandle
);
2996 handleModalCancel: function(modalMap
, ev
) {
2997 var prevNode
= this.getPreviousModalMap(),
2998 resetTasks
= Promise
.resolve();
3001 var heading
= prevNode
.parentNode
.querySelector('h4'),
3002 prevMap
= dom
.findClassInstance(prevNode
);
3005 resetTasks
= resetTasks
3006 .then(L
.bind(prevMap
.load
, prevMap
))
3007 .then(L
.bind(prevMap
.reset
, prevMap
));
3009 prevMap
= prevMap
.parent
;
3012 prevNode
.classList
.add('flash');
3013 prevNode
.classList
.remove('hidden');
3014 prevNode
.parentNode
.removeChild(prevNode
.nextElementSibling
);
3016 heading
.removeChild(heading
.lastElementChild
);
3018 if (!this.getPreviousModalMap())
3020 .querySelector('div.right > button')
3021 .firstChild
.data
= _('Dismiss');
3031 handleModalSave: function(modalMap
, ev
) {
3032 var mapNode
= this.getActiveModalMap(),
3033 activeMap
= dom
.findClassInstance(mapNode
),
3034 saveTasks
= activeMap
.save(null, true);
3036 while (activeMap
.parent
) {
3037 activeMap
= activeMap
.parent
;
3038 saveTasks
= saveTasks
3039 .then(L
.bind(activeMap
.load
, activeMap
))
3040 .then(L
.bind(activeMap
.reset
, activeMap
));
3044 .then(L
.bind(this.handleModalCancel
, this, modalMap
, ev
))
3045 .catch(function() {});
3049 handleSort: function(ev
) {
3050 if (!ev
.target
.matches('th[data-sortable-row]'))
3054 descending
= (th
.getAttribute('data-sort-direction') == 'desc'),
3055 config_name
= this.uciconfig
|| this.map
.config
,
3059 ev
.currentTarget
.querySelectorAll('th').forEach(function(other_th
, i
) {
3060 if (other_th
!== th
)
3061 other_th
.removeAttribute('data-sort-direction');
3066 ev
.currentTarget
.parentNode
.querySelectorAll('tr.cbi-section-table-row').forEach(L
.bind(function(tr
, i
) {
3067 var sid
= tr
.getAttribute('data-sid'),
3068 opt
= tr
.childNodes
[index
].getAttribute('data-name'),
3069 val
= this.cfgvalue(sid
, opt
);
3071 tr
.querySelectorAll('.flash').forEach(function(n
) {
3072 n
.classList
.remove('flash')
3076 ui
.Table
.prototype.deriveSortKey((val
!= null) ? val
.trim() : ''),
3081 list
.sort(function(a
, b
) {
3083 return descending
? 1 : -1;
3086 return descending
? -1 : 1;
3091 window
.requestAnimationFrame(L
.bind(function() {
3092 var ref_sid
, cur_sid
;
3094 for (var i
= 0; i
< list
.length
; i
++) {
3095 list
[i
][1].childNodes
[index
].classList
.add('flash');
3096 th
.parentNode
.parentNode
.appendChild(list
[i
][1]);
3098 cur_sid
= list
[i
][1].getAttribute('data-sid');
3101 this.map
.data
.move(config_name
, cur_sid
, ref_sid
, true);
3106 th
.setAttribute('data-sort-direction', descending
? 'asc' : 'desc');
3111 * Add further options to the per-section instanced modal popup.
3113 * This function may be overwritten by user code to perform additional
3114 * setup steps before displaying the more options modal which is useful to
3115 * e.g. query additional data or to inject further option elements.
3117 * The default implementation of this function does nothing.
3120 * @param {LuCI.form.NamedSection} modalSection
3121 * The `NamedSection` instance about to be rendered in the modal popup.
3123 * @param {string} section_id
3124 * The ID of the underlying UCI section the modal popup belongs to.
3127 * The DOM event emitted by clicking the `More…` button.
3129 * @returns {*|Promise<*>}
3130 * Return values of this function are ignored but if a promise is returned,
3131 * it is run to completion before the rendering is continued, allowing
3132 * custom logic to perform asynchroneous work before the modal dialog
3135 addModalOptions: function(modalSection
, section_id
, ev
) {
3140 getActiveModalMap: function() {
3141 return document
.querySelector('body.modal-overlay-active > #modal_overlay > .modal.cbi-modal > .cbi-map:not(.hidden)');
3145 getPreviousModalMap: function() {
3146 var mapNode
= this.getActiveModalMap(),
3147 prevNode
= mapNode
? mapNode
.previousElementSibling
: null;
3149 return (prevNode
&& prevNode
.matches('.cbi-map.hidden')) ? prevNode
: null;
3153 renderMoreOptionsModal: function(section_id
, ev
) {
3154 var parent
= this.map
,
3155 title
= parent
.title
,
3157 m
= new CBIMap(this.map
.config
, null, null),
3158 s
= m
.section(CBINamedSection
, section_id
, this.sectiontype
);
3161 m
.section
= section_id
;
3162 m
.readonly
= parent
.readonly
;
3165 s
.tab_names
= this.tab_names
;
3167 if ((name
= this.titleFn('modaltitle', section_id
)) != null)
3169 else if ((name
= this.titleFn('sectiontitle', section_id
)) != null)
3170 title
= '%s - %s'.format(parent
.title
, name
);
3171 else if (!this.anonymous
)
3172 title
= '%s - %s'.format(parent
.title
, section_id
);
3174 for (var i
= 0; i
< this.children
.length
; i
++) {
3175 var o1
= this.children
[i
];
3177 if (o1
.modalonly
=== false)
3180 var o2
= s
.option(o1
.constructor, o1
.option
, o1
.title
, o1
.description
);
3183 if (!o1
.hasOwnProperty(k
))
3200 return Promise
.resolve(this.addModalOptions(s
, section_id
, ev
)).then(L
.bind(m
.render
, m
)).then(L
.bind(function(nodes
) {
3201 var mapNode
= this.getActiveModalMap(),
3202 activeMap
= mapNode
? dom
.findClassInstance(mapNode
) : null;
3204 if (activeMap
&& (activeMap
.parent
!== parent
|| activeMap
.section
!== section_id
)) {
3206 .querySelector('h4')
3207 .appendChild(E('span', title
? ' » ' + title
: ''));
3210 .querySelector('div.right > button')
3211 .firstChild
.data
= _('Back');
3213 mapNode
.classList
.add('hidden');
3214 mapNode
.parentNode
.insertBefore(nodes
, mapNode
.nextElementSibling
);
3216 return activeMap
.save(null, true).then(function() {
3217 nodes
.classList
.add('flash');
3221 ui
.showModal(title
, [
3223 E('div', { 'class': 'right' }, [
3225 'class': 'cbi-button',
3226 'click': ui
.createHandlerFn(this, 'handleModalCancel', m
)
3227 }, [ _('Dismiss') ]), ' ',
3229 'class': 'cbi-button cbi-button-positive important',
3230 'click': ui
.createHandlerFn(this, 'handleModalSave', m
),
3231 'disabled': m
.readonly
|| null
3236 }, this)).catch(L
.error
);
3241 * @class GridSection
3242 * @memberof LuCI.form
3243 * @augments LuCI.form.TableSection
3247 * The `GridSection` class maps all or - if `filter()` is overwritten - a
3248 * subset of the underlying UCI configuration sections of a given type.
3250 * A grid section functions similar to a {@link LuCI.form.TableSection} but
3251 * supports tabbing in the modal overlay. Option elements added with
3252 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
3253 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
3254 * are displayed in the modal popup.
3256 * Another important difference is that the table cells show a readonly text
3257 * preview of the corresponding option elements by default, unless the child
3258 * option element is explicitely made writable by setting the `editable`
3259 * property to `true`.
3261 * Additionally, the grid section honours a `modalonly` property of child
3262 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
3263 * documentation for details.
3265 * Layout wise, a grid section looks mostly identical to table sections.
3267 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3268 * The configuration form this section is added to. It is automatically passed
3269 * by [section()]{@link LuCI.form.Map#section}.
3271 * @param {string} section_type
3272 * The type of the UCI section to map.
3274 * @param {string} [title]
3275 * The title caption of the form section element.
3277 * @param {string} [description]
3278 * The description text of the form section element.
3280 var CBIGridSection
= CBITableSection
.extend(/** @lends LuCI.form.GridSection.prototype */ {
3282 * Add an option tab to the section.
3284 * The modal option elements of a grid section may be divided into multiple
3285 * tabs to provide a better overview to the user.
3287 * Before options can be moved into a tab pane, the corresponding tab
3288 * has to be defined first, which is done by calling this function.
3290 * Note that tabs are only effective in modal popups, options added with
3291 * `option()` will not be assigned to a specific tab and are rendered in
3292 * the table view only.
3294 * @param {string} name
3295 * The name of the tab to register. It may be freely chosen and just serves
3296 * as an identifier to differentiate tabs.
3298 * @param {string} title
3299 * The human readable caption of the tab.
3301 * @param {string} [description]
3302 * An additional description text for the corresponding tab pane. It is
3303 * displayed as text paragraph below the tab but before the tab pane
3304 * contents. If omitted, no description will be rendered.
3307 * Throws an exeption if a tab with the same `name` already exists.
3309 tab: function(name
, title
, description
) {
3310 CBIAbstractSection
.prototype.tab
.call(this, name
, title
, description
);
3314 handleAdd: function(ev
, name
) {
3315 var config_name
= this.uciconfig
|| this.map
.config
,
3316 section_id
= this.map
.data
.add(config_name
, this.sectiontype
, name
),
3317 mapNode
= this.getPreviousModalMap(),
3318 prevMap
= mapNode
? dom
.findClassInstance(mapNode
) : this.map
;
3320 prevMap
.addedSection
= section_id
;
3322 return this.renderMoreOptionsModal(section_id
);
3326 handleModalSave: function(/* ... */) {
3327 var mapNode
= this.getPreviousModalMap(),
3328 prevMap
= mapNode
? dom
.findClassInstance(mapNode
) : this.map
;
3330 return this.super('handleModalSave', arguments
)
3331 .then(function() { delete prevMap
.addedSection
});
3335 handleModalCancel: function(/* ... */) {
3336 var config_name
= this.uciconfig
|| this.map
.config
,
3337 mapNode
= this.getPreviousModalMap(),
3338 prevMap
= mapNode
? dom
.findClassInstance(mapNode
) : this.map
;
3340 if (prevMap
.addedSection
!= null) {
3341 this.map
.data
.remove(config_name
, prevMap
.addedSection
);
3342 delete prevMap
.addedSection
;
3345 return this.super('handleModalCancel', arguments
);
3349 renderUCISection: function(section_id
) {
3350 return this.renderOptions(null, section_id
);
3354 renderChildren: function(tab_name
, section_id
, in_table
) {
3355 var tasks
= [], index
= 0;
3357 for (var i
= 0, opt
; (opt
= this.children
[i
]) != null; i
++) {
3358 if (opt
.disable
|| opt
.modalonly
)
3362 tasks
.push(opt
.render(index
++, section_id
, in_table
));
3364 tasks
.push(this.renderTextValue(section_id
, opt
));
3367 return Promise
.all(tasks
);
3371 renderTextValue: function(section_id
, opt
) {
3372 var title
= this.stripTags(opt
.title
).trim(),
3373 descr
= this.stripTags(opt
.description
).trim(),
3374 value
= opt
.textvalue(section_id
);
3377 'class': 'td cbi-value-field',
3378 'data-title': (title
!= '') ? title
: null,
3379 'data-description': (descr
!= '') ? descr
: null,
3380 'data-name': opt
.option
,
3381 'data-widget': opt
.typename
|| opt
.__name__
3382 }, (value
!= null) ? value
: E('em', _('none')));
3386 renderHeaderRows: function(section_id
) {
3387 return this.super('renderHeaderRows', [ NaN
, true ]);
3391 renderRowActions: function(section_id
) {
3392 return this.super('renderRowActions', [ section_id
, _('Edit') ]);
3397 var section_ids
= this.cfgsections(),
3400 if (Array
.isArray(this.children
)) {
3401 for (var i
= 0; i
< section_ids
.length
; i
++) {
3402 for (var j
= 0; j
< this.children
.length
; j
++) {
3403 if (!this.children
[j
].editable
|| this.children
[j
].modalonly
)
3406 tasks
.push(this.children
[j
].parse(section_ids
[i
]));
3411 return Promise
.all(tasks
);
3416 * @class NamedSection
3417 * @memberof LuCI.form
3418 * @augments LuCI.form.AbstractSection
3422 * The `NamedSection` class maps exactly one UCI section instance which is
3423 * specified when constructing the class instance.
3425 * Layout and functionality wise, a named section is essentially a
3426 * `TypedSection` which allows exactly one section node.
3428 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3429 * The configuration form this section is added to. It is automatically passed
3430 * by [section()]{@link LuCI.form.Map#section}.
3432 * @param {string} section_id
3433 * The name (ID) of the UCI section to map.
3435 * @param {string} section_type
3436 * The type of the UCI section to map.
3438 * @param {string} [title]
3439 * The title caption of the form section element.
3441 * @param {string} [description]
3442 * The description text of the form section element.
3444 var CBINamedSection
= CBIAbstractSection
.extend(/** @lends LuCI.form.NamedSection.prototype */ {
3445 __name__
: 'CBI.NamedSection',
3446 __init__: function(map
, section_id
/*, ... */) {
3447 this.super('__init__', this.varargs(arguments
, 2, map
));
3449 this.section
= section_id
;
3453 * If set to `true`, the user may remove or recreate the sole mapped
3454 * configuration instance from the form section widget, otherwise only a
3455 * preexisting section may be edited. The default is `false`.
3457 * @name LuCI.form.NamedSection.prototype#addremove
3463 * Override the UCI configuration name to read the section IDs from. By
3464 * default, the configuration name is inherited from the parent `Map`.
3465 * By setting this property, a deviating configuration may be specified.
3466 * The default is `null`, means inheriting from the parent form.
3468 * @name LuCI.form.NamedSection.prototype#uciconfig
3474 * The `NamedSection` class overwrites the generic `cfgsections()`
3475 * implementation to return a one-element array containing the mapped
3476 * section ID as sole element. User code should not normally change this.
3478 * @returns {string[]}
3479 * Returns a one-element array containing the mapped section ID.
3481 cfgsections: function() {
3482 return [ this.section
];
3486 handleAdd: function(ev
) {
3487 var section_id
= this.section
,
3488 config_name
= this.uciconfig
|| this.map
.config
;
3490 this.map
.data
.add(config_name
, this.sectiontype
, section_id
);
3491 return this.map
.save(null, true);
3495 handleRemove: function(ev
) {
3496 var section_id
= this.section
,
3497 config_name
= this.uciconfig
|| this.map
.config
;
3499 this.map
.data
.remove(config_name
, section_id
);
3500 return this.map
.save(null, true);
3504 renderContents: function(data
) {
3505 var ucidata
= data
[0], nodes
= data
[1],
3506 section_id
= this.section
,
3507 config_name
= this.uciconfig
|| this.map
.config
,
3508 sectionEl
= E('div', {
3509 'id': ucidata
? null : 'cbi-%s-%s'.format(config_name
, section_id
),
3510 'class': 'cbi-section',
3511 'data-tab': (this.map
.tabbed
&& !this.parentoption
) ? this.sectiontype
: null,
3512 'data-tab-title': (this.map
.tabbed
&& !this.parentoption
) ? this.title
|| this.sectiontype
: null
3515 if (typeof(this.title
) === 'string' && this.title
!== '')
3516 sectionEl
.appendChild(E('h3', {}, this.title
));
3518 if (typeof(this.description
) === 'string' && this.description
!== '')
3519 sectionEl
.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description
));
3522 if (this.addremove
) {
3523 sectionEl
.appendChild(
3524 E('div', { 'class': 'cbi-section-remove right' },
3526 'class': 'cbi-button',
3527 'click': ui
.createHandlerFn(this, 'handleRemove'),
3528 'disabled': this.map
.readonly
|| null
3529 }, [ _('Delete') ])));
3532 sectionEl
.appendChild(E('div', {
3533 'id': 'cbi-%s-%s'.format(config_name
, section_id
),
3535 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3536 'data-section-id': section_id
3539 else if (this.addremove
) {
3540 sectionEl
.appendChild(
3542 'class': 'cbi-button cbi-button-add',
3543 'click': ui
.createHandlerFn(this, 'handleAdd'),
3544 'disabled': this.map
.readonly
|| null
3548 dom
.bindClassInstance(sectionEl
, this);
3554 render: function() {
3555 var config_name
= this.uciconfig
|| this.map
.config
,
3556 section_id
= this.section
;
3558 return Promise
.all([
3559 this.map
.data
.get(config_name
, section_id
),
3560 this.renderUCISection(section_id
)
3561 ]).then(this.renderContents
.bind(this));
3567 * @memberof LuCI.form
3568 * @augments LuCI.form.AbstractValue
3572 * The `Value` class represents a simple one-line form input using the
3573 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3574 * {@link LuCI.ui.Combobox} class as underlying widget.
3576 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3577 * The configuration form this section is added to. It is automatically passed
3578 * by [option()]{@link LuCI.form.AbstractSection#option} or
3579 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3580 * option to the section.
3582 * @param {LuCI.form.AbstractSection} section
3583 * The configuration section this option is added to. It is automatically passed
3584 * by [option()]{@link LuCI.form.AbstractSection#option} or
3585 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3586 * option to the section.
3588 * @param {string} option
3589 * The name of the UCI option to map.
3591 * @param {string} [title]
3592 * The title caption of the option element.
3594 * @param {string} [description]
3595 * The description text of the option element.
3597 var CBIValue
= CBIAbstractValue
.extend(/** @lends LuCI.form.Value.prototype */ {
3598 __name__
: 'CBI.Value',
3601 * If set to `true`, the field is rendered as password input, otherwise
3602 * as plain text input.
3604 * @name LuCI.form.Value.prototype#password
3610 * Set a placeholder string to use when the input field is empty.
3612 * @name LuCI.form.Value.prototype#placeholder
3618 * Add a predefined choice to the form option. By adding one or more
3619 * choices, the plain text input field is turned into a combobox widget
3620 * which prompts the user to select a predefined choice, or to enter a
3623 * @param {string} key
3624 * The choice value to add.
3626 * @param {Node|string} value
3627 * The caption for the choice value. May be a DOM node, a document fragment
3628 * or a plain text string. If omitted, the `key` value is used as caption.
3630 value: function(key
, val
) {
3631 this.keylist
= this.keylist
|| [];
3632 this.keylist
.push(String(key
));
3634 this.vallist
= this.vallist
|| [];
3635 this.vallist
.push(dom
.elem(val
) ? val
: String(val
!= null ? val
: key
));
3639 render: function(option_index
, section_id
, in_table
) {
3640 return Promise
.resolve(this.cfgvalue(section_id
))
3641 .then(this.renderWidget
.bind(this, section_id
, option_index
))
3642 .then(this.renderFrame
.bind(this, section_id
, in_table
, option_index
));
3646 handleValueChange: function(section_id
, state
, ev
) {
3647 if (typeof(this.onchange
) != 'function')
3650 var value
= this.formvalue(section_id
);
3652 if (isEqual(value
, state
.previousValue
))
3655 state
.previousValue
= value
;
3656 this.onchange
.call(this, ev
, section_id
, value
);
3660 renderFrame: function(section_id
, in_table
, option_index
, nodes
) {
3661 var config_name
= this.uciconfig
|| this.section
.uciconfig
|| this.map
.config
,
3662 depend_list
= this.transformDepList(section_id
),
3666 var title
= this.stripTags(this.title
).trim();
3667 optionEl
= E('td', {
3668 'class': 'td cbi-value-field',
3669 'data-title': (title
!= '') ? title
: null,
3670 'data-description': this.stripTags(this.description
).trim(),
3671 'data-name': this.option
,
3672 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3674 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3675 'data-index': option_index
,
3676 'data-depends': depend_list
,
3677 'data-field': this.cbid(section_id
)
3681 optionEl
= E('div', {
3682 'class': 'cbi-value',
3683 'id': 'cbi-%s-%s-%s'.format(config_name
, section_id
, this.option
),
3684 'data-index': option_index
,
3685 'data-depends': depend_list
,
3686 'data-field': this.cbid(section_id
),
3687 'data-name': this.option
,
3688 'data-widget': this.typename
|| (this.template
? this.template
.replace(/^.+\//, '') : null) || this.__name__
3691 if (this.last_child
)
3692 optionEl
.classList
.add('cbi-value-last');
3694 if (typeof(this.title
) === 'string' && this.title
!== '') {
3695 optionEl
.appendChild(E('label', {
3696 'class': 'cbi-value-title',
3697 'for': 'widget.cbid.%s.%s.%s'.format(config_name
, section_id
, this.option
),
3698 'click': function(ev
) {
3699 var node
= ev
.currentTarget
,
3700 elem
= node
.nextElementSibling
.querySelector('#' + node
.getAttribute('for')) || node
.nextElementSibling
.querySelector('[data-widget-id="' + node
.getAttribute('for') + '"]');
3708 this.titleref
? E('a', {
3709 'class': 'cbi-title-ref',
3710 'href': this.titleref
,
3711 'title': this.titledesc
|| _('Go to relevant configuration page')
3712 }, this.title
) : this.title
));
3714 optionEl
.appendChild(E('div', { 'class': 'cbi-value-field' }));
3719 (optionEl
.lastChild
|| optionEl
).appendChild(nodes
);
3721 if (!in_table
&& typeof(this.description
) === 'string' && this.description
!== '')
3722 dom
.append(optionEl
.lastChild
|| optionEl
,
3723 E('div', { 'class': 'cbi-value-description' }, this.description
));
3725 if (depend_list
&& depend_list
.length
)
3726 optionEl
.classList
.add('hidden');
3728 optionEl
.addEventListener('widget-change',
3729 L
.bind(this.map
.checkDepends
, this.map
));
3731 optionEl
.addEventListener('widget-change',
3732 L
.bind(this.handleValueChange
, this, section_id
, {}));
3734 dom
.bindClassInstance(optionEl
, this);
3740 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3741 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3742 choices
= this.transformChoices(),
3746 var placeholder
= (this.optional
|| this.rmempty
)
3747 ? E('em', _('unspecified')) : _('-- Please choose --');
3749 widget
= new ui
.Combobox(Array
.isArray(value
) ? value
.join(' ') : value
, choices
, {
3750 id
: this.cbid(section_id
),
3752 optional
: this.optional
|| this.rmempty
,
3753 datatype
: this.datatype
,
3754 select_placeholder
: this.placeholder
|| placeholder
,
3755 validate
: L
.bind(this.validate
, this, section_id
),
3756 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3760 widget
= new ui
.Textfield(Array
.isArray(value
) ? value
.join(' ') : value
, {
3761 id
: this.cbid(section_id
),
3762 password
: this.password
,
3763 optional
: this.optional
|| this.rmempty
,
3764 datatype
: this.datatype
,
3765 placeholder
: this.placeholder
,
3766 validate
: L
.bind(this.validate
, this, section_id
),
3767 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3771 return widget
.render();
3776 * @class DynamicList
3777 * @memberof LuCI.form
3778 * @augments LuCI.form.Value
3782 * The `DynamicList` class represents a multi value widget allowing the user
3783 * to enter multiple unique values, optionally selected from a set of
3784 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3786 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3787 * The configuration form this section is added to. It is automatically passed
3788 * by [option()]{@link LuCI.form.AbstractSection#option} or
3789 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3790 * option to the section.
3792 * @param {LuCI.form.AbstractSection} section
3793 * The configuration section this option is added to. It is automatically passed
3794 * by [option()]{@link LuCI.form.AbstractSection#option} or
3795 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3796 * option to the section.
3798 * @param {string} option
3799 * The name of the UCI option to map.
3801 * @param {string} [title]
3802 * The title caption of the option element.
3804 * @param {string} [description]
3805 * The description text of the option element.
3807 var CBIDynamicList
= CBIValue
.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3808 __name__
: 'CBI.DynamicList',
3811 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3812 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
3813 choices
= this.transformChoices(),
3814 items
= L
.toArray(value
);
3816 var widget
= new ui
.DynamicList(items
, choices
, {
3817 id
: this.cbid(section_id
),
3819 optional
: this.optional
|| this.rmempty
,
3820 datatype
: this.datatype
,
3821 placeholder
: this.placeholder
,
3822 validate
: L
.bind(this.validate
, this, section_id
),
3823 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3826 return widget
.render();
3832 * @memberof LuCI.form
3833 * @augments LuCI.form.Value
3837 * The `ListValue` class implements a simple static HTML select element
3838 * allowing the user to chose a single value from a set of predefined choices.
3839 * It builds upon the {@link LuCI.ui.Select} widget.
3841 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3842 * The configuration form this section is added to. It is automatically passed
3843 * by [option()]{@link LuCI.form.AbstractSection#option} or
3844 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3845 * option to the section.
3847 * @param {LuCI.form.AbstractSection} section
3848 * The configuration section this option is added to. It is automatically passed
3849 * by [option()]{@link LuCI.form.AbstractSection#option} or
3850 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3851 * option to the section.
3853 * @param {string} option
3854 * The name of the UCI option to map.
3856 * @param {string} [title]
3857 * The title caption of the option element.
3859 * @param {string} [description]
3860 * The description text of the option element.
3862 var CBIListValue
= CBIValue
.extend(/** @lends LuCI.form.ListValue.prototype */ {
3863 __name__
: 'CBI.ListValue',
3865 __init__: function() {
3866 this.super('__init__', arguments
);
3867 this.widget
= 'select';
3868 this.orientation
= 'horizontal';
3873 * Set the size attribute of the underlying HTML select element.
3875 * @name LuCI.form.ListValue.prototype#size
3881 * Set the type of the underlying form controls.
3883 * May be one of `select` or `radio`. If set to `select`, an HTML
3884 * select element is rendered, otherwise a collection of `radio`
3887 * @name LuCI.form.ListValue.prototype#widget
3893 * Set the orientation of the underlying radio or checkbox elements.
3895 * May be one of `horizontal` or `vertical`. Only applies to non-select
3898 * @name LuCI.form.ListValue.prototype#orientation
3900 * @default horizontal
3904 renderWidget: function(section_id
, option_index
, cfgvalue
) {
3905 var choices
= this.transformChoices();
3906 var widget
= new ui
.Select((cfgvalue
!= null) ? cfgvalue
: this.default, choices
, {
3907 id
: this.cbid(section_id
),
3910 widget
: this.widget
,
3911 optional
: this.optional
,
3912 orientation
: this.orientation
,
3913 placeholder
: this.placeholder
,
3914 validate
: L
.bind(this.validate
, this, section_id
),
3915 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
3918 return widget
.render();
3924 * @memberof LuCI.form
3925 * @augments LuCI.form.Value
3929 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3930 * implement a simple checkbox element.
3932 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3933 * The configuration form this section is added to. It is automatically passed
3934 * by [option()]{@link LuCI.form.AbstractSection#option} or
3935 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3936 * option to the section.
3938 * @param {LuCI.form.AbstractSection} section
3939 * The configuration section this option is added to. It is automatically passed
3940 * by [option()]{@link LuCI.form.AbstractSection#option} or
3941 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3942 * option to the section.
3944 * @param {string} option
3945 * The name of the UCI option to map.
3947 * @param {string} [title]
3948 * The title caption of the option element.
3950 * @param {string} [description]
3951 * The description text of the option element.
3953 var CBIFlagValue
= CBIValue
.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3954 __name__
: 'CBI.FlagValue',
3956 __init__: function() {
3957 this.super('__init__', arguments
);
3960 this.disabled
= '0';
3961 this.default = this.disabled
;
3965 * Sets the input value to use for the checkbox checked state.
3967 * @name LuCI.form.FlagValue.prototype#enabled
3973 * Sets the input value to use for the checkbox unchecked state.
3975 * @name LuCI.form.FlagValue.prototype#disabled
3981 * Set a tooltip for the flag option.
3983 * If set to a string, it will be used as-is as a tooltip.
3985 * If set to a function, the function will be invoked and the return
3986 * value will be shown as a tooltip. If the return value of the function
3987 * is `null` no tooltip will be set.
3989 * @name LuCI.form.TypedSection.prototype#tooltip
3990 * @type string|function
3995 * Set a tooltip icon.
3997 * If set, this icon will be shown for the default one.
3998 * This could also be a png icon from the resources directory.
4000 * @name LuCI.form.TypedSection.prototype#tooltipicon
4006 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4009 if (typeof(this.tooltip
) == 'function')
4010 tooltip
= this.tooltip
.apply(this, [section_id
]);
4011 else if (typeof(this.tooltip
) == 'string')
4012 tooltip
= (arguments
.length
> 1) ? ''.format
.apply(this.tooltip
, this.varargs(arguments
, 1)) : this.tooltip
;
4014 var widget
= new ui
.Checkbox((cfgvalue
!= null) ? cfgvalue
: this.default, {
4015 id
: this.cbid(section_id
),
4016 value_enabled
: this.enabled
,
4017 value_disabled
: this.disabled
,
4018 validate
: L
.bind(this.validate
, this, section_id
),
4020 tooltipicon
: this.tooltipicon
,
4021 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4024 return widget
.render();
4028 * Query the checked state of the underlying checkbox widget and return
4029 * either the `enabled` or the `disabled` property value, depending on
4030 * the checked state.
4034 formvalue: function(section_id
) {
4035 var elem
= this.getUIElement(section_id
),
4036 checked
= elem
? elem
.isChecked() : false;
4037 return checked
? this.enabled
: this.disabled
;
4041 * Query the checked state of the underlying checkbox widget and return
4042 * either a localized `Yes` or `No` string, depending on the checked state.
4046 textvalue: function(section_id
) {
4047 var cval
= this.cfgvalue(section_id
);
4050 cval
= this.default;
4052 return (cval
== this.enabled
) ? _('Yes') : _('No');
4056 parse: function(section_id
) {
4057 if (this.isActive(section_id
)) {
4058 var fval
= this.formvalue(section_id
);
4060 if (!this.isValid(section_id
)) {
4061 var title
= this.stripTags(this.title
).trim();
4062 var error
= this.getValidationError(section_id
);
4063 return Promise
.reject(new TypeError(
4064 _('Option "%s" contains an invalid input value.').format(title
|| this.option
) + ' ' + error
));
4067 if (fval
== this.default && (this.optional
|| this.rmempty
))
4068 return Promise
.resolve(this.remove(section_id
));
4070 return Promise
.resolve(this.write(section_id
, fval
));
4072 else if (!this.retain
) {
4073 return Promise
.resolve(this.remove(section_id
));
4080 * @memberof LuCI.form
4081 * @augments LuCI.form.DynamicList
4085 * The `MultiValue` class is a modified variant of the `DynamicList` element
4086 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
4087 * select dropdown element.
4089 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4090 * The configuration form this section is added to. It is automatically passed
4091 * by [option()]{@link LuCI.form.AbstractSection#option} or
4092 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4093 * option to the section.
4095 * @param {LuCI.form.AbstractSection} section
4096 * The configuration section this option is added to. It is automatically passed
4097 * by [option()]{@link LuCI.form.AbstractSection#option} or
4098 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4099 * option to the section.
4101 * @param {string} option
4102 * The name of the UCI option to map.
4104 * @param {string} [title]
4105 * The title caption of the option element.
4107 * @param {string} [description]
4108 * The description text of the option element.
4110 var CBIMultiValue
= CBIDynamicList
.extend(/** @lends LuCI.form.MultiValue.prototype */ {
4111 __name__
: 'CBI.MultiValue',
4113 __init__: function() {
4114 this.super('__init__', arguments
);
4115 this.placeholder
= _('-- Please choose --');
4119 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
4120 * property of the underlying dropdown widget. If omitted, the value of
4121 * the `size` property is used or `3` when `size` is unspecified as well.
4123 * @name LuCI.form.MultiValue.prototype#display_size
4129 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
4130 * property of the underlying dropdown widget. If omitted, the value of
4131 * the `size` property is used or `-1` when `size` is unspecified as well.
4133 * @name LuCI.form.MultiValue.prototype#dropdown_size
4139 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4140 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
4141 choices
= this.transformChoices();
4143 var widget
= new ui
.Dropdown(L
.toArray(value
), choices
, {
4144 id
: this.cbid(section_id
),
4147 optional
: this.optional
|| this.rmempty
,
4148 select_placeholder
: this.placeholder
,
4149 display_items
: this.display_size
|| this.size
|| 3,
4150 dropdown_items
: this.dropdown_size
|| this.size
|| -1,
4151 validate
: L
.bind(this.validate
, this, section_id
),
4152 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4155 return widget
.render();
4161 * @memberof LuCI.form
4162 * @augments LuCI.form.Value
4166 * The `TextValue` class implements a multi-line textarea input using
4167 * {@link LuCI.ui.Textarea}.
4169 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4170 * The configuration form this section is added to. It is automatically passed
4171 * by [option()]{@link LuCI.form.AbstractSection#option} or
4172 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4173 * option to the section.
4175 * @param {LuCI.form.AbstractSection} section
4176 * The configuration section this option is added to. It is automatically passed
4177 * by [option()]{@link LuCI.form.AbstractSection#option} or
4178 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4179 * option to the section.
4181 * @param {string} option
4182 * The name of the UCI option to map.
4184 * @param {string} [title]
4185 * The title caption of the option element.
4187 * @param {string} [description]
4188 * The description text of the option element.
4190 var CBITextValue
= CBIValue
.extend(/** @lends LuCI.form.TextValue.prototype */ {
4191 __name__
: 'CBI.TextValue',
4197 * Enforces the use of a monospace font for the textarea contents when set
4200 * @name LuCI.form.TextValue.prototype#monospace
4206 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
4207 * property of the underlying textarea widget.
4209 * @name LuCI.form.TextValue.prototype#cols
4215 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
4216 * property of the underlying textarea widget.
4218 * @name LuCI.form.TextValue.prototype#rows
4224 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
4225 * property of the underlying textarea widget.
4227 * @name LuCI.form.TextValue.prototype#wrap
4233 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4234 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default;
4236 var widget
= new ui
.Textarea(value
, {
4237 id
: this.cbid(section_id
),
4238 optional
: this.optional
|| this.rmempty
,
4239 placeholder
: this.placeholder
,
4240 monospace
: this.monospace
,
4244 validate
: L
.bind(this.validate
, this, section_id
),
4245 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4248 return widget
.render();
4254 * @memberof LuCI.form
4255 * @augments LuCI.form.Value
4259 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4260 * renders the underlying UCI option or default value as readonly text.
4262 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4263 * The configuration form this section is added to. It is automatically passed
4264 * by [option()]{@link LuCI.form.AbstractSection#option} or
4265 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4266 * option to the section.
4268 * @param {LuCI.form.AbstractSection} section
4269 * The configuration section this option is added to. It is automatically passed
4270 * by [option()]{@link LuCI.form.AbstractSection#option} or
4271 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4272 * option to the section.
4274 * @param {string} option
4275 * The name of the UCI option to map.
4277 * @param {string} [title]
4278 * The title caption of the option element.
4280 * @param {string} [description]
4281 * The description text of the option element.
4283 var CBIDummyValue
= CBIValue
.extend(/** @lends LuCI.form.DummyValue.prototype */ {
4284 __name__
: 'CBI.DummyValue',
4287 * Set an URL which is opened when clicking on the dummy value text.
4289 * By setting this property, the dummy value text is wrapped in an `<a>`
4290 * element with the property value used as `href` attribute.
4292 * @name LuCI.form.DummyValue.prototype#href
4298 * Treat the UCI option value (or the `default` property value) as HTML.
4300 * By default, the value text is HTML escaped before being rendered as
4301 * text. In some cases it may be needed to actually interpret and render
4302 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
4304 * @name LuCI.form.DummyValue.prototype#rawhtml
4310 * Render the UCI option value as hidden using the HTML display: none style property.
4312 * By default, the value is displayed
4314 * @name LuCI.form.DummyValue.prototype#hidden
4320 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4321 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
4322 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
4323 outputEl
= E('div', { 'style': this.hidden
? 'display:none' : null });
4325 if (this.href
&& !((this.readonly
!= null) ? this.readonly
: this.map
.readonly
))
4326 outputEl
.appendChild(E('a', { 'href': this.href
}));
4328 dom
.append(outputEl
.lastChild
|| outputEl
,
4329 this.rawhtml
? value
: [ value
]);
4338 remove: function() {},
4341 write: function() {}
4345 * @class ButtonValue
4346 * @memberof LuCI.form
4347 * @augments LuCI.form.Value
4351 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4352 * renders the underlying UCI option or default value as readonly text.
4354 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4355 * The configuration form this section is added to. It is automatically passed
4356 * by [option()]{@link LuCI.form.AbstractSection#option} or
4357 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4358 * option to the section.
4360 * @param {LuCI.form.AbstractSection} section
4361 * The configuration section this option is added to. It is automatically passed
4362 * by [option()]{@link LuCI.form.AbstractSection#option} or
4363 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4364 * option to the section.
4366 * @param {string} option
4367 * The name of the UCI option to map.
4369 * @param {string} [title]
4370 * The title caption of the option element.
4372 * @param {string} [description]
4373 * The description text of the option element.
4375 var CBIButtonValue
= CBIValue
.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
4376 __name__
: 'CBI.ButtonValue',
4379 * Override the rendered button caption.
4381 * By default, the option title - which is passed as fourth argument to the
4382 * constructor - is used as caption for the button element. When setting
4383 * this property to a string, it is used as `String.format()` pattern with
4384 * the underlying UCI section name passed as first format argument. When
4385 * set to a function, it is invoked passing the section ID as sole argument
4386 * and the resulting return value is converted to a string before being
4387 * used as button caption.
4389 * The default is `null`, means the option title is used as caption.
4391 * @name LuCI.form.ButtonValue.prototype#inputtitle
4392 * @type string|function
4397 * Override the button style class.
4399 * By setting this property, a specific `cbi-button-*` CSS class can be
4400 * selected to influence the style of the resulting button.
4402 * Suitable values which are implemented by most themes are `positive`,
4403 * `negative` and `primary`.
4405 * The default is `null`, means a neutral button styling is used.
4407 * @name LuCI.form.ButtonValue.prototype#inputstyle
4413 * Override the button click action.
4415 * By default, the underlying UCI option (or default property) value is
4416 * copied into a hidden field tied to the button element and the save
4417 * action is triggered on the parent form element.
4419 * When this property is set to a function, it is invoked instead of
4420 * performing the default actions. The handler function will receive the
4421 * DOM click element as first and the underlying configuration section ID
4422 * as second argument.
4424 * @name LuCI.form.ButtonValue.prototype#onclick
4430 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4431 var value
= (cfgvalue
!= null) ? cfgvalue
: this.default,
4432 hiddenEl
= new ui
.Hiddenfield(value
, { id
: this.cbid(section_id
) }),
4433 outputEl
= E('div'),
4434 btn_title
= this.titleFn('inputtitle', section_id
) || this.titleFn('title', section_id
);
4436 if (value
!== false)
4437 dom
.content(outputEl
, [
4439 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle
|| 'button'),
4440 'click': ui
.createHandlerFn(this, function(section_id
, ev
) {
4442 return this.onclick(ev
, section_id
);
4444 ev
.currentTarget
.parentNode
.nextElementSibling
.value
= value
;
4445 return this.map
.save();
4447 'disabled': ((this.readonly
!= null) ? this.readonly
: this.map
.readonly
) || null
4451 dom
.content(outputEl
, ' - ');
4461 * @class HiddenValue
4462 * @memberof LuCI.form
4463 * @augments LuCI.form.Value
4467 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
4469 * Hidden value widgets used to be necessary in legacy code which actually
4470 * submitted the underlying HTML form the server. With client side handling of
4471 * forms, there are more efficient ways to store hidden state data.
4473 * Since this widget has no visible content, the title and description values
4474 * of this form element should be set to `null` as well to avoid a broken or
4475 * distorted form layout when rendering the option element.
4477 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4478 * The configuration form this section is added to. It is automatically passed
4479 * by [option()]{@link LuCI.form.AbstractSection#option} or
4480 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4481 * option to the section.
4483 * @param {LuCI.form.AbstractSection} section
4484 * The configuration section this option is added to. It is automatically passed
4485 * by [option()]{@link LuCI.form.AbstractSection#option} or
4486 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4487 * option to the section.
4489 * @param {string} option
4490 * The name of the UCI option to map.
4492 * @param {string} [title]
4493 * The title caption of the option element.
4495 * @param {string} [description]
4496 * The description text of the option element.
4498 var CBIHiddenValue
= CBIValue
.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
4499 __name__
: 'CBI.HiddenValue',
4502 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4503 var widget
= new ui
.Hiddenfield((cfgvalue
!= null) ? cfgvalue
: this.default, {
4504 id
: this.cbid(section_id
)
4507 return widget
.render();
4513 * @memberof LuCI.form
4514 * @augments LuCI.form.Value
4518 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
4519 * offers the ability to browse, upload and select remote files.
4521 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4522 * The configuration form this section is added to. It is automatically passed
4523 * by [option()]{@link LuCI.form.AbstractSection#option} or
4524 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4525 * option to the section.
4527 * @param {LuCI.form.AbstractSection} section
4528 * The configuration section this option is added to. It is automatically passed
4529 * by [option()]{@link LuCI.form.AbstractSection#option} or
4530 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4531 * option to the section.
4533 * @param {string} option
4534 * The name of the UCI option to map.
4536 * @param {string} [title]
4537 * The title caption of the option element.
4539 * @param {string} [description]
4540 * The description text of the option element.
4542 var CBIFileUpload
= CBIValue
.extend(/** @lends LuCI.form.FileUpload.prototype */ {
4543 __name__
: 'CBI.FileSelect',
4545 __init__: function(/* ... */) {
4546 this.super('__init__', arguments
);
4548 this.show_hidden
= false;
4549 this.enable_upload
= true;
4550 this.enable_remove
= true;
4551 this.root_directory
= '/etc/luci-uploads';
4555 * Toggle display of hidden files.
4557 * Display hidden files when rendering the remote directory listing.
4558 * Note that this is merely a cosmetic feature, hidden files are always
4559 * included in received remote file listings.
4561 * The default is `false`, means hidden files are not displayed.
4563 * @name LuCI.form.FileUpload.prototype#show_hidden
4569 * Toggle file upload functionality.
4571 * When set to `true`, the underlying widget provides a button which lets
4572 * the user select and upload local files to the remote system.
4573 * Note that this is merely a cosmetic feature, remote upload access is
4574 * controlled by the session ACL rules.
4576 * The default is `true`, means file upload functionality is displayed.
4578 * @name LuCI.form.FileUpload.prototype#enable_upload
4584 * Toggle remote file delete functionality.
4586 * When set to `true`, the underlying widget provides a buttons which let
4587 * the user delete files from remote directories. Note that this is merely
4588 * a cosmetic feature, remote delete permissions are controlled by the
4589 * session ACL rules.
4591 * The default is `true`, means file removal buttons are displayed.
4593 * @name LuCI.form.FileUpload.prototype#enable_remove
4599 * Specify the root directory for file browsing.
4601 * This property defines the topmost directory the file browser widget may
4602 * navigate to, the UI will not allow browsing directories outside this
4603 * prefix. Note that this is merely a cosmetic feature, remote file access
4604 * and directory listing permissions are controlled by the session ACL
4607 * The default is `/etc/luci-uploads`.
4609 * @name LuCI.form.FileUpload.prototype#root_directory
4611 * @default /etc/luci-uploads
4615 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4616 var browserEl
= new ui
.FileUpload((cfgvalue
!= null) ? cfgvalue
: this.default, {
4617 id
: this.cbid(section_id
),
4618 name
: this.cbid(section_id
),
4619 show_hidden
: this.show_hidden
,
4620 enable_upload
: this.enable_upload
,
4621 enable_remove
: this.enable_remove
,
4622 root_directory
: this.root_directory
,
4623 disabled
: (this.readonly
!= null) ? this.readonly
: this.map
.readonly
4626 return browserEl
.render();
4631 * @class SectionValue
4632 * @memberof LuCI.form
4633 * @augments LuCI.form.Value
4637 * The `SectionValue` widget embeds a form section element within an option
4638 * element container, allowing to nest form sections into other sections.
4640 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4641 * The configuration form this section is added to. It is automatically passed
4642 * by [option()]{@link LuCI.form.AbstractSection#option} or
4643 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4644 * option to the section.
4646 * @param {LuCI.form.AbstractSection} section
4647 * The configuration section this option is added to. It is automatically passed
4648 * by [option()]{@link LuCI.form.AbstractSection#option} or
4649 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4650 * option to the section.
4652 * @param {string} option
4653 * The internal name of the option element holding the section. Since a section
4654 * container element does not read or write any configuration itself, the name
4655 * is only used internally and does not need to relate to any underlying UCI
4658 * @param {LuCI.form.AbstractSection} subsection_class
4659 * The class to use for instantiating the nested section element. Note that
4660 * the class value itself is expected here, not a class instance obtained by
4661 * calling `new`. The given class argument must be a subclass of the
4662 * `AbstractSection` class.
4664 * @param {...*} [class_args]
4665 * All further arguments are passed as-is to the subclass constructor. Refer
4666 * to the corresponding class constructor documentations for details.
4668 var CBISectionValue
= CBIValue
.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4669 __name__
: 'CBI.ContainerValue',
4670 __init__: function(map
, section
, option
, cbiClass
/*, ... */) {
4671 this.super('__init__', [map
, section
, option
]);
4673 if (!CBIAbstractSection
.isSubclass(cbiClass
))
4674 throw 'Sub section must be a descendent of CBIAbstractSection';
4676 this.subsection
= cbiClass
.instantiate(this.varargs(arguments
, 4, this.map
));
4677 this.subsection
.parentoption
= this;
4681 * Access the embedded section instance.
4683 * This property holds a reference to the instantiated nested section.
4685 * @name LuCI.form.SectionValue.prototype#subsection
4686 * @type LuCI.form.AbstractSection
4691 load: function(section_id
) {
4692 return this.subsection
.load(section_id
);
4696 parse: function(section_id
) {
4697 return this.subsection
.parse(section_id
);
4701 renderWidget: function(section_id
, option_index
, cfgvalue
) {
4702 return this.subsection
.render(section_id
);
4706 checkDepends: function(section_id
) {
4707 this.subsection
.checkDepends(section_id
);
4708 return CBIValue
.prototype.checkDepends
.apply(this, [ section_id
]);
4712 * Since the section container is not rendering an own widget,
4713 * its `value()` implementation is a no-op.
4717 value: function() {},
4720 * Since the section container is not tied to any UCI configuration,
4721 * its `write()` implementation is a no-op.
4725 write: function() {},
4728 * Since the section container is not tied to any UCI configuration,
4729 * its `remove()` implementation is a no-op.
4733 remove: function() {},
4736 * Since the section container is not tied to any UCI configuration,
4737 * its `cfgvalue()` implementation will always return `null`.
4742 cfgvalue: function() { return null },
4745 * Since the section container is not tied to any UCI configuration,
4746 * its `formvalue()` implementation will always return `null`.
4751 formvalue: function() { return null }
4760 * The LuCI form class provides high level abstractions for creating creating
4761 * UCI- or JSON backed configurations forms.
4763 * To import the class in views, use `'require form'`, to import it in
4764 * external JavaScript, use `L.require("form").then(...)`.
4766 * A typical form is created by first constructing a
4767 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4768 * by subsequently adding sections and options to it. Finally
4769 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4770 * assemble the HTML markup and insert it into the DOM.
4780 * m = new form.Map('example', 'Example form',
4781 * 'This is an example form mapping the contents of /etc/config/example');
4783 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4784 * 'This sections maps "config example first_section" of /etc/config/example');
4786 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4788 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4789 * o.value('choice1', 'The first choice');
4790 * o.value('choice2', 'The second choice');
4792 * m.render().then(function(node) {
4793 * document.body.appendChild(node);
4797 return baseclass
.extend(/** @lends LuCI.form.prototype */ {
4799 JSONMap
: CBIJSONMap
,
4800 AbstractSection
: CBIAbstractSection
,
4801 AbstractValue
: CBIAbstractValue
,
4803 TypedSection
: CBITypedSection
,
4804 TableSection
: CBITableSection
,
4805 GridSection
: CBIGridSection
,
4806 NamedSection
: CBINamedSection
,
4809 DynamicList
: CBIDynamicList
,
4810 ListValue
: CBIListValue
,
4812 MultiValue
: CBIMultiValue
,
4813 TextValue
: CBITextValue
,
4814 DummyValue
: CBIDummyValue
,
4815 Button
: CBIButtonValue
,
4816 HiddenValue
: CBIHiddenValue
,
4817 FileUpload
: CBIFileUpload
,
4818 SectionValue
: CBISectionValue