luci-base: form.js: ListValue: support widget and orientation properties
[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 return true;
1781 }
1782
1783 return false;
1784 },
1785
1786 /** @private */
1787 triggerValidation: function(section_id) {
1788 var elem = this.getUIElement(section_id);
1789 return elem ? elem.triggerValidation() : true;
1790 },
1791
1792 /**
1793 * Parse the option element input.
1794 *
1795 * The function is invoked when the `parse()` method has been invoked on
1796 * the parent form and triggers input value reading and validation.
1797 *
1798 * @param {string} section_id
1799 * The configuration section ID
1800 *
1801 * @returns {Promise<void>}
1802 * Returns a promise resolving once the input value has been read and
1803 * validated or rejecting in case the input value does not meet the
1804 * validation constraints.
1805 */
1806 parse: function(section_id) {
1807 var active = this.isActive(section_id),
1808 cval = this.cfgvalue(section_id),
1809 fval = active ? this.formvalue(section_id) : null;
1810
1811 if (active && !this.isValid(section_id)) {
1812 var title = this.stripTags(this.title).trim();
1813 return Promise.reject(new TypeError(_('Option "%s" contains an invalid input value.').format(title || this.option)));
1814 }
1815
1816 if (fval != '' && fval != null) {
1817 if (this.forcewrite || !isEqual(cval, fval))
1818 return Promise.resolve(this.write(section_id, fval));
1819 }
1820 else {
1821 if (!active || this.rmempty || this.optional) {
1822 return Promise.resolve(this.remove(section_id));
1823 }
1824 else if (!isEqual(cval, fval)) {
1825 var title = this.stripTags(this.title).trim();
1826 return Promise.reject(new TypeError(_('Option "%s" must not be empty.').format(title || this.option)));
1827 }
1828 }
1829
1830 return Promise.resolve();
1831 },
1832
1833 /**
1834 * Write the current input value into the configuration.
1835 *
1836 * This function is invoked upon saving the parent form when the option
1837 * element is valid and when its input value has been changed compared to
1838 * the initial value returned by
1839 * [cfgvalue()]{@link LuCI.form.AbstractValue#cfgvalue}.
1840 *
1841 * The default implementation simply sets the given input value in the
1842 * UCI configuration (or the associated JavaScript object property in
1843 * case of `JSONMap` forms). It may be overwritten by user code to
1844 * implement alternative save logic, e.g. to transform the input value
1845 * before it is written.
1846 *
1847 * @param {string} section_id
1848 * The configuration section ID
1849 *
1850 * @param {string|string[]} formvalue
1851 * The input value to write.
1852 */
1853 write: function(section_id, formvalue) {
1854 return this.map.data.set(
1855 this.uciconfig || this.section.uciconfig || this.map.config,
1856 this.ucisection || section_id,
1857 this.ucioption || this.option,
1858 formvalue);
1859 },
1860
1861 /**
1862 * Remove the corresponding value from the configuration.
1863 *
1864 * This function is invoked upon saving the parent form when the option
1865 * element has been hidden due to unsatisfied dependencies or when the
1866 * user cleared the input value and the option is marked optional.
1867 *
1868 * The default implementation simply removes the associated option from the
1869 * UCI configuration (or the associated JavaScript object property in
1870 * case of `JSONMap` forms). It may be overwritten by user code to
1871 * implement alternative removal logic, e.g. to retain the original value.
1872 *
1873 * @param {string} section_id
1874 * The configuration section ID
1875 */
1876 remove: function(section_id) {
1877 return this.map.data.unset(
1878 this.uciconfig || this.section.uciconfig || this.map.config,
1879 this.ucisection || section_id,
1880 this.ucioption || this.option);
1881 }
1882 });
1883
1884 /**
1885 * @class TypedSection
1886 * @memberof LuCI.form
1887 * @augments LuCI.form.AbstractSection
1888 * @hideconstructor
1889 * @classdesc
1890 *
1891 * The `TypedSection` class maps all or - if `filter()` is overwritten - a
1892 * subset of the underlying UCI configuration sections of a given type.
1893 *
1894 * Layout wise, the configuration section instances mapped by the section
1895 * element (sometimes referred to as "section nodes") are stacked beneath
1896 * each other in a single column, with an optional section remove button next
1897 * to each section node and a section add button at the end, depending on the
1898 * value of the `addremove` property.
1899 *
1900 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
1901 * The configuration form this section is added to. It is automatically passed
1902 * by [section()]{@link LuCI.form.Map#section}.
1903 *
1904 * @param {string} section_type
1905 * The type of the UCI section to map.
1906 *
1907 * @param {string} [title]
1908 * The title caption of the form section element.
1909 *
1910 * @param {string} [description]
1911 * The description text of the form section element.
1912 */
1913 var CBITypedSection = CBIAbstractSection.extend(/** @lends LuCI.form.TypedSection.prototype */ {
1914 __name__: 'CBI.TypedSection',
1915
1916 /**
1917 * If set to `true`, the user may add or remove instances from the form
1918 * section widget, otherwise only preexisting sections may be edited.
1919 * The default is `false`.
1920 *
1921 * @name LuCI.form.TypedSection.prototype#addremove
1922 * @type boolean
1923 * @default false
1924 */
1925
1926 /**
1927 * If set to `true`, mapped section instances are treated as anonymous
1928 * UCI sections, which means that section instance elements will be
1929 * rendered without title element and that no name is required when adding
1930 * new sections. The default is `false`.
1931 *
1932 * @name LuCI.form.TypedSection.prototype#anonymous
1933 * @type boolean
1934 * @default false
1935 */
1936
1937 /**
1938 * When set to `true`, instead of rendering section instances one below
1939 * another, treat each instance as separate tab pane and render a tab menu
1940 * at the top of the form section element, allowing the user to switch
1941 * among instances. The default is `false`.
1942 *
1943 * @name LuCI.form.TypedSection.prototype#tabbed
1944 * @type boolean
1945 * @default false
1946 */
1947
1948 /**
1949 * Override the caption used for the section add button at the bottom of
1950 * the section form element. If set to a string, it will be used as-is,
1951 * if set to a function, the function will be invoked and its return value
1952 * is used as caption, after converting it to a string. If this property
1953 * is not set, the default is `Add`.
1954 *
1955 * @name LuCI.form.TypedSection.prototype#addbtntitle
1956 * @type string|function
1957 * @default null
1958 */
1959
1960 /**
1961 * Override the UCI configuration name to read the section IDs from. By
1962 * default, the configuration name is inherited from the parent `Map`.
1963 * By setting this property, a deviating configuration may be specified.
1964 * The default is `null`, means inheriting from the parent form.
1965 *
1966 * @name LuCI.form.TypedSection.prototype#uciconfig
1967 * @type string
1968 * @default null
1969 */
1970
1971 /** @override */
1972 cfgsections: function() {
1973 return this.map.data.sections(this.uciconfig || this.map.config, this.sectiontype)
1974 .map(function(s) { return s['.name'] })
1975 .filter(L.bind(this.filter, this));
1976 },
1977
1978 /** @private */
1979 handleAdd: function(ev, name) {
1980 var config_name = this.uciconfig || this.map.config;
1981
1982 this.map.data.add(config_name, this.sectiontype, name);
1983 return this.map.save(null, true);
1984 },
1985
1986 /** @private */
1987 handleRemove: function(section_id, ev) {
1988 var config_name = this.uciconfig || this.map.config;
1989
1990 this.map.data.remove(config_name, section_id);
1991 return this.map.save(null, true);
1992 },
1993
1994 /** @private */
1995 renderSectionAdd: function(extra_class) {
1996 if (!this.addremove)
1997 return E([]);
1998
1999 var createEl = E('div', { 'class': 'cbi-section-create' }),
2000 config_name = this.uciconfig || this.map.config,
2001 btn_title = this.titleFn('addbtntitle');
2002
2003 if (extra_class != null)
2004 createEl.classList.add(extra_class);
2005
2006 if (this.anonymous) {
2007 createEl.appendChild(E('button', {
2008 'class': 'cbi-button cbi-button-add',
2009 'title': btn_title || _('Add'),
2010 'click': ui.createHandlerFn(this, 'handleAdd'),
2011 'disabled': this.map.readonly || null
2012 }, [ btn_title || _('Add') ]));
2013 }
2014 else {
2015 var nameEl = E('input', {
2016 'type': 'text',
2017 'class': 'cbi-section-create-name',
2018 'disabled': this.map.readonly || null
2019 });
2020
2021 dom.append(createEl, [
2022 E('div', {}, nameEl),
2023 E('input', {
2024 'class': 'cbi-button cbi-button-add',
2025 'type': 'submit',
2026 'value': btn_title || _('Add'),
2027 'title': btn_title || _('Add'),
2028 'click': ui.createHandlerFn(this, function(ev) {
2029 if (nameEl.classList.contains('cbi-input-invalid'))
2030 return;
2031
2032 return this.handleAdd(ev, nameEl.value);
2033 }),
2034 'disabled': this.map.readonly || null
2035 })
2036 ]);
2037
2038 ui.addValidator(nameEl, 'uciname', true, 'blur', 'keyup');
2039 }
2040
2041 return createEl;
2042 },
2043
2044 /** @private */
2045 renderSectionPlaceholder: function() {
2046 return E([
2047 E('em', _('This section contains no values yet')),
2048 E('br'), E('br')
2049 ]);
2050 },
2051
2052 /** @private */
2053 renderContents: function(cfgsections, nodes) {
2054 var section_id = null,
2055 config_name = this.uciconfig || this.map.config,
2056 sectionEl = E('div', {
2057 'id': 'cbi-%s-%s'.format(config_name, this.sectiontype),
2058 'class': 'cbi-section',
2059 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2060 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2061 });
2062
2063 if (this.title != null && this.title != '')
2064 sectionEl.appendChild(E('legend', {}, this.title));
2065
2066 if (this.description != null && this.description != '')
2067 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2068
2069 for (var i = 0; i < nodes.length; i++) {
2070 if (this.addremove) {
2071 sectionEl.appendChild(
2072 E('div', { 'class': 'cbi-section-remove right' },
2073 E('button', {
2074 'class': 'cbi-button',
2075 'name': 'cbi.rts.%s.%s'.format(config_name, cfgsections[i]),
2076 'data-section-id': cfgsections[i],
2077 'click': ui.createHandlerFn(this, 'handleRemove', cfgsections[i]),
2078 'disabled': this.map.readonly || null
2079 }, [ _('Delete') ])));
2080 }
2081
2082 if (!this.anonymous)
2083 sectionEl.appendChild(E('h3', cfgsections[i].toUpperCase()));
2084
2085 sectionEl.appendChild(E('div', {
2086 'id': 'cbi-%s-%s'.format(config_name, cfgsections[i]),
2087 'class': this.tabs
2088 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
2089 'data-section-id': cfgsections[i]
2090 }, nodes[i]));
2091 }
2092
2093 if (nodes.length == 0)
2094 sectionEl.appendChild(this.renderSectionPlaceholder());
2095
2096 sectionEl.appendChild(this.renderSectionAdd());
2097
2098 dom.bindClassInstance(sectionEl, this);
2099
2100 return sectionEl;
2101 },
2102
2103 /** @override */
2104 render: function() {
2105 var cfgsections = this.cfgsections(),
2106 renderTasks = [];
2107
2108 for (var i = 0; i < cfgsections.length; i++)
2109 renderTasks.push(this.renderUCISection(cfgsections[i]));
2110
2111 return Promise.all(renderTasks).then(this.renderContents.bind(this, cfgsections));
2112 }
2113 });
2114
2115 /**
2116 * @class TableSection
2117 * @memberof LuCI.form
2118 * @augments LuCI.form.TypedSection
2119 * @hideconstructor
2120 * @classdesc
2121 *
2122 * The `TableSection` class maps all or - if `filter()` is overwritten - a
2123 * subset of the underlying UCI configuration sections of a given type.
2124 *
2125 * Layout wise, the configuration section instances mapped by the section
2126 * element (sometimes referred to as "section nodes") are rendered as rows
2127 * within an HTML table element, with an optional section remove button in the
2128 * last column and a section add button below the table, depending on the
2129 * value of the `addremove` property.
2130 *
2131 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2132 * The configuration form this section is added to. It is automatically passed
2133 * by [section()]{@link LuCI.form.Map#section}.
2134 *
2135 * @param {string} section_type
2136 * The type of the UCI section to map.
2137 *
2138 * @param {string} [title]
2139 * The title caption of the form section element.
2140 *
2141 * @param {string} [description]
2142 * The description text of the form section element.
2143 */
2144 var CBITableSection = CBITypedSection.extend(/** @lends LuCI.form.TableSection.prototype */ {
2145 __name__: 'CBI.TableSection',
2146
2147 /**
2148 * If set to `true`, the user may add or remove instances from the form
2149 * section widget, otherwise only preexisting sections may be edited.
2150 * The default is `false`.
2151 *
2152 * @name LuCI.form.TableSection.prototype#addremove
2153 * @type boolean
2154 * @default false
2155 */
2156
2157 /**
2158 * If set to `true`, mapped section instances are treated as anonymous
2159 * UCI sections, which means that section instance elements will be
2160 * rendered without title element and that no name is required when adding
2161 * new sections. The default is `false`.
2162 *
2163 * @name LuCI.form.TableSection.prototype#anonymous
2164 * @type boolean
2165 * @default false
2166 */
2167
2168 /**
2169 * Override the caption used for the section add button at the bottom of
2170 * the section form element. If set to a string, it will be used as-is,
2171 * if set to a function, the function will be invoked and its return value
2172 * is used as caption, after converting it to a string. If this property
2173 * is not set, the default is `Add`.
2174 *
2175 * @name LuCI.form.TableSection.prototype#addbtntitle
2176 * @type string|function
2177 * @default null
2178 */
2179
2180 /**
2181 * Override the per-section instance title caption shown in the first
2182 * column of the table unless `anonymous` is set to true. If set to a
2183 * string, it will be used as `String.format()` pattern with the name of
2184 * the underlying UCI section as first argument, if set to a function, the
2185 * function will be invoked with the section name as first argument and
2186 * its return value is used as caption, after converting it to a string.
2187 * If this property is not set, the default is the name of the underlying
2188 * UCI configuration section.
2189 *
2190 * @name LuCI.form.TableSection.prototype#sectiontitle
2191 * @type string|function
2192 * @default null
2193 */
2194
2195 /**
2196 * Override the per-section instance modal popup title caption shown when
2197 * clicking the `More…` button in a section specifying `max_cols`. If set
2198 * to a string, it will be used as `String.format()` pattern with the name
2199 * of the underlying UCI section as first argument, if set to a function,
2200 * the function will be invoked with the section name as first argument and
2201 * its return value is used as caption, after converting it to a string.
2202 * If this property is not set, the default is the name of the underlying
2203 * UCI configuration section.
2204 *
2205 * @name LuCI.form.TableSection.prototype#modaltitle
2206 * @type string|function
2207 * @default null
2208 */
2209
2210 /**
2211 * Override the UCI configuration name to read the section IDs from. By
2212 * default, the configuration name is inherited from the parent `Map`.
2213 * By setting this property, a deviating configuration may be specified.
2214 * The default is `null`, means inheriting from the parent form.
2215 *
2216 * @name LuCI.form.TableSection.prototype#uciconfig
2217 * @type string
2218 * @default null
2219 */
2220
2221 /**
2222 * Specify a maximum amount of columns to display. By default, one table
2223 * column is rendered for each child option of the form section element.
2224 * When this option is set to a positive number, then no more columns than
2225 * the given amount are rendered. When the number of child options exceeds
2226 * the specified amount, a `More…` button is rendered in the last column,
2227 * opening a modal dialog presenting all options elements in `NamedSection`
2228 * style when clicked.
2229 *
2230 * @name LuCI.form.TableSection.prototype#max_cols
2231 * @type number
2232 * @default null
2233 */
2234
2235 /**
2236 * If set to `true`, alternating `cbi-rowstyle-1` and `cbi-rowstyle-2` CSS
2237 * classes are added to the table row elements. Not all LuCI themes
2238 * implement these row style classes. The default is `false`.
2239 *
2240 * @name LuCI.form.TableSection.prototype#rowcolors
2241 * @type boolean
2242 * @default false
2243 */
2244
2245 /**
2246 * Enables a per-section instance row `Edit` button which triggers a certain
2247 * action when clicked. If set to a string, the string value is used
2248 * as `String.format()` pattern with the name of the underlying UCI section
2249 * as first format argument. The result is then interpreted as URL which
2250 * LuCI will navigate to when the user clicks the edit button.
2251 *
2252 * If set to a function, this function will be registered as click event
2253 * handler on the rendered edit button, receiving the section instance
2254 * name as first and the DOM click event as second argument.
2255 *
2256 * @name LuCI.form.TableSection.prototype#extedit
2257 * @type string|function
2258 * @default null
2259 */
2260
2261 /**
2262 * If set to `true`, a sort button is added to the last column, allowing
2263 * the user to reorder the section instances mapped by the section form
2264 * element.
2265 *
2266 * @name LuCI.form.TableSection.prototype#sortable
2267 * @type boolean
2268 * @default false
2269 */
2270
2271 /**
2272 * If set to `true`, the header row with the options descriptions will
2273 * not be displayed. By default, descriptions row is automatically displayed
2274 * when at least one option has a description.
2275 *
2276 * @name LuCI.form.TableSection.prototype#nodescriptions
2277 * @type boolean
2278 * @default false
2279 */
2280
2281 /**
2282 * The `TableSection` implementation does not support option tabbing, so
2283 * its implementation of `tab()` will always throw an exception when
2284 * invoked.
2285 *
2286 * @override
2287 * @throws Throws an exception when invoked.
2288 */
2289 tab: function() {
2290 throw 'Tabs are not supported by TableSection';
2291 },
2292
2293 /** @private */
2294 renderContents: function(cfgsections, nodes) {
2295 var section_id = null,
2296 config_name = this.uciconfig || this.map.config,
2297 max_cols = isNaN(this.max_cols) ? this.children.length : this.max_cols,
2298 has_more = max_cols < this.children.length,
2299 sectionEl = E('div', {
2300 'id': 'cbi-%s-%s'.format(config_name, this.sectiontype),
2301 'class': 'cbi-section cbi-tblsection',
2302 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2303 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2304 }),
2305 tableEl = E('div', {
2306 'class': 'table cbi-section-table'
2307 });
2308
2309 if (this.title != null && this.title != '')
2310 sectionEl.appendChild(E('h3', {}, this.title));
2311
2312 if (this.description != null && this.description != '')
2313 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2314
2315 tableEl.appendChild(this.renderHeaderRows(max_cols));
2316
2317 for (var i = 0; i < nodes.length; i++) {
2318 var sectionname = this.titleFn('sectiontitle', cfgsections[i]);
2319
2320 if (sectionname == null)
2321 sectionname = cfgsections[i];
2322
2323 var trEl = E('div', {
2324 'id': 'cbi-%s-%s'.format(config_name, cfgsections[i]),
2325 'class': 'tr cbi-section-table-row',
2326 'data-sid': cfgsections[i],
2327 'draggable': this.sortable ? true : null,
2328 'mousedown': this.sortable ? L.bind(this.handleDragInit, this) : null,
2329 'dragstart': this.sortable ? L.bind(this.handleDragStart, this) : null,
2330 'dragover': this.sortable ? L.bind(this.handleDragOver, this) : null,
2331 'dragenter': this.sortable ? L.bind(this.handleDragEnter, this) : null,
2332 'dragleave': this.sortable ? L.bind(this.handleDragLeave, this) : null,
2333 'dragend': this.sortable ? L.bind(this.handleDragEnd, this) : null,
2334 'drop': this.sortable ? L.bind(this.handleDrop, this) : null,
2335 'data-title': (sectionname && (!this.anonymous || this.sectiontitle)) ? sectionname : null,
2336 'data-section-id': cfgsections[i]
2337 });
2338
2339 if (this.extedit || this.rowcolors)
2340 trEl.classList.add(!(tableEl.childNodes.length % 2)
2341 ? 'cbi-rowstyle-1' : 'cbi-rowstyle-2');
2342
2343 for (var j = 0; j < max_cols && nodes[i].firstChild; j++)
2344 trEl.appendChild(nodes[i].firstChild);
2345
2346 trEl.appendChild(this.renderRowActions(cfgsections[i], has_more ? _('More…') : null));
2347 tableEl.appendChild(trEl);
2348 }
2349
2350 if (nodes.length == 0)
2351 tableEl.appendChild(E('div', { 'class': 'tr cbi-section-table-row placeholder' },
2352 E('div', { 'class': 'td' },
2353 E('em', {}, _('This section contains no values yet')))));
2354
2355 sectionEl.appendChild(tableEl);
2356
2357 sectionEl.appendChild(this.renderSectionAdd('cbi-tblsection-create'));
2358
2359 dom.bindClassInstance(sectionEl, this);
2360
2361 return sectionEl;
2362 },
2363
2364 /** @private */
2365 renderHeaderRows: function(max_cols, has_action) {
2366 var has_titles = false,
2367 has_descriptions = false,
2368 max_cols = isNaN(this.max_cols) ? this.children.length : this.max_cols,
2369 has_more = max_cols < this.children.length,
2370 anon_class = (!this.anonymous || this.sectiontitle) ? 'named' : 'anonymous',
2371 trEls = E([]);
2372
2373 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2374 if (opt.modalonly)
2375 continue;
2376
2377 has_titles = has_titles || !!opt.title;
2378 has_descriptions = has_descriptions || !!opt.description;
2379 }
2380
2381 if (has_titles) {
2382 var trEl = E('div', {
2383 'class': 'tr cbi-section-table-titles ' + anon_class,
2384 'data-title': (!this.anonymous || this.sectiontitle) ? _('Name') : null
2385 });
2386
2387 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2388 if (opt.modalonly)
2389 continue;
2390
2391 trEl.appendChild(E('div', {
2392 'class': 'th cbi-section-table-cell',
2393 'data-widget': opt.__name__
2394 }));
2395
2396 if (opt.width != null)
2397 trEl.lastElementChild.style.width =
2398 (typeof(opt.width) == 'number') ? opt.width+'px' : opt.width;
2399
2400 if (opt.titleref)
2401 trEl.lastElementChild.appendChild(E('a', {
2402 'href': opt.titleref,
2403 'class': 'cbi-title-ref',
2404 'title': this.titledesc || _('Go to relevant configuration page')
2405 }, opt.title));
2406 else
2407 dom.content(trEl.lastElementChild, opt.title);
2408 }
2409
2410 if (this.sortable || this.extedit || this.addremove || has_more || has_action)
2411 trEl.appendChild(E('div', {
2412 'class': 'th cbi-section-table-cell cbi-section-actions'
2413 }));
2414
2415 trEls.appendChild(trEl);
2416 }
2417
2418 if (has_descriptions && !this.nodescriptions) {
2419 var trEl = E('div', {
2420 'class': 'tr cbi-section-table-descr ' + anon_class
2421 });
2422
2423 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2424 if (opt.modalonly)
2425 continue;
2426
2427 trEl.appendChild(E('div', {
2428 'class': 'th cbi-section-table-cell',
2429 'data-widget': opt.__name__
2430 }, opt.description));
2431
2432 if (opt.width != null)
2433 trEl.lastElementChild.style.width =
2434 (typeof(opt.width) == 'number') ? opt.width+'px' : opt.width;
2435 }
2436
2437 if (this.sortable || this.extedit || this.addremove || has_more || has_action)
2438 trEl.appendChild(E('div', {
2439 'class': 'th cbi-section-table-cell cbi-section-actions'
2440 }));
2441
2442 trEls.appendChild(trEl);
2443 }
2444
2445 return trEls;
2446 },
2447
2448 /** @private */
2449 renderRowActions: function(section_id, more_label) {
2450 var config_name = this.uciconfig || this.map.config;
2451
2452 if (!this.sortable && !this.extedit && !this.addremove && !more_label)
2453 return E([]);
2454
2455 var tdEl = E('div', {
2456 'class': 'td cbi-section-table-cell nowrap cbi-section-actions'
2457 }, E('div'));
2458
2459 if (this.sortable) {
2460 dom.append(tdEl.lastElementChild, [
2461 E('div', {
2462 'title': _('Drag to reorder'),
2463 'class': 'btn cbi-button drag-handle center',
2464 'style': 'cursor:move',
2465 'disabled': this.map.readonly || null
2466 }, '☰')
2467 ]);
2468 }
2469
2470 if (this.extedit) {
2471 var evFn = null;
2472
2473 if (typeof(this.extedit) == 'function')
2474 evFn = L.bind(this.extedit, this);
2475 else if (typeof(this.extedit) == 'string')
2476 evFn = L.bind(function(sid, ev) {
2477 location.href = this.extedit.format(sid);
2478 }, this, section_id);
2479
2480 dom.append(tdEl.lastElementChild,
2481 E('button', {
2482 'title': _('Edit'),
2483 'class': 'cbi-button cbi-button-edit',
2484 'click': evFn
2485 }, [ _('Edit') ])
2486 );
2487 }
2488
2489 if (more_label) {
2490 dom.append(tdEl.lastElementChild,
2491 E('button', {
2492 'title': more_label,
2493 'class': 'cbi-button cbi-button-edit',
2494 'click': ui.createHandlerFn(this, 'renderMoreOptionsModal', section_id)
2495 }, [ more_label ])
2496 );
2497 }
2498
2499 if (this.addremove) {
2500 var btn_title = this.titleFn('removebtntitle', section_id);
2501
2502 dom.append(tdEl.lastElementChild,
2503 E('button', {
2504 'title': btn_title || _('Delete'),
2505 'class': 'cbi-button cbi-button-remove',
2506 'click': ui.createHandlerFn(this, 'handleRemove', section_id),
2507 'disabled': this.map.readonly || null
2508 }, [ btn_title || _('Delete') ])
2509 );
2510 }
2511
2512 return tdEl;
2513 },
2514
2515 /** @private */
2516 handleDragInit: function(ev) {
2517 scope.dragState = { node: ev.target };
2518 },
2519
2520 /** @private */
2521 handleDragStart: function(ev) {
2522 if (!scope.dragState || !scope.dragState.node.classList.contains('drag-handle')) {
2523 scope.dragState = null;
2524 ev.preventDefault();
2525 return false;
2526 }
2527
2528 scope.dragState.node = dom.parent(scope.dragState.node, '.tr');
2529 ev.dataTransfer.setData('text', 'drag');
2530 ev.target.style.opacity = 0.4;
2531 },
2532
2533 /** @private */
2534 handleDragOver: function(ev) {
2535 var n = scope.dragState.targetNode,
2536 r = scope.dragState.rect,
2537 t = r.top + r.height / 2;
2538
2539 if (ev.clientY <= t) {
2540 n.classList.remove('drag-over-below');
2541 n.classList.add('drag-over-above');
2542 }
2543 else {
2544 n.classList.remove('drag-over-above');
2545 n.classList.add('drag-over-below');
2546 }
2547
2548 ev.dataTransfer.dropEffect = 'move';
2549 ev.preventDefault();
2550 return false;
2551 },
2552
2553 /** @private */
2554 handleDragEnter: function(ev) {
2555 scope.dragState.rect = ev.currentTarget.getBoundingClientRect();
2556 scope.dragState.targetNode = ev.currentTarget;
2557 },
2558
2559 /** @private */
2560 handleDragLeave: function(ev) {
2561 ev.currentTarget.classList.remove('drag-over-above');
2562 ev.currentTarget.classList.remove('drag-over-below');
2563 },
2564
2565 /** @private */
2566 handleDragEnd: function(ev) {
2567 var n = ev.target;
2568
2569 n.style.opacity = '';
2570 n.classList.add('flash');
2571 n.parentNode.querySelectorAll('.drag-over-above, .drag-over-below')
2572 .forEach(function(tr) {
2573 tr.classList.remove('drag-over-above');
2574 tr.classList.remove('drag-over-below');
2575 });
2576 },
2577
2578 /** @private */
2579 handleDrop: function(ev) {
2580 var s = scope.dragState;
2581
2582 if (s.node && s.targetNode) {
2583 var config_name = this.uciconfig || this.map.config,
2584 ref_node = s.targetNode,
2585 after = false;
2586
2587 if (ref_node.classList.contains('drag-over-below')) {
2588 ref_node = ref_node.nextElementSibling;
2589 after = true;
2590 }
2591
2592 var sid1 = s.node.getAttribute('data-sid'),
2593 sid2 = s.targetNode.getAttribute('data-sid');
2594
2595 s.node.parentNode.insertBefore(s.node, ref_node);
2596 this.map.data.move(config_name, sid1, sid2, after);
2597 }
2598
2599 scope.dragState = null;
2600 ev.target.style.opacity = '';
2601 ev.stopPropagation();
2602 ev.preventDefault();
2603 return false;
2604 },
2605
2606 /** @private */
2607 handleModalCancel: function(modalMap, ev) {
2608 return Promise.resolve(ui.hideModal());
2609 },
2610
2611 /** @private */
2612 handleModalSave: function(modalMap, ev) {
2613 return modalMap.save()
2614 .then(L.bind(this.map.load, this.map))
2615 .then(L.bind(this.map.reset, this.map))
2616 .then(ui.hideModal)
2617 .catch(function() {});
2618 },
2619
2620 /**
2621 * Add further options to the per-section instanced modal popup.
2622 *
2623 * This function may be overwritten by user code to perform additional
2624 * setup steps before displaying the more options modal which is useful to
2625 * e.g. query additional data or to inject further option elements.
2626 *
2627 * The default implementation of this function does nothing.
2628 *
2629 * @abstract
2630 * @param {LuCI.form.NamedSection} modalSection
2631 * The `NamedSection` instance about to be rendered in the modal popup.
2632 *
2633 * @param {string} section_id
2634 * The ID of the underlying UCI section the modal popup belongs to.
2635 *
2636 * @param {Event} ev
2637 * The DOM event emitted by clicking the `More…` button.
2638 *
2639 * @returns {*|Promise<*>}
2640 * Return values of this function are ignored but if a promise is returned,
2641 * it is run to completion before the rendering is continued, allowing
2642 * custom logic to perform asynchroneous work before the modal dialog
2643 * is shown.
2644 */
2645 addModalOptions: function(modalSection, section_id, ev) {
2646
2647 },
2648
2649 /** @private */
2650 renderMoreOptionsModal: function(section_id, ev) {
2651 var parent = this.map,
2652 title = parent.title,
2653 name = null,
2654 m = new CBIMap(this.map.config, null, null),
2655 s = m.section(CBINamedSection, section_id, this.sectiontype);
2656
2657 m.parent = parent;
2658 m.readonly = parent.readonly;
2659
2660 s.tabs = this.tabs;
2661 s.tab_names = this.tab_names;
2662
2663 if ((name = this.titleFn('modaltitle', section_id)) != null)
2664 title = name;
2665 else if ((name = this.titleFn('sectiontitle', section_id)) != null)
2666 title = '%s - %s'.format(parent.title, name);
2667 else if (!this.anonymous)
2668 title = '%s - %s'.format(parent.title, section_id);
2669
2670 for (var i = 0; i < this.children.length; i++) {
2671 var o1 = this.children[i];
2672
2673 if (o1.modalonly === false)
2674 continue;
2675
2676 var o2 = s.option(o1.constructor, o1.option, o1.title, o1.description);
2677
2678 for (var k in o1) {
2679 if (!o1.hasOwnProperty(k))
2680 continue;
2681
2682 switch (k) {
2683 case 'map':
2684 case 'section':
2685 case 'option':
2686 case 'title':
2687 case 'description':
2688 continue;
2689
2690 default:
2691 o2[k] = o1[k];
2692 }
2693 }
2694 }
2695
2696 return Promise.resolve(this.addModalOptions(s, section_id, ev)).then(L.bind(m.render, m)).then(L.bind(function(nodes) {
2697 ui.showModal(title, [
2698 nodes,
2699 E('div', { 'class': 'right' }, [
2700 E('button', {
2701 'class': 'btn',
2702 'click': ui.createHandlerFn(this, 'handleModalCancel', m)
2703 }, [ _('Dismiss') ]), ' ',
2704 E('button', {
2705 'class': 'cbi-button cbi-button-positive important',
2706 'click': ui.createHandlerFn(this, 'handleModalSave', m),
2707 'disabled': m.readonly || null
2708 }, [ _('Save') ])
2709 ])
2710 ], 'cbi-modal');
2711 }, this)).catch(L.error);
2712 }
2713 });
2714
2715 /**
2716 * @class GridSection
2717 * @memberof LuCI.form
2718 * @augments LuCI.form.TableSection
2719 * @hideconstructor
2720 * @classdesc
2721 *
2722 * The `GridSection` class maps all or - if `filter()` is overwritten - a
2723 * subset of the underlying UCI configuration sections of a given type.
2724 *
2725 * A grid section functions similar to a {@link LuCI.form.TableSection} but
2726 * supports tabbing in the modal overlay. Option elements added with
2727 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
2728 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
2729 * are displayed in the modal popup.
2730 *
2731 * Another important difference is that the table cells show a readonly text
2732 * preview of the corresponding option elements by default, unless the child
2733 * option element is explicitely made writable by setting the `editable`
2734 * property to `true`.
2735 *
2736 * Additionally, the grid section honours a `modalonly` property of child
2737 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
2738 * documentation for details.
2739 *
2740 * Layout wise, a grid section looks mostly identical to table sections.
2741 *
2742 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2743 * The configuration form this section is added to. It is automatically passed
2744 * by [section()]{@link LuCI.form.Map#section}.
2745 *
2746 * @param {string} section_type
2747 * The type of the UCI section to map.
2748 *
2749 * @param {string} [title]
2750 * The title caption of the form section element.
2751 *
2752 * @param {string} [description]
2753 * The description text of the form section element.
2754 */
2755 var CBIGridSection = CBITableSection.extend(/** @lends LuCI.form.GridSection.prototype */ {
2756 /**
2757 * Add an option tab to the section.
2758 *
2759 * The modal option elements of a grid section may be divided into multiple
2760 * tabs to provide a better overview to the user.
2761 *
2762 * Before options can be moved into a tab pane, the corresponding tab
2763 * has to be defined first, which is done by calling this function.
2764 *
2765 * Note that tabs are only effective in modal popups, options added with
2766 * `option()` will not be assigned to a specific tab and are rendered in
2767 * the table view only.
2768 *
2769 * @param {string} name
2770 * The name of the tab to register. It may be freely chosen and just serves
2771 * as an identifier to differentiate tabs.
2772 *
2773 * @param {string} title
2774 * The human readable caption of the tab.
2775 *
2776 * @param {string} [description]
2777 * An additional description text for the corresponding tab pane. It is
2778 * displayed as text paragraph below the tab but before the tab pane
2779 * contents. If omitted, no description will be rendered.
2780 *
2781 * @throws {Error}
2782 * Throws an exeption if a tab with the same `name` already exists.
2783 */
2784 tab: function(name, title, description) {
2785 CBIAbstractSection.prototype.tab.call(this, name, title, description);
2786 },
2787
2788 /** @private */
2789 handleAdd: function(ev, name) {
2790 var config_name = this.uciconfig || this.map.config,
2791 section_id = this.map.data.add(config_name, this.sectiontype, name);
2792
2793 this.addedSection = section_id;
2794 return this.renderMoreOptionsModal(section_id);
2795 },
2796
2797 /** @private */
2798 handleModalSave: function(/* ... */) {
2799 return this.super('handleModalSave', arguments)
2800 .then(L.bind(function() { this.addedSection = null }, this));
2801 },
2802
2803 /** @private */
2804 handleModalCancel: function(/* ... */) {
2805 var config_name = this.uciconfig || this.map.config;
2806
2807 if (this.addedSection != null) {
2808 this.map.data.remove(config_name, this.addedSection);
2809 this.addedSection = null;
2810 }
2811
2812 return this.super('handleModalCancel', arguments);
2813 },
2814
2815 /** @private */
2816 renderUCISection: function(section_id) {
2817 return this.renderOptions(null, section_id);
2818 },
2819
2820 /** @private */
2821 renderChildren: function(tab_name, section_id, in_table) {
2822 var tasks = [], index = 0;
2823
2824 for (var i = 0, opt; (opt = this.children[i]) != null; i++) {
2825 if (opt.disable || opt.modalonly)
2826 continue;
2827
2828 if (opt.editable)
2829 tasks.push(opt.render(index++, section_id, in_table));
2830 else
2831 tasks.push(this.renderTextValue(section_id, opt));
2832 }
2833
2834 return Promise.all(tasks);
2835 },
2836
2837 /** @private */
2838 renderTextValue: function(section_id, opt) {
2839 var title = this.stripTags(opt.title).trim(),
2840 descr = this.stripTags(opt.description).trim(),
2841 value = opt.textvalue(section_id);
2842
2843 return E('div', {
2844 'class': 'td cbi-value-field',
2845 'data-title': (title != '') ? title : null,
2846 'data-description': (descr != '') ? descr : null,
2847 'data-name': opt.option,
2848 'data-widget': opt.typename || opt.__name__
2849 }, (value != null) ? value : E('em', _('none')));
2850 },
2851
2852 /** @private */
2853 renderHeaderRows: function(section_id) {
2854 return this.super('renderHeaderRows', [ NaN, true ]);
2855 },
2856
2857 /** @private */
2858 renderRowActions: function(section_id) {
2859 return this.super('renderRowActions', [ section_id, _('Edit') ]);
2860 },
2861
2862 /** @override */
2863 parse: function() {
2864 var section_ids = this.cfgsections(),
2865 tasks = [];
2866
2867 if (Array.isArray(this.children)) {
2868 for (var i = 0; i < section_ids.length; i++) {
2869 for (var j = 0; j < this.children.length; j++) {
2870 if (!this.children[j].editable || this.children[j].modalonly)
2871 continue;
2872
2873 tasks.push(this.children[j].parse(section_ids[i]));
2874 }
2875 }
2876 }
2877
2878 return Promise.all(tasks);
2879 }
2880 });
2881
2882 /**
2883 * @class NamedSection
2884 * @memberof LuCI.form
2885 * @augments LuCI.form.AbstractSection
2886 * @hideconstructor
2887 * @classdesc
2888 *
2889 * The `NamedSection` class maps exactly one UCI section instance which is
2890 * specified when constructing the class instance.
2891 *
2892 * Layout and functionality wise, a named section is essentially a
2893 * `TypedSection` which allows exactly one section node.
2894 *
2895 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2896 * The configuration form this section is added to. It is automatically passed
2897 * by [section()]{@link LuCI.form.Map#section}.
2898 *
2899 * @param {string} section_id
2900 * The name (ID) of the UCI section to map.
2901 *
2902 * @param {string} section_type
2903 * The type of the UCI section to map.
2904 *
2905 * @param {string} [title]
2906 * The title caption of the form section element.
2907 *
2908 * @param {string} [description]
2909 * The description text of the form section element.
2910 */
2911 var CBINamedSection = CBIAbstractSection.extend(/** @lends LuCI.form.NamedSection.prototype */ {
2912 __name__: 'CBI.NamedSection',
2913 __init__: function(map, section_id /*, ... */) {
2914 this.super('__init__', this.varargs(arguments, 2, map));
2915
2916 this.section = section_id;
2917 },
2918
2919 /**
2920 * If set to `true`, the user may remove or recreate the sole mapped
2921 * configuration instance from the form section widget, otherwise only a
2922 * preexisting section may be edited. The default is `false`.
2923 *
2924 * @name LuCI.form.NamedSection.prototype#addremove
2925 * @type boolean
2926 * @default false
2927 */
2928
2929 /**
2930 * Override the UCI configuration name to read the section IDs from. By
2931 * default, the configuration name is inherited from the parent `Map`.
2932 * By setting this property, a deviating configuration may be specified.
2933 * The default is `null`, means inheriting from the parent form.
2934 *
2935 * @name LuCI.form.NamedSection.prototype#uciconfig
2936 * @type string
2937 * @default null
2938 */
2939
2940 /**
2941 * The `NamedSection` class overwrites the generic `cfgsections()`
2942 * implementation to return a one-element array containing the mapped
2943 * section ID as sole element. User code should not normally change this.
2944 *
2945 * @returns {string[]}
2946 * Returns a one-element array containing the mapped section ID.
2947 */
2948 cfgsections: function() {
2949 return [ this.section ];
2950 },
2951
2952 /** @private */
2953 handleAdd: function(ev) {
2954 var section_id = this.section,
2955 config_name = this.uciconfig || this.map.config;
2956
2957 this.map.data.add(config_name, this.sectiontype, section_id);
2958 return this.map.save(null, true);
2959 },
2960
2961 /** @private */
2962 handleRemove: function(ev) {
2963 var section_id = this.section,
2964 config_name = this.uciconfig || this.map.config;
2965
2966 this.map.data.remove(config_name, section_id);
2967 return this.map.save(null, true);
2968 },
2969
2970 /** @private */
2971 renderContents: function(data) {
2972 var ucidata = data[0], nodes = data[1],
2973 section_id = this.section,
2974 config_name = this.uciconfig || this.map.config,
2975 sectionEl = E('div', {
2976 'id': ucidata ? null : 'cbi-%s-%s'.format(config_name, section_id),
2977 'class': 'cbi-section',
2978 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2979 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2980 });
2981
2982 if (typeof(this.title) === 'string' && this.title !== '')
2983 sectionEl.appendChild(E('legend', {}, this.title));
2984
2985 if (typeof(this.description) === 'string' && this.description !== '')
2986 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2987
2988 if (ucidata) {
2989 if (this.addremove) {
2990 sectionEl.appendChild(
2991 E('div', { 'class': 'cbi-section-remove right' },
2992 E('button', {
2993 'class': 'cbi-button',
2994 'click': ui.createHandlerFn(this, 'handleRemove'),
2995 'disabled': this.map.readonly || null
2996 }, [ _('Delete') ])));
2997 }
2998
2999 sectionEl.appendChild(E('div', {
3000 'id': 'cbi-%s-%s'.format(config_name, section_id),
3001 'class': this.tabs
3002 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3003 'data-section-id': section_id
3004 }, nodes));
3005 }
3006 else if (this.addremove) {
3007 sectionEl.appendChild(
3008 E('button', {
3009 'class': 'cbi-button cbi-button-add',
3010 'click': ui.createHandlerFn(this, 'handleAdd'),
3011 'disabled': this.map.readonly || null
3012 }, [ _('Add') ]));
3013 }
3014
3015 dom.bindClassInstance(sectionEl, this);
3016
3017 return sectionEl;
3018 },
3019
3020 /** @override */
3021 render: function() {
3022 var config_name = this.uciconfig || this.map.config,
3023 section_id = this.section;
3024
3025 return Promise.all([
3026 this.map.data.get(config_name, section_id),
3027 this.renderUCISection(section_id)
3028 ]).then(this.renderContents.bind(this));
3029 }
3030 });
3031
3032 /**
3033 * @class Value
3034 * @memberof LuCI.form
3035 * @augments LuCI.form.AbstractValue
3036 * @hideconstructor
3037 * @classdesc
3038 *
3039 * The `Value` class represents a simple one-line form input using the
3040 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3041 * {@link LuCI.ui.Combobox} class as underlying widget.
3042 *
3043 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3044 * The configuration form this section is added to. It is automatically passed
3045 * by [option()]{@link LuCI.form.AbstractSection#option} or
3046 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3047 * option to the section.
3048 *
3049 * @param {LuCI.form.AbstractSection} section
3050 * The configuration section this option is added to. It is automatically passed
3051 * by [option()]{@link LuCI.form.AbstractSection#option} or
3052 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3053 * option to the section.
3054 *
3055 * @param {string} option
3056 * The name of the UCI option to map.
3057 *
3058 * @param {string} [title]
3059 * The title caption of the option element.
3060 *
3061 * @param {string} [description]
3062 * The description text of the option element.
3063 */
3064 var CBIValue = CBIAbstractValue.extend(/** @lends LuCI.form.Value.prototype */ {
3065 __name__: 'CBI.Value',
3066
3067 /**
3068 * If set to `true`, the field is rendered as password input, otherwise
3069 * as plain text input.
3070 *
3071 * @name LuCI.form.Value.prototype#password
3072 * @type boolean
3073 * @default false
3074 */
3075
3076 /**
3077 * Set a placeholder string to use when the input field is empty.
3078 *
3079 * @name LuCI.form.Value.prototype#placeholder
3080 * @type string
3081 * @default null
3082 */
3083
3084 /**
3085 * Add a predefined choice to the form option. By adding one or more
3086 * choices, the plain text input field is turned into a combobox widget
3087 * which prompts the user to select a predefined choice, or to enter a
3088 * custom value.
3089 *
3090 * @param {string} key
3091 * The choice value to add.
3092 *
3093 * @param {Node|string} value
3094 * The caption for the choice value. May be a DOM node, a document fragment
3095 * or a plain text string. If omitted, the `key` value is used as caption.
3096 */
3097 value: function(key, val) {
3098 this.keylist = this.keylist || [];
3099 this.keylist.push(String(key));
3100
3101 this.vallist = this.vallist || [];
3102 this.vallist.push(dom.elem(val) ? val : String(val != null ? val : key));
3103 },
3104
3105 /** @override */
3106 render: function(option_index, section_id, in_table) {
3107 return Promise.resolve(this.cfgvalue(section_id))
3108 .then(this.renderWidget.bind(this, section_id, option_index))
3109 .then(this.renderFrame.bind(this, section_id, in_table, option_index));
3110 },
3111
3112 /** @private */
3113 renderFrame: function(section_id, in_table, option_index, nodes) {
3114 var config_name = this.uciconfig || this.section.uciconfig || this.map.config,
3115 depend_list = this.transformDepList(section_id),
3116 optionEl;
3117
3118 if (in_table) {
3119 var title = this.stripTags(this.title).trim();
3120 optionEl = E('div', {
3121 'class': 'td cbi-value-field',
3122 'data-title': (title != '') ? title : null,
3123 'data-description': this.stripTags(this.description).trim(),
3124 'data-name': this.option,
3125 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3126 }, E('div', {
3127 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3128 'data-index': option_index,
3129 'data-depends': depend_list,
3130 'data-field': this.cbid(section_id)
3131 }));
3132 }
3133 else {
3134 optionEl = E('div', {
3135 'class': 'cbi-value',
3136 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3137 'data-index': option_index,
3138 'data-depends': depend_list,
3139 'data-field': this.cbid(section_id),
3140 'data-name': this.option,
3141 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3142 });
3143
3144 if (this.last_child)
3145 optionEl.classList.add('cbi-value-last');
3146
3147 if (typeof(this.title) === 'string' && this.title !== '') {
3148 optionEl.appendChild(E('label', {
3149 'class': 'cbi-value-title',
3150 'for': 'widget.cbid.%s.%s.%s'.format(config_name, section_id, this.option),
3151 'click': function(ev) {
3152 var node = ev.currentTarget,
3153 elem = node.nextElementSibling.querySelector('#' + node.getAttribute('for')) || node.nextElementSibling.querySelector('[data-widget-id="' + node.getAttribute('for') + '"]');
3154
3155 if (elem) {
3156 elem.click();
3157 elem.focus();
3158 }
3159 }
3160 },
3161 this.titleref ? E('a', {
3162 'class': 'cbi-title-ref',
3163 'href': this.titleref,
3164 'title': this.titledesc || _('Go to relevant configuration page')
3165 }, this.title) : this.title));
3166
3167 optionEl.appendChild(E('div', { 'class': 'cbi-value-field' }));
3168 }
3169 }
3170
3171 if (nodes)
3172 (optionEl.lastChild || optionEl).appendChild(nodes);
3173
3174 if (!in_table && typeof(this.description) === 'string' && this.description !== '')
3175 dom.append(optionEl.lastChild || optionEl,
3176 E('div', { 'class': 'cbi-value-description' }, this.description));
3177
3178 if (depend_list && depend_list.length)
3179 optionEl.classList.add('hidden');
3180
3181 optionEl.addEventListener('widget-change',
3182 L.bind(this.map.checkDepends, this.map));
3183
3184 dom.bindClassInstance(optionEl, this);
3185
3186 return optionEl;
3187 },
3188
3189 /** @private */
3190 renderWidget: function(section_id, option_index, cfgvalue) {
3191 var value = (cfgvalue != null) ? cfgvalue : this.default,
3192 choices = this.transformChoices(),
3193 widget;
3194
3195 if (choices) {
3196 var placeholder = (this.optional || this.rmempty)
3197 ? E('em', _('unspecified')) : _('-- Please choose --');
3198
3199 widget = new ui.Combobox(Array.isArray(value) ? value.join(' ') : value, choices, {
3200 id: this.cbid(section_id),
3201 sort: this.keylist,
3202 optional: this.optional || this.rmempty,
3203 datatype: this.datatype,
3204 select_placeholder: this.placeholder || placeholder,
3205 validate: L.bind(this.validate, this, section_id),
3206 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3207 });
3208 }
3209 else {
3210 widget = new ui.Textfield(Array.isArray(value) ? value.join(' ') : value, {
3211 id: this.cbid(section_id),
3212 password: this.password,
3213 optional: this.optional || this.rmempty,
3214 datatype: this.datatype,
3215 placeholder: this.placeholder,
3216 validate: L.bind(this.validate, this, section_id),
3217 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3218 });
3219 }
3220
3221 return widget.render();
3222 }
3223 });
3224
3225 /**
3226 * @class DynamicList
3227 * @memberof LuCI.form
3228 * @augments LuCI.form.Value
3229 * @hideconstructor
3230 * @classdesc
3231 *
3232 * The `DynamicList` class represents a multi value widget allowing the user
3233 * to enter multiple unique values, optionally selected from a set of
3234 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3235 *
3236 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3237 * The configuration form this section is added to. It is automatically passed
3238 * by [option()]{@link LuCI.form.AbstractSection#option} or
3239 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3240 * option to the section.
3241 *
3242 * @param {LuCI.form.AbstractSection} section
3243 * The configuration section this option is added to. It is automatically passed
3244 * by [option()]{@link LuCI.form.AbstractSection#option} or
3245 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3246 * option to the section.
3247 *
3248 * @param {string} option
3249 * The name of the UCI option to map.
3250 *
3251 * @param {string} [title]
3252 * The title caption of the option element.
3253 *
3254 * @param {string} [description]
3255 * The description text of the option element.
3256 */
3257 var CBIDynamicList = CBIValue.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3258 __name__: 'CBI.DynamicList',
3259
3260 /** @private */
3261 renderWidget: function(section_id, option_index, cfgvalue) {
3262 var value = (cfgvalue != null) ? cfgvalue : this.default,
3263 choices = this.transformChoices(),
3264 items = L.toArray(value);
3265
3266 var widget = new ui.DynamicList(items, choices, {
3267 id: this.cbid(section_id),
3268 sort: this.keylist,
3269 optional: this.optional || this.rmempty,
3270 datatype: this.datatype,
3271 placeholder: this.placeholder,
3272 validate: L.bind(this.validate, this, section_id),
3273 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3274 });
3275
3276 return widget.render();
3277 },
3278 });
3279
3280 /**
3281 * @class ListValue
3282 * @memberof LuCI.form
3283 * @augments LuCI.form.Value
3284 * @hideconstructor
3285 * @classdesc
3286 *
3287 * The `ListValue` class implements a simple static HTML select element
3288 * allowing the user to chose a single value from a set of predefined choices.
3289 * It builds upon the {@link LuCI.ui.Select} widget.
3290 *
3291 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3292 * The configuration form this section is added to. It is automatically passed
3293 * by [option()]{@link LuCI.form.AbstractSection#option} or
3294 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3295 * option to the section.
3296 *
3297 * @param {LuCI.form.AbstractSection} section
3298 * The configuration section this option is added to. It is automatically passed
3299 * by [option()]{@link LuCI.form.AbstractSection#option} or
3300 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3301 * option to the section.
3302 *
3303 * @param {string} option
3304 * The name of the UCI option to map.
3305 *
3306 * @param {string} [title]
3307 * The title caption of the option element.
3308 *
3309 * @param {string} [description]
3310 * The description text of the option element.
3311 */
3312 var CBIListValue = CBIValue.extend(/** @lends LuCI.form.ListValue.prototype */ {
3313 __name__: 'CBI.ListValue',
3314
3315 __init__: function() {
3316 this.super('__init__', arguments);
3317 this.widget = 'select';
3318 this.orientation = 'horizontal';
3319 this.deplist = [];
3320 },
3321
3322 /**
3323 * Set the size attribute of the underlying HTML select element.
3324 *
3325 * @name LuCI.form.ListValue.prototype#size
3326 * @type number
3327 * @default null
3328 */
3329
3330 /**
3331 * Set the type of the underlying form controls.
3332 *
3333 * May be one of `select` or `radio`. If set to `select`, an HTML
3334 * select element is rendered, otherwise a collection of `radio`
3335 * elements is used.
3336 *
3337 * @name LuCI.form.ListValue.prototype#widget
3338 * @type string
3339 * @default select
3340 */
3341
3342 /**
3343 * Set the orientation of the underlying radio or checkbox elements.
3344 *
3345 * May be one of `horizontal` or `vertical`. Only applies to non-select
3346 * widget types.
3347 *
3348 * @name LuCI.form.ListValue.prototype#orientation
3349 * @type string
3350 * @default horizontal
3351 */
3352
3353 /** @private */
3354 renderWidget: function(section_id, option_index, cfgvalue) {
3355 var choices = this.transformChoices();
3356 var widget = new ui.Select((cfgvalue != null) ? cfgvalue : this.default, choices, {
3357 id: this.cbid(section_id),
3358 size: this.size,
3359 sort: this.keylist,
3360 widget: this.widget,
3361 optional: this.optional,
3362 orientation: this.orientation,
3363 placeholder: this.placeholder,
3364 validate: L.bind(this.validate, this, section_id),
3365 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3366 });
3367
3368 return widget.render();
3369 },
3370 });
3371
3372 /**
3373 * @class FlagValue
3374 * @memberof LuCI.form
3375 * @augments LuCI.form.Value
3376 * @hideconstructor
3377 * @classdesc
3378 *
3379 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3380 * implement a simple checkbox element.
3381 *
3382 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3383 * The configuration form this section is added to. It is automatically passed
3384 * by [option()]{@link LuCI.form.AbstractSection#option} or
3385 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3386 * option to the section.
3387 *
3388 * @param {LuCI.form.AbstractSection} section
3389 * The configuration section this option is added to. It is automatically passed
3390 * by [option()]{@link LuCI.form.AbstractSection#option} or
3391 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3392 * option to the section.
3393 *
3394 * @param {string} option
3395 * The name of the UCI option to map.
3396 *
3397 * @param {string} [title]
3398 * The title caption of the option element.
3399 *
3400 * @param {string} [description]
3401 * The description text of the option element.
3402 */
3403 var CBIFlagValue = CBIValue.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3404 __name__: 'CBI.FlagValue',
3405
3406 __init__: function() {
3407 this.super('__init__', arguments);
3408
3409 this.enabled = '1';
3410 this.disabled = '0';
3411 this.default = this.disabled;
3412 },
3413
3414 /**
3415 * Sets the input value to use for the checkbox checked state.
3416 *
3417 * @name LuCI.form.FlagValue.prototype#enabled
3418 * @type number
3419 * @default 1
3420 */
3421
3422 /**
3423 * Sets the input value to use for the checkbox unchecked state.
3424 *
3425 * @name LuCI.form.FlagValue.prototype#disabled
3426 * @type number
3427 * @default 0
3428 */
3429
3430 /** @private */
3431 renderWidget: function(section_id, option_index, cfgvalue) {
3432 var widget = new ui.Checkbox((cfgvalue != null) ? cfgvalue : this.default, {
3433 id: this.cbid(section_id),
3434 value_enabled: this.enabled,
3435 value_disabled: this.disabled,
3436 validate: L.bind(this.validate, this, section_id),
3437 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3438 });
3439
3440 return widget.render();
3441 },
3442
3443 /**
3444 * Query the checked state of the underlying checkbox widget and return
3445 * either the `enabled` or the `disabled` property value, depending on
3446 * the checked state.
3447 *
3448 * @override
3449 */
3450 formvalue: function(section_id) {
3451 var elem = this.getUIElement(section_id),
3452 checked = elem ? elem.isChecked() : false;
3453 return checked ? this.enabled : this.disabled;
3454 },
3455
3456 /**
3457 * Query the checked state of the underlying checkbox widget and return
3458 * either a localized `Yes` or `No` string, depending on the checked state.
3459 *
3460 * @override
3461 */
3462 textvalue: function(section_id) {
3463 var cval = this.cfgvalue(section_id);
3464
3465 if (cval == null)
3466 cval = this.default;
3467
3468 return (cval == this.enabled) ? _('Yes') : _('No');
3469 },
3470
3471 /** @override */
3472 parse: function(section_id) {
3473 if (this.isActive(section_id)) {
3474 var fval = this.formvalue(section_id);
3475
3476 if (!this.isValid(section_id)) {
3477 var title = this.stripTags(this.title).trim();
3478 return Promise.reject(new TypeError(_('Option "%s" contains an invalid input value.').format(title || this.option)));
3479 }
3480
3481 if (fval == this.default && (this.optional || this.rmempty))
3482 return Promise.resolve(this.remove(section_id));
3483 else
3484 return Promise.resolve(this.write(section_id, fval));
3485 }
3486 else {
3487 return Promise.resolve(this.remove(section_id));
3488 }
3489 },
3490 });
3491
3492 /**
3493 * @class MultiValue
3494 * @memberof LuCI.form
3495 * @augments LuCI.form.DynamicList
3496 * @hideconstructor
3497 * @classdesc
3498 *
3499 * The `MultiValue` class is a modified variant of the `DynamicList` element
3500 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
3501 * select dropdown element.
3502 *
3503 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3504 * The configuration form this section is added to. It is automatically passed
3505 * by [option()]{@link LuCI.form.AbstractSection#option} or
3506 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3507 * option to the section.
3508 *
3509 * @param {LuCI.form.AbstractSection} section
3510 * The configuration section this option is added to. It is automatically passed
3511 * by [option()]{@link LuCI.form.AbstractSection#option} or
3512 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3513 * option to the section.
3514 *
3515 * @param {string} option
3516 * The name of the UCI option to map.
3517 *
3518 * @param {string} [title]
3519 * The title caption of the option element.
3520 *
3521 * @param {string} [description]
3522 * The description text of the option element.
3523 */
3524 var CBIMultiValue = CBIDynamicList.extend(/** @lends LuCI.form.MultiValue.prototype */ {
3525 __name__: 'CBI.MultiValue',
3526
3527 __init__: function() {
3528 this.super('__init__', arguments);
3529 this.placeholder = _('-- Please choose --');
3530 },
3531
3532 /**
3533 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
3534 * property of the underlying dropdown widget. If omitted, the value of
3535 * the `size` property is used or `3` when `size` is unspecified as well.
3536 *
3537 * @name LuCI.form.MultiValue.prototype#display_size
3538 * @type number
3539 * @default null
3540 */
3541
3542 /**
3543 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
3544 * property of the underlying dropdown widget. If omitted, the value of
3545 * the `size` property is used or `-1` when `size` is unspecified as well.
3546 *
3547 * @name LuCI.form.MultiValue.prototype#dropdown_size
3548 * @type number
3549 * @default null
3550 */
3551
3552 /** @private */
3553 renderWidget: function(section_id, option_index, cfgvalue) {
3554 var value = (cfgvalue != null) ? cfgvalue : this.default,
3555 choices = this.transformChoices();
3556
3557 var widget = new ui.Dropdown(L.toArray(value), choices, {
3558 id: this.cbid(section_id),
3559 sort: this.keylist,
3560 multiple: true,
3561 optional: this.optional || this.rmempty,
3562 select_placeholder: this.placeholder,
3563 display_items: this.display_size || this.size || 3,
3564 dropdown_items: this.dropdown_size || this.size || -1,
3565 validate: L.bind(this.validate, this, section_id),
3566 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3567 });
3568
3569 return widget.render();
3570 },
3571 });
3572
3573 /**
3574 * @class TextValue
3575 * @memberof LuCI.form
3576 * @augments LuCI.form.Value
3577 * @hideconstructor
3578 * @classdesc
3579 *
3580 * The `TextValue` class implements a multi-line textarea input using
3581 * {@link LuCI.ui.Textarea}.
3582 *
3583 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3584 * The configuration form this section is added to. It is automatically passed
3585 * by [option()]{@link LuCI.form.AbstractSection#option} or
3586 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3587 * option to the section.
3588 *
3589 * @param {LuCI.form.AbstractSection} section
3590 * The configuration section this option is added to. It is automatically passed
3591 * by [option()]{@link LuCI.form.AbstractSection#option} or
3592 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3593 * option to the section.
3594 *
3595 * @param {string} option
3596 * The name of the UCI option to map.
3597 *
3598 * @param {string} [title]
3599 * The title caption of the option element.
3600 *
3601 * @param {string} [description]
3602 * The description text of the option element.
3603 */
3604 var CBITextValue = CBIValue.extend(/** @lends LuCI.form.TextValue.prototype */ {
3605 __name__: 'CBI.TextValue',
3606
3607 /** @ignore */
3608 value: null,
3609
3610 /**
3611 * Enforces the use of a monospace font for the textarea contents when set
3612 * to `true`.
3613 *
3614 * @name LuCI.form.TextValue.prototype#monospace
3615 * @type boolean
3616 * @default false
3617 */
3618
3619 /**
3620 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
3621 * property of the underlying textarea widget.
3622 *
3623 * @name LuCI.form.TextValue.prototype#cols
3624 * @type number
3625 * @default null
3626 */
3627
3628 /**
3629 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
3630 * property of the underlying textarea widget.
3631 *
3632 * @name LuCI.form.TextValue.prototype#rows
3633 * @type number
3634 * @default null
3635 */
3636
3637 /**
3638 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
3639 * property of the underlying textarea widget.
3640 *
3641 * @name LuCI.form.TextValue.prototype#wrap
3642 * @type number
3643 * @default null
3644 */
3645
3646 /** @private */
3647 renderWidget: function(section_id, option_index, cfgvalue) {
3648 var value = (cfgvalue != null) ? cfgvalue : this.default;
3649
3650 var widget = new ui.Textarea(value, {
3651 id: this.cbid(section_id),
3652 optional: this.optional || this.rmempty,
3653 placeholder: this.placeholder,
3654 monospace: this.monospace,
3655 cols: this.cols,
3656 rows: this.rows,
3657 wrap: this.wrap,
3658 validate: L.bind(this.validate, this, section_id),
3659 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3660 });
3661
3662 return widget.render();
3663 }
3664 });
3665
3666 /**
3667 * @class DummyValue
3668 * @memberof LuCI.form
3669 * @augments LuCI.form.Value
3670 * @hideconstructor
3671 * @classdesc
3672 *
3673 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
3674 * renders the underlying UCI option or default value as readonly text.
3675 *
3676 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3677 * The configuration form this section is added to. It is automatically passed
3678 * by [option()]{@link LuCI.form.AbstractSection#option} or
3679 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3680 * option to the section.
3681 *
3682 * @param {LuCI.form.AbstractSection} section
3683 * The configuration section this option is added to. It is automatically passed
3684 * by [option()]{@link LuCI.form.AbstractSection#option} or
3685 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3686 * option to the section.
3687 *
3688 * @param {string} option
3689 * The name of the UCI option to map.
3690 *
3691 * @param {string} [title]
3692 * The title caption of the option element.
3693 *
3694 * @param {string} [description]
3695 * The description text of the option element.
3696 */
3697 var CBIDummyValue = CBIValue.extend(/** @lends LuCI.form.DummyValue.prototype */ {
3698 __name__: 'CBI.DummyValue',
3699
3700 /**
3701 * Set an URL which is opened when clicking on the dummy value text.
3702 *
3703 * By setting this property, the dummy value text is wrapped in an `<a>`
3704 * element with the property value used as `href` attribute.
3705 *
3706 * @name LuCI.form.DummyValue.prototype#href
3707 * @type string
3708 * @default null
3709 */
3710
3711 /**
3712 * Treat the UCI option value (or the `default` property value) as HTML.
3713 *
3714 * By default, the value text is HTML escaped before being rendered as
3715 * text. In some cases it may be needed to actually interpret and render
3716 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
3717 *
3718 * @name LuCI.form.DummyValue.prototype#rawhtml
3719 * @type boolean
3720 * @default null
3721 */
3722
3723 /** @private */
3724 renderWidget: function(section_id, option_index, cfgvalue) {
3725 var value = (cfgvalue != null) ? cfgvalue : this.default,
3726 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
3727 outputEl = E('div');
3728
3729 if (this.href && !((this.readonly != null) ? this.readonly : this.map.readonly))
3730 outputEl.appendChild(E('a', { 'href': this.href }));
3731
3732 dom.append(outputEl.lastChild || outputEl,
3733 this.rawhtml ? value : [ value ]);
3734
3735 return E([
3736 outputEl,
3737 hiddenEl.render()
3738 ]);
3739 },
3740
3741 /** @override */
3742 remove: function() {},
3743
3744 /** @override */
3745 write: function() {}
3746 });
3747
3748 /**
3749 * @class ButtonValue
3750 * @memberof LuCI.form
3751 * @augments LuCI.form.Value
3752 * @hideconstructor
3753 * @classdesc
3754 *
3755 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
3756 * renders the underlying UCI option or default value as readonly text.
3757 *
3758 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3759 * The configuration form this section is added to. It is automatically passed
3760 * by [option()]{@link LuCI.form.AbstractSection#option} or
3761 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3762 * option to the section.
3763 *
3764 * @param {LuCI.form.AbstractSection} section
3765 * The configuration section this option is added to. It is automatically passed
3766 * by [option()]{@link LuCI.form.AbstractSection#option} or
3767 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3768 * option to the section.
3769 *
3770 * @param {string} option
3771 * The name of the UCI option to map.
3772 *
3773 * @param {string} [title]
3774 * The title caption of the option element.
3775 *
3776 * @param {string} [description]
3777 * The description text of the option element.
3778 */
3779 var CBIButtonValue = CBIValue.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
3780 __name__: 'CBI.ButtonValue',
3781
3782 /**
3783 * Override the rendered button caption.
3784 *
3785 * By default, the option title - which is passed as fourth argument to the
3786 * constructor - is used as caption for the button element. When setting
3787 * this property to a string, it is used as `String.format()` pattern with
3788 * the underlying UCI section name passed as first format argument. When
3789 * set to a function, it is invoked passing the section ID as sole argument
3790 * and the resulting return value is converted to a string before being
3791 * used as button caption.
3792 *
3793 * The default is `null`, means the option title is used as caption.
3794 *
3795 * @name LuCI.form.ButtonValue.prototype#inputtitle
3796 * @type string|function
3797 * @default null
3798 */
3799
3800 /**
3801 * Override the button style class.
3802 *
3803 * By setting this property, a specific `cbi-button-*` CSS class can be
3804 * selected to influence the style of the resulting button.
3805 *
3806 * Suitable values which are implemented by most themes are `positive`,
3807 * `negative` and `primary`.
3808 *
3809 * The default is `null`, means a neutral button styling is used.
3810 *
3811 * @name LuCI.form.ButtonValue.prototype#inputstyle
3812 * @type string
3813 * @default null
3814 */
3815
3816 /**
3817 * Override the button click action.
3818 *
3819 * By default, the underlying UCI option (or default property) value is
3820 * copied into a hidden field tied to the button element and the save
3821 * action is triggered on the parent form element.
3822 *
3823 * When this property is set to a function, it is invoked instead of
3824 * performing the default actions. The handler function will receive the
3825 * DOM click element as first and the underlying configuration section ID
3826 * as second argument.
3827 *
3828 * @name LuCI.form.ButtonValue.prototype#onclick
3829 * @type function
3830 * @default null
3831 */
3832
3833 /** @private */
3834 renderWidget: function(section_id, option_index, cfgvalue) {
3835 var value = (cfgvalue != null) ? cfgvalue : this.default,
3836 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
3837 outputEl = E('div'),
3838 btn_title = this.titleFn('inputtitle', section_id) || this.titleFn('title', section_id);
3839
3840 if (value !== false)
3841 dom.content(outputEl, [
3842 E('button', {
3843 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle || 'button'),
3844 'click': ui.createHandlerFn(this, function(section_id, ev) {
3845 if (this.onclick)
3846 return this.onclick(ev, section_id);
3847
3848 ev.currentTarget.parentNode.nextElementSibling.value = value;
3849 return this.map.save();
3850 }, section_id),
3851 'disabled': ((this.readonly != null) ? this.readonly : this.map.readonly) || null
3852 }, [ btn_title ])
3853 ]);
3854 else
3855 dom.content(outputEl, ' - ');
3856
3857 return E([
3858 outputEl,
3859 hiddenEl.render()
3860 ]);
3861 }
3862 });
3863
3864 /**
3865 * @class HiddenValue
3866 * @memberof LuCI.form
3867 * @augments LuCI.form.Value
3868 * @hideconstructor
3869 * @classdesc
3870 *
3871 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
3872 *
3873 * Hidden value widgets used to be necessary in legacy code which actually
3874 * submitted the underlying HTML form the server. With client side handling of
3875 * forms, there are more efficient ways to store hidden state data.
3876 *
3877 * Since this widget has no visible content, the title and description values
3878 * of this form element should be set to `null` as well to avoid a broken or
3879 * distorted form layout when rendering the option element.
3880 *
3881 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3882 * The configuration form this section is added to. It is automatically passed
3883 * by [option()]{@link LuCI.form.AbstractSection#option} or
3884 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3885 * option to the section.
3886 *
3887 * @param {LuCI.form.AbstractSection} section
3888 * The configuration section this option is added to. It is automatically passed
3889 * by [option()]{@link LuCI.form.AbstractSection#option} or
3890 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3891 * option to the section.
3892 *
3893 * @param {string} option
3894 * The name of the UCI option to map.
3895 *
3896 * @param {string} [title]
3897 * The title caption of the option element.
3898 *
3899 * @param {string} [description]
3900 * The description text of the option element.
3901 */
3902 var CBIHiddenValue = CBIValue.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
3903 __name__: 'CBI.HiddenValue',
3904
3905 /** @private */
3906 renderWidget: function(section_id, option_index, cfgvalue) {
3907 var widget = new ui.Hiddenfield((cfgvalue != null) ? cfgvalue : this.default, {
3908 id: this.cbid(section_id)
3909 });
3910
3911 return widget.render();
3912 }
3913 });
3914
3915 /**
3916 * @class FileUpload
3917 * @memberof LuCI.form
3918 * @augments LuCI.form.Value
3919 * @hideconstructor
3920 * @classdesc
3921 *
3922 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
3923 * offers the ability to browse, upload and select remote files.
3924 *
3925 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3926 * The configuration form this section is added to. It is automatically passed
3927 * by [option()]{@link LuCI.form.AbstractSection#option} or
3928 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3929 * option to the section.
3930 *
3931 * @param {LuCI.form.AbstractSection} section
3932 * The configuration section this option is added to. It is automatically passed
3933 * by [option()]{@link LuCI.form.AbstractSection#option} or
3934 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3935 * option to the section.
3936 *
3937 * @param {string} option
3938 * The name of the UCI option to map.
3939 *
3940 * @param {string} [title]
3941 * The title caption of the option element.
3942 *
3943 * @param {string} [description]
3944 * The description text of the option element.
3945 */
3946 var CBIFileUpload = CBIValue.extend(/** @lends LuCI.form.FileUpload.prototype */ {
3947 __name__: 'CBI.FileSelect',
3948
3949 __init__: function(/* ... */) {
3950 this.super('__init__', arguments);
3951
3952 this.show_hidden = false;
3953 this.enable_upload = true;
3954 this.enable_remove = true;
3955 this.root_directory = '/etc/luci-uploads';
3956 },
3957
3958 /**
3959 * Toggle display of hidden files.
3960 *
3961 * Display hidden files when rendering the remote directory listing.
3962 * Note that this is merely a cosmetic feature, hidden files are always
3963 * included in received remote file listings.
3964 *
3965 * The default is `false`, means hidden files are not displayed.
3966 *
3967 * @name LuCI.form.FileUpload.prototype#show_hidden
3968 * @type boolean
3969 * @default false
3970 */
3971
3972 /**
3973 * Toggle file upload functionality.
3974 *
3975 * When set to `true`, the underlying widget provides a button which lets
3976 * the user select and upload local files to the remote system.
3977 * Note that this is merely a cosmetic feature, remote upload access is
3978 * controlled by the session ACL rules.
3979 *
3980 * The default is `true`, means file upload functionality is displayed.
3981 *
3982 * @name LuCI.form.FileUpload.prototype#enable_upload
3983 * @type boolean
3984 * @default true
3985 */
3986
3987 /**
3988 * Toggle remote file delete functionality.
3989 *
3990 * When set to `true`, the underlying widget provides a buttons which let
3991 * the user delete files from remote directories. Note that this is merely
3992 * a cosmetic feature, remote delete permissions are controlled by the
3993 * session ACL rules.
3994 *
3995 * The default is `true`, means file removal buttons are displayed.
3996 *
3997 * @name LuCI.form.FileUpload.prototype#enable_remove
3998 * @type boolean
3999 * @default true
4000 */
4001
4002 /**
4003 * Specify the root directory for file browsing.
4004 *
4005 * This property defines the topmost directory the file browser widget may
4006 * navigate to, the UI will not allow browsing directories outside this
4007 * prefix. Note that this is merely a cosmetic feature, remote file access
4008 * and directory listing permissions are controlled by the session ACL
4009 * rules.
4010 *
4011 * The default is `/etc/luci-uploads`.
4012 *
4013 * @name LuCI.form.FileUpload.prototype#root_directory
4014 * @type string
4015 * @default /etc/luci-uploads
4016 */
4017
4018 /** @private */
4019 renderWidget: function(section_id, option_index, cfgvalue) {
4020 var browserEl = new ui.FileUpload((cfgvalue != null) ? cfgvalue : this.default, {
4021 id: this.cbid(section_id),
4022 name: this.cbid(section_id),
4023 show_hidden: this.show_hidden,
4024 enable_upload: this.enable_upload,
4025 enable_remove: this.enable_remove,
4026 root_directory: this.root_directory,
4027 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4028 });
4029
4030 return browserEl.render();
4031 }
4032 });
4033
4034 /**
4035 * @class SectionValue
4036 * @memberof LuCI.form
4037 * @augments LuCI.form.Value
4038 * @hideconstructor
4039 * @classdesc
4040 *
4041 * The `SectionValue` widget embeds a form section element within an option
4042 * element container, allowing to nest form sections into other sections.
4043 *
4044 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4045 * The configuration form this section is added to. It is automatically passed
4046 * by [option()]{@link LuCI.form.AbstractSection#option} or
4047 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4048 * option to the section.
4049 *
4050 * @param {LuCI.form.AbstractSection} section
4051 * The configuration section this option is added to. It is automatically passed
4052 * by [option()]{@link LuCI.form.AbstractSection#option} or
4053 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4054 * option to the section.
4055 *
4056 * @param {string} option
4057 * The internal name of the option element holding the section. Since a section
4058 * container element does not read or write any configuration itself, the name
4059 * is only used internally and does not need to relate to any underlying UCI
4060 * option name.
4061 *
4062 * @param {LuCI.form.AbstractSection} subsection_class
4063 * The class to use for instantiating the nested section element. Note that
4064 * the class value itself is expected here, not a class instance obtained by
4065 * calling `new`. The given class argument must be a subclass of the
4066 * `AbstractSection` class.
4067 *
4068 * @param {...*} [class_args]
4069 * All further arguments are passed as-is to the subclass constructor. Refer
4070 * to the corresponding class constructor documentations for details.
4071 */
4072 var CBISectionValue = CBIValue.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4073 __name__: 'CBI.ContainerValue',
4074 __init__: function(map, section, option, cbiClass /*, ... */) {
4075 this.super('__init__', [map, section, option]);
4076
4077 if (!CBIAbstractSection.isSubclass(cbiClass))
4078 throw 'Sub section must be a descendent of CBIAbstractSection';
4079
4080 this.subsection = cbiClass.instantiate(this.varargs(arguments, 4, this.map));
4081 this.subsection.parentoption = this;
4082 },
4083
4084 /**
4085 * Access the embedded section instance.
4086 *
4087 * This property holds a reference to the instantiated nested section.
4088 *
4089 * @name LuCI.form.SectionValue.prototype#subsection
4090 * @type LuCI.form.AbstractSection
4091 * @readonly
4092 */
4093
4094 /** @override */
4095 load: function(section_id) {
4096 return this.subsection.load();
4097 },
4098
4099 /** @override */
4100 parse: function(section_id) {
4101 return this.subsection.parse();
4102 },
4103
4104 /** @private */
4105 renderWidget: function(section_id, option_index, cfgvalue) {
4106 return this.subsection.render();
4107 },
4108
4109 /** @private */
4110 checkDepends: function(section_id) {
4111 this.subsection.checkDepends();
4112 return CBIValue.prototype.checkDepends.apply(this, [ section_id ]);
4113 },
4114
4115 /**
4116 * Since the section container is not rendering an own widget,
4117 * its `value()` implementation is a no-op.
4118 *
4119 * @override
4120 */
4121 value: function() {},
4122
4123 /**
4124 * Since the section container is not tied to any UCI configuration,
4125 * its `write()` implementation is a no-op.
4126 *
4127 * @override
4128 */
4129 write: function() {},
4130
4131 /**
4132 * Since the section container is not tied to any UCI configuration,
4133 * its `remove()` implementation is a no-op.
4134 *
4135 * @override
4136 */
4137 remove: function() {},
4138
4139 /**
4140 * Since the section container is not tied to any UCI configuration,
4141 * its `cfgvalue()` implementation will always return `null`.
4142 *
4143 * @override
4144 * @returns {null}
4145 */
4146 cfgvalue: function() { return null },
4147
4148 /**
4149 * Since the section container is not tied to any UCI configuration,
4150 * its `formvalue()` implementation will always return `null`.
4151 *
4152 * @override
4153 * @returns {null}
4154 */
4155 formvalue: function() { return null }
4156 });
4157
4158 /**
4159 * @class form
4160 * @memberof LuCI
4161 * @hideconstructor
4162 * @classdesc
4163 *
4164 * The LuCI form class provides high level abstractions for creating creating
4165 * UCI- or JSON backed configurations forms.
4166 *
4167 * To import the class in views, use `'require form'`, to import it in
4168 * external JavaScript, use `L.require("form").then(...)`.
4169 *
4170 * A typical form is created by first constructing a
4171 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4172 * by subsequently adding sections and options to it. Finally
4173 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4174 * assemble the HTML markup and insert it into the DOM.
4175 *
4176 * Example:
4177 *
4178 * <pre>
4179 * 'use strict';
4180 * 'require form';
4181 *
4182 * var m, s, o;
4183 *
4184 * m = new form.Map('example', 'Example form',
4185 * 'This is an example form mapping the contents of /etc/config/example');
4186 *
4187 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4188 * 'This sections maps "config example first_section" of /etc/config/example');
4189 *
4190 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4191 *
4192 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4193 * o.value('choice1', 'The first choice');
4194 * o.value('choice2', 'The second choice');
4195 *
4196 * m.render().then(function(node) {
4197 * document.body.appendChild(node);
4198 * });
4199 * </pre>
4200 */
4201 return baseclass.extend(/** @lends LuCI.form.prototype */ {
4202 Map: CBIMap,
4203 JSONMap: CBIJSONMap,
4204 AbstractSection: CBIAbstractSection,
4205 AbstractValue: CBIAbstractValue,
4206
4207 TypedSection: CBITypedSection,
4208 TableSection: CBITableSection,
4209 GridSection: CBIGridSection,
4210 NamedSection: CBINamedSection,
4211
4212 Value: CBIValue,
4213 DynamicList: CBIDynamicList,
4214 ListValue: CBIListValue,
4215 Flag: CBIFlagValue,
4216 MultiValue: CBIMultiValue,
4217 TextValue: CBITextValue,
4218 DummyValue: CBIDummyValue,
4219 Button: CBIButtonValue,
4220 HiddenValue: CBIHiddenValue,
4221 FileUpload: CBIFileUpload,
4222 SectionValue: CBISectionValue
4223 });