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