Merge pull request #5438 from TDT-AG/pr/20211012-luci-app-vnstat2
[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([
2277 E('em', _('This section contains no values yet')),
2278 E('br'), E('br')
2279 ]);
2280 },
2281
2282 /** @private */
2283 renderContents: function(cfgsections, nodes) {
2284 var section_id = null,
2285 config_name = this.uciconfig || this.map.config,
2286 sectionEl = E('div', {
2287 'id': 'cbi-%s-%s'.format(config_name, this.sectiontype),
2288 'class': 'cbi-section',
2289 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2290 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2291 });
2292
2293 if (this.title != null && this.title != '')
2294 sectionEl.appendChild(E('h3', {}, this.title));
2295
2296 if (this.description != null && this.description != '')
2297 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2298
2299 for (var i = 0; i < nodes.length; i++) {
2300 if (this.addremove) {
2301 sectionEl.appendChild(
2302 E('div', { 'class': 'cbi-section-remove right' },
2303 E('button', {
2304 'class': 'cbi-button',
2305 'name': 'cbi.rts.%s.%s'.format(config_name, cfgsections[i]),
2306 'data-section-id': cfgsections[i],
2307 'click': ui.createHandlerFn(this, 'handleRemove', cfgsections[i]),
2308 'disabled': this.map.readonly || null
2309 }, [ _('Delete') ])));
2310 }
2311
2312 if (!this.anonymous)
2313 sectionEl.appendChild(E('h3', cfgsections[i].toUpperCase()));
2314
2315 sectionEl.appendChild(E('div', {
2316 'id': 'cbi-%s-%s'.format(config_name, cfgsections[i]),
2317 'class': this.tabs
2318 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
2319 'data-section-id': cfgsections[i]
2320 }, nodes[i]));
2321 }
2322
2323 if (nodes.length == 0)
2324 sectionEl.appendChild(this.renderSectionPlaceholder());
2325
2326 sectionEl.appendChild(this.renderSectionAdd());
2327
2328 dom.bindClassInstance(sectionEl, this);
2329
2330 return sectionEl;
2331 },
2332
2333 /** @override */
2334 render: function() {
2335 var cfgsections = this.cfgsections(),
2336 renderTasks = [];
2337
2338 for (var i = 0; i < cfgsections.length; i++)
2339 renderTasks.push(this.renderUCISection(cfgsections[i]));
2340
2341 return Promise.all(renderTasks).then(this.renderContents.bind(this, cfgsections));
2342 }
2343 });
2344
2345 /**
2346 * @class TableSection
2347 * @memberof LuCI.form
2348 * @augments LuCI.form.TypedSection
2349 * @hideconstructor
2350 * @classdesc
2351 *
2352 * The `TableSection` class maps all or - if `filter()` is overwritten - a
2353 * subset of the underlying UCI configuration sections of a given type.
2354 *
2355 * Layout wise, the configuration section instances mapped by the section
2356 * element (sometimes referred to as "section nodes") are rendered as rows
2357 * within an HTML table element, with an optional section remove button in the
2358 * last column and a section add button below the table, depending on the
2359 * value of the `addremove` property.
2360 *
2361 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
2362 * The configuration form this section is added to. It is automatically passed
2363 * by [section()]{@link LuCI.form.Map#section}.
2364 *
2365 * @param {string} section_type
2366 * The type of the UCI section to map.
2367 *
2368 * @param {string} [title]
2369 * The title caption of the form section element.
2370 *
2371 * @param {string} [description]
2372 * The description text of the form section element.
2373 */
2374 var CBITableSection = CBITypedSection.extend(/** @lends LuCI.form.TableSection.prototype */ {
2375 __name__: 'CBI.TableSection',
2376
2377 /**
2378 * If set to `true`, the user may add or remove instances from the form
2379 * section widget, otherwise only preexisting sections may be edited.
2380 * The default is `false`.
2381 *
2382 * @name LuCI.form.TableSection.prototype#addremove
2383 * @type boolean
2384 * @default false
2385 */
2386
2387 /**
2388 * If set to `true`, mapped section instances are treated as anonymous
2389 * UCI sections, which means that section instance elements will be
2390 * rendered without title element and that no name is required when adding
2391 * new sections. The default is `false`.
2392 *
2393 * @name LuCI.form.TableSection.prototype#anonymous
2394 * @type boolean
2395 * @default false
2396 */
2397
2398 /**
2399 * Override the caption used for the section add button at the bottom of
2400 * the section form element. If set to a string, it will be used as-is,
2401 * if set to a function, the function will be invoked and its return value
2402 * is used as caption, after converting it to a string. If this property
2403 * is not set, the default is `Add`.
2404 *
2405 * @name LuCI.form.TableSection.prototype#addbtntitle
2406 * @type string|function
2407 * @default null
2408 */
2409
2410 /**
2411 * Override the per-section instance title caption shown in the first
2412 * column of the table unless `anonymous` is set to true. If set to a
2413 * string, it will be used as `String.format()` pattern with the name of
2414 * the underlying UCI section as first argument, if set to a function, the
2415 * function will be invoked with the section name as first argument and
2416 * its return value is used as caption, after converting it to a string.
2417 * If this property is not set, the default is the name of the underlying
2418 * UCI configuration section.
2419 *
2420 * @name LuCI.form.TableSection.prototype#sectiontitle
2421 * @type string|function
2422 * @default null
2423 */
2424
2425 /**
2426 * Override the per-section instance modal popup title caption shown when
2427 * clicking the `More…` button in a section specifying `max_cols`. If set
2428 * to a string, it will be used as `String.format()` pattern with the name
2429 * of the underlying UCI section as first argument, if set to a function,
2430 * the function will be invoked with the section name as first argument and
2431 * its return value is used as caption, after converting it to a string.
2432 * If this property is not set, the default is the name of the underlying
2433 * UCI configuration section.
2434 *
2435 * @name LuCI.form.TableSection.prototype#modaltitle
2436 * @type string|function
2437 * @default null
2438 */
2439
2440 /**
2441 * Override the UCI configuration name to read the section IDs from. By
2442 * default, the configuration name is inherited from the parent `Map`.
2443 * By setting this property, a deviating configuration may be specified.
2444 * The default is `null`, means inheriting from the parent form.
2445 *
2446 * @name LuCI.form.TableSection.prototype#uciconfig
2447 * @type string
2448 * @default null
2449 */
2450
2451 /**
2452 * Specify a maximum amount of columns to display. By default, one table
2453 * column is rendered for each child option of the form section element.
2454 * When this option is set to a positive number, then no more columns than
2455 * the given amount are rendered. When the number of child options exceeds
2456 * the specified amount, a `More…` button is rendered in the last column,
2457 * opening a modal dialog presenting all options elements in `NamedSection`
2458 * style when clicked.
2459 *
2460 * @name LuCI.form.TableSection.prototype#max_cols
2461 * @type number
2462 * @default null
2463 */
2464
2465 /**
2466 * If set to `true`, alternating `cbi-rowstyle-1` and `cbi-rowstyle-2` CSS
2467 * classes are added to the table row elements. Not all LuCI themes
2468 * implement these row style classes. The default is `false`.
2469 *
2470 * @name LuCI.form.TableSection.prototype#rowcolors
2471 * @type boolean
2472 * @default false
2473 */
2474
2475 /**
2476 * Enables a per-section instance row `Edit` button which triggers a certain
2477 * action when clicked. If set to a string, the string value is used
2478 * as `String.format()` pattern with the name of the underlying UCI section
2479 * as first format argument. The result is then interpreted as URL which
2480 * LuCI will navigate to when the user clicks the edit button.
2481 *
2482 * If set to a function, this function will be registered as click event
2483 * handler on the rendered edit button, receiving the section instance
2484 * name as first and the DOM click event as second argument.
2485 *
2486 * @name LuCI.form.TableSection.prototype#extedit
2487 * @type string|function
2488 * @default null
2489 */
2490
2491 /**
2492 * If set to `true`, a sort button is added to the last column, allowing
2493 * the user to reorder the section instances mapped by the section form
2494 * element.
2495 *
2496 * @name LuCI.form.TableSection.prototype#sortable
2497 * @type boolean
2498 * @default false
2499 */
2500
2501 /**
2502 * If set to `true`, the header row with the options descriptions will
2503 * not be displayed. By default, descriptions row is automatically displayed
2504 * when at least one option has a description.
2505 *
2506 * @name LuCI.form.TableSection.prototype#nodescriptions
2507 * @type boolean
2508 * @default false
2509 */
2510
2511 /**
2512 * The `TableSection` implementation does not support option tabbing, so
2513 * its implementation of `tab()` will always throw an exception when
2514 * invoked.
2515 *
2516 * @override
2517 * @throws Throws an exception when invoked.
2518 */
2519 tab: function() {
2520 throw 'Tabs are not supported by TableSection';
2521 },
2522
2523 /** @private */
2524 renderContents: function(cfgsections, nodes) {
2525 var section_id = null,
2526 config_name = this.uciconfig || this.map.config,
2527 max_cols = isNaN(this.max_cols) ? this.children.length : this.max_cols,
2528 has_more = max_cols < this.children.length,
2529 drag_sort = this.sortable && !('ontouchstart' in window),
2530 touch_sort = this.sortable && ('ontouchstart' in window),
2531 sectionEl = E('div', {
2532 'id': 'cbi-%s-%s'.format(config_name, this.sectiontype),
2533 'class': 'cbi-section cbi-tblsection',
2534 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
2535 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
2536 }),
2537 tableEl = E('table', {
2538 'class': 'table cbi-section-table'
2539 });
2540
2541 if (this.title != null && this.title != '')
2542 sectionEl.appendChild(E('h3', {}, this.title));
2543
2544 if (this.description != null && this.description != '')
2545 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
2546
2547 tableEl.appendChild(this.renderHeaderRows(max_cols));
2548
2549 for (var i = 0; i < nodes.length; i++) {
2550 var sectionname = this.titleFn('sectiontitle', cfgsections[i]);
2551
2552 if (sectionname == null)
2553 sectionname = cfgsections[i];
2554
2555 var trEl = E('tr', {
2556 'id': 'cbi-%s-%s'.format(config_name, cfgsections[i]),
2557 'class': 'tr cbi-section-table-row',
2558 'data-sid': cfgsections[i],
2559 'draggable': (drag_sort || touch_sort) ? true : null,
2560 'mousedown': drag_sort ? L.bind(this.handleDragInit, this) : null,
2561 'dragstart': drag_sort ? L.bind(this.handleDragStart, this) : null,
2562 'dragover': drag_sort ? L.bind(this.handleDragOver, this) : null,
2563 'dragenter': drag_sort ? L.bind(this.handleDragEnter, this) : null,
2564 'dragleave': drag_sort ? L.bind(this.handleDragLeave, this) : null,
2565 'dragend': drag_sort ? L.bind(this.handleDragEnd, this) : null,
2566 'drop': drag_sort ? L.bind(this.handleDrop, this) : null,
2567 'touchmove': touch_sort ? L.bind(this.handleTouchMove, this) : null,
2568 'touchend': touch_sort ? L.bind(this.handleTouchEnd, this) : null,
2569 'data-title': (sectionname && (!this.anonymous || this.sectiontitle)) ? sectionname : null,
2570 'data-section-id': cfgsections[i]
2571 });
2572
2573 if (this.extedit || this.rowcolors)
2574 trEl.classList.add(!(tableEl.childNodes.length % 2)
2575 ? 'cbi-rowstyle-1' : 'cbi-rowstyle-2');
2576
2577 for (var j = 0; j < max_cols && nodes[i].firstChild; j++)
2578 trEl.appendChild(nodes[i].firstChild);
2579
2580 trEl.appendChild(this.renderRowActions(cfgsections[i], has_more ? _('More…') : null));
2581 tableEl.appendChild(trEl);
2582 }
2583
2584 if (nodes.length == 0)
2585 tableEl.appendChild(E('tr', { 'class': 'tr cbi-section-table-row placeholder' },
2586 E('td', { 'class': 'td' },
2587 E('em', {}, _('This section contains no values yet')))));
2588
2589 sectionEl.appendChild(tableEl);
2590
2591 sectionEl.appendChild(this.renderSectionAdd('cbi-tblsection-create'));
2592
2593 dom.bindClassInstance(sectionEl, this);
2594
2595 return sectionEl;
2596 },
2597
2598 /** @private */
2599 renderHeaderRows: function(max_cols, has_action) {
2600 var has_titles = false,
2601 has_descriptions = false,
2602 max_cols = isNaN(this.max_cols) ? this.children.length : this.max_cols,
2603 has_more = max_cols < this.children.length,
2604 anon_class = (!this.anonymous || this.sectiontitle) ? 'named' : 'anonymous',
2605 trEls = E([]);
2606
2607 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2608 if (opt.modalonly)
2609 continue;
2610
2611 has_titles = has_titles || !!opt.title;
2612 has_descriptions = has_descriptions || !!opt.description;
2613 }
2614
2615 if (has_titles) {
2616 var trEl = E('tr', {
2617 'class': 'tr cbi-section-table-titles ' + anon_class,
2618 'data-title': (!this.anonymous || this.sectiontitle) ? _('Name') : null,
2619 'click': this.sortable ? ui.createHandlerFn(this, 'handleSort') : null
2620 });
2621
2622 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2623 if (opt.modalonly)
2624 continue;
2625
2626 trEl.appendChild(E('th', {
2627 'class': 'th cbi-section-table-cell',
2628 'data-widget': opt.__name__,
2629 'data-sortable-row': this.sortable ? '' : null
2630 }));
2631
2632 if (opt.width != null)
2633 trEl.lastElementChild.style.width =
2634 (typeof(opt.width) == 'number') ? opt.width+'px' : opt.width;
2635
2636 if (opt.titleref)
2637 trEl.lastElementChild.appendChild(E('a', {
2638 'href': opt.titleref,
2639 'class': 'cbi-title-ref',
2640 'title': this.titledesc || _('Go to relevant configuration page')
2641 }, opt.title));
2642 else
2643 dom.content(trEl.lastElementChild, opt.title);
2644 }
2645
2646 if (this.sortable || this.extedit || this.addremove || has_more || has_action)
2647 trEl.appendChild(E('th', {
2648 'class': 'th cbi-section-table-cell cbi-section-actions'
2649 }));
2650
2651 trEls.appendChild(trEl);
2652 }
2653
2654 if (has_descriptions && !this.nodescriptions) {
2655 var trEl = E('tr', {
2656 'class': 'tr cbi-section-table-descr ' + anon_class
2657 });
2658
2659 for (var i = 0, opt; i < max_cols && (opt = this.children[i]) != null; i++) {
2660 if (opt.modalonly)
2661 continue;
2662
2663 trEl.appendChild(E('th', {
2664 'class': 'th cbi-section-table-cell',
2665 'data-widget': opt.__name__
2666 }, opt.description));
2667
2668 if (opt.width != null)
2669 trEl.lastElementChild.style.width =
2670 (typeof(opt.width) == 'number') ? opt.width+'px' : opt.width;
2671 }
2672
2673 if (this.sortable || this.extedit || this.addremove || has_more || has_action)
2674 trEl.appendChild(E('th', {
2675 'class': 'th cbi-section-table-cell cbi-section-actions'
2676 }));
2677
2678 trEls.appendChild(trEl);
2679 }
2680
2681 return trEls;
2682 },
2683
2684 /** @private */
2685 renderRowActions: function(section_id, more_label) {
2686 var config_name = this.uciconfig || this.map.config;
2687
2688 if (!this.sortable && !this.extedit && !this.addremove && !more_label)
2689 return E([]);
2690
2691 var tdEl = E('td', {
2692 'class': 'td cbi-section-table-cell nowrap cbi-section-actions'
2693 }, E('div'));
2694
2695 if (this.sortable) {
2696 dom.append(tdEl.lastElementChild, [
2697 E('button', {
2698 'title': _('Drag to reorder'),
2699 'class': 'cbi-button drag-handle center',
2700 'style': 'cursor:move',
2701 'disabled': this.map.readonly || null
2702 }, '☰')
2703 ]);
2704 }
2705
2706 if (this.extedit) {
2707 var evFn = null;
2708
2709 if (typeof(this.extedit) == 'function')
2710 evFn = L.bind(this.extedit, this);
2711 else if (typeof(this.extedit) == 'string')
2712 evFn = L.bind(function(sid, ev) {
2713 location.href = this.extedit.format(sid);
2714 }, this, section_id);
2715
2716 dom.append(tdEl.lastElementChild,
2717 E('button', {
2718 'title': _('Edit'),
2719 'class': 'cbi-button cbi-button-edit',
2720 'click': evFn
2721 }, [ _('Edit') ])
2722 );
2723 }
2724
2725 if (more_label) {
2726 dom.append(tdEl.lastElementChild,
2727 E('button', {
2728 'title': more_label,
2729 'class': 'cbi-button cbi-button-edit',
2730 'click': ui.createHandlerFn(this, 'renderMoreOptionsModal', section_id)
2731 }, [ more_label ])
2732 );
2733 }
2734
2735 if (this.addremove) {
2736 var btn_title = this.titleFn('removebtntitle', section_id);
2737
2738 dom.append(tdEl.lastElementChild,
2739 E('button', {
2740 'title': btn_title || _('Delete'),
2741 'class': 'cbi-button cbi-button-remove',
2742 'click': ui.createHandlerFn(this, 'handleRemove', section_id),
2743 'disabled': this.map.readonly || null
2744 }, [ btn_title || _('Delete') ])
2745 );
2746 }
2747
2748 return tdEl;
2749 },
2750
2751 /** @private */
2752 handleDragInit: function(ev) {
2753 scope.dragState = { node: ev.target };
2754 },
2755
2756 /** @private */
2757 handleDragStart: function(ev) {
2758 if (!scope.dragState || !scope.dragState.node.classList.contains('drag-handle')) {
2759 scope.dragState = null;
2760 ev.preventDefault();
2761 return false;
2762 }
2763
2764 scope.dragState.node = dom.parent(scope.dragState.node, '.tr');
2765 ev.dataTransfer.setData('text', 'drag');
2766 ev.target.style.opacity = 0.4;
2767 },
2768
2769 /** @private */
2770 handleDragOver: function(ev) {
2771 var n = scope.dragState.targetNode,
2772 r = scope.dragState.rect,
2773 t = r.top + r.height / 2;
2774
2775 if (ev.clientY <= t) {
2776 n.classList.remove('drag-over-below');
2777 n.classList.add('drag-over-above');
2778 }
2779 else {
2780 n.classList.remove('drag-over-above');
2781 n.classList.add('drag-over-below');
2782 }
2783
2784 ev.dataTransfer.dropEffect = 'move';
2785 ev.preventDefault();
2786 return false;
2787 },
2788
2789 /** @private */
2790 handleDragEnter: function(ev) {
2791 scope.dragState.rect = ev.currentTarget.getBoundingClientRect();
2792 scope.dragState.targetNode = ev.currentTarget;
2793 },
2794
2795 /** @private */
2796 handleDragLeave: function(ev) {
2797 ev.currentTarget.classList.remove('drag-over-above');
2798 ev.currentTarget.classList.remove('drag-over-below');
2799 },
2800
2801 /** @private */
2802 handleDragEnd: function(ev) {
2803 var n = ev.target;
2804
2805 n.style.opacity = '';
2806 n.classList.add('flash');
2807 n.parentNode.querySelectorAll('.drag-over-above, .drag-over-below')
2808 .forEach(function(tr) {
2809 tr.classList.remove('drag-over-above');
2810 tr.classList.remove('drag-over-below');
2811 });
2812 },
2813
2814 /** @private */
2815 handleDrop: function(ev) {
2816 var s = scope.dragState;
2817
2818 if (s.node && s.targetNode) {
2819 var config_name = this.uciconfig || this.map.config,
2820 ref_node = s.targetNode,
2821 after = false;
2822
2823 if (ref_node.classList.contains('drag-over-below')) {
2824 ref_node = ref_node.nextElementSibling;
2825 after = true;
2826 }
2827
2828 var sid1 = s.node.getAttribute('data-sid'),
2829 sid2 = s.targetNode.getAttribute('data-sid');
2830
2831 s.node.parentNode.insertBefore(s.node, ref_node);
2832 this.map.data.move(config_name, sid1, sid2, after);
2833 }
2834
2835 scope.dragState = null;
2836 ev.target.style.opacity = '';
2837 ev.stopPropagation();
2838 ev.preventDefault();
2839 return false;
2840 },
2841
2842 /** @private */
2843 determineBackgroundColor: function(node) {
2844 var r = 255, g = 255, b = 255;
2845
2846 while (node) {
2847 var s = window.getComputedStyle(node),
2848 c = (s.getPropertyValue('background-color') || '').replace(/ /g, '');
2849
2850 if (c != '' && c != 'transparent' && c != 'rgba(0,0,0,0)') {
2851 if (/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.test(c)) {
2852 r = parseInt(RegExp.$1, 16);
2853 g = parseInt(RegExp.$2, 16);
2854 b = parseInt(RegExp.$3, 16);
2855 }
2856 else if (/^rgba?\(([0-9]+),([0-9]+),([0-9]+)[,)]$/.test(c)) {
2857 r = +RegExp.$1;
2858 g = +RegExp.$2;
2859 b = +RegExp.$3;
2860 }
2861
2862 break;
2863 }
2864
2865 node = node.parentNode;
2866 }
2867
2868 return [ r, g, b ];
2869 },
2870
2871 /** @private */
2872 handleTouchMove: function(ev) {
2873 if (!ev.target.classList.contains('drag-handle'))
2874 return;
2875
2876 var touchLoc = ev.targetTouches[0],
2877 rowBtn = ev.target,
2878 rowElem = dom.parent(rowBtn, '.tr'),
2879 htmlElem = document.querySelector('html'),
2880 dragHandle = document.querySelector('.touchsort-element'),
2881 viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
2882
2883 if (!dragHandle) {
2884 var rowRect = rowElem.getBoundingClientRect(),
2885 btnRect = rowBtn.getBoundingClientRect(),
2886 paddingLeft = btnRect.left - rowRect.left,
2887 paddingRight = rowRect.right - btnRect.right,
2888 colorBg = this.determineBackgroundColor(rowElem),
2889 colorFg = (colorBg[0] * 0.299 + colorBg[1] * 0.587 + colorBg[2] * 0.114) > 186 ? [ 0, 0, 0 ] : [ 255, 255, 255 ];
2890
2891 dragHandle = E('div', { 'class': 'touchsort-element' }, [
2892 E('strong', [ rowElem.getAttribute('data-title') ]),
2893 rowBtn.cloneNode(true)
2894 ]);
2895
2896 Object.assign(dragHandle.style, {
2897 position: 'absolute',
2898 boxShadow: '0 0 3px rgba(%d, %d, %d, 1)'.format(colorFg[0], colorFg[1], colorFg[2]),
2899 background: 'rgba(%d, %d, %d, 0.8)'.format(colorBg[0], colorBg[1], colorBg[2]),
2900 top: rowRect.top + 'px',
2901 left: rowRect.left + 'px',
2902 width: rowRect.width + 'px',
2903 height: (rowBtn.offsetHeight + 4) + 'px'
2904 });
2905
2906 Object.assign(dragHandle.firstElementChild.style, {
2907 position: 'absolute',
2908 lineHeight: dragHandle.style.height,
2909 whiteSpace: 'nowrap',
2910 overflow: 'hidden',
2911 textOverflow: 'ellipsis',
2912 left: (paddingRight > paddingLeft) ? '' : '5px',
2913 right: (paddingRight > paddingLeft) ? '5px' : '',
2914 width: (Math.max(paddingLeft, paddingRight) - 10) + 'px'
2915 });
2916
2917 Object.assign(dragHandle.lastElementChild.style, {
2918 position: 'absolute',
2919 top: '2px',
2920 left: paddingLeft + 'px',
2921 width: rowBtn.offsetWidth + 'px'
2922 });
2923
2924 document.body.appendChild(dragHandle);
2925
2926 rowElem.classList.remove('flash');
2927 rowBtn.blur();
2928 }
2929
2930 dragHandle.style.top = (touchLoc.pageY - (parseInt(dragHandle.style.height) / 2)) + 'px';
2931
2932 rowElem.parentNode.querySelectorAll('[draggable]').forEach(function(tr, i, trs) {
2933 var trRect = tr.getBoundingClientRect(),
2934 yTop = trRect.top + window.scrollY,
2935 yBottom = trRect.bottom + window.scrollY,
2936 yMiddle = yTop + ((yBottom - yTop) / 2);
2937
2938 tr.classList.remove('drag-over-above', 'drag-over-below');
2939
2940 if ((i == 0 || touchLoc.pageY >= yTop) && touchLoc.pageY <= yMiddle)
2941 tr.classList.add('drag-over-above');
2942 else if ((i == (trs.length - 1) || touchLoc.pageY <= yBottom) && touchLoc.pageY > yMiddle)
2943 tr.classList.add('drag-over-below');
2944 });
2945
2946 /* prevent standard scrolling and scroll page when drag handle is
2947 * moved very close (~30px) to the viewport edge */
2948
2949 ev.preventDefault();
2950
2951 if (touchLoc.clientY < 30)
2952 window.requestAnimationFrame(function() { htmlElem.scrollTop -= 30 });
2953 else if (touchLoc.clientY > viewportHeight - 30)
2954 window.requestAnimationFrame(function() { htmlElem.scrollTop += 30 });
2955 },
2956
2957 /** @private */
2958 handleTouchEnd: function(ev) {
2959 var rowElem = dom.parent(ev.target, '.tr'),
2960 htmlElem = document.querySelector('html'),
2961 dragHandle = document.querySelector('.touchsort-element'),
2962 targetElem = rowElem.parentNode.querySelector('.drag-over-above, .drag-over-below'),
2963 viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
2964
2965 if (!dragHandle)
2966 return;
2967
2968 if (targetElem) {
2969 var isBelow = targetElem.classList.contains('drag-over-below');
2970
2971 rowElem.parentNode.insertBefore(rowElem, isBelow ? targetElem.nextElementSibling : targetElem);
2972
2973 this.map.data.move(
2974 this.uciconfig || this.map.config,
2975 rowElem.getAttribute('data-sid'),
2976 targetElem.getAttribute('data-sid'),
2977 isBelow);
2978
2979 window.requestAnimationFrame(function() {
2980 var rowRect = rowElem.getBoundingClientRect();
2981
2982 if (rowRect.top < 50)
2983 htmlElem.scrollTop = (htmlElem.scrollTop + rowRect.top - 50);
2984 else if (rowRect.bottom > viewportHeight - 50)
2985 htmlElem.scrollTop = (htmlElem.scrollTop + viewportHeight - 50 - rowRect.height);
2986
2987 rowElem.classList.add('flash');
2988 });
2989
2990 targetElem.classList.remove('drag-over-above', 'drag-over-below');
2991 }
2992
2993 document.body.removeChild(dragHandle);
2994 },
2995
2996 /** @private */
2997 handleModalCancel: function(modalMap, ev) {
2998 var prevNode = this.getPreviousModalMap();
2999
3000 if (prevNode) {
3001 var heading = prevNode.parentNode.querySelector('h4');
3002
3003 prevNode.classList.add('flash');
3004 prevNode.classList.remove('hidden');
3005 prevNode.parentNode.removeChild(prevNode.nextElementSibling);
3006
3007 heading.removeChild(heading.lastElementChild);
3008
3009 if (!this.getPreviousModalMap())
3010 prevNode.parentNode
3011 .querySelector('div.right > button')
3012 .firstChild.data = _('Dismiss');
3013 }
3014 else {
3015 ui.hideModal();
3016 }
3017
3018 return Promise.resolve();
3019 },
3020
3021 /** @private */
3022 handleModalSave: function(modalMap, ev) {
3023 var mapNode = this.getActiveModalMap(),
3024 activeMap = dom.findClassInstance(mapNode),
3025 saveTasks = activeMap.save(null, true);
3026
3027 while (activeMap.parent) {
3028 activeMap = activeMap.parent;
3029 saveTasks = saveTasks
3030 .then(L.bind(activeMap.load, activeMap))
3031 .then(L.bind(activeMap.reset, activeMap));
3032 }
3033
3034 return saveTasks
3035 .then(L.bind(this.handleModalCancel, this, modalMap, ev))
3036 .catch(function() {});
3037 },
3038
3039 /** @private */
3040 handleSort: function(ev) {
3041 if (!ev.target.matches('th[data-sortable-row]'))
3042 return;
3043
3044 var th = ev.target,
3045 descending = (th.getAttribute('data-sort-direction') == 'desc'),
3046 config_name = this.uciconfig || this.map.config,
3047 index = 0,
3048 list = [];
3049
3050 ev.currentTarget.querySelectorAll('th').forEach(function(other_th, i) {
3051 if (other_th !== th)
3052 other_th.removeAttribute('data-sort-direction');
3053 else
3054 index = i;
3055 });
3056
3057 ev.currentTarget.parentNode.querySelectorAll('tr.cbi-section-table-row').forEach(L.bind(function(tr, i) {
3058 var sid = tr.getAttribute('data-sid'),
3059 opt = tr.childNodes[index].getAttribute('data-name'),
3060 val = this.cfgvalue(sid, opt);
3061
3062 tr.querySelectorAll('.flash').forEach(function(n) {
3063 n.classList.remove('flash')
3064 });
3065
3066 list.push([
3067 ui.Table.prototype.deriveSortKey((val != null) ? val.trim() : ''),
3068 tr
3069 ]);
3070 }, this));
3071
3072 list.sort(function(a, b) {
3073 if (a[0] < b[0])
3074 return descending ? 1 : -1;
3075
3076 if (a[0] > b[0])
3077 return descending ? -1 : 1;
3078
3079 return 0;
3080 });
3081
3082 window.requestAnimationFrame(L.bind(function() {
3083 var ref_sid, cur_sid;
3084
3085 for (var i = 0; i < list.length; i++) {
3086 list[i][1].childNodes[index].classList.add('flash');
3087 th.parentNode.parentNode.appendChild(list[i][1]);
3088
3089 cur_sid = list[i][1].getAttribute('data-sid');
3090
3091 if (ref_sid)
3092 this.map.data.move(config_name, cur_sid, ref_sid, true);
3093
3094 ref_sid = cur_sid;
3095 }
3096
3097 th.setAttribute('data-sort-direction', descending ? 'asc' : 'desc');
3098 }, this));
3099 },
3100
3101 /**
3102 * Add further options to the per-section instanced modal popup.
3103 *
3104 * This function may be overwritten by user code to perform additional
3105 * setup steps before displaying the more options modal which is useful to
3106 * e.g. query additional data or to inject further option elements.
3107 *
3108 * The default implementation of this function does nothing.
3109 *
3110 * @abstract
3111 * @param {LuCI.form.NamedSection} modalSection
3112 * The `NamedSection` instance about to be rendered in the modal popup.
3113 *
3114 * @param {string} section_id
3115 * The ID of the underlying UCI section the modal popup belongs to.
3116 *
3117 * @param {Event} ev
3118 * The DOM event emitted by clicking the `More…` button.
3119 *
3120 * @returns {*|Promise<*>}
3121 * Return values of this function are ignored but if a promise is returned,
3122 * it is run to completion before the rendering is continued, allowing
3123 * custom logic to perform asynchroneous work before the modal dialog
3124 * is shown.
3125 */
3126 addModalOptions: function(modalSection, section_id, ev) {
3127
3128 },
3129
3130 /** @private */
3131 getActiveModalMap: function() {
3132 return document.querySelector('body.modal-overlay-active > #modal_overlay > .modal.cbi-modal > .cbi-map:not(.hidden)');
3133 },
3134
3135 /** @private */
3136 getPreviousModalMap: function() {
3137 var mapNode = this.getActiveModalMap(),
3138 prevNode = mapNode ? mapNode.previousElementSibling : null;
3139
3140 return (prevNode && prevNode.matches('.cbi-map.hidden')) ? prevNode : null;
3141 },
3142
3143 /** @private */
3144 renderMoreOptionsModal: function(section_id, ev) {
3145 var parent = this.map,
3146 title = parent.title,
3147 name = null,
3148 m = new CBIMap(this.map.config, null, null),
3149 s = m.section(CBINamedSection, section_id, this.sectiontype);
3150
3151 m.parent = parent;
3152 m.readonly = parent.readonly;
3153
3154 s.tabs = this.tabs;
3155 s.tab_names = this.tab_names;
3156
3157 if ((name = this.titleFn('modaltitle', section_id)) != null)
3158 title = name;
3159 else if ((name = this.titleFn('sectiontitle', section_id)) != null)
3160 title = '%s - %s'.format(parent.title, name);
3161 else if (!this.anonymous)
3162 title = '%s - %s'.format(parent.title, section_id);
3163
3164 for (var i = 0; i < this.children.length; i++) {
3165 var o1 = this.children[i];
3166
3167 if (o1.modalonly === false)
3168 continue;
3169
3170 var o2 = s.option(o1.constructor, o1.option, o1.title, o1.description);
3171
3172 for (var k in o1) {
3173 if (!o1.hasOwnProperty(k))
3174 continue;
3175
3176 switch (k) {
3177 case 'map':
3178 case 'section':
3179 case 'option':
3180 case 'title':
3181 case 'description':
3182 continue;
3183
3184 default:
3185 o2[k] = o1[k];
3186 }
3187 }
3188 }
3189
3190 return Promise.resolve(this.addModalOptions(s, section_id, ev)).then(L.bind(m.render, m)).then(L.bind(function(nodes) {
3191 var modalMap = this.getActiveModalMap();
3192
3193 if (modalMap) {
3194 modalMap.parentNode
3195 .querySelector('h4')
3196 .appendChild(E('span', title ? ' » ' + title : ''));
3197
3198 modalMap.parentNode
3199 .querySelector('div.right > button')
3200 .firstChild.data = _('Back');
3201
3202 modalMap.classList.add('hidden');
3203 modalMap.parentNode.insertBefore(nodes, modalMap.nextElementSibling);
3204 nodes.classList.add('flash');
3205 }
3206 else {
3207 ui.showModal(title, [
3208 nodes,
3209 E('div', { 'class': 'right' }, [
3210 E('button', {
3211 'class': 'cbi-button',
3212 'click': ui.createHandlerFn(this, 'handleModalCancel', m)
3213 }, [ _('Dismiss') ]), ' ',
3214 E('button', {
3215 'class': 'cbi-button cbi-button-positive important',
3216 'click': ui.createHandlerFn(this, 'handleModalSave', m),
3217 'disabled': m.readonly || null
3218 }, [ _('Save') ])
3219 ])
3220 ], 'cbi-modal');
3221 }
3222 }, this)).catch(L.error);
3223 }
3224 });
3225
3226 /**
3227 * @class GridSection
3228 * @memberof LuCI.form
3229 * @augments LuCI.form.TableSection
3230 * @hideconstructor
3231 * @classdesc
3232 *
3233 * The `GridSection` class maps all or - if `filter()` is overwritten - a
3234 * subset of the underlying UCI configuration sections of a given type.
3235 *
3236 * A grid section functions similar to a {@link LuCI.form.TableSection} but
3237 * supports tabbing in the modal overlay. Option elements added with
3238 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
3239 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
3240 * are displayed in the modal popup.
3241 *
3242 * Another important difference is that the table cells show a readonly text
3243 * preview of the corresponding option elements by default, unless the child
3244 * option element is explicitely made writable by setting the `editable`
3245 * property to `true`.
3246 *
3247 * Additionally, the grid section honours a `modalonly` property of child
3248 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
3249 * documentation for details.
3250 *
3251 * Layout wise, a grid section looks mostly identical to table sections.
3252 *
3253 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3254 * The configuration form this section is added to. It is automatically passed
3255 * by [section()]{@link LuCI.form.Map#section}.
3256 *
3257 * @param {string} section_type
3258 * The type of the UCI section to map.
3259 *
3260 * @param {string} [title]
3261 * The title caption of the form section element.
3262 *
3263 * @param {string} [description]
3264 * The description text of the form section element.
3265 */
3266 var CBIGridSection = CBITableSection.extend(/** @lends LuCI.form.GridSection.prototype */ {
3267 /**
3268 * Add an option tab to the section.
3269 *
3270 * The modal option elements of a grid section may be divided into multiple
3271 * tabs to provide a better overview to the user.
3272 *
3273 * Before options can be moved into a tab pane, the corresponding tab
3274 * has to be defined first, which is done by calling this function.
3275 *
3276 * Note that tabs are only effective in modal popups, options added with
3277 * `option()` will not be assigned to a specific tab and are rendered in
3278 * the table view only.
3279 *
3280 * @param {string} name
3281 * The name of the tab to register. It may be freely chosen and just serves
3282 * as an identifier to differentiate tabs.
3283 *
3284 * @param {string} title
3285 * The human readable caption of the tab.
3286 *
3287 * @param {string} [description]
3288 * An additional description text for the corresponding tab pane. It is
3289 * displayed as text paragraph below the tab but before the tab pane
3290 * contents. If omitted, no description will be rendered.
3291 *
3292 * @throws {Error}
3293 * Throws an exeption if a tab with the same `name` already exists.
3294 */
3295 tab: function(name, title, description) {
3296 CBIAbstractSection.prototype.tab.call(this, name, title, description);
3297 },
3298
3299 /** @private */
3300 handleAdd: function(ev, name) {
3301 var config_name = this.uciconfig || this.map.config,
3302 section_id = this.map.data.add(config_name, this.sectiontype, name),
3303 mapNode = this.getPreviousModalMap(),
3304 prevMap = mapNode ? dom.findClassInstance(mapNode) : this.map;
3305
3306 prevMap.addedSection = section_id;
3307
3308 return this.renderMoreOptionsModal(section_id);
3309 },
3310
3311 /** @private */
3312 handleModalSave: function(/* ... */) {
3313 var mapNode = this.getPreviousModalMap(),
3314 prevMap = mapNode ? dom.findClassInstance(mapNode) : this.map;
3315
3316 return this.super('handleModalSave', arguments)
3317 .then(function() { delete prevMap.addedSection });
3318 },
3319
3320 /** @private */
3321 handleModalCancel: function(/* ... */) {
3322 var config_name = this.uciconfig || this.map.config,
3323 mapNode = this.getPreviousModalMap(),
3324 prevMap = mapNode ? dom.findClassInstance(mapNode) : this.map;
3325
3326 if (prevMap.addedSection != null) {
3327 this.map.data.remove(config_name, prevMap.addedSection);
3328 delete prevMap.addedSection;
3329 }
3330
3331 return this.super('handleModalCancel', arguments);
3332 },
3333
3334 /** @private */
3335 renderUCISection: function(section_id) {
3336 return this.renderOptions(null, section_id);
3337 },
3338
3339 /** @private */
3340 renderChildren: function(tab_name, section_id, in_table) {
3341 var tasks = [], index = 0;
3342
3343 for (var i = 0, opt; (opt = this.children[i]) != null; i++) {
3344 if (opt.disable || opt.modalonly)
3345 continue;
3346
3347 if (opt.editable)
3348 tasks.push(opt.render(index++, section_id, in_table));
3349 else
3350 tasks.push(this.renderTextValue(section_id, opt));
3351 }
3352
3353 return Promise.all(tasks);
3354 },
3355
3356 /** @private */
3357 renderTextValue: function(section_id, opt) {
3358 var title = this.stripTags(opt.title).trim(),
3359 descr = this.stripTags(opt.description).trim(),
3360 value = opt.textvalue(section_id);
3361
3362 return E('td', {
3363 'class': 'td cbi-value-field',
3364 'data-title': (title != '') ? title : null,
3365 'data-description': (descr != '') ? descr : null,
3366 'data-name': opt.option,
3367 'data-widget': opt.typename || opt.__name__
3368 }, (value != null) ? value : E('em', _('none')));
3369 },
3370
3371 /** @private */
3372 renderHeaderRows: function(section_id) {
3373 return this.super('renderHeaderRows', [ NaN, true ]);
3374 },
3375
3376 /** @private */
3377 renderRowActions: function(section_id) {
3378 return this.super('renderRowActions', [ section_id, _('Edit') ]);
3379 },
3380
3381 /** @override */
3382 parse: function() {
3383 var section_ids = this.cfgsections(),
3384 tasks = [];
3385
3386 if (Array.isArray(this.children)) {
3387 for (var i = 0; i < section_ids.length; i++) {
3388 for (var j = 0; j < this.children.length; j++) {
3389 if (!this.children[j].editable || this.children[j].modalonly)
3390 continue;
3391
3392 tasks.push(this.children[j].parse(section_ids[i]));
3393 }
3394 }
3395 }
3396
3397 return Promise.all(tasks);
3398 }
3399 });
3400
3401 /**
3402 * @class NamedSection
3403 * @memberof LuCI.form
3404 * @augments LuCI.form.AbstractSection
3405 * @hideconstructor
3406 * @classdesc
3407 *
3408 * The `NamedSection` class maps exactly one UCI section instance which is
3409 * specified when constructing the class instance.
3410 *
3411 * Layout and functionality wise, a named section is essentially a
3412 * `TypedSection` which allows exactly one section node.
3413 *
3414 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3415 * The configuration form this section is added to. It is automatically passed
3416 * by [section()]{@link LuCI.form.Map#section}.
3417 *
3418 * @param {string} section_id
3419 * The name (ID) of the UCI section to map.
3420 *
3421 * @param {string} section_type
3422 * The type of the UCI section to map.
3423 *
3424 * @param {string} [title]
3425 * The title caption of the form section element.
3426 *
3427 * @param {string} [description]
3428 * The description text of the form section element.
3429 */
3430 var CBINamedSection = CBIAbstractSection.extend(/** @lends LuCI.form.NamedSection.prototype */ {
3431 __name__: 'CBI.NamedSection',
3432 __init__: function(map, section_id /*, ... */) {
3433 this.super('__init__', this.varargs(arguments, 2, map));
3434
3435 this.section = section_id;
3436 },
3437
3438 /**
3439 * If set to `true`, the user may remove or recreate the sole mapped
3440 * configuration instance from the form section widget, otherwise only a
3441 * preexisting section may be edited. The default is `false`.
3442 *
3443 * @name LuCI.form.NamedSection.prototype#addremove
3444 * @type boolean
3445 * @default false
3446 */
3447
3448 /**
3449 * Override the UCI configuration name to read the section IDs from. By
3450 * default, the configuration name is inherited from the parent `Map`.
3451 * By setting this property, a deviating configuration may be specified.
3452 * The default is `null`, means inheriting from the parent form.
3453 *
3454 * @name LuCI.form.NamedSection.prototype#uciconfig
3455 * @type string
3456 * @default null
3457 */
3458
3459 /**
3460 * The `NamedSection` class overwrites the generic `cfgsections()`
3461 * implementation to return a one-element array containing the mapped
3462 * section ID as sole element. User code should not normally change this.
3463 *
3464 * @returns {string[]}
3465 * Returns a one-element array containing the mapped section ID.
3466 */
3467 cfgsections: function() {
3468 return [ this.section ];
3469 },
3470
3471 /** @private */
3472 handleAdd: function(ev) {
3473 var section_id = this.section,
3474 config_name = this.uciconfig || this.map.config;
3475
3476 this.map.data.add(config_name, this.sectiontype, section_id);
3477 return this.map.save(null, true);
3478 },
3479
3480 /** @private */
3481 handleRemove: function(ev) {
3482 var section_id = this.section,
3483 config_name = this.uciconfig || this.map.config;
3484
3485 this.map.data.remove(config_name, section_id);
3486 return this.map.save(null, true);
3487 },
3488
3489 /** @private */
3490 renderContents: function(data) {
3491 var ucidata = data[0], nodes = data[1],
3492 section_id = this.section,
3493 config_name = this.uciconfig || this.map.config,
3494 sectionEl = E('div', {
3495 'id': ucidata ? null : 'cbi-%s-%s'.format(config_name, section_id),
3496 'class': 'cbi-section',
3497 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
3498 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
3499 });
3500
3501 if (typeof(this.title) === 'string' && this.title !== '')
3502 sectionEl.appendChild(E('h3', {}, this.title));
3503
3504 if (typeof(this.description) === 'string' && this.description !== '')
3505 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
3506
3507 if (ucidata) {
3508 if (this.addremove) {
3509 sectionEl.appendChild(
3510 E('div', { 'class': 'cbi-section-remove right' },
3511 E('button', {
3512 'class': 'cbi-button',
3513 'click': ui.createHandlerFn(this, 'handleRemove'),
3514 'disabled': this.map.readonly || null
3515 }, [ _('Delete') ])));
3516 }
3517
3518 sectionEl.appendChild(E('div', {
3519 'id': 'cbi-%s-%s'.format(config_name, section_id),
3520 'class': this.tabs
3521 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3522 'data-section-id': section_id
3523 }, nodes));
3524 }
3525 else if (this.addremove) {
3526 sectionEl.appendChild(
3527 E('button', {
3528 'class': 'cbi-button cbi-button-add',
3529 'click': ui.createHandlerFn(this, 'handleAdd'),
3530 'disabled': this.map.readonly || null
3531 }, [ _('Add') ]));
3532 }
3533
3534 dom.bindClassInstance(sectionEl, this);
3535
3536 return sectionEl;
3537 },
3538
3539 /** @override */
3540 render: function() {
3541 var config_name = this.uciconfig || this.map.config,
3542 section_id = this.section;
3543
3544 return Promise.all([
3545 this.map.data.get(config_name, section_id),
3546 this.renderUCISection(section_id)
3547 ]).then(this.renderContents.bind(this));
3548 }
3549 });
3550
3551 /**
3552 * @class Value
3553 * @memberof LuCI.form
3554 * @augments LuCI.form.AbstractValue
3555 * @hideconstructor
3556 * @classdesc
3557 *
3558 * The `Value` class represents a simple one-line form input using the
3559 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3560 * {@link LuCI.ui.Combobox} class as underlying widget.
3561 *
3562 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3563 * The configuration form this section is added to. It is automatically passed
3564 * by [option()]{@link LuCI.form.AbstractSection#option} or
3565 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3566 * option to the section.
3567 *
3568 * @param {LuCI.form.AbstractSection} section
3569 * The configuration section this option is added to. It is automatically passed
3570 * by [option()]{@link LuCI.form.AbstractSection#option} or
3571 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3572 * option to the section.
3573 *
3574 * @param {string} option
3575 * The name of the UCI option to map.
3576 *
3577 * @param {string} [title]
3578 * The title caption of the option element.
3579 *
3580 * @param {string} [description]
3581 * The description text of the option element.
3582 */
3583 var CBIValue = CBIAbstractValue.extend(/** @lends LuCI.form.Value.prototype */ {
3584 __name__: 'CBI.Value',
3585
3586 /**
3587 * If set to `true`, the field is rendered as password input, otherwise
3588 * as plain text input.
3589 *
3590 * @name LuCI.form.Value.prototype#password
3591 * @type boolean
3592 * @default false
3593 */
3594
3595 /**
3596 * Set a placeholder string to use when the input field is empty.
3597 *
3598 * @name LuCI.form.Value.prototype#placeholder
3599 * @type string
3600 * @default null
3601 */
3602
3603 /**
3604 * Add a predefined choice to the form option. By adding one or more
3605 * choices, the plain text input field is turned into a combobox widget
3606 * which prompts the user to select a predefined choice, or to enter a
3607 * custom value.
3608 *
3609 * @param {string} key
3610 * The choice value to add.
3611 *
3612 * @param {Node|string} value
3613 * The caption for the choice value. May be a DOM node, a document fragment
3614 * or a plain text string. If omitted, the `key` value is used as caption.
3615 */
3616 value: function(key, val) {
3617 this.keylist = this.keylist || [];
3618 this.keylist.push(String(key));
3619
3620 this.vallist = this.vallist || [];
3621 this.vallist.push(dom.elem(val) ? val : String(val != null ? val : key));
3622 },
3623
3624 /** @override */
3625 render: function(option_index, section_id, in_table) {
3626 return Promise.resolve(this.cfgvalue(section_id))
3627 .then(this.renderWidget.bind(this, section_id, option_index))
3628 .then(this.renderFrame.bind(this, section_id, in_table, option_index));
3629 },
3630
3631 /** @private */
3632 handleValueChange: function(section_id, state, ev) {
3633 if (typeof(this.onchange) != 'function')
3634 return;
3635
3636 var value = this.formvalue(section_id);
3637
3638 if (isEqual(value, state.previousValue))
3639 return;
3640
3641 state.previousValue = value;
3642 this.onchange.call(this, ev, section_id, value);
3643 },
3644
3645 /** @private */
3646 renderFrame: function(section_id, in_table, option_index, nodes) {
3647 var config_name = this.uciconfig || this.section.uciconfig || this.map.config,
3648 depend_list = this.transformDepList(section_id),
3649 optionEl;
3650
3651 if (in_table) {
3652 var title = this.stripTags(this.title).trim();
3653 optionEl = E('td', {
3654 'class': 'td cbi-value-field',
3655 'data-title': (title != '') ? title : null,
3656 'data-description': this.stripTags(this.description).trim(),
3657 'data-name': this.option,
3658 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3659 }, E('div', {
3660 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3661 'data-index': option_index,
3662 'data-depends': depend_list,
3663 'data-field': this.cbid(section_id)
3664 }));
3665 }
3666 else {
3667 optionEl = E('div', {
3668 'class': 'cbi-value',
3669 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3670 'data-index': option_index,
3671 'data-depends': depend_list,
3672 'data-field': this.cbid(section_id),
3673 'data-name': this.option,
3674 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3675 });
3676
3677 if (this.last_child)
3678 optionEl.classList.add('cbi-value-last');
3679
3680 if (typeof(this.title) === 'string' && this.title !== '') {
3681 optionEl.appendChild(E('label', {
3682 'class': 'cbi-value-title',
3683 'for': 'widget.cbid.%s.%s.%s'.format(config_name, section_id, this.option),
3684 'click': function(ev) {
3685 var node = ev.currentTarget,
3686 elem = node.nextElementSibling.querySelector('#' + node.getAttribute('for')) || node.nextElementSibling.querySelector('[data-widget-id="' + node.getAttribute('for') + '"]');
3687
3688 if (elem) {
3689 elem.click();
3690 elem.focus();
3691 }
3692 }
3693 },
3694 this.titleref ? E('a', {
3695 'class': 'cbi-title-ref',
3696 'href': this.titleref,
3697 'title': this.titledesc || _('Go to relevant configuration page')
3698 }, this.title) : this.title));
3699
3700 optionEl.appendChild(E('div', { 'class': 'cbi-value-field' }));
3701 }
3702 }
3703
3704 if (nodes)
3705 (optionEl.lastChild || optionEl).appendChild(nodes);
3706
3707 if (!in_table && typeof(this.description) === 'string' && this.description !== '')
3708 dom.append(optionEl.lastChild || optionEl,
3709 E('div', { 'class': 'cbi-value-description' }, this.description));
3710
3711 if (depend_list && depend_list.length)
3712 optionEl.classList.add('hidden');
3713
3714 optionEl.addEventListener('widget-change',
3715 L.bind(this.map.checkDepends, this.map));
3716
3717 optionEl.addEventListener('widget-change',
3718 L.bind(this.handleValueChange, this, section_id, {}));
3719
3720 dom.bindClassInstance(optionEl, this);
3721
3722 return optionEl;
3723 },
3724
3725 /** @private */
3726 renderWidget: function(section_id, option_index, cfgvalue) {
3727 var value = (cfgvalue != null) ? cfgvalue : this.default,
3728 choices = this.transformChoices(),
3729 widget;
3730
3731 if (choices) {
3732 var placeholder = (this.optional || this.rmempty)
3733 ? E('em', _('unspecified')) : _('-- Please choose --');
3734
3735 widget = new ui.Combobox(Array.isArray(value) ? value.join(' ') : value, choices, {
3736 id: this.cbid(section_id),
3737 sort: this.keylist,
3738 optional: this.optional || this.rmempty,
3739 datatype: this.datatype,
3740 select_placeholder: this.placeholder || placeholder,
3741 validate: L.bind(this.validate, this, section_id),
3742 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3743 });
3744 }
3745 else {
3746 widget = new ui.Textfield(Array.isArray(value) ? value.join(' ') : value, {
3747 id: this.cbid(section_id),
3748 password: this.password,
3749 optional: this.optional || this.rmempty,
3750 datatype: this.datatype,
3751 placeholder: this.placeholder,
3752 validate: L.bind(this.validate, this, section_id),
3753 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3754 });
3755 }
3756
3757 return widget.render();
3758 }
3759 });
3760
3761 /**
3762 * @class DynamicList
3763 * @memberof LuCI.form
3764 * @augments LuCI.form.Value
3765 * @hideconstructor
3766 * @classdesc
3767 *
3768 * The `DynamicList` class represents a multi value widget allowing the user
3769 * to enter multiple unique values, optionally selected from a set of
3770 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3771 *
3772 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3773 * The configuration form this section is added to. It is automatically passed
3774 * by [option()]{@link LuCI.form.AbstractSection#option} or
3775 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3776 * option to the section.
3777 *
3778 * @param {LuCI.form.AbstractSection} section
3779 * The configuration section this option is added to. It is automatically passed
3780 * by [option()]{@link LuCI.form.AbstractSection#option} or
3781 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3782 * option to the section.
3783 *
3784 * @param {string} option
3785 * The name of the UCI option to map.
3786 *
3787 * @param {string} [title]
3788 * The title caption of the option element.
3789 *
3790 * @param {string} [description]
3791 * The description text of the option element.
3792 */
3793 var CBIDynamicList = CBIValue.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3794 __name__: 'CBI.DynamicList',
3795
3796 /** @private */
3797 renderWidget: function(section_id, option_index, cfgvalue) {
3798 var value = (cfgvalue != null) ? cfgvalue : this.default,
3799 choices = this.transformChoices(),
3800 items = L.toArray(value);
3801
3802 var widget = new ui.DynamicList(items, choices, {
3803 id: this.cbid(section_id),
3804 sort: this.keylist,
3805 optional: this.optional || this.rmempty,
3806 datatype: this.datatype,
3807 placeholder: this.placeholder,
3808 validate: L.bind(this.validate, this, section_id),
3809 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3810 });
3811
3812 return widget.render();
3813 },
3814 });
3815
3816 /**
3817 * @class ListValue
3818 * @memberof LuCI.form
3819 * @augments LuCI.form.Value
3820 * @hideconstructor
3821 * @classdesc
3822 *
3823 * The `ListValue` class implements a simple static HTML select element
3824 * allowing the user to chose a single value from a set of predefined choices.
3825 * It builds upon the {@link LuCI.ui.Select} widget.
3826 *
3827 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3828 * The configuration form this section is added to. It is automatically passed
3829 * by [option()]{@link LuCI.form.AbstractSection#option} or
3830 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3831 * option to the section.
3832 *
3833 * @param {LuCI.form.AbstractSection} section
3834 * The configuration section this option is added to. It is automatically passed
3835 * by [option()]{@link LuCI.form.AbstractSection#option} or
3836 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3837 * option to the section.
3838 *
3839 * @param {string} option
3840 * The name of the UCI option to map.
3841 *
3842 * @param {string} [title]
3843 * The title caption of the option element.
3844 *
3845 * @param {string} [description]
3846 * The description text of the option element.
3847 */
3848 var CBIListValue = CBIValue.extend(/** @lends LuCI.form.ListValue.prototype */ {
3849 __name__: 'CBI.ListValue',
3850
3851 __init__: function() {
3852 this.super('__init__', arguments);
3853 this.widget = 'select';
3854 this.orientation = 'horizontal';
3855 this.deplist = [];
3856 },
3857
3858 /**
3859 * Set the size attribute of the underlying HTML select element.
3860 *
3861 * @name LuCI.form.ListValue.prototype#size
3862 * @type number
3863 * @default null
3864 */
3865
3866 /**
3867 * Set the type of the underlying form controls.
3868 *
3869 * May be one of `select` or `radio`. If set to `select`, an HTML
3870 * select element is rendered, otherwise a collection of `radio`
3871 * elements is used.
3872 *
3873 * @name LuCI.form.ListValue.prototype#widget
3874 * @type string
3875 * @default select
3876 */
3877
3878 /**
3879 * Set the orientation of the underlying radio or checkbox elements.
3880 *
3881 * May be one of `horizontal` or `vertical`. Only applies to non-select
3882 * widget types.
3883 *
3884 * @name LuCI.form.ListValue.prototype#orientation
3885 * @type string
3886 * @default horizontal
3887 */
3888
3889 /** @private */
3890 renderWidget: function(section_id, option_index, cfgvalue) {
3891 var choices = this.transformChoices();
3892 var widget = new ui.Select((cfgvalue != null) ? cfgvalue : this.default, choices, {
3893 id: this.cbid(section_id),
3894 size: this.size,
3895 sort: this.keylist,
3896 widget: this.widget,
3897 optional: this.optional,
3898 orientation: this.orientation,
3899 placeholder: this.placeholder,
3900 validate: L.bind(this.validate, this, section_id),
3901 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3902 });
3903
3904 return widget.render();
3905 },
3906 });
3907
3908 /**
3909 * @class FlagValue
3910 * @memberof LuCI.form
3911 * @augments LuCI.form.Value
3912 * @hideconstructor
3913 * @classdesc
3914 *
3915 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3916 * implement a simple checkbox element.
3917 *
3918 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3919 * The configuration form this section is added to. It is automatically passed
3920 * by [option()]{@link LuCI.form.AbstractSection#option} or
3921 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3922 * option to the section.
3923 *
3924 * @param {LuCI.form.AbstractSection} section
3925 * The configuration section this option is added to. It is automatically passed
3926 * by [option()]{@link LuCI.form.AbstractSection#option} or
3927 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3928 * option to the section.
3929 *
3930 * @param {string} option
3931 * The name of the UCI option to map.
3932 *
3933 * @param {string} [title]
3934 * The title caption of the option element.
3935 *
3936 * @param {string} [description]
3937 * The description text of the option element.
3938 */
3939 var CBIFlagValue = CBIValue.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3940 __name__: 'CBI.FlagValue',
3941
3942 __init__: function() {
3943 this.super('__init__', arguments);
3944
3945 this.enabled = '1';
3946 this.disabled = '0';
3947 this.default = this.disabled;
3948 },
3949
3950 /**
3951 * Sets the input value to use for the checkbox checked state.
3952 *
3953 * @name LuCI.form.FlagValue.prototype#enabled
3954 * @type number
3955 * @default 1
3956 */
3957
3958 /**
3959 * Sets the input value to use for the checkbox unchecked state.
3960 *
3961 * @name LuCI.form.FlagValue.prototype#disabled
3962 * @type number
3963 * @default 0
3964 */
3965
3966 /**
3967 * Set a tooltip for the flag option.
3968 *
3969 * If set to a string, it will be used as-is as a tooltip.
3970 *
3971 * If set to a function, the function will be invoked and the return
3972 * value will be shown as a tooltip. If the return value of the function
3973 * is `null` no tooltip will be set.
3974 *
3975 * @name LuCI.form.TypedSection.prototype#tooltip
3976 * @type string|function
3977 * @default null
3978 */
3979
3980 /**
3981 * Set a tooltip icon.
3982 *
3983 * If set, this icon will be shown for the default one.
3984 * This could also be a png icon from the resources directory.
3985 *
3986 * @name LuCI.form.TypedSection.prototype#tooltipicon
3987 * @type string
3988 * @default 'ℹ️';
3989 */
3990
3991 /** @private */
3992 renderWidget: function(section_id, option_index, cfgvalue) {
3993 var tooltip = null;
3994
3995 if (typeof(this.tooltip) == 'function')
3996 tooltip = this.tooltip.apply(this, [section_id]);
3997 else if (typeof(this.tooltip) == 'string')
3998 tooltip = (arguments.length > 1) ? ''.format.apply(this.tooltip, this.varargs(arguments, 1)) : this.tooltip;
3999
4000 var widget = new ui.Checkbox((cfgvalue != null) ? cfgvalue : this.default, {
4001 id: this.cbid(section_id),
4002 value_enabled: this.enabled,
4003 value_disabled: this.disabled,
4004 validate: L.bind(this.validate, this, section_id),
4005 tooltip: tooltip,
4006 tooltipicon: this.tooltipicon,
4007 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4008 });
4009
4010 return widget.render();
4011 },
4012
4013 /**
4014 * Query the checked state of the underlying checkbox widget and return
4015 * either the `enabled` or the `disabled` property value, depending on
4016 * the checked state.
4017 *
4018 * @override
4019 */
4020 formvalue: function(section_id) {
4021 var elem = this.getUIElement(section_id),
4022 checked = elem ? elem.isChecked() : false;
4023 return checked ? this.enabled : this.disabled;
4024 },
4025
4026 /**
4027 * Query the checked state of the underlying checkbox widget and return
4028 * either a localized `Yes` or `No` string, depending on the checked state.
4029 *
4030 * @override
4031 */
4032 textvalue: function(section_id) {
4033 var cval = this.cfgvalue(section_id);
4034
4035 if (cval == null)
4036 cval = this.default;
4037
4038 return (cval == this.enabled) ? _('Yes') : _('No');
4039 },
4040
4041 /** @override */
4042 parse: function(section_id) {
4043 if (this.isActive(section_id)) {
4044 var fval = this.formvalue(section_id);
4045
4046 if (!this.isValid(section_id)) {
4047 var title = this.stripTags(this.title).trim();
4048 var error = this.getValidationError(section_id);
4049 return Promise.reject(new TypeError(
4050 _('Option "%s" contains an invalid input value.').format(title || this.option) + ' ' + error));
4051 }
4052
4053 if (fval == this.default && (this.optional || this.rmempty))
4054 return Promise.resolve(this.remove(section_id));
4055 else
4056 return Promise.resolve(this.write(section_id, fval));
4057 }
4058 else if (!this.retain) {
4059 return Promise.resolve(this.remove(section_id));
4060 }
4061 },
4062 });
4063
4064 /**
4065 * @class MultiValue
4066 * @memberof LuCI.form
4067 * @augments LuCI.form.DynamicList
4068 * @hideconstructor
4069 * @classdesc
4070 *
4071 * The `MultiValue` class is a modified variant of the `DynamicList` element
4072 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
4073 * select dropdown element.
4074 *
4075 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4076 * The configuration form this section is added to. It is automatically passed
4077 * by [option()]{@link LuCI.form.AbstractSection#option} or
4078 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4079 * option to the section.
4080 *
4081 * @param {LuCI.form.AbstractSection} section
4082 * The configuration section this option is added to. It is automatically passed
4083 * by [option()]{@link LuCI.form.AbstractSection#option} or
4084 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4085 * option to the section.
4086 *
4087 * @param {string} option
4088 * The name of the UCI option to map.
4089 *
4090 * @param {string} [title]
4091 * The title caption of the option element.
4092 *
4093 * @param {string} [description]
4094 * The description text of the option element.
4095 */
4096 var CBIMultiValue = CBIDynamicList.extend(/** @lends LuCI.form.MultiValue.prototype */ {
4097 __name__: 'CBI.MultiValue',
4098
4099 __init__: function() {
4100 this.super('__init__', arguments);
4101 this.placeholder = _('-- Please choose --');
4102 },
4103
4104 /**
4105 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
4106 * property of the underlying dropdown widget. If omitted, the value of
4107 * the `size` property is used or `3` when `size` is unspecified as well.
4108 *
4109 * @name LuCI.form.MultiValue.prototype#display_size
4110 * @type number
4111 * @default null
4112 */
4113
4114 /**
4115 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
4116 * property of the underlying dropdown widget. If omitted, the value of
4117 * the `size` property is used or `-1` when `size` is unspecified as well.
4118 *
4119 * @name LuCI.form.MultiValue.prototype#dropdown_size
4120 * @type number
4121 * @default null
4122 */
4123
4124 /** @private */
4125 renderWidget: function(section_id, option_index, cfgvalue) {
4126 var value = (cfgvalue != null) ? cfgvalue : this.default,
4127 choices = this.transformChoices();
4128
4129 var widget = new ui.Dropdown(L.toArray(value), choices, {
4130 id: this.cbid(section_id),
4131 sort: this.keylist,
4132 multiple: true,
4133 optional: this.optional || this.rmempty,
4134 select_placeholder: this.placeholder,
4135 display_items: this.display_size || this.size || 3,
4136 dropdown_items: this.dropdown_size || this.size || -1,
4137 validate: L.bind(this.validate, this, section_id),
4138 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4139 });
4140
4141 return widget.render();
4142 },
4143 });
4144
4145 /**
4146 * @class TextValue
4147 * @memberof LuCI.form
4148 * @augments LuCI.form.Value
4149 * @hideconstructor
4150 * @classdesc
4151 *
4152 * The `TextValue` class implements a multi-line textarea input using
4153 * {@link LuCI.ui.Textarea}.
4154 *
4155 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4156 * The configuration form this section is added to. It is automatically passed
4157 * by [option()]{@link LuCI.form.AbstractSection#option} or
4158 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4159 * option to the section.
4160 *
4161 * @param {LuCI.form.AbstractSection} section
4162 * The configuration section this option is added to. It is automatically passed
4163 * by [option()]{@link LuCI.form.AbstractSection#option} or
4164 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4165 * option to the section.
4166 *
4167 * @param {string} option
4168 * The name of the UCI option to map.
4169 *
4170 * @param {string} [title]
4171 * The title caption of the option element.
4172 *
4173 * @param {string} [description]
4174 * The description text of the option element.
4175 */
4176 var CBITextValue = CBIValue.extend(/** @lends LuCI.form.TextValue.prototype */ {
4177 __name__: 'CBI.TextValue',
4178
4179 /** @ignore */
4180 value: null,
4181
4182 /**
4183 * Enforces the use of a monospace font for the textarea contents when set
4184 * to `true`.
4185 *
4186 * @name LuCI.form.TextValue.prototype#monospace
4187 * @type boolean
4188 * @default false
4189 */
4190
4191 /**
4192 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
4193 * property of the underlying textarea widget.
4194 *
4195 * @name LuCI.form.TextValue.prototype#cols
4196 * @type number
4197 * @default null
4198 */
4199
4200 /**
4201 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
4202 * property of the underlying textarea widget.
4203 *
4204 * @name LuCI.form.TextValue.prototype#rows
4205 * @type number
4206 * @default null
4207 */
4208
4209 /**
4210 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
4211 * property of the underlying textarea widget.
4212 *
4213 * @name LuCI.form.TextValue.prototype#wrap
4214 * @type number
4215 * @default null
4216 */
4217
4218 /** @private */
4219 renderWidget: function(section_id, option_index, cfgvalue) {
4220 var value = (cfgvalue != null) ? cfgvalue : this.default;
4221
4222 var widget = new ui.Textarea(value, {
4223 id: this.cbid(section_id),
4224 optional: this.optional || this.rmempty,
4225 placeholder: this.placeholder,
4226 monospace: this.monospace,
4227 cols: this.cols,
4228 rows: this.rows,
4229 wrap: this.wrap,
4230 validate: L.bind(this.validate, this, section_id),
4231 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4232 });
4233
4234 return widget.render();
4235 }
4236 });
4237
4238 /**
4239 * @class DummyValue
4240 * @memberof LuCI.form
4241 * @augments LuCI.form.Value
4242 * @hideconstructor
4243 * @classdesc
4244 *
4245 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4246 * renders the underlying UCI option or default value as readonly text.
4247 *
4248 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4249 * The configuration form this section is added to. It is automatically passed
4250 * by [option()]{@link LuCI.form.AbstractSection#option} or
4251 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4252 * option to the section.
4253 *
4254 * @param {LuCI.form.AbstractSection} section
4255 * The configuration section this option is added to. It is automatically passed
4256 * by [option()]{@link LuCI.form.AbstractSection#option} or
4257 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4258 * option to the section.
4259 *
4260 * @param {string} option
4261 * The name of the UCI option to map.
4262 *
4263 * @param {string} [title]
4264 * The title caption of the option element.
4265 *
4266 * @param {string} [description]
4267 * The description text of the option element.
4268 */
4269 var CBIDummyValue = CBIValue.extend(/** @lends LuCI.form.DummyValue.prototype */ {
4270 __name__: 'CBI.DummyValue',
4271
4272 /**
4273 * Set an URL which is opened when clicking on the dummy value text.
4274 *
4275 * By setting this property, the dummy value text is wrapped in an `<a>`
4276 * element with the property value used as `href` attribute.
4277 *
4278 * @name LuCI.form.DummyValue.prototype#href
4279 * @type string
4280 * @default null
4281 */
4282
4283 /**
4284 * Treat the UCI option value (or the `default` property value) as HTML.
4285 *
4286 * By default, the value text is HTML escaped before being rendered as
4287 * text. In some cases it may be needed to actually interpret and render
4288 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
4289 *
4290 * @name LuCI.form.DummyValue.prototype#rawhtml
4291 * @type boolean
4292 * @default null
4293 */
4294
4295 /**
4296 * Render the UCI option value as hidden using the HTML display: none style property.
4297 *
4298 * By default, the value is displayed
4299 *
4300 * @name LuCI.form.DummyValue.prototype#hidden
4301 * @type boolean
4302 * @default null
4303 */
4304
4305 /** @private */
4306 renderWidget: function(section_id, option_index, cfgvalue) {
4307 var value = (cfgvalue != null) ? cfgvalue : this.default,
4308 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
4309 outputEl = E('div', { 'style': this.hidden ? 'display:none' : null });
4310
4311 if (this.href && !((this.readonly != null) ? this.readonly : this.map.readonly))
4312 outputEl.appendChild(E('a', { 'href': this.href }));
4313
4314 dom.append(outputEl.lastChild || outputEl,
4315 this.rawhtml ? value : [ value ]);
4316
4317 return E([
4318 outputEl,
4319 hiddenEl.render()
4320 ]);
4321 },
4322
4323 /** @override */
4324 remove: function() {},
4325
4326 /** @override */
4327 write: function() {}
4328 });
4329
4330 /**
4331 * @class ButtonValue
4332 * @memberof LuCI.form
4333 * @augments LuCI.form.Value
4334 * @hideconstructor
4335 * @classdesc
4336 *
4337 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4338 * renders the underlying UCI option or default value as readonly text.
4339 *
4340 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4341 * The configuration form this section is added to. It is automatically passed
4342 * by [option()]{@link LuCI.form.AbstractSection#option} or
4343 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4344 * option to the section.
4345 *
4346 * @param {LuCI.form.AbstractSection} section
4347 * The configuration section this option is added to. It is automatically passed
4348 * by [option()]{@link LuCI.form.AbstractSection#option} or
4349 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4350 * option to the section.
4351 *
4352 * @param {string} option
4353 * The name of the UCI option to map.
4354 *
4355 * @param {string} [title]
4356 * The title caption of the option element.
4357 *
4358 * @param {string} [description]
4359 * The description text of the option element.
4360 */
4361 var CBIButtonValue = CBIValue.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
4362 __name__: 'CBI.ButtonValue',
4363
4364 /**
4365 * Override the rendered button caption.
4366 *
4367 * By default, the option title - which is passed as fourth argument to the
4368 * constructor - is used as caption for the button element. When setting
4369 * this property to a string, it is used as `String.format()` pattern with
4370 * the underlying UCI section name passed as first format argument. When
4371 * set to a function, it is invoked passing the section ID as sole argument
4372 * and the resulting return value is converted to a string before being
4373 * used as button caption.
4374 *
4375 * The default is `null`, means the option title is used as caption.
4376 *
4377 * @name LuCI.form.ButtonValue.prototype#inputtitle
4378 * @type string|function
4379 * @default null
4380 */
4381
4382 /**
4383 * Override the button style class.
4384 *
4385 * By setting this property, a specific `cbi-button-*` CSS class can be
4386 * selected to influence the style of the resulting button.
4387 *
4388 * Suitable values which are implemented by most themes are `positive`,
4389 * `negative` and `primary`.
4390 *
4391 * The default is `null`, means a neutral button styling is used.
4392 *
4393 * @name LuCI.form.ButtonValue.prototype#inputstyle
4394 * @type string
4395 * @default null
4396 */
4397
4398 /**
4399 * Override the button click action.
4400 *
4401 * By default, the underlying UCI option (or default property) value is
4402 * copied into a hidden field tied to the button element and the save
4403 * action is triggered on the parent form element.
4404 *
4405 * When this property is set to a function, it is invoked instead of
4406 * performing the default actions. The handler function will receive the
4407 * DOM click element as first and the underlying configuration section ID
4408 * as second argument.
4409 *
4410 * @name LuCI.form.ButtonValue.prototype#onclick
4411 * @type function
4412 * @default null
4413 */
4414
4415 /** @private */
4416 renderWidget: function(section_id, option_index, cfgvalue) {
4417 var value = (cfgvalue != null) ? cfgvalue : this.default,
4418 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
4419 outputEl = E('div'),
4420 btn_title = this.titleFn('inputtitle', section_id) || this.titleFn('title', section_id);
4421
4422 if (value !== false)
4423 dom.content(outputEl, [
4424 E('button', {
4425 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle || 'button'),
4426 'click': ui.createHandlerFn(this, function(section_id, ev) {
4427 if (this.onclick)
4428 return this.onclick(ev, section_id);
4429
4430 ev.currentTarget.parentNode.nextElementSibling.value = value;
4431 return this.map.save();
4432 }, section_id),
4433 'disabled': ((this.readonly != null) ? this.readonly : this.map.readonly) || null
4434 }, [ btn_title ])
4435 ]);
4436 else
4437 dom.content(outputEl, ' - ');
4438
4439 return E([
4440 outputEl,
4441 hiddenEl.render()
4442 ]);
4443 }
4444 });
4445
4446 /**
4447 * @class HiddenValue
4448 * @memberof LuCI.form
4449 * @augments LuCI.form.Value
4450 * @hideconstructor
4451 * @classdesc
4452 *
4453 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
4454 *
4455 * Hidden value widgets used to be necessary in legacy code which actually
4456 * submitted the underlying HTML form the server. With client side handling of
4457 * forms, there are more efficient ways to store hidden state data.
4458 *
4459 * Since this widget has no visible content, the title and description values
4460 * of this form element should be set to `null` as well to avoid a broken or
4461 * distorted form layout when rendering the option element.
4462 *
4463 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4464 * The configuration form this section is added to. It is automatically passed
4465 * by [option()]{@link LuCI.form.AbstractSection#option} or
4466 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4467 * option to the section.
4468 *
4469 * @param {LuCI.form.AbstractSection} section
4470 * The configuration section this option is added to. It is automatically passed
4471 * by [option()]{@link LuCI.form.AbstractSection#option} or
4472 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4473 * option to the section.
4474 *
4475 * @param {string} option
4476 * The name of the UCI option to map.
4477 *
4478 * @param {string} [title]
4479 * The title caption of the option element.
4480 *
4481 * @param {string} [description]
4482 * The description text of the option element.
4483 */
4484 var CBIHiddenValue = CBIValue.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
4485 __name__: 'CBI.HiddenValue',
4486
4487 /** @private */
4488 renderWidget: function(section_id, option_index, cfgvalue) {
4489 var widget = new ui.Hiddenfield((cfgvalue != null) ? cfgvalue : this.default, {
4490 id: this.cbid(section_id)
4491 });
4492
4493 return widget.render();
4494 }
4495 });
4496
4497 /**
4498 * @class FileUpload
4499 * @memberof LuCI.form
4500 * @augments LuCI.form.Value
4501 * @hideconstructor
4502 * @classdesc
4503 *
4504 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
4505 * offers the ability to browse, upload and select remote files.
4506 *
4507 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4508 * The configuration form this section is added to. It is automatically passed
4509 * by [option()]{@link LuCI.form.AbstractSection#option} or
4510 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4511 * option to the section.
4512 *
4513 * @param {LuCI.form.AbstractSection} section
4514 * The configuration section this option is added to. It is automatically passed
4515 * by [option()]{@link LuCI.form.AbstractSection#option} or
4516 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4517 * option to the section.
4518 *
4519 * @param {string} option
4520 * The name of the UCI option to map.
4521 *
4522 * @param {string} [title]
4523 * The title caption of the option element.
4524 *
4525 * @param {string} [description]
4526 * The description text of the option element.
4527 */
4528 var CBIFileUpload = CBIValue.extend(/** @lends LuCI.form.FileUpload.prototype */ {
4529 __name__: 'CBI.FileSelect',
4530
4531 __init__: function(/* ... */) {
4532 this.super('__init__', arguments);
4533
4534 this.show_hidden = false;
4535 this.enable_upload = true;
4536 this.enable_remove = true;
4537 this.root_directory = '/etc/luci-uploads';
4538 },
4539
4540 /**
4541 * Toggle display of hidden files.
4542 *
4543 * Display hidden files when rendering the remote directory listing.
4544 * Note that this is merely a cosmetic feature, hidden files are always
4545 * included in received remote file listings.
4546 *
4547 * The default is `false`, means hidden files are not displayed.
4548 *
4549 * @name LuCI.form.FileUpload.prototype#show_hidden
4550 * @type boolean
4551 * @default false
4552 */
4553
4554 /**
4555 * Toggle file upload functionality.
4556 *
4557 * When set to `true`, the underlying widget provides a button which lets
4558 * the user select and upload local files to the remote system.
4559 * Note that this is merely a cosmetic feature, remote upload access is
4560 * controlled by the session ACL rules.
4561 *
4562 * The default is `true`, means file upload functionality is displayed.
4563 *
4564 * @name LuCI.form.FileUpload.prototype#enable_upload
4565 * @type boolean
4566 * @default true
4567 */
4568
4569 /**
4570 * Toggle remote file delete functionality.
4571 *
4572 * When set to `true`, the underlying widget provides a buttons which let
4573 * the user delete files from remote directories. Note that this is merely
4574 * a cosmetic feature, remote delete permissions are controlled by the
4575 * session ACL rules.
4576 *
4577 * The default is `true`, means file removal buttons are displayed.
4578 *
4579 * @name LuCI.form.FileUpload.prototype#enable_remove
4580 * @type boolean
4581 * @default true
4582 */
4583
4584 /**
4585 * Specify the root directory for file browsing.
4586 *
4587 * This property defines the topmost directory the file browser widget may
4588 * navigate to, the UI will not allow browsing directories outside this
4589 * prefix. Note that this is merely a cosmetic feature, remote file access
4590 * and directory listing permissions are controlled by the session ACL
4591 * rules.
4592 *
4593 * The default is `/etc/luci-uploads`.
4594 *
4595 * @name LuCI.form.FileUpload.prototype#root_directory
4596 * @type string
4597 * @default /etc/luci-uploads
4598 */
4599
4600 /** @private */
4601 renderWidget: function(section_id, option_index, cfgvalue) {
4602 var browserEl = new ui.FileUpload((cfgvalue != null) ? cfgvalue : this.default, {
4603 id: this.cbid(section_id),
4604 name: this.cbid(section_id),
4605 show_hidden: this.show_hidden,
4606 enable_upload: this.enable_upload,
4607 enable_remove: this.enable_remove,
4608 root_directory: this.root_directory,
4609 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4610 });
4611
4612 return browserEl.render();
4613 }
4614 });
4615
4616 /**
4617 * @class SectionValue
4618 * @memberof LuCI.form
4619 * @augments LuCI.form.Value
4620 * @hideconstructor
4621 * @classdesc
4622 *
4623 * The `SectionValue` widget embeds a form section element within an option
4624 * element container, allowing to nest form sections into other sections.
4625 *
4626 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4627 * The configuration form this section is added to. It is automatically passed
4628 * by [option()]{@link LuCI.form.AbstractSection#option} or
4629 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4630 * option to the section.
4631 *
4632 * @param {LuCI.form.AbstractSection} section
4633 * The configuration section this option is added to. It is automatically passed
4634 * by [option()]{@link LuCI.form.AbstractSection#option} or
4635 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4636 * option to the section.
4637 *
4638 * @param {string} option
4639 * The internal name of the option element holding the section. Since a section
4640 * container element does not read or write any configuration itself, the name
4641 * is only used internally and does not need to relate to any underlying UCI
4642 * option name.
4643 *
4644 * @param {LuCI.form.AbstractSection} subsection_class
4645 * The class to use for instantiating the nested section element. Note that
4646 * the class value itself is expected here, not a class instance obtained by
4647 * calling `new`. The given class argument must be a subclass of the
4648 * `AbstractSection` class.
4649 *
4650 * @param {...*} [class_args]
4651 * All further arguments are passed as-is to the subclass constructor. Refer
4652 * to the corresponding class constructor documentations for details.
4653 */
4654 var CBISectionValue = CBIValue.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4655 __name__: 'CBI.ContainerValue',
4656 __init__: function(map, section, option, cbiClass /*, ... */) {
4657 this.super('__init__', [map, section, option]);
4658
4659 if (!CBIAbstractSection.isSubclass(cbiClass))
4660 throw 'Sub section must be a descendent of CBIAbstractSection';
4661
4662 this.subsection = cbiClass.instantiate(this.varargs(arguments, 4, this.map));
4663 this.subsection.parentoption = this;
4664 },
4665
4666 /**
4667 * Access the embedded section instance.
4668 *
4669 * This property holds a reference to the instantiated nested section.
4670 *
4671 * @name LuCI.form.SectionValue.prototype#subsection
4672 * @type LuCI.form.AbstractSection
4673 * @readonly
4674 */
4675
4676 /** @override */
4677 load: function(section_id) {
4678 return this.subsection.load(section_id);
4679 },
4680
4681 /** @override */
4682 parse: function(section_id) {
4683 return this.subsection.parse(section_id);
4684 },
4685
4686 /** @private */
4687 renderWidget: function(section_id, option_index, cfgvalue) {
4688 return this.subsection.render(section_id);
4689 },
4690
4691 /** @private */
4692 checkDepends: function(section_id) {
4693 this.subsection.checkDepends(section_id);
4694 return CBIValue.prototype.checkDepends.apply(this, [ section_id ]);
4695 },
4696
4697 /**
4698 * Since the section container is not rendering an own widget,
4699 * its `value()` implementation is a no-op.
4700 *
4701 * @override
4702 */
4703 value: function() {},
4704
4705 /**
4706 * Since the section container is not tied to any UCI configuration,
4707 * its `write()` implementation is a no-op.
4708 *
4709 * @override
4710 */
4711 write: function() {},
4712
4713 /**
4714 * Since the section container is not tied to any UCI configuration,
4715 * its `remove()` implementation is a no-op.
4716 *
4717 * @override
4718 */
4719 remove: function() {},
4720
4721 /**
4722 * Since the section container is not tied to any UCI configuration,
4723 * its `cfgvalue()` implementation will always return `null`.
4724 *
4725 * @override
4726 * @returns {null}
4727 */
4728 cfgvalue: function() { return null },
4729
4730 /**
4731 * Since the section container is not tied to any UCI configuration,
4732 * its `formvalue()` implementation will always return `null`.
4733 *
4734 * @override
4735 * @returns {null}
4736 */
4737 formvalue: function() { return null }
4738 });
4739
4740 /**
4741 * @class form
4742 * @memberof LuCI
4743 * @hideconstructor
4744 * @classdesc
4745 *
4746 * The LuCI form class provides high level abstractions for creating creating
4747 * UCI- or JSON backed configurations forms.
4748 *
4749 * To import the class in views, use `'require form'`, to import it in
4750 * external JavaScript, use `L.require("form").then(...)`.
4751 *
4752 * A typical form is created by first constructing a
4753 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4754 * by subsequently adding sections and options to it. Finally
4755 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4756 * assemble the HTML markup and insert it into the DOM.
4757 *
4758 * Example:
4759 *
4760 * <pre>
4761 * 'use strict';
4762 * 'require form';
4763 *
4764 * var m, s, o;
4765 *
4766 * m = new form.Map('example', 'Example form',
4767 * 'This is an example form mapping the contents of /etc/config/example');
4768 *
4769 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4770 * 'This sections maps "config example first_section" of /etc/config/example');
4771 *
4772 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4773 *
4774 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4775 * o.value('choice1', 'The first choice');
4776 * o.value('choice2', 'The second choice');
4777 *
4778 * m.render().then(function(node) {
4779 * document.body.appendChild(node);
4780 * });
4781 * </pre>
4782 */
4783 return baseclass.extend(/** @lends LuCI.form.prototype */ {
4784 Map: CBIMap,
4785 JSONMap: CBIJSONMap,
4786 AbstractSection: CBIAbstractSection,
4787 AbstractValue: CBIAbstractValue,
4788
4789 TypedSection: CBITypedSection,
4790 TableSection: CBITableSection,
4791 GridSection: CBIGridSection,
4792 NamedSection: CBINamedSection,
4793
4794 Value: CBIValue,
4795 DynamicList: CBIDynamicList,
4796 ListValue: CBIListValue,
4797 Flag: CBIFlagValue,
4798 MultiValue: CBIMultiValue,
4799 TextValue: CBITextValue,
4800 DummyValue: CBIDummyValue,
4801 Button: CBIButtonValue,
4802 HiddenValue: CBIHiddenValue,
4803 FileUpload: CBIFileUpload,
4804 SectionValue: CBISectionValue
4805 });