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