luci-base: form.js: toggle inactive CSS class on unsatisfied field cells
[project/luci.git] / modules / luci-base / htdocs / luci-static / resources / form.js
1 'use strict';
2 'require ui';
3 'require uci';
4 'require rpc';
5 'require dom';
6 'require baseclass';
7
8 var scope = this;
9
10 var callSessionAccess = rpc.declare({
11 object: 'session',
12 method: 'access',
13 params: [ 'scope', 'object', 'function' ],
14 expect: { 'access': false }
15 });
16
17 var CBIJSONConfig = baseclass.extend({
18 __init__: function(data) {
19 data = Object.assign({}, data);
20
21 this.data = {};
22
23 var num_sections = 0,
24 section_ids = [];
25
26 for (var sectiontype in data) {
27 if (!data.hasOwnProperty(sectiontype))
28 continue;
29
30 if (L.isObject(data[sectiontype])) {
31 this.data[sectiontype] = Object.assign(data[sectiontype], {
32 '.anonymous': false,
33 '.name': sectiontype,
34 '.type': sectiontype
35 });
36
37 section_ids.push(sectiontype);
38 num_sections++;
39 }
40 else if (Array.isArray(data[sectiontype])) {
41 for (var i = 0, index = 0; i < data[sectiontype].length; i++) {
42 var item = data[sectiontype][i],
43 anonymous, name;
44
45 if (!L.isObject(item))
46 continue;
47
48 if (typeof(item['.name']) == 'string') {
49 name = item['.name'];
50 anonymous = false;
51 }
52 else {
53 name = sectiontype + num_sections;
54 anonymous = true;
55 }
56
57 if (!this.data.hasOwnProperty(name))
58 section_ids.push(name);
59
60 this.data[name] = Object.assign(item, {
61 '.index': num_sections++,
62 '.anonymous': anonymous,
63 '.name': name,
64 '.type': sectiontype
65 });
66 }
67 }
68 }
69
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;
73
74 if (indexA != indexB)
75 return (indexA - indexB);
76
77 return (a > b);
78 }, this));
79
80 for (var i = 0; i < section_ids.length; i++)
81 this.data[section_ids[i]]['.index'] = i;
82 },
83
84 load: function() {
85 return Promise.resolve(this.data);
86 },
87
88 save: function() {
89 return Promise.resolve();
90 },
91
92 get: function(config, section, option) {
93 if (section == null)
94 return null;
95
96 if (option == null)
97 return this.data[section];
98
99 if (!this.data.hasOwnProperty(section))
100 return null;
101
102 var value = this.data[section][option];
103
104 if (Array.isArray(value))
105 return value;
106
107 if (value != null)
108 return String(value);
109
110 return null;
111 },
112
113 set: function(config, section, option, value) {
114 if (section == null || option == null || option.charAt(0) == '.')
115 return;
116
117 if (!this.data.hasOwnProperty(section))
118 return;
119
120 if (value == null)
121 delete this.data[section][option];
122 else if (Array.isArray(value))
123 this.data[section][option] = value;
124 else
125 this.data[section][option] = String(value);
126 },
127
128 unset: function(config, section, option) {
129 return this.set(config, section, option, null);
130 },
131
132 sections: function(config, sectiontype, callback) {
133 var rv = [];
134
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]);
138
139 rv.sort(function(a, b) { return a['.index'] - b['.index'] });
140
141 if (typeof(callback) == 'function')
142 for (var i = 0; i < rv.length; i++)
143 callback.call(this, rv[i], rv[i]['.name']);
144
145 return rv;
146 },
147
148 add: function(config, sectiontype, sectionname) {
149 var num_sections_type = 0, next_index = 0;
150
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']);
154 }
155
156 var section_id = sectionname || sectiontype + num_sections_type;
157
158 if (!this.data.hasOwnProperty(section_id)) {
159 this.data[section_id] = {
160 '.name': section_id,
161 '.type': sectiontype,
162 '.anonymous': (sectionname == null),
163 '.index': next_index + 1
164 };
165 }
166
167 return section_id;
168 },
169
170 remove: function(config, section) {
171 if (this.data.hasOwnProperty(section))
172 delete this.data[section];
173 },
174
175 resolveSID: function(config, section_id) {
176 return section_id;
177 },
178
179 move: function(config, section_id1, section_id2, after) {
180 return uci.move.apply(this, [config, section_id1, section_id2, after]);
181 }
182 });
183
184 /**
185 * @class AbstractElement
186 * @memberof LuCI.form
187 * @hideconstructor
188 * @classdesc
189 *
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
193 * properties.
194 *
195 * This class is private and not directly accessible by user code.
196 */
197 var CBIAbstractElement = baseclass.extend(/** @lends LuCI.form.AbstractElement.prototype */ {
198 __init__: function(title, description) {
199 this.title = title || '';
200 this.description = description || '';
201 this.children = [];
202 },
203
204 /**
205 * Add another form element as children to this element.
206 *
207 * @param {AbstractElement} element
208 * The form element to add.
209 */
210 append: function(obj) {
211 this.children.push(obj);
212 },
213
214 /**
215 * Parse this elements form input.
216 *
217 * The `parse()` function recursively walks the form element tree and
218 * triggers input value reading and validation for each encountered element.
219 *
220 * Elements which are hidden due to unsatisified dependencies are skipped.
221 *
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.
227 */
228 parse: function() {
229 var args = arguments;
230 this.children.forEach(function(child) {
231 child.parse.apply(child, args);
232 });
233 },
234
235 /**
236 * Render the form element.
237 *
238 * The `render()` function recursively walks the form element tree and
239 * renders the markup for each element, returning the assembled DOM tree.
240 *
241 * @abstract
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.
245 */
246 render: function() {
247 L.error('InternalError', 'Not implemented');
248 },
249
250 /** @private */
251 loadChildren: function(/* ... */) {
252 var tasks = [];
253
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));
258
259 return Promise.all(tasks);
260 },
261
262 /** @private */
263 renderChildren: function(tab_name /*, ... */) {
264 var tasks = [],
265 index = 0;
266
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++)));
273
274 return Promise.all(tasks);
275 },
276
277 /**
278 * Strip any HTML tags from the given input string.
279 *
280 * @param {string} input
281 * The input string to clean.
282 *
283 * @returns {string}
284 * The cleaned input string with HTML removes removed.
285 */
286 stripTags: function(s) {
287 if (typeof(s) == 'string' && !s.match(/[<>]/))
288 return s;
289
290 var x = E('div', {}, s);
291 return x.textContent || x.innerText || '';
292 },
293
294 /**
295 * Format the given named property as title string.
296 *
297 * This function looks up the given named property and formats its value
298 * suitable for use as element caption or description string. It also
299 * strips any HTML tags from the result.
300 *
301 * If the property value is a string, it is passed to `String.format()`
302 * along with any additional parameters passed to `titleFn()`.
303 *
304 * If the property value is a function, it is invoked with any additional
305 * `titleFn()` parameters as arguments and the obtained return value is
306 * converted to a string.
307 *
308 * In all other cases, `null` is returned.
309 *
310 * @param {string} property
311 * The name of the element property to use.
312 *
313 * @param {...*} fmt_args
314 * Extra values to format the title string with.
315 *
316 * @returns {string|null}
317 * The formatted title string or `null` if the property did not exist or
318 * was neither a string nor a function.
319 */
320 titleFn: function(attr /*, ... */) {
321 var s = null;
322
323 if (typeof(this[attr]) == 'function')
324 s = this[attr].apply(this, this.varargs(arguments, 1));
325 else if (typeof(this[attr]) == 'string')
326 s = (arguments.length > 1) ? ''.format.apply(this[attr], this.varargs(arguments, 1)) : this[attr];
327
328 if (s != null)
329 s = this.stripTags(String(s)).trim();
330
331 if (s == null || s == '')
332 return null;
333
334 return s;
335 }
336 });
337
338 /**
339 * @constructor Map
340 * @memberof LuCI.form
341 * @augments LuCI.form.AbstractElement
342 *
343 * @classdesc
344 *
345 * The `Map` class represents one complete form. A form usually maps one UCI
346 * configuraton file and is divided into multiple sections containing multiple
347 * fields each.
348 *
349 * It serves as main entry point into the `LuCI.form` for typical view code.
350 *
351 * @param {string} config
352 * The UCI configuration to map. It is automatically loaded along when the
353 * resulting map instance.
354 *
355 * @param {string} [title]
356 * The title caption of the form. A form title is usually rendered as separate
357 * headline element before the actual form contents. If omitted, the
358 * corresponding headline element will not be rendered.
359 *
360 * @param {string} [description]
361 * The description text of the form which is usually rendered as text
362 * paragraph below the form title and before the actual form conents.
363 * If omitted, the corresponding paragraph element will not be rendered.
364 */
365 var CBIMap = CBIAbstractElement.extend(/** @lends LuCI.form.Map.prototype */ {
366 __init__: function(config /*, ... */) {
367 this.super('__init__', this.varargs(arguments, 1));
368
369 this.config = config;
370 this.parsechain = [ config ];
371 this.data = uci;
372 },
373
374 /**
375 * Toggle readonly state of the form.
376 *
377 * If set to `true`, the Map instance is marked readonly and any form
378 * option elements added to it will inherit the readonly state.
379 *
380 * If left unset, the Map will test the access permission of the primary
381 * uci configuration upon loading and mark the form readonly if no write
382 * permissions are granted.
383 *
384 * @name LuCI.form.Map.prototype#readonly
385 * @type boolean
386 */
387
388 /**
389 * Find all DOM nodes within this Map which match the given search
390 * parameters. This function is essentially a convenience wrapper around
391 * `querySelectorAll()`.
392 *
393 * This function is sensitive to the amount of arguments passed to it;
394 * if only one argument is specified, it is used as selector-expression
395 * as-is. When two arguments are passed, the first argument is treated
396 * as attribute name, the second one as attribute value to match.
397 *
398 * As an example, `map.findElements('input')` would find all `<input>`
399 * nodes while `map.findElements('type', 'text')` would find any DOM node
400 * with a `type="text"` attribute.
401 *
402 * @param {string} selector_or_attrname
403 * If invoked with only one parameter, this argument is a
404 * `querySelectorAll()` compatible selector expression. If invoked with
405 * two parameters, this argument is the attribute name to filter for.
406 *
407 * @param {string} [attrvalue]
408 * In case the function is invoked with two parameters, this argument
409 * specifies the attribute value to match.
410 *
411 * @throws {InternalError}
412 * Throws an `InternalError` if more than two function parameters are
413 * passed.
414 *
415 * @returns {NodeList}
416 * Returns a (possibly empty) DOM `NodeList` containing the found DOM nodes.
417 */
418 findElements: function(/* ... */) {
419 var q = null;
420
421 if (arguments.length == 1)
422 q = arguments[0];
423 else if (arguments.length == 2)
424 q = '[%s="%s"]'.format(arguments[0], arguments[1]);
425 else
426 L.error('InternalError', 'Expecting one or two arguments to findElements()');
427
428 return this.root.querySelectorAll(q);
429 },
430
431 /**
432 * Find the first DOM node within this Map which matches the given search
433 * parameters. This function is essentially a convenience wrapper around
434 * `findElements()` which only returns the first found node.
435 *
436 * This function is sensitive to the amount of arguments passed to it;
437 * if only one argument is specified, it is used as selector-expression
438 * as-is. When two arguments are passed, the first argument is treated
439 * as attribute name, the second one as attribute value to match.
440 *
441 * As an example, `map.findElement('input')` would find the first `<input>`
442 * node while `map.findElement('type', 'text')` would find the first DOM
443 * node with a `type="text"` attribute.
444 *
445 * @param {string} selector_or_attrname
446 * If invoked with only one parameter, this argument is a `querySelector()`
447 * compatible selector expression. If invoked with two parameters, this
448 * argument is the attribute name to filter for.
449 *
450 * @param {string} [attrvalue]
451 * In case the function is invoked with two parameters, this argument
452 * specifies the attribute value to match.
453 *
454 * @throws {InternalError}
455 * Throws an `InternalError` if more than two function parameters are
456 * passed.
457 *
458 * @returns {Node|null}
459 * Returns the first found DOM node or `null` if no element matched.
460 */
461 findElement: function(/* ... */) {
462 var res = this.findElements.apply(this, arguments);
463 return res.length ? res[0] : null;
464 },
465
466 /**
467 * Tie another UCI configuration to the map.
468 *
469 * By default, a map instance will only load the UCI configuration file
470 * specified in the constructor but sometimes access to values from
471 * further configuration files is required. This function allows for such
472 * use cases by registering further UCI configuration files which are
473 * needed by the map.
474 *
475 * @param {string} config
476 * The additional UCI configuration file to tie to the map. If the given
477 * config already is in the list of required files, it will be ignored.
478 */
479 chain: function(config) {
480 if (this.parsechain.indexOf(config) == -1)
481 this.parsechain.push(config);
482 },
483
484 /**
485 * Add a configuration section to the map.
486 *
487 * LuCI forms follow the structure of the underlying UCI configurations,
488 * means that a map, which represents a single UCI configuration, is
489 * divided into multiple sections which in turn contain an arbitrary
490 * number of options.
491 *
492 * While UCI itself only knows two kinds of sections - named and anonymous
493 * ones - the form class offers various flavors of form section elements
494 * to present configuration sections in different ways. Refer to the
495 * documentation of the different section classes for details.
496 *
497 * @param {LuCI.form.AbstractSection} sectionclass
498 * The section class to use for rendering the configuration section.
499 * Note that this value must be the class itself, not a class instance
500 * obtained from calling `new`. It must also be a class dervied from
501 * `LuCI.form.AbstractSection`.
502 *
503 * @param {...string} classargs
504 * Additional arguments which are passed as-is to the contructor of the
505 * given section class. Refer to the class specific constructor
506 * documentation for details.
507 *
508 * @returns {LuCI.form.AbstractSection}
509 * Returns the instantiated section class instance.
510 */
511 section: function(cbiClass /*, ... */) {
512 if (!CBIAbstractSection.isSubclass(cbiClass))
513 L.error('TypeError', 'Class must be a descendent of CBIAbstractSection');
514
515 var obj = cbiClass.instantiate(this.varargs(arguments, 1, this));
516 this.append(obj);
517 return obj;
518 },
519
520 /**
521 * Load the configuration covered by this map.
522 *
523 * The `load()` function first loads all referenced UCI configurations,
524 * then it recursively walks the form element tree and invokes the
525 * load function of each child element.
526 *
527 * @returns {Promise<void>}
528 * Returns a promise resolving once the entire form completed loading all
529 * data. The promise may reject with an error if any configuration failed
530 * to load or if any of the child elements load functions rejected with
531 * an error.
532 */
533 load: function() {
534 var doCheckACL = (!(this instanceof CBIJSONMap) && this.readonly == null),
535 loadTasks = [ doCheckACL ? callSessionAccess('uci', this.config, 'write') : true ],
536 configs = this.parsechain || [ this.config ];
537
538 loadTasks.push.apply(loadTasks, configs.map(L.bind(function(config, i) {
539 return i ? L.resolveDefault(this.data.load(config)) : this.data.load(config);
540 }, this)));
541
542 return Promise.all(loadTasks).then(L.bind(function(res) {
543 if (res[0] === false)
544 this.readonly = true;
545
546 return this.loadChildren();
547 }, this));
548 },
549
550 /**
551 * Parse the form input values.
552 *
553 * The `parse()` function recursively walks the form element tree and
554 * triggers input value reading and validation for each child element.
555 *
556 * Elements which are hidden due to unsatisified dependencies are skipped.
557 *
558 * @returns {Promise<void>}
559 * Returns a promise resolving once the entire form completed parsing all
560 * input values. The returned promise is rejected if any parsed values are
561 * not meeting the validation constraints of their respective elements.
562 */
563 parse: function() {
564 var tasks = [];
565
566 if (Array.isArray(this.children))
567 for (var i = 0; i < this.children.length; i++)
568 tasks.push(this.children[i].parse());
569
570 return Promise.all(tasks);
571 },
572
573 /**
574 * Save the form input values.
575 *
576 * This function parses the current form, saves the resulting UCI changes,
577 * reloads the UCI configuration data and redraws the form elements.
578 *
579 * @param {function} [cb]
580 * An optional callback function that is invoked after the form is parsed
581 * but before the changed UCI data is saved. This is useful to perform
582 * additional data manipulation steps before saving the changes.
583 *
584 * @param {boolean} [silent=false]
585 * If set to `true`, trigger an alert message to the user in case saving
586 * the form data failes. Otherwise fail silently.
587 *
588 * @returns {Promise<void>}
589 * Returns a promise resolving once the entire save operation is complete.
590 * The returned promise is rejected if any step of the save operation
591 * failed.
592 */
593 save: function(cb, silent) {
594 this.checkDepends();
595
596 return this.parse()
597 .then(cb)
598 .then(this.data.save.bind(this.data))
599 .then(this.load.bind(this))
600 .catch(function(e) {
601 if (!silent) {
602 ui.showModal(_('Save error'), [
603 E('p', {}, [ _('An error occurred while saving the form:') ]),
604 E('p', {}, [ E('em', { 'style': 'white-space:pre' }, [ e.message ]) ]),
605 E('div', { 'class': 'right' }, [
606 E('button', { 'click': ui.hideModal }, [ _('Dismiss') ])
607 ])
608 ]);
609 }
610
611 return Promise.reject(e);
612 }).then(this.renderContents.bind(this));
613 },
614
615 /**
616 * Reset the form by re-rendering its contents. This will revert all
617 * unsaved user inputs to their initial form state.
618 *
619 * @returns {Promise<Node>}
620 * Returns a promise resolving to the toplevel form DOM node once the
621 * re-rendering is complete.
622 */
623 reset: function() {
624 return this.renderContents();
625 },
626
627 /**
628 * Render the form markup.
629 *
630 * @returns {Promise<Node>}
631 * Returns a promise resolving to the toplevel form DOM node once the
632 * rendering is complete.
633 */
634 render: function() {
635 return this.load().then(this.renderContents.bind(this));
636 },
637
638 /** @private */
639 renderContents: function() {
640 var mapEl = this.root || (this.root = E('div', {
641 'id': 'cbi-%s'.format(this.config),
642 'class': 'cbi-map',
643 'cbi-dependency-check': L.bind(this.checkDepends, this)
644 }));
645
646 dom.bindClassInstance(mapEl, this);
647
648 return this.renderChildren(null).then(L.bind(function(nodes) {
649 var initialRender = !mapEl.firstChild;
650
651 dom.content(mapEl, null);
652
653 if (this.title != null && this.title != '')
654 mapEl.appendChild(E('h2', { 'name': 'content' }, this.title));
655
656 if (this.description != null && this.description != '')
657 mapEl.appendChild(E('div', { 'class': 'cbi-map-descr' }, this.description));
658
659 if (this.tabbed)
660 dom.append(mapEl, E('div', { 'class': 'cbi-map-tabbed' }, nodes));
661 else
662 dom.append(mapEl, nodes);
663
664 if (!initialRender) {
665 mapEl.classList.remove('flash');
666
667 window.setTimeout(function() {
668 mapEl.classList.add('flash');
669 }, 1);
670 }
671
672 this.checkDepends();
673
674 var tabGroups = mapEl.querySelectorAll('.cbi-map-tabbed, .cbi-section-node-tabbed');
675
676 for (var i = 0; i < tabGroups.length; i++)
677 ui.tabs.initTabGroup(tabGroups[i].childNodes);
678
679 return mapEl;
680 }, this));
681 },
682
683 /**
684 * Find a form option element instance.
685 *
686 * @param {string} name_or_id
687 * The name or the full ID of the option element to look up.
688 *
689 * @param {string} [section_id]
690 * The ID of the UCI section containing the option to look up. May be
691 * omitted if a full ID is passed as first argument.
692 *
693 * @param {string} [config]
694 * The name of the UCI configuration the option instance is belonging to.
695 * Defaults to the main UCI configuration of the map if omitted.
696 *
697 * @returns {Array<LuCI.form.AbstractValue,string>|null}
698 * Returns a two-element array containing the form option instance as
699 * first item and the corresponding UCI section ID as second item.
700 * Returns `null` if the option could not be found.
701 */
702 lookupOption: function(name, section_id, config_name) {
703 var id, elem, sid, inst;
704
705 if (name.indexOf('.') > -1)
706 id = 'cbid.%s'.format(name);
707 else
708 id = 'cbid.%s.%s.%s'.format(config_name || this.config, section_id, name);
709
710 elem = this.findElement('data-field', id);
711 sid = elem ? id.split(/\./)[2] : null;
712 inst = elem ? dom.findClassInstance(elem) : null;
713
714 return (inst instanceof CBIAbstractValue) ? [ inst, sid ] : null;
715 },
716
717 /** @private */
718 checkDepends: function(ev, n) {
719 var changed = false;
720
721 for (var i = 0, s = this.children[0]; (s = this.children[i]) != null; i++)
722 if (s.checkDepends(ev, n))
723 changed = true;
724
725 if (changed && (n || 0) < 10)
726 this.checkDepends(ev, (n || 10) + 1);
727
728 ui.tabs.updateTabs(ev, this.root);
729 },
730
731 /** @private */
732 isDependencySatisfied: function(depends, config_name, section_id) {
733 var def = false;
734
735 if (!Array.isArray(depends) || !depends.length)
736 return true;
737
738 for (var i = 0; i < depends.length; i++) {
739 var istat = true,
740 reverse = depends[i]['!reverse'],
741 contains = depends[i]['!contains'];
742
743 for (var dep in depends[i]) {
744 if (dep == '!reverse' || dep == '!contains') {
745 continue;
746 }
747 else if (dep == '!default') {
748 def = true;
749 istat = false;
750 }
751 else {
752 var res = this.lookupOption(dep, section_id, config_name),
753 val = (res && res[0].isActive(res[1])) ? res[0].formvalue(res[1]) : null;
754
755 var equal = contains
756 ? isContained(val, depends[i][dep])
757 : isEqual(val, depends[i][dep]);
758
759 istat = (istat && equal);
760 }
761 }
762
763 if (istat ^ reverse)
764 return true;
765 }
766
767 return def;
768 }
769 });
770
771 /**
772 * @constructor JSONMap
773 * @memberof LuCI.form
774 * @augments LuCI.form.Map
775 *
776 * @classdesc
777 *
778 * A `JSONMap` class functions similar to [LuCI.form.Map]{@link LuCI.form.Map}
779 * but uses a multidimensional JavaScript object instead of UCI configuration
780 * as data source.
781 *
782 * @param {Object<string, Object<string, *>|Array<Object<string, *>>>} data
783 * The JavaScript object to use as data source. Internally, the object is
784 * converted into an UCI-like format. Its toplevel keys are treated like UCI
785 * section types while the object or array-of-object values are treated as
786 * section contents.
787 *
788 * @param {string} [title]
789 * The title caption of the form. A form title is usually rendered as separate
790 * headline element before the actual form contents. If omitted, the
791 * corresponding headline element will not be rendered.
792 *
793 * @param {string} [description]
794 * The description text of the form which is usually rendered as text
795 * paragraph below the form title and before the actual form conents.
796 * If omitted, the corresponding paragraph element will not be rendered.
797 */
798 var CBIJSONMap = CBIMap.extend(/** @lends LuCI.form.JSONMap.prototype */ {
799 __init__: function(data /*, ... */) {
800 this.super('__init__', this.varargs(arguments, 1, 'json'));
801
802 this.config = 'json';
803 this.parsechain = [ 'json' ];
804 this.data = new CBIJSONConfig(data);
805 }
806 });
807
808 /**
809 * @class AbstractSection
810 * @memberof LuCI.form
811 * @augments LuCI.form.AbstractElement
812 * @hideconstructor
813 * @classdesc
814 *
815 * The `AbstractSection` class serves as abstract base for the different form
816 * section styles implemented by `LuCI.form`. It provides the common logic for
817 * enumerating underlying configuration section instances, for registering
818 * form options and for handling tabs to segment child options.
819 *
820 * This class is private and not directly accessible by user code.
821 */
822 var CBIAbstractSection = CBIAbstractElement.extend(/** @lends LuCI.form.AbstractSection.prototype */ {
823 __init__: function(map, sectionType /*, ... */) {
824 this.super('__init__', this.varargs(arguments, 2));
825
826 this.sectiontype = sectionType;
827 this.map = map;
828 this.config = map.config;
829
830 this.optional = true;
831 this.addremove = false;
832 this.dynamic = false;
833 },
834
835 /**
836 * Access the parent option container instance.
837 *
838 * In case this section is nested within an option element container,
839 * this property will hold a reference to the parent option instance.
840 *
841 * If this section is not nested, the property is `null`.
842 *
843 * @name LuCI.form.AbstractSection.prototype#parentoption
844 * @type LuCI.form.AbstractValue
845 * @readonly
846 */
847
848 /**
849 * Enumerate the UCI section IDs covered by this form section element.
850 *
851 * @abstract
852 * @throws {InternalError}
853 * Throws an `InternalError` exception if the function is not implemented.
854 *
855 * @returns {string[]}
856 * Returns an array of UCI section IDs covered by this form element.
857 * The sections will be rendered in the same order as the returned array.
858 */
859 cfgsections: function() {
860 L.error('InternalError', 'Not implemented');
861 },
862
863 /**
864 * Filter UCI section IDs to render.
865 *
866 * The filter function is invoked for each UCI section ID of a given type
867 * and controls whether the given UCI section is rendered or ignored by
868 * the form section element.
869 *
870 * The default implementation always returns `true`. User code or
871 * classes extending `AbstractSection` may overwrite this function with
872 * custom implementations.
873 *
874 * @abstract
875 * @param {string} section_id
876 * The UCI section ID to test.
877 *
878 * @returns {boolean}
879 * Returns `true` when the given UCI section ID should be handled and
880 * `false` when it should be ignored.
881 */
882 filter: function(section_id) {
883 return true;
884 },
885
886 /**
887 * Load the configuration covered by this section.
888 *
889 * The `load()` function recursively walks the section element tree and
890 * invokes the load function of each child option element.
891 *
892 * @returns {Promise<void>}
893 * Returns a promise resolving once the values of all child elements have
894 * been loaded. The promise may reject with an error if any of the child
895 * elements load functions rejected with an error.
896 */
897 load: function() {
898 var section_ids = this.cfgsections(),
899 tasks = [];
900
901 if (Array.isArray(this.children))
902 for (var i = 0; i < section_ids.length; i++)
903 tasks.push(this.loadChildren(section_ids[i])
904 .then(Function.prototype.bind.call(function(section_id, set_values) {
905 for (var i = 0; i < set_values.length; i++)
906 this.children[i].cfgvalue(section_id, set_values[i]);
907 }, this, section_ids[i])));
908
909 return Promise.all(tasks);
910 },
911
912 /**
913 * Parse this sections form input.
914 *
915 * The `parse()` function recursively walks the section element tree and
916 * triggers input value reading and validation for each encountered child
917 * option element.
918 *
919 * Options which are hidden due to unsatisified dependencies are skipped.
920 *
921 * @returns {Promise<void>}
922 * Returns a promise resolving once the values of all child elements have
923 * been parsed. The returned promise is rejected if any parsed values are
924 * not meeting the validation constraints of their respective elements.
925 */
926 parse: function() {
927 var section_ids = this.cfgsections(),
928 tasks = [];
929
930 if (Array.isArray(this.children))
931 for (var i = 0; i < section_ids.length; i++)
932 for (var j = 0; j < this.children.length; j++)
933 tasks.push(this.children[j].parse(section_ids[i]));
934
935 return Promise.all(tasks);
936 },
937
938 /**
939 * Add an option tab to the section.
940 *
941 * The child option elements of a section may be divided into multiple
942 * tabs to provide a better overview to the user.
943 *
944 * Before options can be moved into a tab pane, the corresponding tab
945 * has to be defined first, which is done by calling this function.
946 *
947 * Note that once tabs are defined, user code must use the `taboption()`
948 * method to add options to specific tabs. Option elements added by
949 * `option()` will not be assigned to any tab and not be rendered in this
950 * case.
951 *
952 * @param {string} name
953 * The name of the tab to register. It may be freely chosen and just serves
954 * as an identifier to differentiate tabs.
955 *
956 * @param {string} title
957 * The human readable caption of the tab.
958 *
959 * @param {string} [description]
960 * An additional description text for the corresponding tab pane. It is
961 * displayed as text paragraph below the tab but before the tab pane
962 * contents. If omitted, no description will be rendered.
963 *
964 * @throws {Error}
965 * Throws an exeption if a tab with the same `name` already exists.
966 */
967 tab: function(name, title, description) {
968 if (this.tabs && this.tabs[name])
969 throw 'Tab already declared';
970
971 var entry = {
972 name: name,
973 title: title,
974 description: description,
975 children: []
976 };
977
978 this.tabs = this.tabs || [];
979 this.tabs.push(entry);
980 this.tabs[name] = entry;
981
982 this.tab_names = this.tab_names || [];
983 this.tab_names.push(name);
984 },
985
986 /**
987 * Add a configuration option widget to the section.
988 *
989 * Note that [taboption()]{@link LuCI.form.AbstractSection#taboption}
990 * should be used instead if this form section element uses tabs.
991 *
992 * @param {LuCI.form.AbstractValue} optionclass
993 * The option class to use for rendering the configuration option. Note
994 * that this value must be the class itself, not a class instance obtained
995 * from calling `new`. It must also be a class dervied from
996 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
997 *
998 * @param {...*} classargs
999 * Additional arguments which are passed as-is to the contructor of the
1000 * given option class. Refer to the class specific constructor
1001 * documentation for details.
1002 *
1003 * @throws {TypeError}
1004 * Throws a `TypeError` exception in case the passed class value is not a
1005 * descendent of `AbstractValue`.
1006 *
1007 * @returns {LuCI.form.AbstractValue}
1008 * Returns the instantiated option class instance.
1009 */
1010 option: function(cbiClass /*, ... */) {
1011 if (!CBIAbstractValue.isSubclass(cbiClass))
1012 throw L.error('TypeError', 'Class must be a descendent of CBIAbstractValue');
1013
1014 var obj = cbiClass.instantiate(this.varargs(arguments, 1, this.map, this));
1015 this.append(obj);
1016 return obj;
1017 },
1018
1019 /**
1020 * Add a configuration option widget to a tab of the section.
1021 *
1022 * @param {string} tabname
1023 * The name of the section tab to add the option element to.
1024 *
1025 * @param {LuCI.form.AbstractValue} optionclass
1026 * The option class to use for rendering the configuration option. Note
1027 * that this value must be the class itself, not a class instance obtained
1028 * from calling `new`. It must also be a class dervied from
1029 * [LuCI.form.AbstractSection]{@link LuCI.form.AbstractSection}.
1030 *
1031 * @param {...*} classargs
1032 * Additional arguments which are passed as-is to the contructor of the
1033 * given option class. Refer to the class specific constructor
1034 * documentation for details.
1035 *
1036 * @throws {ReferenceError}
1037 * Throws a `ReferenceError` exception when the given tab name does not
1038 * exist.
1039 *
1040 * @throws {TypeError}
1041 * Throws a `TypeError` exception in case the passed class value is not a
1042 * descendent of `AbstractValue`.
1043 *
1044 * @returns {LuCI.form.AbstractValue}
1045 * Returns the instantiated option class instance.
1046 */
1047 taboption: function(tabName /*, ... */) {
1048 if (!this.tabs || !this.tabs[tabName])
1049 throw L.error('ReferenceError', 'Associated tab not declared');
1050
1051 var obj = this.option.apply(this, this.varargs(arguments, 1));
1052 obj.tab = tabName;
1053 this.tabs[tabName].children.push(obj);
1054 return obj;
1055 },
1056
1057 /** @private */
1058 renderUCISection: function(section_id) {
1059 var renderTasks = [];
1060
1061 if (!this.tabs)
1062 return this.renderOptions(null, section_id);
1063
1064 for (var i = 0; i < this.tab_names.length; i++)
1065 renderTasks.push(this.renderOptions(this.tab_names[i], section_id));
1066
1067 return Promise.all(renderTasks)
1068 .then(this.renderTabContainers.bind(this, section_id));
1069 },
1070
1071 /** @private */
1072 renderTabContainers: function(section_id, nodes) {
1073 var config_name = this.uciconfig || this.map.config,
1074 containerEls = E([]);
1075
1076 for (var i = 0; i < nodes.length; i++) {
1077 var tab_name = this.tab_names[i],
1078 tab_data = this.tabs[tab_name],
1079 containerEl = E('div', {
1080 'id': 'container.%s.%s.%s'.format(config_name, section_id, tab_name),
1081 'data-tab': tab_name,
1082 'data-tab-title': tab_data.title,
1083 'data-tab-active': tab_name === this.selected_tab
1084 });
1085
1086 if (tab_data.description != null && tab_data.description != '')
1087 containerEl.appendChild(
1088 E('div', { 'class': 'cbi-tab-descr' }, tab_data.description));
1089
1090 containerEl.appendChild(nodes[i]);
1091 containerEls.appendChild(containerEl);
1092 }
1093
1094 return containerEls;
1095 },
1096
1097 /** @private */
1098 renderOptions: function(tab_name, section_id) {
1099 var in_table = (this instanceof CBITableSection);
1100 return this.renderChildren(tab_name, section_id, in_table).then(function(nodes) {
1101 var optionEls = E([]);
1102 for (var i = 0; i < nodes.length; i++)
1103 optionEls.appendChild(nodes[i]);
1104 return optionEls;
1105 });
1106 },
1107
1108 /** @private */
1109 checkDepends: function(ev, n) {
1110 var changed = false,
1111 sids = this.cfgsections();
1112
1113 for (var i = 0, sid = sids[0]; (sid = sids[i]) != null; i++) {
1114 for (var j = 0, o = this.children[0]; (o = this.children[j]) != null; j++) {
1115 var isActive = o.isActive(sid),
1116 isSatisified = o.checkDepends(sid);
1117
1118 if (isActive != isSatisified) {
1119 o.setActive(sid, !isActive);
1120 isActive = !isActive;
1121 changed = true;
1122 }
1123
1124 if (!n && isActive)
1125 o.triggerValidation(sid);
1126 }
1127 }
1128
1129 return changed;
1130 }
1131 });
1132
1133
1134 var isEqual = function(x, y) {
1135 if (x != null && y != null && typeof(x) != typeof(y))
1136 return false;
1137
1138 if ((x == null && y != null) || (x != null && y == null))
1139 return false;
1140
1141 if (Array.isArray(x)) {
1142 if (x.length != y.length)
1143 return false;
1144
1145 for (var i = 0; i < x.length; i++)
1146 if (!isEqual(x[i], y[i]))
1147 return false;
1148 }
1149 else if (typeof(x) == 'object') {
1150 for (var k in x) {
1151 if (x.hasOwnProperty(k) && !y.hasOwnProperty(k))
1152 return false;
1153
1154 if (!isEqual(x[k], y[k]))
1155 return false;
1156 }
1157
1158 for (var k in y)
1159 if (y.hasOwnProperty(k) && !x.hasOwnProperty(k))
1160 return false;
1161 }
1162 else if (x != y) {
1163 return false;
1164 }
1165
1166 return true;
1167 };
1168
1169 var isContained = function(x, y) {
1170 if (Array.isArray(x)) {
1171 for (var i = 0; i < x.length; i++)
1172 if (x[i] == y)
1173 return true;
1174 }
1175 else if (L.isObject(x)) {
1176 if (x.hasOwnProperty(y) && x[y] != null)
1177 return true;
1178 }
1179 else if (typeof(x) == 'string') {
1180 return (x.indexOf(y) > -1);
1181 }
1182
1183 return false;
1184 };
1185
1186 /**
1187 * @class AbstractValue
1188 * @memberof LuCI.form
1189 * @augments LuCI.form.AbstractElement
1190 * @hideconstructor
1191 * @classdesc
1192 *
1193 * The `AbstractValue` class serves as abstract base for the different form
1194 * option styles implemented by `LuCI.form`. It provides the common logic for
1195 * handling option input values, for dependencies among options and for
1196 * validation constraints that should be applied to entered values.
1197 *
1198 * This class is private and not directly accessible by user code.
1199 */
1200 var CBIAbstractValue = CBIAbstractElement.extend(/** @lends LuCI.form.AbstractValue.prototype */ {
1201 __init__: function(map, section, option /*, ... */) {
1202 this.super('__init__', this.varargs(arguments, 3));
1203
1204 this.section = section;
1205 this.option = option;
1206 this.map = map;
1207 this.config = map.config;
1208
1209 this.deps = [];
1210 this.initial = {};
1211 this.rmempty = true;
1212 this.default = null;
1213 this.size = null;
1214 this.optional = false;
1215 },
1216
1217 /**
1218 * If set to `false`, the underlying option value is retained upon saving
1219 * the form when the option element is disabled due to unsatisfied
1220 * dependency constraints.
1221 *
1222 * @name LuCI.form.AbstractValue.prototype#rmempty
1223 * @type boolean
1224 * @default true
1225 */
1226
1227 /**
1228 * If set to `true`, the underlying ui input widget is allowed to be empty,
1229 * otherwise the option element is marked invalid when no value is entered
1230 * or selected by the user.
1231 *
1232 * @name LuCI.form.AbstractValue.prototype#optional
1233 * @type boolean
1234 * @default false
1235 */
1236
1237 /**
1238 * Sets a default value to use when the underlying UCI option is not set.
1239 *
1240 * @name LuCI.form.AbstractValue.prototype#default
1241 * @type *
1242 * @default null
1243 */
1244
1245 /**
1246 * Specifies a datatype constraint expression to validate input values
1247 * against. Refer to {@link LuCI.validation} for details on the format.
1248 *
1249 * If the user entered input does not match the datatype validation, the
1250 * option element is marked as invalid.
1251 *
1252 * @name LuCI.form.AbstractValue.prototype#datatype
1253 * @type string
1254 * @default null
1255 */
1256
1257 /**
1258 * Specifies a custom validation function to test the user input for
1259 * validity. The validation function must return `true` to accept the
1260 * value. Any other return value type is converted to a string and
1261 * displayed to the user as validation error message.
1262 *
1263 * If the user entered input does not pass the validation function, the
1264 * option element is marked as invalid.
1265 *
1266 * @name LuCI.form.AbstractValue.prototype#validate
1267 * @type function
1268 * @default null
1269 */
1270
1271 /**
1272 * Override the UCI configuration name to read the option value from.
1273 *
1274 * By default, the configuration name is inherited from the parent Map.
1275 * By setting this property, a deviating configuration may be specified.
1276 *
1277 * The default is null, means inheriting from the parent form.
1278 *
1279 * @name LuCI.form.AbstractValue.prototype#uciconfig
1280 * @type string
1281 * @default null
1282 */
1283
1284 /**
1285 * Override the UCI section name to read the option value from.
1286 *
1287 * By default, the section ID is inherited from the parent section element.
1288 * By setting this property, a deviating section may be specified.
1289 *
1290 * The default is null, means inheriting from the parent section.
1291 *
1292 * @name LuCI.form.AbstractValue.prototype#ucisection
1293 * @type string
1294 * @default null
1295 */
1296
1297 /**
1298 * Override the UCI option name to read the value from.
1299 *
1300 * By default, the elements name, which is passed as third argument to
1301 * the constructor, is used as UCI option name. By setting this property,
1302 * a deviating UCI option may be specified.
1303 *
1304 * The default is null, means using the option element name.
1305 *
1306 * @name LuCI.form.AbstractValue.prototype#ucioption
1307 * @type string
1308 * @default null
1309 */
1310
1311 /**
1312 * Mark grid section option element as editable.
1313 *
1314 * Options which are displayed in the table portion of a `GridSection`
1315 * instance are rendered as readonly text by default. By setting the
1316 * `editable` property of a child option element to `true`, that element
1317 * is rendered as full input widget within its cell instead of a text only
1318 * preview.
1319 *
1320 * This property has no effect on options that are not children of grid
1321 * section elements.
1322 *
1323 * @name LuCI.form.AbstractValue.prototype#editable
1324 * @type boolean
1325 * @default false
1326 */
1327
1328 /**
1329 * Move grid section option element into the table, the modal popup or both.
1330 *
1331 * If this property is `null` (the default), the option element is
1332 * displayed in both the table preview area and the per-section instance
1333 * modal popup of a grid section. When it is set to `false` the option
1334 * is only shown in the table but not the modal popup. When set to `true`,
1335 * the option is only visible in the modal popup but not the table.
1336 *
1337 * This property has no effect on options that are not children of grid
1338 * section elements.
1339 *
1340 * @name LuCI.form.AbstractValue.prototype#modalonly
1341 * @type boolean
1342 * @default null
1343 */
1344
1345 /**
1346 * Make option element readonly.
1347 *
1348 * This property defaults to the readonly state of the parent form element.
1349 * When set to `true`, the underlying widget is rendered in disabled state,
1350 * means its contents cannot be changed and the widget cannot be interacted
1351 * with.
1352 *
1353 * @name LuCI.form.AbstractValue.prototype#readonly
1354 * @type boolean
1355 * @default false
1356 */
1357
1358 /**
1359 * Override the cell width of a table or grid section child option.
1360 *
1361 * If the property is set to a numeric value, it is treated as pixel width
1362 * which is set on the containing cell element of the option, essentially
1363 * forcing a certain column width. When the property is set to a string
1364 * value, it is applied as-is to the CSS `width` property.
1365 *
1366 * This property has no effect on options that are not children of grid or
1367 * table section elements.
1368 *
1369 * @name LuCI.form.AbstractValue.prototype#width
1370 * @type number|string
1371 * @default null
1372 */
1373
1374 /**
1375 * Add a dependency contraint to the option.
1376 *
1377 * Dependency constraints allow making the presence of option elements
1378 * dependant on the current values of certain other options within the
1379 * same form. An option element with unsatisfied dependencies will be
1380 * hidden from the view and its current value is omitted when saving.
1381 *
1382 * Multiple constraints (that is, multiple calls to `depends()`) are
1383 * treated as alternatives, forming a logical "or" expression.
1384 *
1385 * By passing an object of name => value pairs as first argument, it is
1386 * possible to depend on multiple options simultaneously, allowing to form
1387 * a logical "and" expression.
1388 *
1389 * Option names may be given in "dot notation" which allows to reference
1390 * option elements outside of the current form section. If a name without
1391 * dot is specified, it refers to an option within the same configuration
1392 * section. If specified as <code>configname.sectionid.optionname</code>,
1393 * options anywhere within the same form may be specified.
1394 *
1395 * The object notation also allows for a number of special keys which are
1396 * not treated as option names but as modifiers to influence the dependency
1397 * constraint evaluation. The associated value of these special "tag" keys
1398 * is ignored. The recognized tags are:
1399 *
1400 * <ul>
1401 * <li>
1402 * <code>!reverse</code><br>
1403 * Invert the dependency, instead of requiring another option to be
1404 * equal to the dependency value, that option should <em>not</em> be
1405 * equal.
1406 * </li>
1407 * <li>
1408 * <code>!contains</code><br>
1409 * Instead of requiring an exact match, the dependency is considered
1410 * satisfied when the dependency value is contained within the option
1411 * value.
1412 * </li>
1413 * <li>
1414 * <code>!default</code><br>
1415 * The dependency is always satisfied
1416 * </li>
1417 * </ul>
1418 *
1419 * Examples:
1420 *
1421 * <ul>
1422 * <li>
1423 * <code>opt.depends("foo", "test")</code><br>
1424 * Require the value of `foo` to be `test`.
1425 * </li>
1426 * <li>
1427 * <code>opt.depends({ foo: "test" })</code><br>
1428 * Equivalent to the previous example.
1429 * </li>
1430 * <li>
1431 * <code>opt.depends({ foo: "test", bar: "qrx" })</code><br>
1432 * Require the value of `foo` to be `test` and the value of `bar` to be
1433 * `qrx`.
1434 * </li>
1435 * <li>
1436 * <code>opt.depends({ foo: "test" })<br>
1437 * opt.depends({ bar: "qrx" })</code><br>
1438 * Require either <code>foo</code> to be set to <code>test</code>,
1439 * <em>or</em> the <code>bar</code> option to be <code>qrx</code>.
1440 * </li>
1441 * <li>
1442 * <code>opt.depends("test.section1.foo", "bar")</code><br>
1443 * Require the "foo" form option within the "section1" section to be
1444 * set to "bar".
1445 * </li>
1446 * <li>
1447 * <code>opt.depends({ foo: "test", "!contains": true })</code><br>
1448 * Require the "foo" option value to contain the substring "test".
1449 * </li>
1450 * </ul>
1451 *
1452 * @param {string|Object<string, string|boolean>} optionname_or_depends
1453 * The name of the option to depend on or an object describing multiple
1454 * dependencies which must be satified (a logical "and" expression).
1455 *
1456 * @param {string} optionvalue
1457 * When invoked with a plain option name as first argument, this parameter
1458 * specifies the expected value. In case an object is passed as first
1459 * argument, this parameter is ignored.
1460 */
1461 depends: function(field, value) {
1462 var deps;
1463
1464 if (typeof(field) === 'string')
1465 deps = {}, deps[field] = value;
1466 else
1467 deps = field;
1468
1469 this.deps.push(deps);
1470 },
1471
1472 /** @private */
1473 transformDepList: function(section_id, deplist) {
1474 var list = deplist || this.deps,
1475 deps = [];
1476
1477 if (Array.isArray(list)) {
1478 for (var i = 0; i < list.length; i++) {
1479 var dep = {};
1480
1481 for (var k in list[i]) {
1482 if (list[i].hasOwnProperty(k)) {
1483 if (k.charAt(0) === '!')
1484 dep[k] = list[i][k];
1485 else if (k.indexOf('.') !== -1)
1486 dep['cbid.%s'.format(k)] = list[i][k];
1487 else
1488 dep['cbid.%s.%s.%s'.format(
1489 this.uciconfig || this.section.uciconfig || this.map.config,
1490 this.ucisection || section_id,
1491 k
1492 )] = list[i][k];
1493 }
1494 }
1495
1496 for (var k in dep) {
1497 if (dep.hasOwnProperty(k)) {
1498 deps.push(dep);
1499 break;
1500 }
1501 }
1502 }
1503 }
1504
1505 return deps;
1506 },
1507
1508 /** @private */
1509 transformChoices: function() {
1510 if (!Array.isArray(this.keylist) || this.keylist.length == 0)
1511 return null;
1512
1513 var choices = {};
1514
1515 for (var i = 0; i < this.keylist.length; i++)
1516 choices[this.keylist[i]] = this.vallist[i];
1517
1518 return choices;
1519 },
1520
1521 /** @private */
1522 checkDepends: function(section_id) {
1523 var config_name = this.uciconfig || this.section.uciconfig || this.map.config,
1524 active = this.map.isDependencySatisfied(this.deps, config_name, section_id);
1525
1526 if (active)
1527 this.updateDefaultValue(section_id);
1528
1529 return active;
1530 },
1531
1532 /** @private */
1533 updateDefaultValue: function(section_id) {
1534 if (!L.isObject(this.defaults))
1535 return;
1536
1537 var config_name = this.uciconfig || this.section.uciconfig || this.map.config,
1538 cfgvalue = L.toArray(this.cfgvalue(section_id))[0],
1539 default_defval = null, satisified_defval = null;
1540
1541 for (var value in this.defaults) {
1542 if (!this.defaults[value] || this.defaults[value].length == 0) {
1543 default_defval = value;
1544 continue;
1545 }
1546 else if (this.map.isDependencySatisfied(this.defaults[value], config_name, section_id)) {
1547 satisified_defval = value;
1548 break;
1549 }
1550 }
1551
1552 if (satisified_defval == null)
1553 satisified_defval = default_defval;
1554
1555 var node = this.map.findElement('id', this.cbid(section_id));
1556 if (node && node.getAttribute('data-changed') != 'true' && satisified_defval != null && cfgvalue == null)
1557 dom.callClassMethod(node, 'setValue', satisified_defval);
1558
1559 this.default = satisified_defval;
1560 },
1561
1562 /**
1563 * Obtain the internal ID ("cbid") of the element instance.
1564 *
1565 * Since each form section element may map multiple underlying
1566 * configuration sections, the configuration section ID is required to
1567 * form a fully qualified ID pointing to the specific element instance
1568 * within the given specific section.
1569 *
1570 * @param {string} section_id
1571 * The configuration section ID
1572 *
1573 * @throws {TypeError}
1574 * Throws a `TypeError` exception when no `section_id` was specified.
1575 *
1576 * @returns {string}
1577 * Returns the element ID.
1578 */
1579 cbid: function(section_id) {
1580 if (section_id == null)
1581 L.error('TypeError', 'Section ID required');
1582
1583 return 'cbid.%s.%s.%s'.format(
1584 this.uciconfig || this.section.uciconfig || this.map.config,
1585 section_id, this.option);
1586 },
1587
1588 /**
1589 * Load the underlying configuration value.
1590 *
1591 * The default implementation of this method reads and returns the
1592 * underlying UCI option value (or the related JavaScript property for
1593 * `JSONMap` instances). It may be overwritten by user code to load data
1594 * from nonstandard sources.
1595 *
1596 * @param {string} section_id
1597 * The configuration section ID
1598 *
1599 * @throws {TypeError}
1600 * Throws a `TypeError` exception when no `section_id` was specified.
1601 *
1602 * @returns {*|Promise<*>}
1603 * Returns the configuration value to initialize the option element with.
1604 * The return value of this function is filtered through `Promise.resolve()`
1605 * so it may return promises if overridden by user code.
1606 */
1607 load: function(section_id) {
1608 if (section_id == null)
1609 L.error('TypeError', 'Section ID required');
1610
1611 return this.map.data.get(
1612 this.uciconfig || this.section.uciconfig || this.map.config,
1613 this.ucisection || section_id,
1614 this.ucioption || this.option);
1615 },
1616
1617 /**
1618 * Obtain the underlying `LuCI.ui` element instance.
1619 *
1620 * @param {string} section_id
1621 * The configuration section ID
1622 *
1623 * @throws {TypeError}
1624 * Throws a `TypeError` exception when no `section_id` was specified.
1625 *
1626 * @return {LuCI.ui.AbstractElement|null}
1627 * Returns the `LuCI.ui` element instance or `null` in case the form
1628 * option implementation does not use `LuCI.ui` widgets.
1629 */
1630 getUIElement: function(section_id) {
1631 var node = this.map.findElement('id', this.cbid(section_id)),
1632 inst = node ? dom.findClassInstance(node) : null;
1633 return (inst instanceof ui.AbstractElement) ? inst : null;
1634 },
1635
1636 /**
1637 * Query the underlying configuration value.
1638 *
1639 * The default implementation of this method returns the cached return
1640 * value of [load()]{@link LuCI.form.AbstractValue#load}. It may be
1641 * overwritten by user code to obtain the configuration value in a
1642 * different way.
1643 *
1644 * @param {string} section_id
1645 * The configuration section ID
1646 *
1647 * @throws {TypeError}
1648 * Throws a `TypeError` exception when no `section_id` was specified.
1649 *
1650 * @returns {*}
1651 * Returns the configuration value.
1652 */
1653 cfgvalue: function(section_id, set_value) {
1654 if (section_id == null)
1655 L.error('TypeError', 'Section ID required');
1656
1657 if (arguments.length == 2) {
1658 this.data = this.data || {};
1659 this.data[section_id] = set_value;
1660 }
1661
1662 return this.data ? this.data[section_id] : null;
1663 },
1664
1665 /**
1666 * Query the current form input value.
1667 *
1668 * The default implementation of this method returns the current input
1669 * value of the underlying [LuCI.ui]{@link LuCI.ui.AbstractElement} widget.
1670 * It may be overwritten by user code to handle input values differently.
1671 *
1672 * @param {string} section_id
1673 * The configuration section ID
1674 *
1675 * @throws {TypeError}
1676 * Throws a `TypeError` exception when no `section_id` was specified.
1677 *
1678 * @returns {*}
1679 * Returns the current input value.
1680 */
1681 formvalue: function(section_id) {
1682 var elem = this.getUIElement(section_id);
1683 return elem ? elem.getValue() : null;
1684 },
1685
1686 /**
1687 * Obtain a textual input representation.
1688 *
1689 * The default implementation of this method returns the HTML escaped
1690 * current input value of the underlying
1691 * [LuCI.ui]{@link LuCI.ui.AbstractElement} widget. User code or specific
1692 * option element implementations may overwrite this function to apply a
1693 * different logic, e.g. to return `Yes` or `No` depending on the checked
1694 * state of checkbox elements.
1695 *
1696 * @param {string} section_id
1697 * The configuration section ID
1698 *
1699 * @throws {TypeError}
1700 * Throws a `TypeError` exception when no `section_id` was specified.
1701 *
1702 * @returns {string}
1703 * Returns the text representation of the current input value.
1704 */
1705 textvalue: function(section_id) {
1706 var cval = this.cfgvalue(section_id);
1707
1708 if (cval == null)
1709 cval = this.default;
1710
1711 return (cval != null) ? '%h'.format(cval) : null;
1712 },
1713
1714 /**
1715 * Apply custom validation logic.
1716 *
1717 * This method is invoked whenever incremental validation is performed on
1718 * the user input, e.g. on keyup or blur events.
1719 *
1720 * The default implementation of this method does nothing and always
1721 * returns `true`. User code may overwrite this method to provide
1722 * additional validation logic which is not covered by data type
1723 * constraints.
1724 *
1725 * @abstract
1726 * @param {string} section_id
1727 * The configuration section ID
1728 *
1729 * @param {*} value
1730 * The value to validate
1731 *
1732 * @returns {*}
1733 * The method shall return `true` to accept the given value. Any other
1734 * return value is treated as failure, converted to a string and displayed
1735 * as error message to the user.
1736 */
1737 validate: function(section_id, value) {
1738 return true;
1739 },
1740
1741 /**
1742 * Test whether the input value is currently valid.
1743 *
1744 * @param {string} section_id
1745 * The configuration section ID
1746 *
1747 * @returns {boolean}
1748 * Returns `true` if the input value currently is valid, otherwise it
1749 * returns `false`.
1750 */
1751 isValid: function(section_id) {
1752 var elem = this.getUIElement(section_id);
1753 return elem ? elem.isValid() : true;
1754 },
1755
1756 /**
1757 * Test whether the option element is currently active.
1758 *
1759 * An element is active when it is not hidden due to unsatisfied dependency
1760 * constraints.
1761 *
1762 * @param {string} section_id
1763 * The configuration section ID
1764 *
1765 * @returns {boolean}
1766 * Returns `true` if the option element currently is active, otherwise it
1767 * returns `false`.
1768 */
1769 isActive: function(section_id) {
1770 var field = this.map.findElement('data-field', this.cbid(section_id));
1771 return (field != null && !field.classList.contains('hidden'));
1772 },
1773
1774 /** @private */
1775 setActive: function(section_id, active) {
1776 var field = this.map.findElement('data-field', this.cbid(section_id));
1777
1778 if (field && field.classList.contains('hidden') == active) {
1779 field.classList[active ? 'remove' : 'add']('hidden');
1780
1781 if (dom.matches(field.parentNode, '.td.cbi-value-field'))
1782 field.parentNode.classList[active ? 'remove' : 'add']('inactive');
1783
1784 return true;
1785 }
1786
1787 return false;
1788 },
1789
1790 /** @private */
1791 triggerValidation: function(section_id) {
1792 var elem = this.getUIElement(section_id);
1793 return elem ? elem.triggerValidation() : true;
1794 },
1795
1796 /**
1797 * Parse the option element input.
1798 *
1799 * The function is invoked when the `parse()` method has been invoked on
1800 * the parent form and triggers input value reading and validation.
1801 *
1802 * @param {string} section_id
1803 * The configuration section ID
1804 *
1805 * @returns {Promise<void>}
1806 * Returns a promise resolving once the input value has been read and
1807 * validated or rejecting in case the input value does not meet the
1808 * validation constraints.
1809 */
1810 parse: function(section_id) {
1811 var active = this.isActive(section_id),
1812 cval = this.cfgvalue(section_id),
1813 fval = active ? this.formvalue(section_id) : null;
1814
1815 if (active && !this.isValid(section_id)) {
1816 var title = this.stripTags(this.title).trim();
1817 return Promise.reject(new TypeError(_('Option "%s" contains an invalid input value.').format(title || this.option)));
1818 }
1819
1820 if (fval != '' && fval != null) {
1821 if (this.forcewrite || !isEqual(cval, fval))
1822 return Promise.resolve(this.write(section_id, fval));
1823 }
1824 else {
1825 if (!active || this.rmempty || this.optional) {
1826 return Promise.resolve(this.remove(section_id));
1827 }
1828 else if (!isEqual(cval, fval)) {
1829 var title = this.stripTags(this.title).trim();
1830 return Promise.reject(new TypeError(_('Option "%s" must not be empty.').format(title || this.option)));
1831 }
1832 }
1833
1834 return Promise.resolve();
1835 },
1836
1837 /**
1838 * Write the current input value into the configuration.
1839 *
1840 * This function is invoked upon saving the parent form when the option
1841 * element is valid and when its input value has been changed compared to
1842 * the initial value returned by
1843 * [cfgvalue()]{@link LuCI.form.AbstractValue#cfgvalue}.
1844 *
1845 * The default implementation simply sets the given input value in the
1846 * UCI configuration (or the associated JavaScript object property in
1847 * case of `JSONMap` forms). It may be overwritten by user code to
1848 * implement alternative save logic, e.g. to transform the input value
1849 * before it is written.
1850 *
1851 * @param {string} section_id
1852 * The configuration section ID
1853 *
1854 * @param {string|string[]} formvalue
1855 * The input value to write.
1856 */
1857 write: function(section_id, formvalue) {
1858 return this.map.data.set(
1859 this.uciconfig || this.section.uciconfig || this.map.config,
1860 this.ucisection || section_id,
1861 this.ucioption || this.option,
1862 formvalue);
1863 },
1864
1865 /**
1866 * Remove the corresponding value from the configuration.
1867 *
1868 * This function is invoked upon saving the parent form when the option
1869 * element has been hidden due to unsatisfied dependencies or when the
1870 * user cleared the input value and the option is marked optional.
1871 *
1872 * The default implementation simply removes the associated option from the
1873 * UCI configuration (or the associated JavaScript object property in
1874 * case of `JSONMap` forms). It may be overwritten by user code to
1875 * implement alternative removal logic, e.g. to retain the original value.
1876 *
1877 * @param {string} section_id
1878 * The configuration section ID
1879 */
1880 remove: function(section_id) {
1881 return this.map.data.unset(
1882 this.uciconfig || this.section.uciconfig || this.map.config,
1883 this.ucisection || section_id,
1884 this.ucioption || this.option);
1885 }
1886 });
1887
1888 /**
1889 * @class TypedSection
1890 * @memberof LuCI.form
1891 * @augments LuCI.form.AbstractSection
1892 * @hideconstructor
1893 * @classdesc
1894 *
1895 * The `TypedSection` class maps all or - if `filter()` is overwritten - a
1896 * subset of the underlying UCI configuration sections of a given type.
1897 *
1898 * Layout wise, the configuration section instances mapped by the section
1899 * element (sometimes referred to as "section nodes") are stacked beneath
1900 * each other in a single column, with an optional section remove button next
1901 * to each section node and a section add button at the end, depending on the
1902 * value of the `addremove` property.
1903 *
1904 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
1905 * The configuration form this section is added to. It is automatically passed
1906 * by [section()]{@link LuCI.form.Map#section}.
1907 *
1908 * @param {string} section_type
1909 * The type of the UCI section to map.
1910 *
1911 * @param {string} [title]
1912 * The title caption of the form section element.
1913 *
1914 * @param {string} [description]
1915 * The description text of the form section element.
1916 */
1917 var CBITypedSection = CBIAbstractSection.extend(/** @lends LuCI.form.TypedSection.prototype */ {
1918 __name__: 'CBI.TypedSection',
1919
1920 /**
1921 * If set to `true`, the user may add or remove instances from the form
1922 * section widget, otherwise only preexisting sections may be edited.
1923 * The default is `false`.
1924 *
1925 * @name LuCI.form.TypedSection.prototype#addremove
1926 * @type boolean
1927 * @default false
1928 */
1929
1930 /**
1931 * If set to `true`, mapped section instances are treated as anonymous
1932 * UCI sections, which means that section instance elements will be
1933 * rendered without title element and that no name is required when adding
1934 * new sections. The default is `false`.
1935 *
1936 * @name LuCI.form.TypedSection.prototype#anonymous
1937 * @type boolean
1938 * @default false
1939 */
1940
1941 /**
1942 * When set to `true`, instead of rendering section instances one below
1943 * another, treat each instance as separate tab pane and render a tab menu
1944 * at the top of the form section element, allowing the user to switch
1945 * among instances. The default is `false`.
1946 *
1947 * @name LuCI.form.TypedSection.prototype#tabbed
1948 * @type boolean
1949 * @default false
1950 */
1951
1952 /**
1953 * Override the caption used for the section add button at the bottom of
1954 * the section form element. If set to a string, it will be used as-is,
1955 * if set to a function, the function will be invoked and its return value
1956 * is used as caption, after converting it to a string. If this property
1957 * is not set, the default is `Add`.
1958 *
1959 * @name LuCI.form.TypedSection.prototype#addbtntitle
1960 * @type string|function
1961 * @default null
1962 */
1963
1964 /**
1965 * Override the UCI configuration name to read the section IDs from. By
1966 * default, the configuration name is inherited from the parent `Map`.
1967 * By setting this property, a deviating configuration may be specified.
1968 * The default is `null`, means inheriting from the parent form.
1969 *
1970 * @name LuCI.form.TypedSection.prototype#uciconfig
1971 * @type string
1972 * @default null
1973 */
1974
1975 /** @override */
1976 cfgsections: function() {
1977 return this.map.data.sections(this.uciconfig || this.map.config, this.sectiontype)
1978 .map(function(s) { return s['.name'] })
1979 .filter(L.bind(this.filter, this));
1980 },
1981
1982 /** @private */
1983 handleAdd: function(ev, name) {
1984 var config_name = this.uciconfig || this.map.config;
1985
1986 this.map.data.add(config_name, this.sectiontype, name);
1987 return this.map.save(null, true);
1988 },
1989
1990 /** @private */
1991 handleRemove: function(section_id, ev) {
1992 var config_name = this.uciconfig || this.map.config;
1993
1994 this.map.data.remove(config_name, section_id);
1995 return this.map.save(null, true);
1996 },
1997
1998 /** @private */
1999 renderSectionAdd: function(extra_class) {
2000 if (!this.addremove)
2001 return E([]);
2002
2003 var createEl = E('div', { 'class': 'cbi-section-create' }),
2004 config_name = this.uciconfig || this.map.config,
2005 btn_title = this.titleFn('addbtntitle');
2006
2007 if (extra_class != null)
2008 createEl.classList.add(extra_class);
2009
2010 if (this.anonymous) {
2011 createEl.appendChild(E('button', {
2012 'class': 'cbi-button cbi-button-add',
2013 'title': btn_title || _('Add'),
2014 'click': ui.createHandlerFn(this, 'handleAdd'),
2015 'disabled': this.map.readonly || null
2016 }, [ btn_title || _('Add') ]));
2017 }
2018 else {
2019 var nameEl = E('input', {
2020 'type': 'text',
2021 'class': 'cbi-section-create-name',
2022 'disabled': this.map.readonly || null
2023 });
2024
2025 dom.append(createEl, [
2026 E('div', {}, nameEl),
2027 E('input', {
2028 'class': 'cbi-button cbi-button-add',
2029 'type': 'submit',
2030 'value': btn_title || _('Add'),
2031 'title': btn_title || _('Add'),
2032 'click': ui.createHandlerFn(this, function(ev) {
2033 if (nameEl.classList.contains('cbi-input-invalid'))
2034 return;
2035
2036 return this.handleAdd(ev, nameEl.value);
2037 }),
2038 'disabled': this.map.readonly || null
2039 })
2040 ]);
2041
2042 ui.addValidator(nameEl, 'uciname', true, 'blur', 'keyup');
2043 }
2044
2045 return createEl;
2046 },
2047
2048 /** @private */
2049 renderSectionPlaceholder: function() {
2050 return E([
2051 E('em', _('This section contains no values yet')),
2052 E('br'), E('br')
2053 ]);
2054 },
2055
2056 /** @private */
2057 renderContents: function(cfgsections, nodes) {
2058 var section_id = null,
2059 config_name = this.uciconfig || this.map.config,
2060 sectionEl = E('div', {
2061 'id': 'cbi-%s-%s'.format(config_name, this.sectiontype),
2062 'class': 'cbi-section',
2063 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2064 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2065 });
2066
2067 if (this.title != null && this.title != '')
2068 sectionEl.appendChild(E('legend', {}, this.title));
2069
2070 if (this.description != null && this.description != '')
2071 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2072
2073 for (var i = 0; i < nodes.length; i++) {
2074 if (this.addremove) {
2075 sectionEl.appendChild(
2076 E('div', { 'class': 'cbi-section-remove right' },
2077 E('button', {
2078 'class': 'cbi-button',
2079 'name': 'cbi.rts.%s.%s'.format(config_name, cfgsections[i]),
2080 'data-section-id': cfgsections[i],
2081 'click': ui.createHandlerFn(this, 'handleRemove', cfgsections[i]),
2082 'disabled': this.map.readonly || null
2083 }, [ _('Delete') ])));
2084 }
2085
2086 if (!this.anonymous)
2087 sectionEl.appendChild(E('h3', cfgsections[i].toUpperCase()));
2088
2089 sectionEl.appendChild(E('div', {
2090 'id': 'cbi-%s-%s'.format(config_name, cfgsections[i]),
2091 'class': this.tabs
2092 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
2093 'data-section-id': cfgsections[i]
2094 }, nodes[i]));
2095 }
2096
2097 if (nodes.length == 0)
2098 sectionEl.appendChild(this.renderSectionPlaceholder());
2099
2100 sectionEl.appendChild(this.renderSectionAdd());
2101
2102 dom.bindClassInstance(sectionEl, this);
2103
2104 return sectionEl;
2105 },
2106
2107 /** @override */
2108 render: function() {
2109 var cfgsections = this.cfgsections(),
2110 renderTasks = [];
2111
2112 for (var i = 0; i < cfgsections.length; i++)
2113 renderTasks.push(this.renderUCISection(cfgsections[i]));
2114
2115 return Promise.all(renderTasks).then(this.renderContents.bind(this, cfgsections));
2116 }
2117 });
2118
2119 /**
2120 * @class TableSection
2121 * @memberof LuCI.form
2122 * @augments LuCI.form.TypedSection
2123 * @hideconstructor
2124 * @classdesc
2125 *
2126 * The `TableSection` class maps all or - if `filter()` is overwritten - a
2127 * subset of the underlying UCI configuration sections of a given type.
2128 *
2129 * Layout wise, the configuration section instances mapped by the section
2130 * element (sometimes referred to as "section nodes") are rendered as rows
2131 * within an HTML table element, with an optional section remove button in the
2132 * last column and a section add button below the table, depending on the
2133 * value of the `addremove` property.
2134 *
2135 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2136 * The configuration form this section is added to. It is automatically passed
2137 * by [section()]{@link LuCI.form.Map#section}.
2138 *
2139 * @param {string} section_type
2140 * The type of the UCI section to map.
2141 *
2142 * @param {string} [title]
2143 * The title caption of the form section element.
2144 *
2145 * @param {string} [description]
2146 * The description text of the form section element.
2147 */
2148 var CBITableSection = CBITypedSection.extend(/** @lends LuCI.form.TableSection.prototype */ {
2149 __name__: 'CBI.TableSection',
2150
2151 /**
2152 * If set to `true`, the user may add or remove instances from the form
2153 * section widget, otherwise only preexisting sections may be edited.
2154 * The default is `false`.
2155 *
2156 * @name LuCI.form.TableSection.prototype#addremove
2157 * @type boolean
2158 * @default false
2159 */
2160
2161 /**
2162 * If set to `true`, mapped section instances are treated as anonymous
2163 * UCI sections, which means that section instance elements will be
2164 * rendered without title element and that no name is required when adding
2165 * new sections. The default is `false`.
2166 *
2167 * @name LuCI.form.TableSection.prototype#anonymous
2168 * @type boolean
2169 * @default false
2170 */
2171
2172 /**
2173 * Override the caption used for the section add button at the bottom of
2174 * the section form element. If set to a string, it will be used as-is,
2175 * if set to a function, the function will be invoked and its return value
2176 * is used as caption, after converting it to a string. If this property
2177 * is not set, the default is `Add`.
2178 *
2179 * @name LuCI.form.TableSection.prototype#addbtntitle
2180 * @type string|function
2181 * @default null
2182 */
2183
2184 /**
2185 * Override the per-section instance title caption shown in the first
2186 * column of the table unless `anonymous` is set to true. If set to a
2187 * string, it will be used as `String.format()` pattern with the name of
2188 * the underlying UCI section as first argument, if set to a function, the
2189 * function will be invoked with the section name as first argument and
2190 * its return value is used as caption, after converting it to a string.
2191 * If this property is not set, the default is the name of the underlying
2192 * UCI configuration section.
2193 *
2194 * @name LuCI.form.TableSection.prototype#sectiontitle
2195 * @type string|function
2196 * @default null
2197 */
2198
2199 /**
2200 * Override the per-section instance modal popup title caption shown when
2201 * clicking the `More…` button in a section specifying `max_cols`. If set
2202 * to a string, it will be used as `String.format()` pattern with the name
2203 * of the underlying UCI section as first argument, if set to a function,
2204 * the function will be invoked with the section name as first argument and
2205 * its return value is used as caption, after converting it to a string.
2206 * If this property is not set, the default is the name of the underlying
2207 * UCI configuration section.
2208 *
2209 * @name LuCI.form.TableSection.prototype#modaltitle
2210 * @type string|function
2211 * @default null
2212 */
2213
2214 /**
2215 * Override the UCI configuration name to read the section IDs from. By
2216 * default, the configuration name is inherited from the parent `Map`.
2217 * By setting this property, a deviating configuration may be specified.
2218 * The default is `null`, means inheriting from the parent form.
2219 *
2220 * @name LuCI.form.TableSection.prototype#uciconfig
2221 * @type string
2222 * @default null
2223 */
2224
2225 /**
2226 * Specify a maximum amount of columns to display. By default, one table
2227 * column is rendered for each child option of the form section element.
2228 * When this option is set to a positive number, then no more columns than
2229 * the given amount are rendered. When the number of child options exceeds
2230 * the specified amount, a `More…` button is rendered in the last column,
2231 * opening a modal dialog presenting all options elements in `NamedSection`
2232 * style when clicked.
2233 *
2234 * @name LuCI.form.TableSection.prototype#max_cols
2235 * @type number
2236 * @default null
2237 */
2238
2239 /**
2240 * If set to `true`, alternating `cbi-rowstyle-1` and `cbi-rowstyle-2` CSS
2241 * classes are added to the table row elements. Not all LuCI themes
2242 * implement these row style classes. The default is `false`.
2243 *
2244 * @name LuCI.form.TableSection.prototype#rowcolors
2245 * @type boolean
2246 * @default false
2247 */
2248
2249 /**
2250 * Enables a per-section instance row `Edit` button which triggers a certain
2251 * action when clicked. If set to a string, the string value is used
2252 * as `String.format()` pattern with the name of the underlying UCI section
2253 * as first format argument. The result is then interpreted as URL which
2254 * LuCI will navigate to when the user clicks the edit button.
2255 *
2256 * If set to a function, this function will be registered as click event
2257 * handler on the rendered edit button, receiving the section instance
2258 * name as first and the DOM click event as second argument.
2259 *
2260 * @name LuCI.form.TableSection.prototype#extedit
2261 * @type string|function
2262 * @default null
2263 */
2264
2265 /**
2266 * If set to `true`, a sort button is added to the last column, allowing
2267 * the user to reorder the section instances mapped by the section form
2268 * element.
2269 *
2270 * @name LuCI.form.TableSection.prototype#sortable
2271 * @type boolean
2272 * @default false
2273 */
2274
2275 /**
2276 * If set to `true`, the header row with the options descriptions will
2277 * not be displayed. By default, descriptions row is automatically displayed
2278 * when at least one option has a description.
2279 *
2280 * @name LuCI.form.TableSection.prototype#nodescriptions
2281 * @type boolean
2282 * @default false
2283 */
2284
2285 /**
2286 * The `TableSection` implementation does not support option tabbing, so
2287 * its implementation of `tab()` will always throw an exception when
2288 * invoked.
2289 *
2290 * @override
2291 * @throws Throws an exception when invoked.
2292 */
2293 tab: function() {
2294 throw 'Tabs are not supported by TableSection';
2295 },
2296
2297 /** @private */
2298 renderContents: function(cfgsections, nodes) {
2299 var section_id = null,
2300 config_name = this.uciconfig || this.map.config,
2301 max_cols = isNaN(this.max_cols) ? this.children.length : this.max_cols,
2302 has_more = max_cols < this.children.length,
2303 sectionEl = E('div', {
2304 'id': 'cbi-%s-%s'.format(config_name, this.sectiontype),
2305 'class': 'cbi-section cbi-tblsection',
2306 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2307 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2308 }),
2309 tableEl = E('div', {
2310 'class': 'table cbi-section-table'
2311 });
2312
2313 if (this.title != null && this.title != '')
2314 sectionEl.appendChild(E('h3', {}, this.title));
2315
2316 if (this.description != null && this.description != '')
2317 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2318
2319 tableEl.appendChild(this.renderHeaderRows(max_cols));
2320
2321 for (var i = 0; i < nodes.length; i++) {
2322 var sectionname = this.titleFn('sectiontitle', cfgsections[i]);
2323
2324 if (sectionname == null)
2325 sectionname = cfgsections[i];
2326
2327 var trEl = E('div', {
2328 'id': 'cbi-%s-%s'.format(config_name, cfgsections[i]),
2329 'class': 'tr cbi-section-table-row',
2330 'data-sid': cfgsections[i],
2331 'draggable': this.sortable ? true : null,
2332 'mousedown': this.sortable ? L.bind(this.handleDragInit, this) : null,
2333 'dragstart': this.sortable ? L.bind(this.handleDragStart, this) : null,
2334 'dragover': this.sortable ? L.bind(this.handleDragOver, this) : null,
2335 'dragenter': this.sortable ? L.bind(this.handleDragEnter, this) : null,
2336 'dragleave': this.sortable ? L.bind(this.handleDragLeave, this) : null,
2337 'dragend': this.sortable ? L.bind(this.handleDragEnd, this) : null,
2338 'drop': this.sortable ? L.bind(this.handleDrop, this) : null,
2339 'data-title': (sectionname && (!this.anonymous || this.sectiontitle)) ? sectionname : null,
2340 'data-section-id': cfgsections[i]
2341 });
2342
2343 if (this.extedit || this.rowcolors)
2344 trEl.classList.add(!(tableEl.childNodes.length % 2)
2345 ? 'cbi-rowstyle-1' : 'cbi-rowstyle-2');
2346
2347 for (var j = 0; j < max_cols && nodes[i].firstChild; j++)
2348 trEl.appendChild(nodes[i].firstChild);
2349
2350 trEl.appendChild(this.renderRowActions(cfgsections[i], has_more ? _('More…') : null));
2351 tableEl.appendChild(trEl);
2352 }
2353
2354 if (nodes.length == 0)
2355 tableEl.appendChild(E('div', { 'class': 'tr cbi-section-table-row placeholder' },
2356 E('div', { 'class': 'td' },
2357 E('em', {}, _('This section contains no values yet')))));
2358
2359 sectionEl.appendChild(tableEl);
2360
2361 sectionEl.appendChild(this.renderSectionAdd('cbi-tblsection-create'));
2362
2363 dom.bindClassInstance(sectionEl, this);
2364
2365 return sectionEl;
2366 },
2367
2368 /** @private */
2369 renderHeaderRows: function(max_cols, has_action) {
2370 var has_titles = false,
2371 has_descriptions = false,
2372 max_cols = isNaN(this.max_cols) ? this.children.length : this.max_cols,
2373 has_more = max_cols < this.children.length,
2374 anon_class = (!this.anonymous || this.sectiontitle) ? 'named' : 'anonymous',
2375 trEls = E([]);
2376
2377 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2378 if (opt.modalonly)
2379 continue;
2380
2381 has_titles = has_titles || !!opt.title;
2382 has_descriptions = has_descriptions || !!opt.description;
2383 }
2384
2385 if (has_titles) {
2386 var trEl = E('div', {
2387 'class': 'tr cbi-section-table-titles ' + anon_class,
2388 'data-title': (!this.anonymous || this.sectiontitle) ? _('Name') : null
2389 });
2390
2391 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2392 if (opt.modalonly)
2393 continue;
2394
2395 trEl.appendChild(E('div', {
2396 'class': 'th cbi-section-table-cell',
2397 'data-widget': opt.__name__
2398 }));
2399
2400 if (opt.width != null)
2401 trEl.lastElementChild.style.width =
2402 (typeof(opt.width) == 'number') ? opt.width+'px' : opt.width;
2403
2404 if (opt.titleref)
2405 trEl.lastElementChild.appendChild(E('a', {
2406 'href': opt.titleref,
2407 'class': 'cbi-title-ref',
2408 'title': this.titledesc || _('Go to relevant configuration page')
2409 }, opt.title));
2410 else
2411 dom.content(trEl.lastElementChild, opt.title);
2412 }
2413
2414 if (this.sortable || this.extedit || this.addremove || has_more || has_action)
2415 trEl.appendChild(E('div', {
2416 'class': 'th cbi-section-table-cell cbi-section-actions'
2417 }));
2418
2419 trEls.appendChild(trEl);
2420 }
2421
2422 if (has_descriptions && !this.nodescriptions) {
2423 var trEl = E('div', {
2424 'class': 'tr cbi-section-table-descr ' + anon_class
2425 });
2426
2427 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2428 if (opt.modalonly)
2429 continue;
2430
2431 trEl.appendChild(E('div', {
2432 'class': 'th cbi-section-table-cell',
2433 'data-widget': opt.__name__
2434 }, opt.description));
2435
2436 if (opt.width != null)
2437 trEl.lastElementChild.style.width =
2438 (typeof(opt.width) == 'number') ? opt.width+'px' : opt.width;
2439 }
2440
2441 if (this.sortable || this.extedit || this.addremove || has_more || has_action)
2442 trEl.appendChild(E('div', {
2443 'class': 'th cbi-section-table-cell cbi-section-actions'
2444 }));
2445
2446 trEls.appendChild(trEl);
2447 }
2448
2449 return trEls;
2450 },
2451
2452 /** @private */
2453 renderRowActions: function(section_id, more_label) {
2454 var config_name = this.uciconfig || this.map.config;
2455
2456 if (!this.sortable && !this.extedit && !this.addremove && !more_label)
2457 return E([]);
2458
2459 var tdEl = E('div', {
2460 'class': 'td cbi-section-table-cell nowrap cbi-section-actions'
2461 }, E('div'));
2462
2463 if (this.sortable) {
2464 dom.append(tdEl.lastElementChild, [
2465 E('div', {
2466 'title': _('Drag to reorder'),
2467 'class': 'btn cbi-button drag-handle center',
2468 'style': 'cursor:move',
2469 'disabled': this.map.readonly || null
2470 }, '☰')
2471 ]);
2472 }
2473
2474 if (this.extedit) {
2475 var evFn = null;
2476
2477 if (typeof(this.extedit) == 'function')
2478 evFn = L.bind(this.extedit, this);
2479 else if (typeof(this.extedit) == 'string')
2480 evFn = L.bind(function(sid, ev) {
2481 location.href = this.extedit.format(sid);
2482 }, this, section_id);
2483
2484 dom.append(tdEl.lastElementChild,
2485 E('button', {
2486 'title': _('Edit'),
2487 'class': 'cbi-button cbi-button-edit',
2488 'click': evFn
2489 }, [ _('Edit') ])
2490 );
2491 }
2492
2493 if (more_label) {
2494 dom.append(tdEl.lastElementChild,
2495 E('button', {
2496 'title': more_label,
2497 'class': 'cbi-button cbi-button-edit',
2498 'click': ui.createHandlerFn(this, 'renderMoreOptionsModal', section_id)
2499 }, [ more_label ])
2500 );
2501 }
2502
2503 if (this.addremove) {
2504 var btn_title = this.titleFn('removebtntitle', section_id);
2505
2506 dom.append(tdEl.lastElementChild,
2507 E('button', {
2508 'title': btn_title || _('Delete'),
2509 'class': 'cbi-button cbi-button-remove',
2510 'click': ui.createHandlerFn(this, 'handleRemove', section_id),
2511 'disabled': this.map.readonly || null
2512 }, [ btn_title || _('Delete') ])
2513 );
2514 }
2515
2516 return tdEl;
2517 },
2518
2519 /** @private */
2520 handleDragInit: function(ev) {
2521 scope.dragState = { node: ev.target };
2522 },
2523
2524 /** @private */
2525 handleDragStart: function(ev) {
2526 if (!scope.dragState || !scope.dragState.node.classList.contains('drag-handle')) {
2527 scope.dragState = null;
2528 ev.preventDefault();
2529 return false;
2530 }
2531
2532 scope.dragState.node = dom.parent(scope.dragState.node, '.tr');
2533 ev.dataTransfer.setData('text', 'drag');
2534 ev.target.style.opacity = 0.4;
2535 },
2536
2537 /** @private */
2538 handleDragOver: function(ev) {
2539 var n = scope.dragState.targetNode,
2540 r = scope.dragState.rect,
2541 t = r.top + r.height / 2;
2542
2543 if (ev.clientY <= t) {
2544 n.classList.remove('drag-over-below');
2545 n.classList.add('drag-over-above');
2546 }
2547 else {
2548 n.classList.remove('drag-over-above');
2549 n.classList.add('drag-over-below');
2550 }
2551
2552 ev.dataTransfer.dropEffect = 'move';
2553 ev.preventDefault();
2554 return false;
2555 },
2556
2557 /** @private */
2558 handleDragEnter: function(ev) {
2559 scope.dragState.rect = ev.currentTarget.getBoundingClientRect();
2560 scope.dragState.targetNode = ev.currentTarget;
2561 },
2562
2563 /** @private */
2564 handleDragLeave: function(ev) {
2565 ev.currentTarget.classList.remove('drag-over-above');
2566 ev.currentTarget.classList.remove('drag-over-below');
2567 },
2568
2569 /** @private */
2570 handleDragEnd: function(ev) {
2571 var n = ev.target;
2572
2573 n.style.opacity = '';
2574 n.classList.add('flash');
2575 n.parentNode.querySelectorAll('.drag-over-above, .drag-over-below')
2576 .forEach(function(tr) {
2577 tr.classList.remove('drag-over-above');
2578 tr.classList.remove('drag-over-below');
2579 });
2580 },
2581
2582 /** @private */
2583 handleDrop: function(ev) {
2584 var s = scope.dragState;
2585
2586 if (s.node && s.targetNode) {
2587 var config_name = this.uciconfig || this.map.config,
2588 ref_node = s.targetNode,
2589 after = false;
2590
2591 if (ref_node.classList.contains('drag-over-below')) {
2592 ref_node = ref_node.nextElementSibling;
2593 after = true;
2594 }
2595
2596 var sid1 = s.node.getAttribute('data-sid'),
2597 sid2 = s.targetNode.getAttribute('data-sid');
2598
2599 s.node.parentNode.insertBefore(s.node, ref_node);
2600 this.map.data.move(config_name, sid1, sid2, after);
2601 }
2602
2603 scope.dragState = null;
2604 ev.target.style.opacity = '';
2605 ev.stopPropagation();
2606 ev.preventDefault();
2607 return false;
2608 },
2609
2610 /** @private */
2611 handleModalCancel: function(modalMap, ev) {
2612 return Promise.resolve(ui.hideModal());
2613 },
2614
2615 /** @private */
2616 handleModalSave: function(modalMap, ev) {
2617 return modalMap.save()
2618 .then(L.bind(this.map.load, this.map))
2619 .then(L.bind(this.map.reset, this.map))
2620 .then(ui.hideModal)
2621 .catch(function() {});
2622 },
2623
2624 /**
2625 * Add further options to the per-section instanced modal popup.
2626 *
2627 * This function may be overwritten by user code to perform additional
2628 * setup steps before displaying the more options modal which is useful to
2629 * e.g. query additional data or to inject further option elements.
2630 *
2631 * The default implementation of this function does nothing.
2632 *
2633 * @abstract
2634 * @param {LuCI.form.NamedSection} modalSection
2635 * The `NamedSection` instance about to be rendered in the modal popup.
2636 *
2637 * @param {string} section_id
2638 * The ID of the underlying UCI section the modal popup belongs to.
2639 *
2640 * @param {Event} ev
2641 * The DOM event emitted by clicking the `More…` button.
2642 *
2643 * @returns {*|Promise<*>}
2644 * Return values of this function are ignored but if a promise is returned,
2645 * it is run to completion before the rendering is continued, allowing
2646 * custom logic to perform asynchroneous work before the modal dialog
2647 * is shown.
2648 */
2649 addModalOptions: function(modalSection, section_id, ev) {
2650
2651 },
2652
2653 /** @private */
2654 renderMoreOptionsModal: function(section_id, ev) {
2655 var parent = this.map,
2656 title = parent.title,
2657 name = null,
2658 m = new CBIMap(this.map.config, null, null),
2659 s = m.section(CBINamedSection, section_id, this.sectiontype);
2660
2661 m.parent = parent;
2662 m.readonly = parent.readonly;
2663
2664 s.tabs = this.tabs;
2665 s.tab_names = this.tab_names;
2666
2667 if ((name = this.titleFn('modaltitle', section_id)) != null)
2668 title = name;
2669 else if ((name = this.titleFn('sectiontitle', section_id)) != null)
2670 title = '%s - %s'.format(parent.title, name);
2671 else if (!this.anonymous)
2672 title = '%s - %s'.format(parent.title, section_id);
2673
2674 for (var i = 0; i < this.children.length; i++) {
2675 var o1 = this.children[i];
2676
2677 if (o1.modalonly === false)
2678 continue;
2679
2680 var o2 = s.option(o1.constructor, o1.option, o1.title, o1.description);
2681
2682 for (var k in o1) {
2683 if (!o1.hasOwnProperty(k))
2684 continue;
2685
2686 switch (k) {
2687 case 'map':
2688 case 'section':
2689 case 'option':
2690 case 'title':
2691 case 'description':
2692 continue;
2693
2694 default:
2695 o2[k] = o1[k];
2696 }
2697 }
2698 }
2699
2700 return Promise.resolve(this.addModalOptions(s, section_id, ev)).then(L.bind(m.render, m)).then(L.bind(function(nodes) {
2701 ui.showModal(title, [
2702 nodes,
2703 E('div', { 'class': 'right' }, [
2704 E('button', {
2705 'class': 'btn',
2706 'click': ui.createHandlerFn(this, 'handleModalCancel', m)
2707 }, [ _('Dismiss') ]), ' ',
2708 E('button', {
2709 'class': 'cbi-button cbi-button-positive important',
2710 'click': ui.createHandlerFn(this, 'handleModalSave', m),
2711 'disabled': m.readonly || null
2712 }, [ _('Save') ])
2713 ])
2714 ], 'cbi-modal');
2715 }, this)).catch(L.error);
2716 }
2717 });
2718
2719 /**
2720 * @class GridSection
2721 * @memberof LuCI.form
2722 * @augments LuCI.form.TableSection
2723 * @hideconstructor
2724 * @classdesc
2725 *
2726 * The `GridSection` class maps all or - if `filter()` is overwritten - a
2727 * subset of the underlying UCI configuration sections of a given type.
2728 *
2729 * A grid section functions similar to a {@link LuCI.form.TableSection} but
2730 * supports tabbing in the modal overlay. Option elements added with
2731 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
2732 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
2733 * are displayed in the modal popup.
2734 *
2735 * Another important difference is that the table cells show a readonly text
2736 * preview of the corresponding option elements by default, unless the child
2737 * option element is explicitely made writable by setting the `editable`
2738 * property to `true`.
2739 *
2740 * Additionally, the grid section honours a `modalonly` property of child
2741 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
2742 * documentation for details.
2743 *
2744 * Layout wise, a grid section looks mostly identical to table sections.
2745 *
2746 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2747 * The configuration form this section is added to. It is automatically passed
2748 * by [section()]{@link LuCI.form.Map#section}.
2749 *
2750 * @param {string} section_type
2751 * The type of the UCI section to map.
2752 *
2753 * @param {string} [title]
2754 * The title caption of the form section element.
2755 *
2756 * @param {string} [description]
2757 * The description text of the form section element.
2758 */
2759 var CBIGridSection = CBITableSection.extend(/** @lends LuCI.form.GridSection.prototype */ {
2760 /**
2761 * Add an option tab to the section.
2762 *
2763 * The modal option elements of a grid section may be divided into multiple
2764 * tabs to provide a better overview to the user.
2765 *
2766 * Before options can be moved into a tab pane, the corresponding tab
2767 * has to be defined first, which is done by calling this function.
2768 *
2769 * Note that tabs are only effective in modal popups, options added with
2770 * `option()` will not be assigned to a specific tab and are rendered in
2771 * the table view only.
2772 *
2773 * @param {string} name
2774 * The name of the tab to register. It may be freely chosen and just serves
2775 * as an identifier to differentiate tabs.
2776 *
2777 * @param {string} title
2778 * The human readable caption of the tab.
2779 *
2780 * @param {string} [description]
2781 * An additional description text for the corresponding tab pane. It is
2782 * displayed as text paragraph below the tab but before the tab pane
2783 * contents. If omitted, no description will be rendered.
2784 *
2785 * @throws {Error}
2786 * Throws an exeption if a tab with the same `name` already exists.
2787 */
2788 tab: function(name, title, description) {
2789 CBIAbstractSection.prototype.tab.call(this, name, title, description);
2790 },
2791
2792 /** @private */
2793 handleAdd: function(ev, name) {
2794 var config_name = this.uciconfig || this.map.config,
2795 section_id = this.map.data.add(config_name, this.sectiontype, name);
2796
2797 this.addedSection = section_id;
2798 return this.renderMoreOptionsModal(section_id);
2799 },
2800
2801 /** @private */
2802 handleModalSave: function(/* ... */) {
2803 return this.super('handleModalSave', arguments)
2804 .then(L.bind(function() { this.addedSection = null }, this));
2805 },
2806
2807 /** @private */
2808 handleModalCancel: function(/* ... */) {
2809 var config_name = this.uciconfig || this.map.config;
2810
2811 if (this.addedSection != null) {
2812 this.map.data.remove(config_name, this.addedSection);
2813 this.addedSection = null;
2814 }
2815
2816 return this.super('handleModalCancel', arguments);
2817 },
2818
2819 /** @private */
2820 renderUCISection: function(section_id) {
2821 return this.renderOptions(null, section_id);
2822 },
2823
2824 /** @private */
2825 renderChildren: function(tab_name, section_id, in_table) {
2826 var tasks = [], index = 0;
2827
2828 for (var i = 0, opt; (opt = this.children[i]) != null; i++) {
2829 if (opt.disable || opt.modalonly)
2830 continue;
2831
2832 if (opt.editable)
2833 tasks.push(opt.render(index++, section_id, in_table));
2834 else
2835 tasks.push(this.renderTextValue(section_id, opt));
2836 }
2837
2838 return Promise.all(tasks);
2839 },
2840
2841 /** @private */
2842 renderTextValue: function(section_id, opt) {
2843 var title = this.stripTags(opt.title).trim(),
2844 descr = this.stripTags(opt.description).trim(),
2845 value = opt.textvalue(section_id);
2846
2847 return E('div', {
2848 'class': 'td cbi-value-field',
2849 'data-title': (title != '') ? title : null,
2850 'data-description': (descr != '') ? descr : null,
2851 'data-name': opt.option,
2852 'data-widget': opt.typename || opt.__name__
2853 }, (value != null) ? value : E('em', _('none')));
2854 },
2855
2856 /** @private */
2857 renderHeaderRows: function(section_id) {
2858 return this.super('renderHeaderRows', [ NaN, true ]);
2859 },
2860
2861 /** @private */
2862 renderRowActions: function(section_id) {
2863 return this.super('renderRowActions', [ section_id, _('Edit') ]);
2864 },
2865
2866 /** @override */
2867 parse: function() {
2868 var section_ids = this.cfgsections(),
2869 tasks = [];
2870
2871 if (Array.isArray(this.children)) {
2872 for (var i = 0; i < section_ids.length; i++) {
2873 for (var j = 0; j < this.children.length; j++) {
2874 if (!this.children[j].editable || this.children[j].modalonly)
2875 continue;
2876
2877 tasks.push(this.children[j].parse(section_ids[i]));
2878 }
2879 }
2880 }
2881
2882 return Promise.all(tasks);
2883 }
2884 });
2885
2886 /**
2887 * @class NamedSection
2888 * @memberof LuCI.form
2889 * @augments LuCI.form.AbstractSection
2890 * @hideconstructor
2891 * @classdesc
2892 *
2893 * The `NamedSection` class maps exactly one UCI section instance which is
2894 * specified when constructing the class instance.
2895 *
2896 * Layout and functionality wise, a named section is essentially a
2897 * `TypedSection` which allows exactly one section node.
2898 *
2899 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2900 * The configuration form this section is added to. It is automatically passed
2901 * by [section()]{@link LuCI.form.Map#section}.
2902 *
2903 * @param {string} section_id
2904 * The name (ID) of the UCI section to map.
2905 *
2906 * @param {string} section_type
2907 * The type of the UCI section to map.
2908 *
2909 * @param {string} [title]
2910 * The title caption of the form section element.
2911 *
2912 * @param {string} [description]
2913 * The description text of the form section element.
2914 */
2915 var CBINamedSection = CBIAbstractSection.extend(/** @lends LuCI.form.NamedSection.prototype */ {
2916 __name__: 'CBI.NamedSection',
2917 __init__: function(map, section_id /*, ... */) {
2918 this.super('__init__', this.varargs(arguments, 2, map));
2919
2920 this.section = section_id;
2921 },
2922
2923 /**
2924 * If set to `true`, the user may remove or recreate the sole mapped
2925 * configuration instance from the form section widget, otherwise only a
2926 * preexisting section may be edited. The default is `false`.
2927 *
2928 * @name LuCI.form.NamedSection.prototype#addremove
2929 * @type boolean
2930 * @default false
2931 */
2932
2933 /**
2934 * Override the UCI configuration name to read the section IDs from. By
2935 * default, the configuration name is inherited from the parent `Map`.
2936 * By setting this property, a deviating configuration may be specified.
2937 * The default is `null`, means inheriting from the parent form.
2938 *
2939 * @name LuCI.form.NamedSection.prototype#uciconfig
2940 * @type string
2941 * @default null
2942 */
2943
2944 /**
2945 * The `NamedSection` class overwrites the generic `cfgsections()`
2946 * implementation to return a one-element array containing the mapped
2947 * section ID as sole element. User code should not normally change this.
2948 *
2949 * @returns {string[]}
2950 * Returns a one-element array containing the mapped section ID.
2951 */
2952 cfgsections: function() {
2953 return [ this.section ];
2954 },
2955
2956 /** @private */
2957 handleAdd: function(ev) {
2958 var section_id = this.section,
2959 config_name = this.uciconfig || this.map.config;
2960
2961 this.map.data.add(config_name, this.sectiontype, section_id);
2962 return this.map.save(null, true);
2963 },
2964
2965 /** @private */
2966 handleRemove: function(ev) {
2967 var section_id = this.section,
2968 config_name = this.uciconfig || this.map.config;
2969
2970 this.map.data.remove(config_name, section_id);
2971 return this.map.save(null, true);
2972 },
2973
2974 /** @private */
2975 renderContents: function(data) {
2976 var ucidata = data[0], nodes = data[1],
2977 section_id = this.section,
2978 config_name = this.uciconfig || this.map.config,
2979 sectionEl = E('div', {
2980 'id': ucidata ? null : 'cbi-%s-%s'.format(config_name, section_id),
2981 'class': 'cbi-section',
2982 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2983 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2984 });
2985
2986 if (typeof(this.title) === 'string' && this.title !== '')
2987 sectionEl.appendChild(E('legend', {}, this.title));
2988
2989 if (typeof(this.description) === 'string' && this.description !== '')
2990 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2991
2992 if (ucidata) {
2993 if (this.addremove) {
2994 sectionEl.appendChild(
2995 E('div', { 'class': 'cbi-section-remove right' },
2996 E('button', {
2997 'class': 'cbi-button',
2998 'click': ui.createHandlerFn(this, 'handleRemove'),
2999 'disabled': this.map.readonly || null
3000 }, [ _('Delete') ])));
3001 }
3002
3003 sectionEl.appendChild(E('div', {
3004 'id': 'cbi-%s-%s'.format(config_name, section_id),
3005 'class': this.tabs
3006 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3007 'data-section-id': section_id
3008 }, nodes));
3009 }
3010 else if (this.addremove) {
3011 sectionEl.appendChild(
3012 E('button', {
3013 'class': 'cbi-button cbi-button-add',
3014 'click': ui.createHandlerFn(this, 'handleAdd'),
3015 'disabled': this.map.readonly || null
3016 }, [ _('Add') ]));
3017 }
3018
3019 dom.bindClassInstance(sectionEl, this);
3020
3021 return sectionEl;
3022 },
3023
3024 /** @override */
3025 render: function() {
3026 var config_name = this.uciconfig || this.map.config,
3027 section_id = this.section;
3028
3029 return Promise.all([
3030 this.map.data.get(config_name, section_id),
3031 this.renderUCISection(section_id)
3032 ]).then(this.renderContents.bind(this));
3033 }
3034 });
3035
3036 /**
3037 * @class Value
3038 * @memberof LuCI.form
3039 * @augments LuCI.form.AbstractValue
3040 * @hideconstructor
3041 * @classdesc
3042 *
3043 * The `Value` class represents a simple one-line form input using the
3044 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3045 * {@link LuCI.ui.Combobox} class as underlying widget.
3046 *
3047 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3048 * The configuration form this section is added to. It is automatically passed
3049 * by [option()]{@link LuCI.form.AbstractSection#option} or
3050 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3051 * option to the section.
3052 *
3053 * @param {LuCI.form.AbstractSection} section
3054 * The configuration section this option is added to. It is automatically passed
3055 * by [option()]{@link LuCI.form.AbstractSection#option} or
3056 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3057 * option to the section.
3058 *
3059 * @param {string} option
3060 * The name of the UCI option to map.
3061 *
3062 * @param {string} [title]
3063 * The title caption of the option element.
3064 *
3065 * @param {string} [description]
3066 * The description text of the option element.
3067 */
3068 var CBIValue = CBIAbstractValue.extend(/** @lends LuCI.form.Value.prototype */ {
3069 __name__: 'CBI.Value',
3070
3071 /**
3072 * If set to `true`, the field is rendered as password input, otherwise
3073 * as plain text input.
3074 *
3075 * @name LuCI.form.Value.prototype#password
3076 * @type boolean
3077 * @default false
3078 */
3079
3080 /**
3081 * Set a placeholder string to use when the input field is empty.
3082 *
3083 * @name LuCI.form.Value.prototype#placeholder
3084 * @type string
3085 * @default null
3086 */
3087
3088 /**
3089 * Add a predefined choice to the form option. By adding one or more
3090 * choices, the plain text input field is turned into a combobox widget
3091 * which prompts the user to select a predefined choice, or to enter a
3092 * custom value.
3093 *
3094 * @param {string} key
3095 * The choice value to add.
3096 *
3097 * @param {Node|string} value
3098 * The caption for the choice value. May be a DOM node, a document fragment
3099 * or a plain text string. If omitted, the `key` value is used as caption.
3100 */
3101 value: function(key, val) {
3102 this.keylist = this.keylist || [];
3103 this.keylist.push(String(key));
3104
3105 this.vallist = this.vallist || [];
3106 this.vallist.push(dom.elem(val) ? val : String(val != null ? val : key));
3107 },
3108
3109 /** @override */
3110 render: function(option_index, section_id, in_table) {
3111 return Promise.resolve(this.cfgvalue(section_id))
3112 .then(this.renderWidget.bind(this, section_id, option_index))
3113 .then(this.renderFrame.bind(this, section_id, in_table, option_index));
3114 },
3115
3116 /** @private */
3117 renderFrame: function(section_id, in_table, option_index, nodes) {
3118 var config_name = this.uciconfig || this.section.uciconfig || this.map.config,
3119 depend_list = this.transformDepList(section_id),
3120 optionEl;
3121
3122 if (in_table) {
3123 var title = this.stripTags(this.title).trim();
3124 optionEl = E('div', {
3125 'class': 'td cbi-value-field',
3126 'data-title': (title != '') ? title : null,
3127 'data-description': this.stripTags(this.description).trim(),
3128 'data-name': this.option,
3129 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3130 }, E('div', {
3131 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3132 'data-index': option_index,
3133 'data-depends': depend_list,
3134 'data-field': this.cbid(section_id)
3135 }));
3136 }
3137 else {
3138 optionEl = E('div', {
3139 'class': 'cbi-value',
3140 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3141 'data-index': option_index,
3142 'data-depends': depend_list,
3143 'data-field': this.cbid(section_id),
3144 'data-name': this.option,
3145 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3146 });
3147
3148 if (this.last_child)
3149 optionEl.classList.add('cbi-value-last');
3150
3151 if (typeof(this.title) === 'string' && this.title !== '') {
3152 optionEl.appendChild(E('label', {
3153 'class': 'cbi-value-title',
3154 'for': 'widget.cbid.%s.%s.%s'.format(config_name, section_id, this.option),
3155 'click': function(ev) {
3156 var node = ev.currentTarget,
3157 elem = node.nextElementSibling.querySelector('#' + node.getAttribute('for')) || node.nextElementSibling.querySelector('[data-widget-id="' + node.getAttribute('for') + '"]');
3158
3159 if (elem) {
3160 elem.click();
3161 elem.focus();
3162 }
3163 }
3164 },
3165 this.titleref ? E('a', {
3166 'class': 'cbi-title-ref',
3167 'href': this.titleref,
3168 'title': this.titledesc || _('Go to relevant configuration page')
3169 }, this.title) : this.title));
3170
3171 optionEl.appendChild(E('div', { 'class': 'cbi-value-field' }));
3172 }
3173 }
3174
3175 if (nodes)
3176 (optionEl.lastChild || optionEl).appendChild(nodes);
3177
3178 if (!in_table && typeof(this.description) === 'string' && this.description !== '')
3179 dom.append(optionEl.lastChild || optionEl,
3180 E('div', { 'class': 'cbi-value-description' }, this.description));
3181
3182 if (depend_list && depend_list.length)
3183 optionEl.classList.add('hidden');
3184
3185 optionEl.addEventListener('widget-change',
3186 L.bind(this.map.checkDepends, this.map));
3187
3188 dom.bindClassInstance(optionEl, this);
3189
3190 return optionEl;
3191 },
3192
3193 /** @private */
3194 renderWidget: function(section_id, option_index, cfgvalue) {
3195 var value = (cfgvalue != null) ? cfgvalue : this.default,
3196 choices = this.transformChoices(),
3197 widget;
3198
3199 if (choices) {
3200 var placeholder = (this.optional || this.rmempty)
3201 ? E('em', _('unspecified')) : _('-- Please choose --');
3202
3203 widget = new ui.Combobox(Array.isArray(value) ? value.join(' ') : value, choices, {
3204 id: this.cbid(section_id),
3205 sort: this.keylist,
3206 optional: this.optional || this.rmempty,
3207 datatype: this.datatype,
3208 select_placeholder: this.placeholder || placeholder,
3209 validate: L.bind(this.validate, this, section_id),
3210 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3211 });
3212 }
3213 else {
3214 widget = new ui.Textfield(Array.isArray(value) ? value.join(' ') : value, {
3215 id: this.cbid(section_id),
3216 password: this.password,
3217 optional: this.optional || this.rmempty,
3218 datatype: this.datatype,
3219 placeholder: this.placeholder,
3220 validate: L.bind(this.validate, this, section_id),
3221 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3222 });
3223 }
3224
3225 return widget.render();
3226 }
3227 });
3228
3229 /**
3230 * @class DynamicList
3231 * @memberof LuCI.form
3232 * @augments LuCI.form.Value
3233 * @hideconstructor
3234 * @classdesc
3235 *
3236 * The `DynamicList` class represents a multi value widget allowing the user
3237 * to enter multiple unique values, optionally selected from a set of
3238 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3239 *
3240 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3241 * The configuration form this section is added to. It is automatically passed
3242 * by [option()]{@link LuCI.form.AbstractSection#option} or
3243 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3244 * option to the section.
3245 *
3246 * @param {LuCI.form.AbstractSection} section
3247 * The configuration section this option is added to. It is automatically passed
3248 * by [option()]{@link LuCI.form.AbstractSection#option} or
3249 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3250 * option to the section.
3251 *
3252 * @param {string} option
3253 * The name of the UCI option to map.
3254 *
3255 * @param {string} [title]
3256 * The title caption of the option element.
3257 *
3258 * @param {string} [description]
3259 * The description text of the option element.
3260 */
3261 var CBIDynamicList = CBIValue.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3262 __name__: 'CBI.DynamicList',
3263
3264 /** @private */
3265 renderWidget: function(section_id, option_index, cfgvalue) {
3266 var value = (cfgvalue != null) ? cfgvalue : this.default,
3267 choices = this.transformChoices(),
3268 items = L.toArray(value);
3269
3270 var widget = new ui.DynamicList(items, choices, {
3271 id: this.cbid(section_id),
3272 sort: this.keylist,
3273 optional: this.optional || this.rmempty,
3274 datatype: this.datatype,
3275 placeholder: this.placeholder,
3276 validate: L.bind(this.validate, this, section_id),
3277 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3278 });
3279
3280 return widget.render();
3281 },
3282 });
3283
3284 /**
3285 * @class ListValue
3286 * @memberof LuCI.form
3287 * @augments LuCI.form.Value
3288 * @hideconstructor
3289 * @classdesc
3290 *
3291 * The `ListValue` class implements a simple static HTML select element
3292 * allowing the user to chose a single value from a set of predefined choices.
3293 * It builds upon the {@link LuCI.ui.Select} widget.
3294 *
3295 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3296 * The configuration form this section is added to. It is automatically passed
3297 * by [option()]{@link LuCI.form.AbstractSection#option} or
3298 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3299 * option to the section.
3300 *
3301 * @param {LuCI.form.AbstractSection} section
3302 * The configuration section this option is added to. It is automatically passed
3303 * by [option()]{@link LuCI.form.AbstractSection#option} or
3304 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3305 * option to the section.
3306 *
3307 * @param {string} option
3308 * The name of the UCI option to map.
3309 *
3310 * @param {string} [title]
3311 * The title caption of the option element.
3312 *
3313 * @param {string} [description]
3314 * The description text of the option element.
3315 */
3316 var CBIListValue = CBIValue.extend(/** @lends LuCI.form.ListValue.prototype */ {
3317 __name__: 'CBI.ListValue',
3318
3319 __init__: function() {
3320 this.super('__init__', arguments);
3321 this.widget = 'select';
3322 this.orientation = 'horizontal';
3323 this.deplist = [];
3324 },
3325
3326 /**
3327 * Set the size attribute of the underlying HTML select element.
3328 *
3329 * @name LuCI.form.ListValue.prototype#size
3330 * @type number
3331 * @default null
3332 */
3333
3334 /**
3335 * Set the type of the underlying form controls.
3336 *
3337 * May be one of `select` or `radio`. If set to `select`, an HTML
3338 * select element is rendered, otherwise a collection of `radio`
3339 * elements is used.
3340 *
3341 * @name LuCI.form.ListValue.prototype#widget
3342 * @type string
3343 * @default select
3344 */
3345
3346 /**
3347 * Set the orientation of the underlying radio or checkbox elements.
3348 *
3349 * May be one of `horizontal` or `vertical`. Only applies to non-select
3350 * widget types.
3351 *
3352 * @name LuCI.form.ListValue.prototype#orientation
3353 * @type string
3354 * @default horizontal
3355 */
3356
3357 /** @private */
3358 renderWidget: function(section_id, option_index, cfgvalue) {
3359 var choices = this.transformChoices();
3360 var widget = new ui.Select((cfgvalue != null) ? cfgvalue : this.default, choices, {
3361 id: this.cbid(section_id),
3362 size: this.size,
3363 sort: this.keylist,
3364 widget: this.widget,
3365 optional: this.optional,
3366 orientation: this.orientation,
3367 placeholder: this.placeholder,
3368 validate: L.bind(this.validate, this, section_id),
3369 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3370 });
3371
3372 return widget.render();
3373 },
3374 });
3375
3376 /**
3377 * @class FlagValue
3378 * @memberof LuCI.form
3379 * @augments LuCI.form.Value
3380 * @hideconstructor
3381 * @classdesc
3382 *
3383 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3384 * implement a simple checkbox element.
3385 *
3386 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3387 * The configuration form this section is added to. It is automatically passed
3388 * by [option()]{@link LuCI.form.AbstractSection#option} or
3389 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3390 * option to the section.
3391 *
3392 * @param {LuCI.form.AbstractSection} section
3393 * The configuration section this option is added to. It is automatically passed
3394 * by [option()]{@link LuCI.form.AbstractSection#option} or
3395 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3396 * option to the section.
3397 *
3398 * @param {string} option
3399 * The name of the UCI option to map.
3400 *
3401 * @param {string} [title]
3402 * The title caption of the option element.
3403 *
3404 * @param {string} [description]
3405 * The description text of the option element.
3406 */
3407 var CBIFlagValue = CBIValue.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3408 __name__: 'CBI.FlagValue',
3409
3410 __init__: function() {
3411 this.super('__init__', arguments);
3412
3413 this.enabled = '1';
3414 this.disabled = '0';
3415 this.default = this.disabled;
3416 },
3417
3418 /**
3419 * Sets the input value to use for the checkbox checked state.
3420 *
3421 * @name LuCI.form.FlagValue.prototype#enabled
3422 * @type number
3423 * @default 1
3424 */
3425
3426 /**
3427 * Sets the input value to use for the checkbox unchecked state.
3428 *
3429 * @name LuCI.form.FlagValue.prototype#disabled
3430 * @type number
3431 * @default 0
3432 */
3433
3434 /** @private */
3435 renderWidget: function(section_id, option_index, cfgvalue) {
3436 var widget = new ui.Checkbox((cfgvalue != null) ? cfgvalue : this.default, {
3437 id: this.cbid(section_id),
3438 value_enabled: this.enabled,
3439 value_disabled: this.disabled,
3440 validate: L.bind(this.validate, this, section_id),
3441 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3442 });
3443
3444 return widget.render();
3445 },
3446
3447 /**
3448 * Query the checked state of the underlying checkbox widget and return
3449 * either the `enabled` or the `disabled` property value, depending on
3450 * the checked state.
3451 *
3452 * @override
3453 */
3454 formvalue: function(section_id) {
3455 var elem = this.getUIElement(section_id),
3456 checked = elem ? elem.isChecked() : false;
3457 return checked ? this.enabled : this.disabled;
3458 },
3459
3460 /**
3461 * Query the checked state of the underlying checkbox widget and return
3462 * either a localized `Yes` or `No` string, depending on the checked state.
3463 *
3464 * @override
3465 */
3466 textvalue: function(section_id) {
3467 var cval = this.cfgvalue(section_id);
3468
3469 if (cval == null)
3470 cval = this.default;
3471
3472 return (cval == this.enabled) ? _('Yes') : _('No');
3473 },
3474
3475 /** @override */
3476 parse: function(section_id) {
3477 if (this.isActive(section_id)) {
3478 var fval = this.formvalue(section_id);
3479
3480 if (!this.isValid(section_id)) {
3481 var title = this.stripTags(this.title).trim();
3482 return Promise.reject(new TypeError(_('Option "%s" contains an invalid input value.').format(title || this.option)));
3483 }
3484
3485 if (fval == this.default && (this.optional || this.rmempty))
3486 return Promise.resolve(this.remove(section_id));
3487 else
3488 return Promise.resolve(this.write(section_id, fval));
3489 }
3490 else {
3491 return Promise.resolve(this.remove(section_id));
3492 }
3493 },
3494 });
3495
3496 /**
3497 * @class MultiValue
3498 * @memberof LuCI.form
3499 * @augments LuCI.form.DynamicList
3500 * @hideconstructor
3501 * @classdesc
3502 *
3503 * The `MultiValue` class is a modified variant of the `DynamicList` element
3504 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
3505 * select dropdown element.
3506 *
3507 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3508 * The configuration form this section is added to. It is automatically passed
3509 * by [option()]{@link LuCI.form.AbstractSection#option} or
3510 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3511 * option to the section.
3512 *
3513 * @param {LuCI.form.AbstractSection} section
3514 * The configuration section this option is added to. It is automatically passed
3515 * by [option()]{@link LuCI.form.AbstractSection#option} or
3516 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3517 * option to the section.
3518 *
3519 * @param {string} option
3520 * The name of the UCI option to map.
3521 *
3522 * @param {string} [title]
3523 * The title caption of the option element.
3524 *
3525 * @param {string} [description]
3526 * The description text of the option element.
3527 */
3528 var CBIMultiValue = CBIDynamicList.extend(/** @lends LuCI.form.MultiValue.prototype */ {
3529 __name__: 'CBI.MultiValue',
3530
3531 __init__: function() {
3532 this.super('__init__', arguments);
3533 this.placeholder = _('-- Please choose --');
3534 },
3535
3536 /**
3537 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
3538 * property of the underlying dropdown widget. If omitted, the value of
3539 * the `size` property is used or `3` when `size` is unspecified as well.
3540 *
3541 * @name LuCI.form.MultiValue.prototype#display_size
3542 * @type number
3543 * @default null
3544 */
3545
3546 /**
3547 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
3548 * property of the underlying dropdown widget. If omitted, the value of
3549 * the `size` property is used or `-1` when `size` is unspecified as well.
3550 *
3551 * @name LuCI.form.MultiValue.prototype#dropdown_size
3552 * @type number
3553 * @default null
3554 */
3555
3556 /** @private */
3557 renderWidget: function(section_id, option_index, cfgvalue) {
3558 var value = (cfgvalue != null) ? cfgvalue : this.default,
3559 choices = this.transformChoices();
3560
3561 var widget = new ui.Dropdown(L.toArray(value), choices, {
3562 id: this.cbid(section_id),
3563 sort: this.keylist,
3564 multiple: true,
3565 optional: this.optional || this.rmempty,
3566 select_placeholder: this.placeholder,
3567 display_items: this.display_size || this.size || 3,
3568 dropdown_items: this.dropdown_size || this.size || -1,
3569 validate: L.bind(this.validate, this, section_id),
3570 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3571 });
3572
3573 return widget.render();
3574 },
3575 });
3576
3577 /**
3578 * @class TextValue
3579 * @memberof LuCI.form
3580 * @augments LuCI.form.Value
3581 * @hideconstructor
3582 * @classdesc
3583 *
3584 * The `TextValue` class implements a multi-line textarea input using
3585 * {@link LuCI.ui.Textarea}.
3586 *
3587 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3588 * The configuration form this section is added to. It is automatically passed
3589 * by [option()]{@link LuCI.form.AbstractSection#option} or
3590 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3591 * option to the section.
3592 *
3593 * @param {LuCI.form.AbstractSection} section
3594 * The configuration section this option is added to. It is automatically passed
3595 * by [option()]{@link LuCI.form.AbstractSection#option} or
3596 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3597 * option to the section.
3598 *
3599 * @param {string} option
3600 * The name of the UCI option to map.
3601 *
3602 * @param {string} [title]
3603 * The title caption of the option element.
3604 *
3605 * @param {string} [description]
3606 * The description text of the option element.
3607 */
3608 var CBITextValue = CBIValue.extend(/** @lends LuCI.form.TextValue.prototype */ {
3609 __name__: 'CBI.TextValue',
3610
3611 /** @ignore */
3612 value: null,
3613
3614 /**
3615 * Enforces the use of a monospace font for the textarea contents when set
3616 * to `true`.
3617 *
3618 * @name LuCI.form.TextValue.prototype#monospace
3619 * @type boolean
3620 * @default false
3621 */
3622
3623 /**
3624 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
3625 * property of the underlying textarea widget.
3626 *
3627 * @name LuCI.form.TextValue.prototype#cols
3628 * @type number
3629 * @default null
3630 */
3631
3632 /**
3633 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
3634 * property of the underlying textarea widget.
3635 *
3636 * @name LuCI.form.TextValue.prototype#rows
3637 * @type number
3638 * @default null
3639 */
3640
3641 /**
3642 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
3643 * property of the underlying textarea widget.
3644 *
3645 * @name LuCI.form.TextValue.prototype#wrap
3646 * @type number
3647 * @default null
3648 */
3649
3650 /** @private */
3651 renderWidget: function(section_id, option_index, cfgvalue) {
3652 var value = (cfgvalue != null) ? cfgvalue : this.default;
3653
3654 var widget = new ui.Textarea(value, {
3655 id: this.cbid(section_id),
3656 optional: this.optional || this.rmempty,
3657 placeholder: this.placeholder,
3658 monospace: this.monospace,
3659 cols: this.cols,
3660 rows: this.rows,
3661 wrap: this.wrap,
3662 validate: L.bind(this.validate, this, section_id),
3663 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3664 });
3665
3666 return widget.render();
3667 }
3668 });
3669
3670 /**
3671 * @class DummyValue
3672 * @memberof LuCI.form
3673 * @augments LuCI.form.Value
3674 * @hideconstructor
3675 * @classdesc
3676 *
3677 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
3678 * renders the underlying UCI option or default value as readonly text.
3679 *
3680 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3681 * The configuration form this section is added to. It is automatically passed
3682 * by [option()]{@link LuCI.form.AbstractSection#option} or
3683 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3684 * option to the section.
3685 *
3686 * @param {LuCI.form.AbstractSection} section
3687 * The configuration section this option is added to. It is automatically passed
3688 * by [option()]{@link LuCI.form.AbstractSection#option} or
3689 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3690 * option to the section.
3691 *
3692 * @param {string} option
3693 * The name of the UCI option to map.
3694 *
3695 * @param {string} [title]
3696 * The title caption of the option element.
3697 *
3698 * @param {string} [description]
3699 * The description text of the option element.
3700 */
3701 var CBIDummyValue = CBIValue.extend(/** @lends LuCI.form.DummyValue.prototype */ {
3702 __name__: 'CBI.DummyValue',
3703
3704 /**
3705 * Set an URL which is opened when clicking on the dummy value text.
3706 *
3707 * By setting this property, the dummy value text is wrapped in an `<a>`
3708 * element with the property value used as `href` attribute.
3709 *
3710 * @name LuCI.form.DummyValue.prototype#href
3711 * @type string
3712 * @default null
3713 */
3714
3715 /**
3716 * Treat the UCI option value (or the `default` property value) as HTML.
3717 *
3718 * By default, the value text is HTML escaped before being rendered as
3719 * text. In some cases it may be needed to actually interpret and render
3720 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
3721 *
3722 * @name LuCI.form.DummyValue.prototype#rawhtml
3723 * @type boolean
3724 * @default null
3725 */
3726
3727 /** @private */
3728 renderWidget: function(section_id, option_index, cfgvalue) {
3729 var value = (cfgvalue != null) ? cfgvalue : this.default,
3730 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
3731 outputEl = E('div');
3732
3733 if (this.href && !((this.readonly != null) ? this.readonly : this.map.readonly))
3734 outputEl.appendChild(E('a', { 'href': this.href }));
3735
3736 dom.append(outputEl.lastChild || outputEl,
3737 this.rawhtml ? value : [ value ]);
3738
3739 return E([
3740 outputEl,
3741 hiddenEl.render()
3742 ]);
3743 },
3744
3745 /** @override */
3746 remove: function() {},
3747
3748 /** @override */
3749 write: function() {}
3750 });
3751
3752 /**
3753 * @class ButtonValue
3754 * @memberof LuCI.form
3755 * @augments LuCI.form.Value
3756 * @hideconstructor
3757 * @classdesc
3758 *
3759 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
3760 * renders the underlying UCI option or default value as readonly text.
3761 *
3762 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3763 * The configuration form this section is added to. It is automatically passed
3764 * by [option()]{@link LuCI.form.AbstractSection#option} or
3765 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3766 * option to the section.
3767 *
3768 * @param {LuCI.form.AbstractSection} section
3769 * The configuration section this option is added to. It is automatically passed
3770 * by [option()]{@link LuCI.form.AbstractSection#option} or
3771 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3772 * option to the section.
3773 *
3774 * @param {string} option
3775 * The name of the UCI option to map.
3776 *
3777 * @param {string} [title]
3778 * The title caption of the option element.
3779 *
3780 * @param {string} [description]
3781 * The description text of the option element.
3782 */
3783 var CBIButtonValue = CBIValue.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
3784 __name__: 'CBI.ButtonValue',
3785
3786 /**
3787 * Override the rendered button caption.
3788 *
3789 * By default, the option title - which is passed as fourth argument to the
3790 * constructor - is used as caption for the button element. When setting
3791 * this property to a string, it is used as `String.format()` pattern with
3792 * the underlying UCI section name passed as first format argument. When
3793 * set to a function, it is invoked passing the section ID as sole argument
3794 * and the resulting return value is converted to a string before being
3795 * used as button caption.
3796 *
3797 * The default is `null`, means the option title is used as caption.
3798 *
3799 * @name LuCI.form.ButtonValue.prototype#inputtitle
3800 * @type string|function
3801 * @default null
3802 */
3803
3804 /**
3805 * Override the button style class.
3806 *
3807 * By setting this property, a specific `cbi-button-*` CSS class can be
3808 * selected to influence the style of the resulting button.
3809 *
3810 * Suitable values which are implemented by most themes are `positive`,
3811 * `negative` and `primary`.
3812 *
3813 * The default is `null`, means a neutral button styling is used.
3814 *
3815 * @name LuCI.form.ButtonValue.prototype#inputstyle
3816 * @type string
3817 * @default null
3818 */
3819
3820 /**
3821 * Override the button click action.
3822 *
3823 * By default, the underlying UCI option (or default property) value is
3824 * copied into a hidden field tied to the button element and the save
3825 * action is triggered on the parent form element.
3826 *
3827 * When this property is set to a function, it is invoked instead of
3828 * performing the default actions. The handler function will receive the
3829 * DOM click element as first and the underlying configuration section ID
3830 * as second argument.
3831 *
3832 * @name LuCI.form.ButtonValue.prototype#onclick
3833 * @type function
3834 * @default null
3835 */
3836
3837 /** @private */
3838 renderWidget: function(section_id, option_index, cfgvalue) {
3839 var value = (cfgvalue != null) ? cfgvalue : this.default,
3840 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
3841 outputEl = E('div'),
3842 btn_title = this.titleFn('inputtitle', section_id) || this.titleFn('title', section_id);
3843
3844 if (value !== false)
3845 dom.content(outputEl, [
3846 E('button', {
3847 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle || 'button'),
3848 'click': ui.createHandlerFn(this, function(section_id, ev) {
3849 if (this.onclick)
3850 return this.onclick(ev, section_id);
3851
3852 ev.currentTarget.parentNode.nextElementSibling.value = value;
3853 return this.map.save();
3854 }, section_id),
3855 'disabled': ((this.readonly != null) ? this.readonly : this.map.readonly) || null
3856 }, [ btn_title ])
3857 ]);
3858 else
3859 dom.content(outputEl, ' - ');
3860
3861 return E([
3862 outputEl,
3863 hiddenEl.render()
3864 ]);
3865 }
3866 });
3867
3868 /**
3869 * @class HiddenValue
3870 * @memberof LuCI.form
3871 * @augments LuCI.form.Value
3872 * @hideconstructor
3873 * @classdesc
3874 *
3875 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
3876 *
3877 * Hidden value widgets used to be necessary in legacy code which actually
3878 * submitted the underlying HTML form the server. With client side handling of
3879 * forms, there are more efficient ways to store hidden state data.
3880 *
3881 * Since this widget has no visible content, the title and description values
3882 * of this form element should be set to `null` as well to avoid a broken or
3883 * distorted form layout when rendering the option element.
3884 *
3885 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3886 * The configuration form this section is added to. It is automatically passed
3887 * by [option()]{@link LuCI.form.AbstractSection#option} or
3888 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3889 * option to the section.
3890 *
3891 * @param {LuCI.form.AbstractSection} section
3892 * The configuration section this option is added to. It is automatically passed
3893 * by [option()]{@link LuCI.form.AbstractSection#option} or
3894 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3895 * option to the section.
3896 *
3897 * @param {string} option
3898 * The name of the UCI option to map.
3899 *
3900 * @param {string} [title]
3901 * The title caption of the option element.
3902 *
3903 * @param {string} [description]
3904 * The description text of the option element.
3905 */
3906 var CBIHiddenValue = CBIValue.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
3907 __name__: 'CBI.HiddenValue',
3908
3909 /** @private */
3910 renderWidget: function(section_id, option_index, cfgvalue) {
3911 var widget = new ui.Hiddenfield((cfgvalue != null) ? cfgvalue : this.default, {
3912 id: this.cbid(section_id)
3913 });
3914
3915 return widget.render();
3916 }
3917 });
3918
3919 /**
3920 * @class FileUpload
3921 * @memberof LuCI.form
3922 * @augments LuCI.form.Value
3923 * @hideconstructor
3924 * @classdesc
3925 *
3926 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
3927 * offers the ability to browse, upload and select remote files.
3928 *
3929 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3930 * The configuration form this section is added to. It is automatically passed
3931 * by [option()]{@link LuCI.form.AbstractSection#option} or
3932 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3933 * option to the section.
3934 *
3935 * @param {LuCI.form.AbstractSection} section
3936 * The configuration section this option is added to. It is automatically passed
3937 * by [option()]{@link LuCI.form.AbstractSection#option} or
3938 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3939 * option to the section.
3940 *
3941 * @param {string} option
3942 * The name of the UCI option to map.
3943 *
3944 * @param {string} [title]
3945 * The title caption of the option element.
3946 *
3947 * @param {string} [description]
3948 * The description text of the option element.
3949 */
3950 var CBIFileUpload = CBIValue.extend(/** @lends LuCI.form.FileUpload.prototype */ {
3951 __name__: 'CBI.FileSelect',
3952
3953 __init__: function(/* ... */) {
3954 this.super('__init__', arguments);
3955
3956 this.show_hidden = false;
3957 this.enable_upload = true;
3958 this.enable_remove = true;
3959 this.root_directory = '/etc/luci-uploads';
3960 },
3961
3962 /**
3963 * Toggle display of hidden files.
3964 *
3965 * Display hidden files when rendering the remote directory listing.
3966 * Note that this is merely a cosmetic feature, hidden files are always
3967 * included in received remote file listings.
3968 *
3969 * The default is `false`, means hidden files are not displayed.
3970 *
3971 * @name LuCI.form.FileUpload.prototype#show_hidden
3972 * @type boolean
3973 * @default false
3974 */
3975
3976 /**
3977 * Toggle file upload functionality.
3978 *
3979 * When set to `true`, the underlying widget provides a button which lets
3980 * the user select and upload local files to the remote system.
3981 * Note that this is merely a cosmetic feature, remote upload access is
3982 * controlled by the session ACL rules.
3983 *
3984 * The default is `true`, means file upload functionality is displayed.
3985 *
3986 * @name LuCI.form.FileUpload.prototype#enable_upload
3987 * @type boolean
3988 * @default true
3989 */
3990
3991 /**
3992 * Toggle remote file delete functionality.
3993 *
3994 * When set to `true`, the underlying widget provides a buttons which let
3995 * the user delete files from remote directories. Note that this is merely
3996 * a cosmetic feature, remote delete permissions are controlled by the
3997 * session ACL rules.
3998 *
3999 * The default is `true`, means file removal buttons are displayed.
4000 *
4001 * @name LuCI.form.FileUpload.prototype#enable_remove
4002 * @type boolean
4003 * @default true
4004 */
4005
4006 /**
4007 * Specify the root directory for file browsing.
4008 *
4009 * This property defines the topmost directory the file browser widget may
4010 * navigate to, the UI will not allow browsing directories outside this
4011 * prefix. Note that this is merely a cosmetic feature, remote file access
4012 * and directory listing permissions are controlled by the session ACL
4013 * rules.
4014 *
4015 * The default is `/etc/luci-uploads`.
4016 *
4017 * @name LuCI.form.FileUpload.prototype#root_directory
4018 * @type string
4019 * @default /etc/luci-uploads
4020 */
4021
4022 /** @private */
4023 renderWidget: function(section_id, option_index, cfgvalue) {
4024 var browserEl = new ui.FileUpload((cfgvalue != null) ? cfgvalue : this.default, {
4025 id: this.cbid(section_id),
4026 name: this.cbid(section_id),
4027 show_hidden: this.show_hidden,
4028 enable_upload: this.enable_upload,
4029 enable_remove: this.enable_remove,
4030 root_directory: this.root_directory,
4031 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4032 });
4033
4034 return browserEl.render();
4035 }
4036 });
4037
4038 /**
4039 * @class SectionValue
4040 * @memberof LuCI.form
4041 * @augments LuCI.form.Value
4042 * @hideconstructor
4043 * @classdesc
4044 *
4045 * The `SectionValue` widget embeds a form section element within an option
4046 * element container, allowing to nest form sections into other sections.
4047 *
4048 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4049 * The configuration form this section is added to. It is automatically passed
4050 * by [option()]{@link LuCI.form.AbstractSection#option} or
4051 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4052 * option to the section.
4053 *
4054 * @param {LuCI.form.AbstractSection} section
4055 * The configuration section this option is added to. It is automatically passed
4056 * by [option()]{@link LuCI.form.AbstractSection#option} or
4057 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4058 * option to the section.
4059 *
4060 * @param {string} option
4061 * The internal name of the option element holding the section. Since a section
4062 * container element does not read or write any configuration itself, the name
4063 * is only used internally and does not need to relate to any underlying UCI
4064 * option name.
4065 *
4066 * @param {LuCI.form.AbstractSection} subsection_class
4067 * The class to use for instantiating the nested section element. Note that
4068 * the class value itself is expected here, not a class instance obtained by
4069 * calling `new`. The given class argument must be a subclass of the
4070 * `AbstractSection` class.
4071 *
4072 * @param {...*} [class_args]
4073 * All further arguments are passed as-is to the subclass constructor. Refer
4074 * to the corresponding class constructor documentations for details.
4075 */
4076 var CBISectionValue = CBIValue.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4077 __name__: 'CBI.ContainerValue',
4078 __init__: function(map, section, option, cbiClass /*, ... */) {
4079 this.super('__init__', [map, section, option]);
4080
4081 if (!CBIAbstractSection.isSubclass(cbiClass))
4082 throw 'Sub section must be a descendent of CBIAbstractSection';
4083
4084 this.subsection = cbiClass.instantiate(this.varargs(arguments, 4, this.map));
4085 this.subsection.parentoption = this;
4086 },
4087
4088 /**
4089 * Access the embedded section instance.
4090 *
4091 * This property holds a reference to the instantiated nested section.
4092 *
4093 * @name LuCI.form.SectionValue.prototype#subsection
4094 * @type LuCI.form.AbstractSection
4095 * @readonly
4096 */
4097
4098 /** @override */
4099 load: function(section_id) {
4100 return this.subsection.load();
4101 },
4102
4103 /** @override */
4104 parse: function(section_id) {
4105 return this.subsection.parse();
4106 },
4107
4108 /** @private */
4109 renderWidget: function(section_id, option_index, cfgvalue) {
4110 return this.subsection.render();
4111 },
4112
4113 /** @private */
4114 checkDepends: function(section_id) {
4115 this.subsection.checkDepends();
4116 return CBIValue.prototype.checkDepends.apply(this, [ section_id ]);
4117 },
4118
4119 /**
4120 * Since the section container is not rendering an own widget,
4121 * its `value()` implementation is a no-op.
4122 *
4123 * @override
4124 */
4125 value: function() {},
4126
4127 /**
4128 * Since the section container is not tied to any UCI configuration,
4129 * its `write()` implementation is a no-op.
4130 *
4131 * @override
4132 */
4133 write: function() {},
4134
4135 /**
4136 * Since the section container is not tied to any UCI configuration,
4137 * its `remove()` implementation is a no-op.
4138 *
4139 * @override
4140 */
4141 remove: function() {},
4142
4143 /**
4144 * Since the section container is not tied to any UCI configuration,
4145 * its `cfgvalue()` implementation will always return `null`.
4146 *
4147 * @override
4148 * @returns {null}
4149 */
4150 cfgvalue: function() { return null },
4151
4152 /**
4153 * Since the section container is not tied to any UCI configuration,
4154 * its `formvalue()` implementation will always return `null`.
4155 *
4156 * @override
4157 * @returns {null}
4158 */
4159 formvalue: function() { return null }
4160 });
4161
4162 /**
4163 * @class form
4164 * @memberof LuCI
4165 * @hideconstructor
4166 * @classdesc
4167 *
4168 * The LuCI form class provides high level abstractions for creating creating
4169 * UCI- or JSON backed configurations forms.
4170 *
4171 * To import the class in views, use `'require form'`, to import it in
4172 * external JavaScript, use `L.require("form").then(...)`.
4173 *
4174 * A typical form is created by first constructing a
4175 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4176 * by subsequently adding sections and options to it. Finally
4177 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4178 * assemble the HTML markup and insert it into the DOM.
4179 *
4180 * Example:
4181 *
4182 * <pre>
4183 * 'use strict';
4184 * 'require form';
4185 *
4186 * var m, s, o;
4187 *
4188 * m = new form.Map('example', 'Example form',
4189 * 'This is an example form mapping the contents of /etc/config/example');
4190 *
4191 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4192 * 'This sections maps "config example first_section" of /etc/config/example');
4193 *
4194 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4195 *
4196 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4197 * o.value('choice1', 'The first choice');
4198 * o.value('choice2', 'The second choice');
4199 *
4200 * m.render().then(function(node) {
4201 * document.body.appendChild(node);
4202 * });
4203 * </pre>
4204 */
4205 return baseclass.extend(/** @lends LuCI.form.prototype */ {
4206 Map: CBIMap,
4207 JSONMap: CBIJSONMap,
4208 AbstractSection: CBIAbstractSection,
4209 AbstractValue: CBIAbstractValue,
4210
4211 TypedSection: CBITypedSection,
4212 TableSection: CBITableSection,
4213 GridSection: CBIGridSection,
4214 NamedSection: CBINamedSection,
4215
4216 Value: CBIValue,
4217 DynamicList: CBIDynamicList,
4218 ListValue: CBIListValue,
4219 Flag: CBIFlagValue,
4220 MultiValue: CBIMultiValue,
4221 TextValue: CBITextValue,
4222 DummyValue: CBIDummyValue,
4223 Button: CBIButtonValue,
4224 HiddenValue: CBIHiddenValue,
4225 FileUpload: CBIFileUpload,
4226 SectionValue: CBISectionValue
4227 });