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