aae8b3684a0cce56518df5299bfbb9fa74b829c2
[project/luci.git] / modules / luci-base / htdocs / luci-static / resources / form.js
1 'use strict';
2 'require ui';
3 'require uci';
4 'require rpc';
5 'require dom';
6 'require baseclass';
7
8 var scope = this;
9
10 var callSessionAccess = rpc.declare({
11 object: 'session',
12 method: 'access',
13 params: [ 'scope', 'object', 'function' ],
14 expect: { 'access': false }
15 });
16
17 var CBIJSONConfig = baseclass.extend({
18 __init__: function(data) {
19 data = Object.assign({}, data);
20
21 this.data = {};
22
23 var num_sections = 0,
24 section_ids = [];
25
26 for (var sectiontype in data) {
27 if (!data.hasOwnProperty(sectiontype))
28 continue;
29
30 if (Array.isArray(data[sectiontype])) {
31 for (var i = 0, index = 0; i < data[sectiontype].length; i++) {
32 var item = data[sectiontype][i],
33 anonymous, name;
34
35 if (!L.isObject(item))
36 continue;
37
38 if (typeof(item['.name']) == 'string') {
39 name = item['.name'];
40 anonymous = false;
41 }
42 else {
43 name = sectiontype + num_sections;
44 anonymous = true;
45 }
46
47 if (!this.data.hasOwnProperty(name))
48 section_ids.push(name);
49
50 this.data[name] = Object.assign(item, {
51 '.index': num_sections++,
52 '.anonymous': anonymous,
53 '.name': name,
54 '.type': sectiontype
55 });
56 }
57 }
58 else if (L.isObject(data[sectiontype])) {
59 this.data[sectiontype] = Object.assign(data[sectiontype], {
60 '.anonymous': false,
61 '.name': sectiontype,
62 '.type': sectiontype
63 });
64
65 section_ids.push(sectiontype);
66 num_sections++;
67 }
68 }
69
70 section_ids.sort(L.bind(function(a, b) {
71 var indexA = (this.data[a]['.index'] != null) ? +this.data[a]['.index'] : 9999,
72 indexB = (this.data[b]['.index'] != null) ? +this.data[b]['.index'] : 9999;
73
74 if (indexA != indexB)
75 return (indexA - indexB);
76
77 return (a > b);
78 }, this));
79
80 for (var i = 0; i < section_ids.length; i++)
81 this.data[section_ids[i]]['.index'] = i;
82 },
83
84 load: function() {
85 return Promise.resolve(this.data);
86 },
87
88 save: function() {
89 return Promise.resolve();
90 },
91
92 get: function(config, section, option) {
93 if (section == null)
94 return null;
95
96 if (option == null)
97 return this.data[section];
98
99 if (!this.data.hasOwnProperty(section))
100 return null;
101
102 var value = this.data[section][option];
103
104 if (Array.isArray(value))
105 return value;
106
107 if (value != null)
108 return String(value);
109
110 return null;
111 },
112
113 set: function(config, section, option, value) {
114 if (section == null || option == null || option.charAt(0) == '.')
115 return;
116
117 if (!this.data.hasOwnProperty(section))
118 return;
119
120 if (value == null)
121 delete this.data[section][option];
122 else if (Array.isArray(value))
123 this.data[section][option] = value;
124 else
125 this.data[section][option] = String(value);
126 },
127
128 unset: function(config, section, option) {
129 return this.set(config, section, option, null);
130 },
131
132 sections: function(config, sectiontype, callback) {
133 var rv = [];
134
135 for (var section_id in this.data)
136 if (sectiontype == null || this.data[section_id]['.type'] == sectiontype)
137 rv.push(this.data[section_id]);
138
139 rv.sort(function(a, b) { return a['.index'] - b['.index'] });
140
141 if (typeof(callback) == 'function')
142 for (var i = 0; i < rv.length; i++)
143 callback.call(this, rv[i], rv[i]['.name']);
144
145 return rv;
146 },
147
148 add: function(config, sectiontype, sectionname) {
149 var num_sections_type = 0, next_index = 0;
150
151 for (var name in this.data) {
152 num_sections_type += (this.data[name]['.type'] == sectiontype);
153 next_index = Math.max(next_index, this.data[name]['.index']);
154 }
155
156 var section_id = sectionname || sectiontype + num_sections_type;
157
158 if (!this.data.hasOwnProperty(section_id)) {
159 this.data[section_id] = {
160 '.name': section_id,
161 '.type': sectiontype,
162 '.anonymous': (sectionname == null),
163 '.index': next_index + 1
164 };
165 }
166
167 return section_id;
168 },
169
170 remove: function(config, section) {
171 if (this.data.hasOwnProperty(section))
172 delete this.data[section];
173 },
174
175 resolveSID: function(config, section_id) {
176 return section_id;
177 },
178
179 move: function(config, section_id1, section_id2, after) {
180 return uci.move.apply(this, [config, section_id1, section_id2, after]);
181 }
182 });
183
184 /**
185 * @class AbstractElement
186 * @memberof LuCI.form
187 * @hideconstructor
188 * @classdesc
189 *
190 * The `AbstractElement` class serves as abstract base for the different form
191 * elements implemented by `LuCI.form`. It provides the common logic for
192 * loading and rendering values, for nesting elements and for defining common
193 * properties.
194 *
195 * This class is private and not directly accessible by user code.
196 */
197 var CBIAbstractElement = baseclass.extend(/** @lends LuCI.form.AbstractElement.prototype */ {
198 __init__: function(title, description) {
199 this.title = title || '';
200 this.description = description || '';
201 this.children = [];
202 },
203
204 /**
205 * Add another form element as children to this element.
206 *
207 * @param {AbstractElement} element
208 * The form element to add.
209 */
210 append: function(obj) {
211 this.children.push(obj);
212 },
213
214 /**
215 * Parse this elements form input.
216 *
217 * The `parse()` function recursively walks the form element tree and
218 * triggers input value reading and validation for each encountered element.
219 *
220 * Elements which are hidden due to unsatisified dependencies are skipped.
221 *
222 * @returns {Promise<void>}
223 * Returns a promise resolving once this element's value and the values of
224 * all child elements have been parsed. The returned promise is rejected
225 * if any parsed values are not meeting the validation constraints of their
226 * respective elements.
227 */
228 parse: function() {
229 var args = arguments;
230 this.children.forEach(function(child) {
231 child.parse.apply(child, args);
232 });
233 },
234
235 /**
236 * Render the form element.
237 *
238 * The `render()` function recursively walks the form element tree and
239 * renders the markup for each element, returning the assembled DOM tree.
240 *
241 * @abstract
242 * @returns {Node|Promise<Node>}
243 * May return a DOM Node or a promise resolving to a DOM node containing
244 * the form element's markup, including the markup of any child elements.
245 */
246 render: function() {
247 L.error('InternalError', 'Not implemented');
248 },
249
250 /** @private */
251 loadChildren: function(/* ... */) {
252 var tasks = [];
253
254 if (Array.isArray(this.children))
255 for (var i = 0; i < this.children.length; i++)
256 if (!this.children[i].disable)
257 tasks.push(this.children[i].load.apply(this.children[i], arguments));
258
259 return Promise.all(tasks);
260 },
261
262 /** @private */
263 renderChildren: function(tab_name /*, ... */) {
264 var tasks = [],
265 index = 0;
266
267 if (Array.isArray(this.children))
268 for (var i = 0; i < this.children.length; i++)
269 if (tab_name === null || this.children[i].tab === tab_name)
270 if (!this.children[i].disable)
271 tasks.push(this.children[i].render.apply(
272 this.children[i], this.varargs(arguments, 1, index++)));
273
274 return Promise.all(tasks);
275 },
276
277 /**
278 * Strip any HTML tags from the given input string.
279 *
280 * @param {string} input
281 * The input string to clean.
282 *
283 * @returns {string}
284 * The cleaned input string with HTML removes removed.
285 */
286 stripTags: function(s) {
287 if (typeof(s) == 'string' && !s.match(/[<>]/))
288 return s;
289
290 var x = dom.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 = document.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 if (a[0] < b[0])
3084 return descending ? 1 : -1;
3085
3086 if (a[0] > b[0])
3087 return descending ? -1 : 1;
3088
3089 return 0;
3090 });
3091
3092 window.requestAnimationFrame(L.bind(function() {
3093 var ref_sid, cur_sid;
3094
3095 for (var i = 0; i < list.length; i++) {
3096 list[i][1].childNodes[index].classList.add('flash');
3097 th.parentNode.parentNode.appendChild(list[i][1]);
3098
3099 cur_sid = list[i][1].getAttribute('data-sid');
3100
3101 if (ref_sid)
3102 this.map.data.move(config_name, cur_sid, ref_sid, true);
3103
3104 ref_sid = cur_sid;
3105 }
3106
3107 th.setAttribute('data-sort-direction', descending ? 'asc' : 'desc');
3108 }, this));
3109 },
3110
3111 /**
3112 * Add further options to the per-section instanced modal popup.
3113 *
3114 * This function may be overwritten by user code to perform additional
3115 * setup steps before displaying the more options modal which is useful to
3116 * e.g. query additional data or to inject further option elements.
3117 *
3118 * The default implementation of this function does nothing.
3119 *
3120 * @abstract
3121 * @param {LuCI.form.NamedSection} modalSection
3122 * The `NamedSection` instance about to be rendered in the modal popup.
3123 *
3124 * @param {string} section_id
3125 * The ID of the underlying UCI section the modal popup belongs to.
3126 *
3127 * @param {Event} ev
3128 * The DOM event emitted by clicking the `More…` button.
3129 *
3130 * @returns {*|Promise<*>}
3131 * Return values of this function are ignored but if a promise is returned,
3132 * it is run to completion before the rendering is continued, allowing
3133 * custom logic to perform asynchroneous work before the modal dialog
3134 * is shown.
3135 */
3136 addModalOptions: function(modalSection, section_id, ev) {
3137
3138 },
3139
3140 /** @private */
3141 getActiveModalMap: function() {
3142 return document.querySelector('body.modal-overlay-active > #modal_overlay > .modal.cbi-modal > .cbi-map:not(.hidden)');
3143 },
3144
3145 /** @private */
3146 getPreviousModalMap: function() {
3147 var mapNode = this.getActiveModalMap(),
3148 prevNode = mapNode ? mapNode.previousElementSibling : null;
3149
3150 return (prevNode && prevNode.matches('.cbi-map.hidden')) ? prevNode : null;
3151 },
3152
3153 /** @private */
3154 cloneOptions: function(src_section, dest_section) {
3155 for (var i = 0; i < src_section.children.length; i++) {
3156 var o1 = src_section.children[i];
3157
3158 if (o1.modalonly === false && src_section === this)
3159 continue;
3160
3161 var o2;
3162
3163 if (o1.subsection) {
3164 o2 = dest_section.option(o1.constructor, o1.option, o1.subsection.constructor, o1.subsection.sectiontype, o1.subsection.title, o1.subsection.description);
3165
3166 for (var k in o1.subsection) {
3167 if (!o1.subsection.hasOwnProperty(k))
3168 continue;
3169
3170 switch (k) {
3171 case 'map':
3172 case 'children':
3173 case 'parentoption':
3174 continue;
3175
3176 default:
3177 o2.subsection[k] = o1.subsection[k];
3178 }
3179 }
3180
3181 this.cloneOptions(o1.subsection, o2.subsection);
3182 }
3183 else {
3184 o2 = dest_section.option(o1.constructor, o1.option, o1.title, o1.description);
3185 }
3186
3187 for (var k in o1) {
3188 if (!o1.hasOwnProperty(k))
3189 continue;
3190
3191 switch (k) {
3192 case 'map':
3193 case 'section':
3194 case 'option':
3195 case 'title':
3196 case 'description':
3197 case 'subsection':
3198 continue;
3199
3200 default:
3201 o2[k] = o1[k];
3202 }
3203 }
3204 }
3205 },
3206
3207 /** @private */
3208 renderMoreOptionsModal: function(section_id, ev) {
3209 var parent = this.map,
3210 sref = parent.data.get(parent.config, section_id),
3211 mapNode = this.getActiveModalMap(),
3212 activeMap = mapNode ? dom.findClassInstance(mapNode) : null,
3213 stackedMap = activeMap && (activeMap.parent !== parent || activeMap.section !== section_id);
3214
3215 return (stackedMap ? activeMap.save(null, true) : Promise.resolve()).then(L.bind(function() {
3216 section_id = sref['.name'];
3217
3218 var m = new CBIMap(parent.config, null, null),
3219 s = m.section(CBINamedSection, section_id, this.sectiontype);
3220
3221 m.parent = parent;
3222 m.section = section_id;
3223 m.readonly = parent.readonly;
3224
3225 s.tabs = this.tabs;
3226 s.tab_names = this.tab_names;
3227
3228 this.cloneOptions(this, s);
3229
3230 return Promise.resolve(this.addModalOptions(s, section_id, ev)).then(function() {
3231 return m.render();
3232 }).then(L.bind(function(nodes) {
3233 var title = parent.title,
3234 name = null;
3235
3236 if ((name = this.titleFn('modaltitle', section_id)) != null)
3237 title = name;
3238 else if ((name = this.titleFn('sectiontitle', section_id)) != null)
3239 title = '%s - %s'.format(parent.title, name);
3240 else if (!this.anonymous)
3241 title = '%s - %s'.format(parent.title, section_id);
3242
3243 if (stackedMap) {
3244 mapNode.parentNode
3245 .querySelector('h4')
3246 .appendChild(E('span', title ? ' » ' + title : ''));
3247
3248 mapNode.parentNode
3249 .querySelector('div.right > button')
3250 .firstChild.data = _('Back');
3251
3252 mapNode.classList.add('hidden');
3253 mapNode.parentNode.insertBefore(nodes, mapNode.nextElementSibling);
3254
3255 nodes.classList.add('flash');
3256 }
3257 else {
3258 ui.showModal(title, [
3259 nodes,
3260 E('div', { 'class': 'right' }, [
3261 E('button', {
3262 'class': 'cbi-button',
3263 'click': ui.createHandlerFn(this, 'handleModalCancel', m)
3264 }, [ _('Dismiss') ]), ' ',
3265 E('button', {
3266 'class': 'cbi-button cbi-button-positive important',
3267 'click': ui.createHandlerFn(this, 'handleModalSave', m),
3268 'disabled': m.readonly || null
3269 }, [ _('Save') ])
3270 ])
3271 ], 'cbi-modal');
3272 }
3273 }, this));
3274 }, this)).catch(L.error);
3275 }
3276 });
3277
3278 /**
3279 * @class GridSection
3280 * @memberof LuCI.form
3281 * @augments LuCI.form.TableSection
3282 * @hideconstructor
3283 * @classdesc
3284 *
3285 * The `GridSection` class maps all or - if `filter()` is overwritten - a
3286 * subset of the underlying UCI configuration sections of a given type.
3287 *
3288 * A grid section functions similar to a {@link LuCI.form.TableSection} but
3289 * supports tabbing in the modal overlay. Option elements added with
3290 * [option()]{@link LuCI.form.GridSection#option} are shown in the table while
3291 * elements added with [taboption()]{@link LuCI.form.GridSection#taboption}
3292 * are displayed in the modal popup.
3293 *
3294 * Another important difference is that the table cells show a readonly text
3295 * preview of the corresponding option elements by default, unless the child
3296 * option element is explicitely made writable by setting the `editable`
3297 * property to `true`.
3298 *
3299 * Additionally, the grid section honours a `modalonly` property of child
3300 * option elements. Refer to the [AbstractValue]{@link LuCI.form.AbstractValue}
3301 * documentation for details.
3302 *
3303 * Layout wise, a grid section looks mostly identical to table sections.
3304 *
3305 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3306 * The configuration form this section is added to. It is automatically passed
3307 * by [section()]{@link LuCI.form.Map#section}.
3308 *
3309 * @param {string} section_type
3310 * The type of the UCI section to map.
3311 *
3312 * @param {string} [title]
3313 * The title caption of the form section element.
3314 *
3315 * @param {string} [description]
3316 * The description text of the form section element.
3317 */
3318 var CBIGridSection = CBITableSection.extend(/** @lends LuCI.form.GridSection.prototype */ {
3319 /**
3320 * Add an option tab to the section.
3321 *
3322 * The modal option elements of a grid section may be divided into multiple
3323 * tabs to provide a better overview to the user.
3324 *
3325 * Before options can be moved into a tab pane, the corresponding tab
3326 * has to be defined first, which is done by calling this function.
3327 *
3328 * Note that tabs are only effective in modal popups, options added with
3329 * `option()` will not be assigned to a specific tab and are rendered in
3330 * the table view only.
3331 *
3332 * @param {string} name
3333 * The name of the tab to register. It may be freely chosen and just serves
3334 * as an identifier to differentiate tabs.
3335 *
3336 * @param {string} title
3337 * The human readable caption of the tab.
3338 *
3339 * @param {string} [description]
3340 * An additional description text for the corresponding tab pane. It is
3341 * displayed as text paragraph below the tab but before the tab pane
3342 * contents. If omitted, no description will be rendered.
3343 *
3344 * @throws {Error}
3345 * Throws an exeption if a tab with the same `name` already exists.
3346 */
3347 tab: function(name, title, description) {
3348 CBIAbstractSection.prototype.tab.call(this, name, title, description);
3349 },
3350
3351 /** @private */
3352 handleAdd: function(ev, name) {
3353 var config_name = this.uciconfig || this.map.config,
3354 section_id = this.map.data.add(config_name, this.sectiontype, name),
3355 mapNode = this.getPreviousModalMap(),
3356 prevMap = mapNode ? dom.findClassInstance(mapNode) : this.map;
3357
3358 prevMap.addedSection = section_id;
3359
3360 return this.renderMoreOptionsModal(section_id);
3361 },
3362
3363 /** @private */
3364 handleModalSave: function(/* ... */) {
3365 var mapNode = this.getPreviousModalMap(),
3366 prevMap = mapNode ? dom.findClassInstance(mapNode) : this.map;
3367
3368 return this.super('handleModalSave', arguments);
3369 },
3370
3371 /** @private */
3372 handleModalCancel: function(modalMap, ev, isSaving) {
3373 var config_name = this.uciconfig || this.map.config,
3374 mapNode = this.getPreviousModalMap(),
3375 prevMap = mapNode ? dom.findClassInstance(mapNode) : this.map;
3376
3377 if (prevMap.addedSection != null && !isSaving)
3378 this.map.data.remove(config_name, prevMap.addedSection);
3379
3380 delete prevMap.addedSection;
3381
3382 return this.super('handleModalCancel', arguments);
3383 },
3384
3385 /** @private */
3386 renderUCISection: function(section_id) {
3387 return this.renderOptions(null, section_id);
3388 },
3389
3390 /** @private */
3391 renderChildren: function(tab_name, section_id, in_table) {
3392 var tasks = [], index = 0;
3393
3394 for (var i = 0, opt; (opt = this.children[i]) != null; i++) {
3395 if (opt.disable || opt.modalonly)
3396 continue;
3397
3398 if (opt.editable)
3399 tasks.push(opt.render(index++, section_id, in_table));
3400 else
3401 tasks.push(this.renderTextValue(section_id, opt));
3402 }
3403
3404 return Promise.all(tasks);
3405 },
3406
3407 /** @private */
3408 renderTextValue: function(section_id, opt) {
3409 var title = this.stripTags(opt.title).trim(),
3410 descr = this.stripTags(opt.description).trim(),
3411 value = opt.textvalue(section_id);
3412
3413 return E('td', {
3414 'class': 'td cbi-value-field',
3415 'data-title': (title != '') ? title : null,
3416 'data-description': (descr != '') ? descr : null,
3417 'data-name': opt.option,
3418 'data-widget': 'CBI.DummyValue'
3419 }, (value != null) ? value : E('em', _('none')));
3420 },
3421
3422 /** @private */
3423 renderHeaderRows: function(section_id) {
3424 return this.super('renderHeaderRows', [ NaN, true ]);
3425 },
3426
3427 /** @private */
3428 renderRowActions: function(section_id) {
3429 return this.super('renderRowActions', [ section_id, _('Edit') ]);
3430 },
3431
3432 /** @override */
3433 parse: function() {
3434 var section_ids = this.cfgsections(),
3435 tasks = [];
3436
3437 if (Array.isArray(this.children)) {
3438 for (var i = 0; i < section_ids.length; i++) {
3439 for (var j = 0; j < this.children.length; j++) {
3440 if (!this.children[j].editable || this.children[j].modalonly)
3441 continue;
3442
3443 tasks.push(this.children[j].parse(section_ids[i]));
3444 }
3445 }
3446 }
3447
3448 return Promise.all(tasks);
3449 }
3450 });
3451
3452 /**
3453 * @class NamedSection
3454 * @memberof LuCI.form
3455 * @augments LuCI.form.AbstractSection
3456 * @hideconstructor
3457 * @classdesc
3458 *
3459 * The `NamedSection` class maps exactly one UCI section instance which is
3460 * specified when constructing the class instance.
3461 *
3462 * Layout and functionality wise, a named section is essentially a
3463 * `TypedSection` which allows exactly one section node.
3464 *
3465 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3466 * The configuration form this section is added to. It is automatically passed
3467 * by [section()]{@link LuCI.form.Map#section}.
3468 *
3469 * @param {string} section_id
3470 * The name (ID) of the UCI section to map.
3471 *
3472 * @param {string} section_type
3473 * The type of the UCI section to map.
3474 *
3475 * @param {string} [title]
3476 * The title caption of the form section element.
3477 *
3478 * @param {string} [description]
3479 * The description text of the form section element.
3480 */
3481 var CBINamedSection = CBIAbstractSection.extend(/** @lends LuCI.form.NamedSection.prototype */ {
3482 __name__: 'CBI.NamedSection',
3483 __init__: function(map, section_id /*, ... */) {
3484 this.super('__init__', this.varargs(arguments, 2, map));
3485
3486 this.section = section_id;
3487 },
3488
3489 /**
3490 * If set to `true`, the user may remove or recreate the sole mapped
3491 * configuration instance from the form section widget, otherwise only a
3492 * preexisting section may be edited. The default is `false`.
3493 *
3494 * @name LuCI.form.NamedSection.prototype#addremove
3495 * @type boolean
3496 * @default false
3497 */
3498
3499 /**
3500 * Override the UCI configuration name to read the section IDs from. By
3501 * default, the configuration name is inherited from the parent `Map`.
3502 * By setting this property, a deviating configuration may be specified.
3503 * The default is `null`, means inheriting from the parent form.
3504 *
3505 * @name LuCI.form.NamedSection.prototype#uciconfig
3506 * @type string
3507 * @default null
3508 */
3509
3510 /**
3511 * The `NamedSection` class overwrites the generic `cfgsections()`
3512 * implementation to return a one-element array containing the mapped
3513 * section ID as sole element. User code should not normally change this.
3514 *
3515 * @returns {string[]}
3516 * Returns a one-element array containing the mapped section ID.
3517 */
3518 cfgsections: function() {
3519 return [ this.section ];
3520 },
3521
3522 /** @private */
3523 handleAdd: function(ev) {
3524 var section_id = this.section,
3525 config_name = this.uciconfig || this.map.config;
3526
3527 this.map.data.add(config_name, this.sectiontype, section_id);
3528 return this.map.save(null, true);
3529 },
3530
3531 /** @private */
3532 handleRemove: function(ev) {
3533 var section_id = this.section,
3534 config_name = this.uciconfig || this.map.config;
3535
3536 this.map.data.remove(config_name, section_id);
3537 return this.map.save(null, true);
3538 },
3539
3540 /** @private */
3541 renderContents: function(data) {
3542 var ucidata = data[0], nodes = data[1],
3543 section_id = this.section,
3544 config_name = this.uciconfig || this.map.config,
3545 sectionEl = E('div', {
3546 'id': ucidata ? null : 'cbi-%s-%s'.format(config_name, section_id),
3547 'class': 'cbi-section',
3548 'data-tab': (this.map.tabbed && !this.parentoption) ? this.sectiontype : null,
3549 'data-tab-title': (this.map.tabbed && !this.parentoption) ? this.title || this.sectiontype : null
3550 });
3551
3552 if (typeof(this.title) === 'string' && this.title !== '')
3553 sectionEl.appendChild(E('h3', {}, this.title));
3554
3555 if (typeof(this.description) === 'string' && this.description !== '')
3556 sectionEl.appendChild(E('div', { 'class': 'cbi-section-descr' }, this.description));
3557
3558 if (ucidata) {
3559 if (this.addremove) {
3560 sectionEl.appendChild(
3561 E('div', { 'class': 'cbi-section-remove right' },
3562 E('button', {
3563 'class': 'cbi-button',
3564 'click': ui.createHandlerFn(this, 'handleRemove'),
3565 'disabled': this.map.readonly || null
3566 }, [ _('Delete') ])));
3567 }
3568
3569 sectionEl.appendChild(E('div', {
3570 'id': 'cbi-%s-%s'.format(config_name, section_id),
3571 'class': this.tabs
3572 ? 'cbi-section-node cbi-section-node-tabbed' : 'cbi-section-node',
3573 'data-section-id': section_id
3574 }, nodes));
3575 }
3576 else if (this.addremove) {
3577 sectionEl.appendChild(
3578 E('button', {
3579 'class': 'cbi-button cbi-button-add',
3580 'click': ui.createHandlerFn(this, 'handleAdd'),
3581 'disabled': this.map.readonly || null
3582 }, [ _('Add') ]));
3583 }
3584
3585 dom.bindClassInstance(sectionEl, this);
3586
3587 return sectionEl;
3588 },
3589
3590 /** @override */
3591 render: function() {
3592 var config_name = this.uciconfig || this.map.config,
3593 section_id = this.section;
3594
3595 return Promise.all([
3596 this.map.data.get(config_name, section_id),
3597 this.renderUCISection(section_id)
3598 ]).then(this.renderContents.bind(this));
3599 }
3600 });
3601
3602 /**
3603 * @class Value
3604 * @memberof LuCI.form
3605 * @augments LuCI.form.AbstractValue
3606 * @hideconstructor
3607 * @classdesc
3608 *
3609 * The `Value` class represents a simple one-line form input using the
3610 * {@link LuCI.ui.Textfield} or - in case choices are added - the
3611 * {@link LuCI.ui.Combobox} class as underlying widget.
3612 *
3613 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3614 * The configuration form this section is added to. It is automatically passed
3615 * by [option()]{@link LuCI.form.AbstractSection#option} or
3616 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3617 * option to the section.
3618 *
3619 * @param {LuCI.form.AbstractSection} section
3620 * The configuration section this option is added to. It is automatically passed
3621 * by [option()]{@link LuCI.form.AbstractSection#option} or
3622 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3623 * option to the section.
3624 *
3625 * @param {string} option
3626 * The name of the UCI option to map.
3627 *
3628 * @param {string} [title]
3629 * The title caption of the option element.
3630 *
3631 * @param {string} [description]
3632 * The description text of the option element.
3633 */
3634 var CBIValue = CBIAbstractValue.extend(/** @lends LuCI.form.Value.prototype */ {
3635 __name__: 'CBI.Value',
3636
3637 /**
3638 * If set to `true`, the field is rendered as password input, otherwise
3639 * as plain text input.
3640 *
3641 * @name LuCI.form.Value.prototype#password
3642 * @type boolean
3643 * @default false
3644 */
3645
3646 /**
3647 * Set a placeholder string to use when the input field is empty.
3648 *
3649 * @name LuCI.form.Value.prototype#placeholder
3650 * @type string
3651 * @default null
3652 */
3653
3654 /**
3655 * Add a predefined choice to the form option. By adding one or more
3656 * choices, the plain text input field is turned into a combobox widget
3657 * which prompts the user to select a predefined choice, or to enter a
3658 * custom value.
3659 *
3660 * @param {string} key
3661 * The choice value to add.
3662 *
3663 * @param {Node|string} value
3664 * The caption for the choice value. May be a DOM node, a document fragment
3665 * or a plain text string. If omitted, the `key` value is used as caption.
3666 */
3667 value: function(key, val) {
3668 this.keylist = this.keylist || [];
3669 this.keylist.push(String(key));
3670
3671 this.vallist = this.vallist || [];
3672 this.vallist.push(dom.elem(val) ? val : String(val != null ? val : key));
3673 },
3674
3675 /** @override */
3676 render: function(option_index, section_id, in_table) {
3677 return Promise.resolve(this.cfgvalue(section_id))
3678 .then(this.renderWidget.bind(this, section_id, option_index))
3679 .then(this.renderFrame.bind(this, section_id, in_table, option_index));
3680 },
3681
3682 /** @private */
3683 handleValueChange: function(section_id, state, ev) {
3684 if (typeof(this.onchange) != 'function')
3685 return;
3686
3687 var value = this.formvalue(section_id);
3688
3689 if (isEqual(value, state.previousValue))
3690 return;
3691
3692 state.previousValue = value;
3693 this.onchange.call(this, ev, section_id, value);
3694 },
3695
3696 /** @private */
3697 renderFrame: function(section_id, in_table, option_index, nodes) {
3698 var config_name = this.uciconfig || this.section.uciconfig || this.map.config,
3699 depend_list = this.transformDepList(section_id),
3700 optionEl;
3701
3702 if (in_table) {
3703 var title = this.stripTags(this.title).trim();
3704 optionEl = E('td', {
3705 'class': 'td cbi-value-field',
3706 'data-title': (title != '') ? title : null,
3707 'data-description': this.stripTags(this.description).trim(),
3708 'data-name': this.option,
3709 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3710 }, E('div', {
3711 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3712 'data-index': option_index,
3713 'data-depends': depend_list,
3714 'data-field': this.cbid(section_id)
3715 }));
3716 }
3717 else {
3718 optionEl = E('div', {
3719 'class': 'cbi-value',
3720 'id': 'cbi-%s-%s-%s'.format(config_name, section_id, this.option),
3721 'data-index': option_index,
3722 'data-depends': depend_list,
3723 'data-field': this.cbid(section_id),
3724 'data-name': this.option,
3725 'data-widget': this.typename || (this.template ? this.template.replace(/^.+\//, '') : null) || this.__name__
3726 });
3727
3728 if (this.last_child)
3729 optionEl.classList.add('cbi-value-last');
3730
3731 if (typeof(this.title) === 'string' && this.title !== '') {
3732 optionEl.appendChild(E('label', {
3733 'class': 'cbi-value-title',
3734 'for': 'widget.cbid.%s.%s.%s'.format(config_name, section_id, this.option),
3735 'click': function(ev) {
3736 var node = ev.currentTarget,
3737 elem = node.nextElementSibling.querySelector('#' + node.getAttribute('for')) || node.nextElementSibling.querySelector('[data-widget-id="' + node.getAttribute('for') + '"]');
3738
3739 if (elem) {
3740 elem.click();
3741 elem.focus();
3742 }
3743 }
3744 },
3745 this.titleref ? E('a', {
3746 'class': 'cbi-title-ref',
3747 'href': this.titleref,
3748 'title': this.titledesc || _('Go to relevant configuration page')
3749 }, this.title) : this.title));
3750
3751 optionEl.appendChild(E('div', { 'class': 'cbi-value-field' }));
3752 }
3753 }
3754
3755 if (nodes)
3756 (optionEl.lastChild || optionEl).appendChild(nodes);
3757
3758 if (!in_table && typeof(this.description) === 'string' && this.description !== '')
3759 dom.append(optionEl.lastChild || optionEl,
3760 E('div', { 'class': 'cbi-value-description' }, this.description.trim()));
3761
3762 if (depend_list && depend_list.length)
3763 optionEl.classList.add('hidden');
3764
3765 optionEl.addEventListener('widget-change',
3766 L.bind(this.map.checkDepends, this.map));
3767
3768 optionEl.addEventListener('widget-change',
3769 L.bind(this.handleValueChange, this, section_id, {}));
3770
3771 dom.bindClassInstance(optionEl, this);
3772
3773 return optionEl;
3774 },
3775
3776 /** @private */
3777 renderWidget: function(section_id, option_index, cfgvalue) {
3778 var value = (cfgvalue != null) ? cfgvalue : this.default,
3779 choices = this.transformChoices(),
3780 widget;
3781
3782 if (choices) {
3783 var placeholder = (this.optional || this.rmempty)
3784 ? E('em', _('unspecified')) : _('-- Please choose --');
3785
3786 widget = new ui.Combobox(Array.isArray(value) ? value.join(' ') : value, choices, {
3787 id: this.cbid(section_id),
3788 sort: this.keylist,
3789 optional: this.optional || this.rmempty,
3790 datatype: this.datatype,
3791 select_placeholder: this.placeholder || placeholder,
3792 validate: L.bind(this.validate, this, section_id),
3793 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3794 });
3795 }
3796 else {
3797 widget = new ui.Textfield(Array.isArray(value) ? value.join(' ') : value, {
3798 id: this.cbid(section_id),
3799 password: this.password,
3800 optional: this.optional || this.rmempty,
3801 datatype: this.datatype,
3802 placeholder: this.placeholder,
3803 validate: L.bind(this.validate, this, section_id),
3804 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3805 });
3806 }
3807
3808 return widget.render();
3809 }
3810 });
3811
3812 /**
3813 * @class DynamicList
3814 * @memberof LuCI.form
3815 * @augments LuCI.form.Value
3816 * @hideconstructor
3817 * @classdesc
3818 *
3819 * The `DynamicList` class represents a multi value widget allowing the user
3820 * to enter multiple unique values, optionally selected from a set of
3821 * predefined choices. It builds upon the {@link LuCI.ui.DynamicList} widget.
3822 *
3823 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3824 * The configuration form this section is added to. It is automatically passed
3825 * by [option()]{@link LuCI.form.AbstractSection#option} or
3826 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3827 * option to the section.
3828 *
3829 * @param {LuCI.form.AbstractSection} section
3830 * The configuration section this option is added to. It is automatically passed
3831 * by [option()]{@link LuCI.form.AbstractSection#option} or
3832 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3833 * option to the section.
3834 *
3835 * @param {string} option
3836 * The name of the UCI option to map.
3837 *
3838 * @param {string} [title]
3839 * The title caption of the option element.
3840 *
3841 * @param {string} [description]
3842 * The description text of the option element.
3843 */
3844 var CBIDynamicList = CBIValue.extend(/** @lends LuCI.form.DynamicList.prototype */ {
3845 __name__: 'CBI.DynamicList',
3846
3847 /** @private */
3848 renderWidget: function(section_id, option_index, cfgvalue) {
3849 var value = (cfgvalue != null) ? cfgvalue : this.default,
3850 choices = this.transformChoices(),
3851 items = L.toArray(value);
3852
3853 var widget = new ui.DynamicList(items, choices, {
3854 id: this.cbid(section_id),
3855 sort: this.keylist,
3856 optional: this.optional || this.rmempty,
3857 datatype: this.datatype,
3858 placeholder: this.placeholder,
3859 validate: L.bind(this.validate, this, section_id),
3860 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3861 });
3862
3863 return widget.render();
3864 },
3865 });
3866
3867 /**
3868 * @class ListValue
3869 * @memberof LuCI.form
3870 * @augments LuCI.form.Value
3871 * @hideconstructor
3872 * @classdesc
3873 *
3874 * The `ListValue` class implements a simple static HTML select element
3875 * allowing the user to chose a single value from a set of predefined choices.
3876 * It builds upon the {@link LuCI.ui.Select} widget.
3877 *
3878 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3879 * The configuration form this section is added to. It is automatically passed
3880 * by [option()]{@link LuCI.form.AbstractSection#option} or
3881 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3882 * option to the section.
3883 *
3884 * @param {LuCI.form.AbstractSection} section
3885 * The configuration section this option is added to. It is automatically passed
3886 * by [option()]{@link LuCI.form.AbstractSection#option} or
3887 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3888 * option to the section.
3889 *
3890 * @param {string} option
3891 * The name of the UCI option to map.
3892 *
3893 * @param {string} [title]
3894 * The title caption of the option element.
3895 *
3896 * @param {string} [description]
3897 * The description text of the option element.
3898 */
3899 var CBIListValue = CBIValue.extend(/** @lends LuCI.form.ListValue.prototype */ {
3900 __name__: 'CBI.ListValue',
3901
3902 __init__: function() {
3903 this.super('__init__', arguments);
3904 this.widget = 'select';
3905 this.orientation = 'horizontal';
3906 this.deplist = [];
3907 },
3908
3909 /**
3910 * Set the size attribute of the underlying HTML select element.
3911 *
3912 * @name LuCI.form.ListValue.prototype#size
3913 * @type number
3914 * @default null
3915 */
3916
3917 /**
3918 * Set the type of the underlying form controls.
3919 *
3920 * May be one of `select` or `radio`. If set to `select`, an HTML
3921 * select element is rendered, otherwise a collection of `radio`
3922 * elements is used.
3923 *
3924 * @name LuCI.form.ListValue.prototype#widget
3925 * @type string
3926 * @default select
3927 */
3928
3929 /**
3930 * Set the orientation of the underlying radio or checkbox elements.
3931 *
3932 * May be one of `horizontal` or `vertical`. Only applies to non-select
3933 * widget types.
3934 *
3935 * @name LuCI.form.ListValue.prototype#orientation
3936 * @type string
3937 * @default horizontal
3938 */
3939
3940 /** @private */
3941 renderWidget: function(section_id, option_index, cfgvalue) {
3942 var choices = this.transformChoices();
3943 var widget = new ui.Select((cfgvalue != null) ? cfgvalue : this.default, choices, {
3944 id: this.cbid(section_id),
3945 size: this.size,
3946 sort: this.keylist,
3947 widget: this.widget,
3948 optional: this.optional,
3949 orientation: this.orientation,
3950 placeholder: this.placeholder,
3951 validate: L.bind(this.validate, this, section_id),
3952 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
3953 });
3954
3955 return widget.render();
3956 },
3957 });
3958
3959 /**
3960 * @class FlagValue
3961 * @memberof LuCI.form
3962 * @augments LuCI.form.Value
3963 * @hideconstructor
3964 * @classdesc
3965 *
3966 * The `FlagValue` element builds upon the {@link LuCI.ui.Checkbox} widget to
3967 * implement a simple checkbox element.
3968 *
3969 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
3970 * The configuration form this section is added to. It is automatically passed
3971 * by [option()]{@link LuCI.form.AbstractSection#option} or
3972 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3973 * option to the section.
3974 *
3975 * @param {LuCI.form.AbstractSection} section
3976 * The configuration section this option is added to. It is automatically passed
3977 * by [option()]{@link LuCI.form.AbstractSection#option} or
3978 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
3979 * option to the section.
3980 *
3981 * @param {string} option
3982 * The name of the UCI option to map.
3983 *
3984 * @param {string} [title]
3985 * The title caption of the option element.
3986 *
3987 * @param {string} [description]
3988 * The description text of the option element.
3989 */
3990 var CBIFlagValue = CBIValue.extend(/** @lends LuCI.form.FlagValue.prototype */ {
3991 __name__: 'CBI.FlagValue',
3992
3993 __init__: function() {
3994 this.super('__init__', arguments);
3995
3996 this.enabled = '1';
3997 this.disabled = '0';
3998 this.default = this.disabled;
3999 },
4000
4001 /**
4002 * Sets the input value to use for the checkbox checked state.
4003 *
4004 * @name LuCI.form.FlagValue.prototype#enabled
4005 * @type number
4006 * @default 1
4007 */
4008
4009 /**
4010 * Sets the input value to use for the checkbox unchecked state.
4011 *
4012 * @name LuCI.form.FlagValue.prototype#disabled
4013 * @type number
4014 * @default 0
4015 */
4016
4017 /**
4018 * Set a tooltip for the flag option.
4019 *
4020 * If set to a string, it will be used as-is as a tooltip.
4021 *
4022 * If set to a function, the function will be invoked and the return
4023 * value will be shown as a tooltip. If the return value of the function
4024 * is `null` no tooltip will be set.
4025 *
4026 * @name LuCI.form.TypedSection.prototype#tooltip
4027 * @type string|function
4028 * @default null
4029 */
4030
4031 /**
4032 * Set a tooltip icon.
4033 *
4034 * If set, this icon will be shown for the default one.
4035 * This could also be a png icon from the resources directory.
4036 *
4037 * @name LuCI.form.TypedSection.prototype#tooltipicon
4038 * @type string
4039 * @default 'ℹ️';
4040 */
4041
4042 /** @private */
4043 renderWidget: function(section_id, option_index, cfgvalue) {
4044 var tooltip = null;
4045
4046 if (typeof(this.tooltip) == 'function')
4047 tooltip = this.tooltip.apply(this, [section_id]);
4048 else if (typeof(this.tooltip) == 'string')
4049 tooltip = (arguments.length > 1) ? ''.format.apply(this.tooltip, this.varargs(arguments, 1)) : this.tooltip;
4050
4051 var widget = new ui.Checkbox((cfgvalue != null) ? cfgvalue : this.default, {
4052 id: this.cbid(section_id),
4053 value_enabled: this.enabled,
4054 value_disabled: this.disabled,
4055 validate: L.bind(this.validate, this, section_id),
4056 tooltip: tooltip,
4057 tooltipicon: this.tooltipicon,
4058 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4059 });
4060
4061 return widget.render();
4062 },
4063
4064 /**
4065 * Query the checked state of the underlying checkbox widget and return
4066 * either the `enabled` or the `disabled` property value, depending on
4067 * the checked state.
4068 *
4069 * @override
4070 */
4071 formvalue: function(section_id) {
4072 var elem = this.getUIElement(section_id),
4073 checked = elem ? elem.isChecked() : false;
4074 return checked ? this.enabled : this.disabled;
4075 },
4076
4077 /**
4078 * Query the checked state of the underlying checkbox widget and return
4079 * either a localized `Yes` or `No` string, depending on the checked state.
4080 *
4081 * @override
4082 */
4083 textvalue: function(section_id) {
4084 var cval = this.cfgvalue(section_id);
4085
4086 if (cval == null)
4087 cval = this.default;
4088
4089 return (cval == this.enabled) ? _('Yes') : _('No');
4090 },
4091
4092 /** @override */
4093 parse: function(section_id) {
4094 if (this.isActive(section_id)) {
4095 var fval = this.formvalue(section_id);
4096
4097 if (!this.isValid(section_id)) {
4098 var title = this.stripTags(this.title).trim();
4099 var error = this.getValidationError(section_id);
4100 return Promise.reject(new TypeError(
4101 _('Option "%s" contains an invalid input value.').format(title || this.option) + ' ' + error));
4102 }
4103
4104 if (fval == this.default && (this.optional || this.rmempty))
4105 return Promise.resolve(this.remove(section_id));
4106 else
4107 return Promise.resolve(this.write(section_id, fval));
4108 }
4109 else if (!this.retain) {
4110 return Promise.resolve(this.remove(section_id));
4111 }
4112 },
4113 });
4114
4115 /**
4116 * @class MultiValue
4117 * @memberof LuCI.form
4118 * @augments LuCI.form.DynamicList
4119 * @hideconstructor
4120 * @classdesc
4121 *
4122 * The `MultiValue` class is a modified variant of the `DynamicList` element
4123 * which leverages the {@link LuCI.ui.Dropdown} widget to implement a multi
4124 * select dropdown element.
4125 *
4126 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4127 * The configuration form this section is added to. It is automatically passed
4128 * by [option()]{@link LuCI.form.AbstractSection#option} or
4129 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4130 * option to the section.
4131 *
4132 * @param {LuCI.form.AbstractSection} section
4133 * The configuration section this option is added to. It is automatically passed
4134 * by [option()]{@link LuCI.form.AbstractSection#option} or
4135 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4136 * option to the section.
4137 *
4138 * @param {string} option
4139 * The name of the UCI option to map.
4140 *
4141 * @param {string} [title]
4142 * The title caption of the option element.
4143 *
4144 * @param {string} [description]
4145 * The description text of the option element.
4146 */
4147 var CBIMultiValue = CBIDynamicList.extend(/** @lends LuCI.form.MultiValue.prototype */ {
4148 __name__: 'CBI.MultiValue',
4149
4150 __init__: function() {
4151 this.super('__init__', arguments);
4152 this.placeholder = _('-- Please choose --');
4153 },
4154
4155 /**
4156 * Allows to specify the [display_items]{@link LuCI.ui.Dropdown.InitOptions}
4157 * property of the underlying dropdown widget. If omitted, the value of
4158 * the `size` property is used or `3` when `size` is unspecified as well.
4159 *
4160 * @name LuCI.form.MultiValue.prototype#display_size
4161 * @type number
4162 * @default null
4163 */
4164
4165 /**
4166 * Allows to specify the [dropdown_items]{@link LuCI.ui.Dropdown.InitOptions}
4167 * property of the underlying dropdown widget. If omitted, the value of
4168 * the `size` property is used or `-1` when `size` is unspecified as well.
4169 *
4170 * @name LuCI.form.MultiValue.prototype#dropdown_size
4171 * @type number
4172 * @default null
4173 */
4174
4175 /** @private */
4176 renderWidget: function(section_id, option_index, cfgvalue) {
4177 var value = (cfgvalue != null) ? cfgvalue : this.default,
4178 choices = this.transformChoices();
4179
4180 var widget = new ui.Dropdown(L.toArray(value), choices, {
4181 id: this.cbid(section_id),
4182 sort: this.keylist,
4183 multiple: true,
4184 optional: this.optional || this.rmempty,
4185 select_placeholder: this.placeholder,
4186 display_items: this.display_size || this.size || 3,
4187 dropdown_items: this.dropdown_size || this.size || -1,
4188 validate: L.bind(this.validate, this, section_id),
4189 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4190 });
4191
4192 return widget.render();
4193 },
4194 });
4195
4196 /**
4197 * @class TextValue
4198 * @memberof LuCI.form
4199 * @augments LuCI.form.Value
4200 * @hideconstructor
4201 * @classdesc
4202 *
4203 * The `TextValue` class implements a multi-line textarea input using
4204 * {@link LuCI.ui.Textarea}.
4205 *
4206 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4207 * The configuration form this section is added to. It is automatically passed
4208 * by [option()]{@link LuCI.form.AbstractSection#option} or
4209 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4210 * option to the section.
4211 *
4212 * @param {LuCI.form.AbstractSection} section
4213 * The configuration section this option is added to. It is automatically passed
4214 * by [option()]{@link LuCI.form.AbstractSection#option} or
4215 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4216 * option to the section.
4217 *
4218 * @param {string} option
4219 * The name of the UCI option to map.
4220 *
4221 * @param {string} [title]
4222 * The title caption of the option element.
4223 *
4224 * @param {string} [description]
4225 * The description text of the option element.
4226 */
4227 var CBITextValue = CBIValue.extend(/** @lends LuCI.form.TextValue.prototype */ {
4228 __name__: 'CBI.TextValue',
4229
4230 /** @ignore */
4231 value: null,
4232
4233 /**
4234 * Enforces the use of a monospace font for the textarea contents when set
4235 * to `true`.
4236 *
4237 * @name LuCI.form.TextValue.prototype#monospace
4238 * @type boolean
4239 * @default false
4240 */
4241
4242 /**
4243 * Allows to specify the [cols]{@link LuCI.ui.Textarea.InitOptions}
4244 * property of the underlying textarea widget.
4245 *
4246 * @name LuCI.form.TextValue.prototype#cols
4247 * @type number
4248 * @default null
4249 */
4250
4251 /**
4252 * Allows to specify the [rows]{@link LuCI.ui.Textarea.InitOptions}
4253 * property of the underlying textarea widget.
4254 *
4255 * @name LuCI.form.TextValue.prototype#rows
4256 * @type number
4257 * @default null
4258 */
4259
4260 /**
4261 * Allows to specify the [wrap]{@link LuCI.ui.Textarea.InitOptions}
4262 * property of the underlying textarea widget.
4263 *
4264 * @name LuCI.form.TextValue.prototype#wrap
4265 * @type number
4266 * @default null
4267 */
4268
4269 /** @private */
4270 renderWidget: function(section_id, option_index, cfgvalue) {
4271 var value = (cfgvalue != null) ? cfgvalue : this.default;
4272
4273 var widget = new ui.Textarea(value, {
4274 id: this.cbid(section_id),
4275 optional: this.optional || this.rmempty,
4276 placeholder: this.placeholder,
4277 monospace: this.monospace,
4278 cols: this.cols,
4279 rows: this.rows,
4280 wrap: this.wrap,
4281 validate: L.bind(this.validate, this, section_id),
4282 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4283 });
4284
4285 return widget.render();
4286 }
4287 });
4288
4289 /**
4290 * @class DummyValue
4291 * @memberof LuCI.form
4292 * @augments LuCI.form.Value
4293 * @hideconstructor
4294 * @classdesc
4295 *
4296 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4297 * renders the underlying UCI option or default value as readonly text.
4298 *
4299 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4300 * The configuration form this section is added to. It is automatically passed
4301 * by [option()]{@link LuCI.form.AbstractSection#option} or
4302 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4303 * option to the section.
4304 *
4305 * @param {LuCI.form.AbstractSection} section
4306 * The configuration section this option is added to. It is automatically passed
4307 * by [option()]{@link LuCI.form.AbstractSection#option} or
4308 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4309 * option to the section.
4310 *
4311 * @param {string} option
4312 * The name of the UCI option to map.
4313 *
4314 * @param {string} [title]
4315 * The title caption of the option element.
4316 *
4317 * @param {string} [description]
4318 * The description text of the option element.
4319 */
4320 var CBIDummyValue = CBIValue.extend(/** @lends LuCI.form.DummyValue.prototype */ {
4321 __name__: 'CBI.DummyValue',
4322
4323 /**
4324 * Set an URL which is opened when clicking on the dummy value text.
4325 *
4326 * By setting this property, the dummy value text is wrapped in an `<a>`
4327 * element with the property value used as `href` attribute.
4328 *
4329 * @name LuCI.form.DummyValue.prototype#href
4330 * @type string
4331 * @default null
4332 */
4333
4334 /**
4335 * Treat the UCI option value (or the `default` property value) as HTML.
4336 *
4337 * By default, the value text is HTML escaped before being rendered as
4338 * text. In some cases it may be needed to actually interpret and render
4339 * HTML contents as-is. When set to `true`, HTML escaping is disabled.
4340 *
4341 * @name LuCI.form.DummyValue.prototype#rawhtml
4342 * @type boolean
4343 * @default null
4344 */
4345
4346 /**
4347 * Render the UCI option value as hidden using the HTML display: none style property.
4348 *
4349 * By default, the value is displayed
4350 *
4351 * @name LuCI.form.DummyValue.prototype#hidden
4352 * @type boolean
4353 * @default null
4354 */
4355
4356 /** @private */
4357 renderWidget: function(section_id, option_index, cfgvalue) {
4358 var value = (cfgvalue != null) ? cfgvalue : this.default,
4359 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
4360 outputEl = E('div', { 'style': this.hidden ? 'display:none' : null });
4361
4362 if (this.href && !((this.readonly != null) ? this.readonly : this.map.readonly))
4363 outputEl.appendChild(E('a', { 'href': this.href }));
4364
4365 dom.append(outputEl.lastChild || outputEl,
4366 this.rawhtml ? value : [ value ]);
4367
4368 return E([
4369 outputEl,
4370 hiddenEl.render()
4371 ]);
4372 },
4373
4374 /** @override */
4375 remove: function() {},
4376
4377 /** @override */
4378 write: function() {}
4379 });
4380
4381 /**
4382 * @class ButtonValue
4383 * @memberof LuCI.form
4384 * @augments LuCI.form.Value
4385 * @hideconstructor
4386 * @classdesc
4387 *
4388 * The `DummyValue` element wraps an {@link LuCI.ui.Hiddenfield} widget and
4389 * renders the underlying UCI option or default value as readonly text.
4390 *
4391 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4392 * The configuration form this section is added to. It is automatically passed
4393 * by [option()]{@link LuCI.form.AbstractSection#option} or
4394 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4395 * option to the section.
4396 *
4397 * @param {LuCI.form.AbstractSection} section
4398 * The configuration section this option is added to. It is automatically passed
4399 * by [option()]{@link LuCI.form.AbstractSection#option} or
4400 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4401 * option to the section.
4402 *
4403 * @param {string} option
4404 * The name of the UCI option to map.
4405 *
4406 * @param {string} [title]
4407 * The title caption of the option element.
4408 *
4409 * @param {string} [description]
4410 * The description text of the option element.
4411 */
4412 var CBIButtonValue = CBIValue.extend(/** @lends LuCI.form.ButtonValue.prototype */ {
4413 __name__: 'CBI.ButtonValue',
4414
4415 /**
4416 * Override the rendered button caption.
4417 *
4418 * By default, the option title - which is passed as fourth argument to the
4419 * constructor - is used as caption for the button element. When setting
4420 * this property to a string, it is used as `String.format()` pattern with
4421 * the underlying UCI section name passed as first format argument. When
4422 * set to a function, it is invoked passing the section ID as sole argument
4423 * and the resulting return value is converted to a string before being
4424 * used as button caption.
4425 *
4426 * The default is `null`, means the option title is used as caption.
4427 *
4428 * @name LuCI.form.ButtonValue.prototype#inputtitle
4429 * @type string|function
4430 * @default null
4431 */
4432
4433 /**
4434 * Override the button style class.
4435 *
4436 * By setting this property, a specific `cbi-button-*` CSS class can be
4437 * selected to influence the style of the resulting button.
4438 *
4439 * Suitable values which are implemented by most themes are `positive`,
4440 * `negative` and `primary`.
4441 *
4442 * The default is `null`, means a neutral button styling is used.
4443 *
4444 * @name LuCI.form.ButtonValue.prototype#inputstyle
4445 * @type string
4446 * @default null
4447 */
4448
4449 /**
4450 * Override the button click action.
4451 *
4452 * By default, the underlying UCI option (or default property) value is
4453 * copied into a hidden field tied to the button element and the save
4454 * action is triggered on the parent form element.
4455 *
4456 * When this property is set to a function, it is invoked instead of
4457 * performing the default actions. The handler function will receive the
4458 * DOM click element as first and the underlying configuration section ID
4459 * as second argument.
4460 *
4461 * @name LuCI.form.ButtonValue.prototype#onclick
4462 * @type function
4463 * @default null
4464 */
4465
4466 /** @private */
4467 renderWidget: function(section_id, option_index, cfgvalue) {
4468 var value = (cfgvalue != null) ? cfgvalue : this.default,
4469 hiddenEl = new ui.Hiddenfield(value, { id: this.cbid(section_id) }),
4470 outputEl = E('div'),
4471 btn_title = this.titleFn('inputtitle', section_id) || this.titleFn('title', section_id);
4472
4473 if (value !== false)
4474 dom.content(outputEl, [
4475 E('button', {
4476 'class': 'cbi-button cbi-button-%s'.format(this.inputstyle || 'button'),
4477 'click': ui.createHandlerFn(this, function(section_id, ev) {
4478 if (this.onclick)
4479 return this.onclick(ev, section_id);
4480
4481 ev.currentTarget.parentNode.nextElementSibling.value = value;
4482 return this.map.save();
4483 }, section_id),
4484 'disabled': ((this.readonly != null) ? this.readonly : this.map.readonly) || null
4485 }, [ btn_title ])
4486 ]);
4487 else
4488 dom.content(outputEl, ' - ');
4489
4490 return E([
4491 outputEl,
4492 hiddenEl.render()
4493 ]);
4494 }
4495 });
4496
4497 /**
4498 * @class HiddenValue
4499 * @memberof LuCI.form
4500 * @augments LuCI.form.Value
4501 * @hideconstructor
4502 * @classdesc
4503 *
4504 * The `HiddenValue` element wraps an {@link LuCI.ui.Hiddenfield} widget.
4505 *
4506 * Hidden value widgets used to be necessary in legacy code which actually
4507 * submitted the underlying HTML form the server. With client side handling of
4508 * forms, there are more efficient ways to store hidden state data.
4509 *
4510 * Since this widget has no visible content, the title and description values
4511 * of this form element should be set to `null` as well to avoid a broken or
4512 * distorted form layout when rendering the option element.
4513 *
4514 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4515 * The configuration form this section is added to. It is automatically passed
4516 * by [option()]{@link LuCI.form.AbstractSection#option} or
4517 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4518 * option to the section.
4519 *
4520 * @param {LuCI.form.AbstractSection} section
4521 * The configuration section this option is added to. It is automatically passed
4522 * by [option()]{@link LuCI.form.AbstractSection#option} or
4523 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4524 * option to the section.
4525 *
4526 * @param {string} option
4527 * The name of the UCI option to map.
4528 *
4529 * @param {string} [title]
4530 * The title caption of the option element.
4531 *
4532 * @param {string} [description]
4533 * The description text of the option element.
4534 */
4535 var CBIHiddenValue = CBIValue.extend(/** @lends LuCI.form.HiddenValue.prototype */ {
4536 __name__: 'CBI.HiddenValue',
4537
4538 /** @private */
4539 renderWidget: function(section_id, option_index, cfgvalue) {
4540 var widget = new ui.Hiddenfield((cfgvalue != null) ? cfgvalue : this.default, {
4541 id: this.cbid(section_id)
4542 });
4543
4544 return widget.render();
4545 }
4546 });
4547
4548 /**
4549 * @class FileUpload
4550 * @memberof LuCI.form
4551 * @augments LuCI.form.Value
4552 * @hideconstructor
4553 * @classdesc
4554 *
4555 * The `FileUpload` element wraps an {@link LuCI.ui.FileUpload} widget and
4556 * offers the ability to browse, upload and select remote files.
4557 *
4558 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4559 * The configuration form this section is added to. It is automatically passed
4560 * by [option()]{@link LuCI.form.AbstractSection#option} or
4561 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4562 * option to the section.
4563 *
4564 * @param {LuCI.form.AbstractSection} section
4565 * The configuration section this option is added to. It is automatically passed
4566 * by [option()]{@link LuCI.form.AbstractSection#option} or
4567 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4568 * option to the section.
4569 *
4570 * @param {string} option
4571 * The name of the UCI option to map.
4572 *
4573 * @param {string} [title]
4574 * The title caption of the option element.
4575 *
4576 * @param {string} [description]
4577 * The description text of the option element.
4578 */
4579 var CBIFileUpload = CBIValue.extend(/** @lends LuCI.form.FileUpload.prototype */ {
4580 __name__: 'CBI.FileSelect',
4581
4582 __init__: function(/* ... */) {
4583 this.super('__init__', arguments);
4584
4585 this.show_hidden = false;
4586 this.enable_upload = true;
4587 this.enable_remove = true;
4588 this.root_directory = '/etc/luci-uploads';
4589 },
4590
4591 /**
4592 * Toggle display of hidden files.
4593 *
4594 * Display hidden files when rendering the remote directory listing.
4595 * Note that this is merely a cosmetic feature, hidden files are always
4596 * included in received remote file listings.
4597 *
4598 * The default is `false`, means hidden files are not displayed.
4599 *
4600 * @name LuCI.form.FileUpload.prototype#show_hidden
4601 * @type boolean
4602 * @default false
4603 */
4604
4605 /**
4606 * Toggle file upload functionality.
4607 *
4608 * When set to `true`, the underlying widget provides a button which lets
4609 * the user select and upload local files to the remote system.
4610 * Note that this is merely a cosmetic feature, remote upload access is
4611 * controlled by the session ACL rules.
4612 *
4613 * The default is `true`, means file upload functionality is displayed.
4614 *
4615 * @name LuCI.form.FileUpload.prototype#enable_upload
4616 * @type boolean
4617 * @default true
4618 */
4619
4620 /**
4621 * Toggle remote file delete functionality.
4622 *
4623 * When set to `true`, the underlying widget provides a buttons which let
4624 * the user delete files from remote directories. Note that this is merely
4625 * a cosmetic feature, remote delete permissions are controlled by the
4626 * session ACL rules.
4627 *
4628 * The default is `true`, means file removal buttons are displayed.
4629 *
4630 * @name LuCI.form.FileUpload.prototype#enable_remove
4631 * @type boolean
4632 * @default true
4633 */
4634
4635 /**
4636 * Specify the root directory for file browsing.
4637 *
4638 * This property defines the topmost directory the file browser widget may
4639 * navigate to, the UI will not allow browsing directories outside this
4640 * prefix. Note that this is merely a cosmetic feature, remote file access
4641 * and directory listing permissions are controlled by the session ACL
4642 * rules.
4643 *
4644 * The default is `/etc/luci-uploads`.
4645 *
4646 * @name LuCI.form.FileUpload.prototype#root_directory
4647 * @type string
4648 * @default /etc/luci-uploads
4649 */
4650
4651 /** @private */
4652 renderWidget: function(section_id, option_index, cfgvalue) {
4653 var browserEl = new ui.FileUpload((cfgvalue != null) ? cfgvalue : this.default, {
4654 id: this.cbid(section_id),
4655 name: this.cbid(section_id),
4656 show_hidden: this.show_hidden,
4657 enable_upload: this.enable_upload,
4658 enable_remove: this.enable_remove,
4659 root_directory: this.root_directory,
4660 disabled: (this.readonly != null) ? this.readonly : this.map.readonly
4661 });
4662
4663 return browserEl.render();
4664 }
4665 });
4666
4667 /**
4668 * @class SectionValue
4669 * @memberof LuCI.form
4670 * @augments LuCI.form.Value
4671 * @hideconstructor
4672 * @classdesc
4673 *
4674 * The `SectionValue` widget embeds a form section element within an option
4675 * element container, allowing to nest form sections into other sections.
4676 *
4677 * @param {LuCI.form.Map|LuCI.form.JSONMap} form
4678 * The configuration form this section is added to. It is automatically passed
4679 * by [option()]{@link LuCI.form.AbstractSection#option} or
4680 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4681 * option to the section.
4682 *
4683 * @param {LuCI.form.AbstractSection} section
4684 * The configuration section this option is added to. It is automatically passed
4685 * by [option()]{@link LuCI.form.AbstractSection#option} or
4686 * [taboption()]{@link LuCI.form.AbstractSection#taboption} when adding the
4687 * option to the section.
4688 *
4689 * @param {string} option
4690 * The internal name of the option element holding the section. Since a section
4691 * container element does not read or write any configuration itself, the name
4692 * is only used internally and does not need to relate to any underlying UCI
4693 * option name.
4694 *
4695 * @param {LuCI.form.AbstractSection} subsection_class
4696 * The class to use for instantiating the nested section element. Note that
4697 * the class value itself is expected here, not a class instance obtained by
4698 * calling `new`. The given class argument must be a subclass of the
4699 * `AbstractSection` class.
4700 *
4701 * @param {...*} [class_args]
4702 * All further arguments are passed as-is to the subclass constructor. Refer
4703 * to the corresponding class constructor documentations for details.
4704 */
4705 var CBISectionValue = CBIValue.extend(/** @lends LuCI.form.SectionValue.prototype */ {
4706 __name__: 'CBI.ContainerValue',
4707 __init__: function(map, section, option, cbiClass /*, ... */) {
4708 this.super('__init__', [map, section, option]);
4709
4710 if (!CBIAbstractSection.isSubclass(cbiClass))
4711 throw 'Sub section must be a descendent of CBIAbstractSection';
4712
4713 this.subsection = cbiClass.instantiate(this.varargs(arguments, 4, this.map));
4714 this.subsection.parentoption = this;
4715 },
4716
4717 /**
4718 * Access the embedded section instance.
4719 *
4720 * This property holds a reference to the instantiated nested section.
4721 *
4722 * @name LuCI.form.SectionValue.prototype#subsection
4723 * @type LuCI.form.AbstractSection
4724 * @readonly
4725 */
4726
4727 /** @override */
4728 load: function(section_id) {
4729 return this.subsection.load(section_id);
4730 },
4731
4732 /** @override */
4733 parse: function(section_id) {
4734 return this.subsection.parse(section_id);
4735 },
4736
4737 /** @private */
4738 renderWidget: function(section_id, option_index, cfgvalue) {
4739 return this.subsection.render(section_id);
4740 },
4741
4742 /** @private */
4743 checkDepends: function(section_id) {
4744 this.subsection.checkDepends(section_id);
4745 return CBIValue.prototype.checkDepends.apply(this, [ section_id ]);
4746 },
4747
4748 /**
4749 * Since the section container is not rendering an own widget,
4750 * its `value()` implementation is a no-op.
4751 *
4752 * @override
4753 */
4754 value: function() {},
4755
4756 /**
4757 * Since the section container is not tied to any UCI configuration,
4758 * its `write()` implementation is a no-op.
4759 *
4760 * @override
4761 */
4762 write: function() {},
4763
4764 /**
4765 * Since the section container is not tied to any UCI configuration,
4766 * its `remove()` implementation is a no-op.
4767 *
4768 * @override
4769 */
4770 remove: function() {},
4771
4772 /**
4773 * Since the section container is not tied to any UCI configuration,
4774 * its `cfgvalue()` implementation will always return `null`.
4775 *
4776 * @override
4777 * @returns {null}
4778 */
4779 cfgvalue: function() { return null },
4780
4781 /**
4782 * Since the section container is not tied to any UCI configuration,
4783 * its `formvalue()` implementation will always return `null`.
4784 *
4785 * @override
4786 * @returns {null}
4787 */
4788 formvalue: function() { return null }
4789 });
4790
4791 /**
4792 * @class form
4793 * @memberof LuCI
4794 * @hideconstructor
4795 * @classdesc
4796 *
4797 * The LuCI form class provides high level abstractions for creating creating
4798 * UCI- or JSON backed configurations forms.
4799 *
4800 * To import the class in views, use `'require form'`, to import it in
4801 * external JavaScript, use `L.require("form").then(...)`.
4802 *
4803 * A typical form is created by first constructing a
4804 * {@link LuCI.form.Map} or {@link LuCI.form.JSONMap} instance using `new` and
4805 * by subsequently adding sections and options to it. Finally
4806 * [render()]{@link LuCI.form.Map#render} is invoked on the instance to
4807 * assemble the HTML markup and insert it into the DOM.
4808 *
4809 * Example:
4810 *
4811 * <pre>
4812 * 'use strict';
4813 * 'require form';
4814 *
4815 * var m, s, o;
4816 *
4817 * m = new form.Map('example', 'Example form',
4818 * 'This is an example form mapping the contents of /etc/config/example');
4819 *
4820 * s = m.section(form.NamedSection, 'first_section', 'example', 'The first section',
4821 * 'This sections maps "config example first_section" of /etc/config/example');
4822 *
4823 * o = s.option(form.Flag, 'some_bool', 'A checkbox option');
4824 *
4825 * o = s.option(form.ListValue, 'some_choice', 'A select element');
4826 * o.value('choice1', 'The first choice');
4827 * o.value('choice2', 'The second choice');
4828 *
4829 * m.render().then(function(node) {
4830 * document.body.appendChild(node);
4831 * });
4832 * </pre>
4833 */
4834 return baseclass.extend(/** @lends LuCI.form.prototype */ {
4835 Map: CBIMap,
4836 JSONMap: CBIJSONMap,
4837 AbstractSection: CBIAbstractSection,
4838 AbstractValue: CBIAbstractValue,
4839
4840 TypedSection: CBITypedSection,
4841 TableSection: CBITableSection,
4842 GridSection: CBIGridSection,
4843 NamedSection: CBINamedSection,
4844
4845 Value: CBIValue,
4846 DynamicList: CBIDynamicList,
4847 ListValue: CBIListValue,
4848 Flag: CBIFlagValue,
4849 MultiValue: CBIMultiValue,
4850 TextValue: CBITextValue,
4851 DummyValue: CBIDummyValue,
4852 Button: CBIButtonValue,
4853 HiddenValue: CBIHiddenValue,
4854 FileUpload: CBIFileUpload,
4855 SectionValue: CBISectionValue
4856 });