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