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