163edb8eaedbb89e5d9bd596e8d41986348cb82b
10 tooltipTimeout
= null;
13 * @class AbstractElement
18 * The `AbstractElement` class serves as abstract base for the different widgets
19 * implemented by `LuCI.ui`. It provides the common logic for getting and
20 * setting values, for checking the validity state and for wiring up required
23 * UI widget instances are usually not supposed to be created by view code
24 * directly, instead they're implicitely created by `LuCI.form` when
25 * instantiating CBI forms.
27 * This class is automatically instantiated as part of `LuCI.ui`. To use it
28 * in views, use `'require ui'` and refer to `ui.AbstractElement`. To import
29 * it in external JavaScript, use `L.require("ui").then(...)` and access the
30 * `AbstractElement` property of the class instance value.
32 var UIElement
= L
.Class
.extend(/** @lends LuCI.ui.AbstractElement.prototype */ {
34 * @typedef {Object} InitOptions
35 * @memberof LuCI.ui.AbstractElement
37 * @property {string} [id]
38 * Specifies the widget ID to use. It will be used as HTML `id` attribute
39 * on the toplevel widget DOM node.
41 * @property {string} [name]
42 * Specifies the widget name which is set as HTML `name` attribute on the
43 * corresponding `<input>` element.
45 * @property {boolean} [optional=true]
46 * Specifies whether the input field allows empty values.
48 * @property {string} [datatype=string]
49 * An expression describing the input data validation constraints.
50 * It defaults to `string` which will allow any value.
51 * See{@link LuCI.validation} for details on the expression format.
53 * @property {function} [validator]
54 * Specifies a custom validator function which is invoked after the
55 * standard validation constraints are checked. The function should return
56 * `true` to accept the given input value. Any other return value type is
57 * converted to a string and treated as validation error message.
61 * Read the current value of the input widget.
64 * @memberof LuCI.ui.AbstractElement
65 * @returns {string|string[]|null}
66 * The current value of the input element. For simple inputs like text
67 * fields or selects, the return value type will be a - possibly empty -
68 * string. Complex widgets such as `DynamicList` instances may result in
69 * an array of strings or `null` for unset values.
71 getValue: function() {
72 if (L
.dom
.matches(this.node
, 'select') || L
.dom
.matches(this.node
, 'input'))
73 return this.node
.value
;
79 * Set the current value of the input widget.
82 * @memberof LuCI.ui.AbstractElement
83 * @param {string|string[]|null} value
84 * The value to set the input element to. For simple inputs like text
85 * fields or selects, the value should be a - possibly empty - string.
86 * Complex widgets such as `DynamicList` instances may accept string array
89 setValue: function(value
) {
90 if (L
.dom
.matches(this.node
, 'select') || L
.dom
.matches(this.node
, 'input'))
91 this.node
.value
= value
;
95 * Check whether the current input value is valid.
98 * @memberof LuCI.ui.AbstractElement
100 * Returns `true` if the current input value is valid or `false` if it does
101 * not meet the validation constraints.
103 isValid: function() {
104 return (this.validState
!== false);
108 * Force validation of the current input value.
110 * Usually input validation is automatically triggered by various DOM events
111 * bound to the input widget. In some cases it is required though to manually
112 * trigger validation runs, e.g. when programmatically altering values.
115 * @memberof LuCI.ui.AbstractElement
117 triggerValidation: function() {
118 if (typeof(this.vfunc
) != 'function')
121 var wasValid
= this.isValid();
125 return (wasValid
!= this.isValid());
129 * Dispatch a custom (synthetic) event in response to received events.
131 * Sets up event handlers on the given target DOM node for the given event
132 * names that dispatch a custom event of the given type to the widget root
135 * The primary purpose of this function is to set up a series of custom
136 * uniform standard events such as `widget-update`, `validation-success`,
137 * `validation-failure` etc. which are triggered by various different
138 * widget specific native DOM events.
141 * @memberof LuCI.ui.AbstractElement
142 * @param {Node} targetNode
143 * Specifies the DOM node on which the native event listeners should be
146 * @param {string} synevent
147 * The name of the custom event to dispatch to the widget root DOM node.
149 * @param {string[]} events
150 * The native DOM events for which event handlers should be registered.
152 registerEvents: function(targetNode
, synevent
, events
) {
153 var dispatchFn
= L
.bind(function(ev
) {
154 this.node
.dispatchEvent(new CustomEvent(synevent
, { bubbles
: true }));
157 for (var i
= 0; i
< events
.length
; i
++)
158 targetNode
.addEventListener(events
[i
], dispatchFn
);
162 * Setup listeners for native DOM events that may update the widget value.
164 * Sets up event handlers on the given target DOM node for the given event
165 * names which may cause the input value to update, such as `keyup` or
166 * `onclick` events. In contrast to change events, such update events will
167 * trigger input value validation.
170 * @memberof LuCI.ui.AbstractElement
171 * @param {Node} targetNode
172 * Specifies the DOM node on which the event listeners should be registered.
174 * @param {...string} events
175 * The DOM events for which event handlers should be registered.
177 setUpdateEvents: function(targetNode
/*, ... */) {
178 var datatype
= this.options
.datatype
,
179 optional
= this.options
.hasOwnProperty('optional') ? this.options
.optional
: true,
180 validate
= this.options
.validate
,
181 events
= this.varargs(arguments
, 1);
183 this.registerEvents(targetNode
, 'widget-update', events
);
185 if (!datatype
&& !validate
)
188 this.vfunc
= L
.ui
.addValidator
.apply(L
.ui
, [
189 targetNode
, datatype
|| 'string',
193 this.node
.addEventListener('validation-success', L
.bind(function(ev
) {
194 this.validState
= true;
197 this.node
.addEventListener('validation-failure', L
.bind(function(ev
) {
198 this.validState
= false;
203 * Setup listeners for native DOM events that may change the widget value.
205 * Sets up event handlers on the given target DOM node for the given event
206 * names which may cause the input value to change completely, such as
207 * `change` events in a select menu. In contrast to update events, such
208 * change events will not trigger input value validation but they may cause
209 * field dependencies to get re-evaluated and will mark the input widget
213 * @memberof LuCI.ui.AbstractElement
214 * @param {Node} targetNode
215 * Specifies the DOM node on which the event listeners should be registered.
217 * @param {...string} events
218 * The DOM events for which event handlers should be registered.
220 setChangeEvents: function(targetNode
/*, ... */) {
221 var tag_changed
= L
.bind(function(ev
) { this.setAttribute('data-changed', true) }, this.node
);
223 for (var i
= 1; i
< arguments
.length
; i
++)
224 targetNode
.addEventListener(arguments
[i
], tag_changed
);
226 this.registerEvents(targetNode
, 'widget-change', this.varargs(arguments
, 1));
230 * Render the widget, setup event listeners and return resulting markup.
233 * @memberof LuCI.ui.AbstractElement
236 * Returns a DOM Node or DocumentFragment containing the rendered
239 render: function() {}
243 * Instantiate a text input widget.
245 * @constructor Textfield
247 * @augments LuCI.ui.AbstractElement
251 * The `Textfield` class implements a standard single line text input field.
253 * UI widget instances are usually not supposed to be created by view code
254 * directly, instead they're implicitely created by `LuCI.form` when
255 * instantiating CBI forms.
257 * This class is automatically instantiated as part of `LuCI.ui`. To use it
258 * in views, use `'require ui'` and refer to `ui.Textfield`. To import it in
259 * external JavaScript, use `L.require("ui").then(...)` and access the
260 * `Textfield` property of the class instance value.
262 * @param {string} [value=null]
263 * The initial input value.
265 * @param {LuCI.ui.Textfield.InitOptions} [options]
266 * Object describing the widget specific options to initialize the input.
268 var UITextfield
= UIElement
.extend(/** @lends LuCI.ui.Textfield.prototype */ {
270 * In addition to the [AbstractElement.InitOptions]{@link LuCI.ui.AbstractElement.InitOptions}
271 * the following properties are recognized:
273 * @typedef {LuCI.ui.AbstractElement.InitOptions} InitOptions
274 * @memberof LuCI.ui.Textfield
276 * @property {boolean} [password=false]
277 * Specifies whether the input should be rendered as concealed password field.
279 * @property {boolean} [readonly=false]
280 * Specifies whether the input widget should be rendered readonly.
282 * @property {number} [maxlength]
283 * Specifies the HTML `maxlength` attribute to set on the corresponding
284 * `<input>` element. Note that this a legacy property that exists for
285 * compatibility reasons. It is usually better to `maxlength(N)` validation
288 * @property {string} [placeholder]
289 * Specifies the HTML `placeholder` attribute which is displayed when the
290 * corresponding `<input>` element is empty.
292 __init__: function(value
, options
) {
294 this.options
= Object
.assign({
302 var frameEl
= E('div', { 'id': this.options
.id
});
304 if (this.options
.password
) {
305 frameEl
.classList
.add('nowrap');
306 frameEl
.appendChild(E('input', {
308 'style': 'position:absolute; left:-100000px',
311 'name': this.options
.name
? 'password.%s'.format(this.options
.name
) : null
315 frameEl
.appendChild(E('input', {
316 'id': this.options
.id
? 'widget.' + this.options
.id
: null,
317 'name': this.options
.name
,
318 'type': this.options
.password
? 'password' : 'text',
319 'class': this.options
.password
? 'cbi-input-password' : 'cbi-input-text',
320 'readonly': this.options
.readonly
? '' : null,
321 'maxlength': this.options
.maxlength
,
322 'placeholder': this.options
.placeholder
,
326 if (this.options
.password
)
327 frameEl
.appendChild(E('button', {
328 'class': 'cbi-button cbi-button-neutral',
329 'title': _('Reveal/hide password'),
330 'aria-label': _('Reveal/hide password'),
331 'click': function(ev
) {
332 var e
= this.previousElementSibling
;
333 e
.type
= (e
.type
=== 'password') ? 'text' : 'password';
338 return this.bind(frameEl
);
342 bind: function(frameEl
) {
343 var inputEl
= frameEl
.childNodes
[+!!this.options
.password
];
347 this.setUpdateEvents(inputEl
, 'keyup', 'blur');
348 this.setChangeEvents(inputEl
, 'change');
350 L
.dom
.bindClassInstance(frameEl
, this);
356 getValue: function() {
357 var inputEl
= this.node
.childNodes
[+!!this.options
.password
];
358 return inputEl
.value
;
362 setValue: function(value
) {
363 var inputEl
= this.node
.childNodes
[+!!this.options
.password
];
364 inputEl
.value
= value
;
369 * Instantiate a textarea widget.
371 * @constructor Textarea
373 * @augments LuCI.ui.AbstractElement
377 * The `Textarea` class implements a multiline text area input field.
379 * UI widget instances are usually not supposed to be created by view code
380 * directly, instead they're implicitely created by `LuCI.form` when
381 * instantiating CBI forms.
383 * This class is automatically instantiated as part of `LuCI.ui`. To use it
384 * in views, use `'require ui'` and refer to `ui.Textarea`. To import it in
385 * external JavaScript, use `L.require("ui").then(...)` and access the
386 * `Textarea` property of the class instance value.
388 * @param {string} [value=null]
389 * The initial input value.
391 * @param {LuCI.ui.Textarea.InitOptions} [options]
392 * Object describing the widget specific options to initialize the input.
394 var UITextarea
= UIElement
.extend(/** @lends LuCI.ui.Textarea.prototype */ {
396 * In addition to the [AbstractElement.InitOptions]{@link LuCI.ui.AbstractElement.InitOptions}
397 * the following properties are recognized:
399 * @typedef {LuCI.ui.AbstractElement.InitOptions} InitOptions
400 * @memberof LuCI.ui.Textarea
402 * @property {boolean} [readonly=false]
403 * Specifies whether the input widget should be rendered readonly.
405 * @property {string} [placeholder]
406 * Specifies the HTML `placeholder` attribute which is displayed when the
407 * corresponding `<textarea>` element is empty.
409 * @property {boolean} [monospace=false]
410 * Specifies whether a monospace font should be forced for the textarea
413 * @property {number} [cols]
414 * Specifies the HTML `cols` attribute to set on the corresponding
415 * `<textarea>` element.
417 * @property {number} [rows]
418 * Specifies the HTML `rows` attribute to set on the corresponding
419 * `<textarea>` element.
421 * @property {boolean} [wrap=false]
422 * Specifies whether the HTML `wrap` attribute should be set.
424 __init__: function(value
, options
) {
426 this.options
= Object
.assign({
436 var frameEl
= E('div', { 'id': this.options
.id
}),
437 value
= (this.value
!= null) ? String(this.value
) : '';
439 frameEl
.appendChild(E('textarea', {
440 'id': this.options
.id
? 'widget.' + this.options
.id
: null,
441 'name': this.options
.name
,
442 'class': 'cbi-input-textarea',
443 'readonly': this.options
.readonly
? '' : null,
444 'placeholder': this.options
.placeholder
,
445 'style': !this.options
.cols
? 'width:100%' : null,
446 'cols': this.options
.cols
,
447 'rows': this.options
.rows
,
448 'wrap': this.options
.wrap
? '' : null
451 if (this.options
.monospace
)
452 frameEl
.firstElementChild
.style
.fontFamily
= 'monospace';
454 return this.bind(frameEl
);
458 bind: function(frameEl
) {
459 var inputEl
= frameEl
.firstElementChild
;
463 this.setUpdateEvents(inputEl
, 'keyup', 'blur');
464 this.setChangeEvents(inputEl
, 'change');
466 L
.dom
.bindClassInstance(frameEl
, this);
472 getValue: function() {
473 return this.node
.firstElementChild
.value
;
477 setValue: function(value
) {
478 this.node
.firstElementChild
.value
= value
;
483 * Instantiate a checkbox widget.
485 * @constructor Checkbox
487 * @augments LuCI.ui.AbstractElement
491 * The `Checkbox` class implements a simple checkbox input field.
493 * UI widget instances are usually not supposed to be created by view code
494 * directly, instead they're implicitely created by `LuCI.form` when
495 * instantiating CBI forms.
497 * This class is automatically instantiated as part of `LuCI.ui`. To use it
498 * in views, use `'require ui'` and refer to `ui.Checkbox`. To import it in
499 * external JavaScript, use `L.require("ui").then(...)` and access the
500 * `Checkbox` property of the class instance value.
502 * @param {string} [value=null]
503 * The initial input value.
505 * @param {LuCI.ui.Checkbox.InitOptions} [options]
506 * Object describing the widget specific options to initialize the input.
508 var UICheckbox
= UIElement
.extend(/** @lends LuCI.ui.Checkbox.prototype */ {
510 * In addition to the [AbstractElement.InitOptions]{@link LuCI.ui.AbstractElement.InitOptions}
511 * the following properties are recognized:
513 * @typedef {LuCI.ui.AbstractElement.InitOptions} InitOptions
514 * @memberof LuCI.ui.Checkbox
516 * @property {string} [value_enabled=1]
517 * Specifies the value corresponding to a checked checkbox.
519 * @property {string} [value_disabled=0]
520 * Specifies the value corresponding to an unchecked checkbox.
522 * @property {string} [hiddenname]
523 * Specifies the HTML `name` attribute of the hidden input backing the
524 * checkbox. This is a legacy property existing for compatibility reasons,
525 * it is required for HTML based form submissions.
527 __init__: function(value
, options
) {
529 this.options
= Object
.assign({
537 var id
= 'cb%08x'.format(Math
.random() * 0xffffffff);
538 var frameEl
= E('div', {
539 'id': this.options
.id
,
540 'class': 'cbi-checkbox'
543 if (this.options
.hiddenname
)
544 frameEl
.appendChild(E('input', {
546 'name': this.options
.hiddenname
,
550 frameEl
.appendChild(E('input', {
552 'name': this.options
.name
,
554 'value': this.options
.value_enabled
,
555 'checked': (this.value
== this.options
.value_enabled
) ? '' : null,
556 'data-widget-id': this.options
.id
? 'widget.' + this.options
.id
: null
559 frameEl
.appendChild(E('label', { 'for': id
}));
561 return this.bind(frameEl
);
565 bind: function(frameEl
) {
568 this.setUpdateEvents(frameEl
.lastElementChild
.previousElementSibling
, 'click', 'blur');
569 this.setChangeEvents(frameEl
.lastElementChild
.previousElementSibling
, 'change');
571 L
.dom
.bindClassInstance(frameEl
, this);
577 * Test whether the checkbox is currently checked.
580 * @memberof LuCI.ui.Checkbox
582 * Returns `true` when the checkbox is currently checked, otherwise `false`.
584 isChecked: function() {
585 return this.node
.lastElementChild
.previousElementSibling
.checked
;
589 getValue: function() {
590 return this.isChecked()
591 ? this.options
.value_enabled
592 : this.options
.value_disabled
;
596 setValue: function(value
) {
597 this.node
.lastElementChild
.previousElementSibling
.checked
= (value
== this.options
.value_enabled
);
602 * Instantiate a select dropdown or checkbox/radiobutton group.
604 * @constructor Select
606 * @augments LuCI.ui.AbstractElement
610 * The `Select` class implements either a traditional HTML `<select>` element
611 * or a group of checkboxes or radio buttons, depending on whether multiple
612 * values are enabled or not.
614 * UI widget instances are usually not supposed to be created by view code
615 * directly, instead they're implicitely created by `LuCI.form` when
616 * instantiating CBI forms.
618 * This class is automatically instantiated as part of `LuCI.ui`. To use it
619 * in views, use `'require ui'` and refer to `ui.Select`. To import it in
620 * external JavaScript, use `L.require("ui").then(...)` and access the
621 * `Select` property of the class instance value.
623 * @param {string|string[]} [value=null]
624 * The initial input value(s).
626 * @param {Object<string, string>} choices
627 * Object containing the selectable choices of the widget. The object keys
628 * serve as values for the different choices while the values are used as
631 * @param {LuCI.ui.Select.InitOptions} [options]
632 * Object describing the widget specific options to initialize the inputs.
634 var UISelect
= UIElement
.extend(/** @lends LuCI.ui.Select.prototype */ {
636 * In addition to the [AbstractElement.InitOptions]{@link LuCI.ui.AbstractElement.InitOptions}
637 * the following properties are recognized:
639 * @typedef {LuCI.ui.AbstractElement.InitOptions} InitOptions
640 * @memberof LuCI.ui.Select
642 * @property {boolean} [multiple=false]
643 * Specifies whether multiple choice values may be selected.
645 * @property {string} [widget=select]
646 * Specifies the kind of widget to render. May be either `select` or
647 * `individual`. When set to `select` an HTML `<select>` element will be
648 * used, otherwise a group of checkbox or radio button elements is created,
649 * depending on the value of the `multiple` option.
651 * @property {string} [orientation=horizontal]
652 * Specifies whether checkbox / radio button groups should be rendered
653 * in a `horizontal` or `vertical` manner. Does not apply to the `select`
656 * @property {boolean|string[]} [sort=false]
657 * Specifies if and how to sort choice values. If set to `true`, the choice
658 * values will be sorted alphabetically. If set to an array of strings, the
659 * choice sort order is derived from the array.
661 * @property {number} [size]
662 * Specifies the HTML `size` attribute to set on the `<select>` element.
663 * Only applicable to the `select` widget type.
665 * @property {string} [placeholder=-- Please choose --]
666 * Specifies a placeholder text which is displayed when no choice is
667 * selected yet. Only applicable to the `select` widget type.
669 __init__: function(value
, choices
, options
) {
670 if (!L
.isObject(choices
))
673 if (!Array
.isArray(value
))
674 value
= (value
!= null && value
!= '') ? [ value
] : [];
676 if (!options
.multiple
&& value
.length
> 1)
680 this.choices
= choices
;
681 this.options
= Object
.assign({
684 orientation
: 'horizontal'
687 if (this.choices
.hasOwnProperty(''))
688 this.options
.optional
= true;
693 var frameEl
= E('div', { 'id': this.options
.id
}),
694 keys
= Object
.keys(this.choices
);
696 if (this.options
.sort
=== true)
698 else if (Array
.isArray(this.options
.sort
))
699 keys
= this.options
.sort
;
701 if (this.options
.widget
== 'select') {
702 frameEl
.appendChild(E('select', {
703 'id': this.options
.id
? 'widget.' + this.options
.id
: null,
704 'name': this.options
.name
,
705 'size': this.options
.size
,
706 'class': 'cbi-input-select',
707 'multiple': this.options
.multiple
? '' : null
710 if (this.options
.optional
)
711 frameEl
.lastChild
.appendChild(E('option', {
713 'selected': (this.values
.length
== 0 || this.values
[0] == '') ? '' : null
714 }, [ this.choices
[''] || this.options
.placeholder
|| _('-- Please choose --') ]));
716 for (var i
= 0; i
< keys
.length
; i
++) {
717 if (keys
[i
] == null || keys
[i
] == '')
720 frameEl
.lastChild
.appendChild(E('option', {
722 'selected': (this.values
.indexOf(keys
[i
]) > -1) ? '' : null
723 }, [ this.choices
[keys
[i
]] || keys
[i
] ]));
727 var brEl
= (this.options
.orientation
=== 'horizontal') ? document
.createTextNode(' ') : E('br');
729 for (var i
= 0; i
< keys
.length
; i
++) {
730 frameEl
.appendChild(E('label', {}, [
732 'id': this.options
.id
? 'widget.' + this.options
.id
: null,
733 'name': this.options
.id
|| this.options
.name
,
734 'type': this.options
.multiple
? 'checkbox' : 'radio',
735 'class': this.options
.multiple
? 'cbi-input-checkbox' : 'cbi-input-radio',
737 'checked': (this.values
.indexOf(keys
[i
]) > -1) ? '' : null
739 this.choices
[keys
[i
]] || keys
[i
]
742 if (i
+ 1 == this.options
.size
)
743 frameEl
.appendChild(brEl
);
747 return this.bind(frameEl
);
751 bind: function(frameEl
) {
754 if (this.options
.widget
== 'select') {
755 this.setUpdateEvents(frameEl
.firstChild
, 'change', 'click', 'blur');
756 this.setChangeEvents(frameEl
.firstChild
, 'change');
759 var radioEls
= frameEl
.querySelectorAll('input[type="radio"]');
760 for (var i
= 0; i
< radioEls
.length
; i
++) {
761 this.setUpdateEvents(radioEls
[i
], 'change', 'click', 'blur');
762 this.setChangeEvents(radioEls
[i
], 'change', 'click', 'blur');
766 L
.dom
.bindClassInstance(frameEl
, this);
772 getValue: function() {
773 if (this.options
.widget
== 'select')
774 return this.node
.firstChild
.value
;
776 var radioEls
= frameEl
.querySelectorAll('input[type="radio"]');
777 for (var i
= 0; i
< radioEls
.length
; i
++)
778 if (radioEls
[i
].checked
)
779 return radioEls
[i
].value
;
785 setValue: function(value
) {
786 if (this.options
.widget
== 'select') {
790 for (var i
= 0; i
< this.node
.firstChild
.options
.length
; i
++)
791 this.node
.firstChild
.options
[i
].selected
= (this.node
.firstChild
.options
[i
].value
== value
);
796 var radioEls
= frameEl
.querySelectorAll('input[type="radio"]');
797 for (var i
= 0; i
< radioEls
.length
; i
++)
798 radioEls
[i
].checked
= (radioEls
[i
].value
== value
);
803 * Instantiate a rich dropdown choice widget.
805 * @constructor Dropdown
807 * @augments LuCI.ui.AbstractElement
811 * The `Dropdown` class implements a rich, stylable dropdown menu which
812 * supports non-text choice labels.
814 * UI widget instances are usually not supposed to be created by view code
815 * directly, instead they're implicitely created by `LuCI.form` when
816 * instantiating CBI forms.
818 * This class is automatically instantiated as part of `LuCI.ui`. To use it
819 * in views, use `'require ui'` and refer to `ui.Dropdown`. To import it in
820 * external JavaScript, use `L.require("ui").then(...)` and access the
821 * `Dropdown` property of the class instance value.
823 * @param {string|string[]} [value=null]
824 * The initial input value(s).
826 * @param {Object<string, *>} choices
827 * Object containing the selectable choices of the widget. The object keys
828 * serve as values for the different choices while the values are used as
831 * @param {LuCI.ui.Dropdown.InitOptions} [options]
832 * Object describing the widget specific options to initialize the dropdown.
834 var UIDropdown
= UIElement
.extend(/** @lends LuCI.ui.Dropdown.prototype */ {
836 * In addition to the [AbstractElement.InitOptions]{@link LuCI.ui.AbstractElement.InitOptions}
837 * the following properties are recognized:
839 * @typedef {LuCI.ui.AbstractElement.InitOptions} InitOptions
840 * @memberof LuCI.ui.Dropdown
842 * @property {boolean} [optional=true]
843 * Specifies whether the dropdown selection is optional. In contrast to
844 * other widgets, the `optional` constraint of dropdowns works differently;
845 * instead of marking the widget invalid on empty values when set to `false`,
846 * the user is not allowed to deselect all choices.
848 * For single value dropdowns that means that no empty "please select"
849 * choice is offered and for multi value dropdowns, the last selected choice
850 * may not be deselected without selecting another choice first.
852 * @property {boolean} [multiple]
853 * Specifies whether multiple choice values may be selected. It defaults
854 * to `true` when an array is passed as input value to the constructor.
856 * @property {boolean|string[]} [sort=false]
857 * Specifies if and how to sort choice values. If set to `true`, the choice
858 * values will be sorted alphabetically. If set to an array of strings, the
859 * choice sort order is derived from the array.
861 * @property {string} [select_placeholder=-- Please choose --]
862 * Specifies a placeholder text which is displayed when no choice is
865 * @property {string} [custom_placeholder=-- custom --]
866 * Specifies a placeholder text which is displayed in the text input
867 * field allowing to enter custom choice values. Only applicable if the
868 * `create` option is set to `true`.
870 * @property {boolean} [create=false]
871 * Specifies whether custom choices may be entered into the dropdown
874 * @property {string} [create_query=.create-item-input]
875 * Specifies a CSS selector expression used to find the input element
876 * which is used to enter custom choice values. This should not normally
877 * be used except by widgets derived from the Dropdown class.
879 * @property {string} [create_template=script[type="item-template"]]
880 * Specifies a CSS selector expression used to find an HTML element
881 * serving as template for newly added custom choice values.
883 * Any `{{value}}` placeholder string within the template elements text
884 * content will be replaced by the user supplied choice value, the
885 * resulting string is parsed as HTML and appended to the end of the
886 * choice list. The template markup may specify one HTML element with a
887 * `data-label-placeholder` attribute which is replaced by a matching
888 * label value from the `choices` object or with the user supplied value
889 * itself in case `choices` contains no matching choice label.
891 * If the template element is not found or if no `create_template` selector
892 * expression is specified, the default markup for newly created elements is
893 * `<li data-value="{{value}}"><span data-label-placeholder="true" /></li>`.
895 * @property {string} [create_markup]
896 * This property allows specifying the markup for custom choices directly
897 * instead of referring to a template element through CSS selectors.
899 * Apart from that it works exactly like `create_template`.
901 * @property {number} [display_items=3]
902 * Specifies the maximum amount of choice labels that should be shown in
903 * collapsed dropdown state before further selected choices are cut off.
905 * Only applicable when `multiple` is `true`.
907 * @property {number} [dropdown_items=-1]
908 * Specifies the maximum amount of choices that should be shown when the
909 * dropdown is open. If the amount of available choices exceeds this number,
910 * the dropdown area must be scrolled to reach further items.
912 * If set to `-1`, the dropdown menu will attempt to show all choice values
913 * and only resort to scrolling if the amount of choices exceeds the available
914 * screen space above and below the dropdown widget.
916 * @property {string} [placeholder]
917 * This property serves as a shortcut to set both `select_placeholder` and
918 * `custom_placeholder`. Either of these properties will fallback to
919 * `placeholder` if not specified.
921 * @property {boolean} [readonly=false]
922 * Specifies whether the custom choice input field should be rendered
923 * readonly. Only applicable when `create` is `true`.
925 * @property {number} [maxlength]
926 * Specifies the HTML `maxlength` attribute to set on the custom choice
927 * `<input>` element. Note that this a legacy property that exists for
928 * compatibility reasons. It is usually better to `maxlength(N)` validation
929 * expression. Only applicable when `create` is `true`.
931 __init__: function(value
, choices
, options
) {
932 if (!L
.isObject(choices
))
935 if (!Array
.isArray(value
))
936 this.values
= (value
!= null && value
!= '') ? [ value
] : [];
940 this.choices
= choices
;
941 this.options
= Object
.assign({
943 multiple
: Array
.isArray(value
),
945 select_placeholder
: _('-- Please choose --'),
946 custom_placeholder
: _('-- custom --'),
950 create_query
: '.create-item-input',
951 create_template
: 'script[type="item-template"]'
958 'id': this.options
.id
,
959 'class': 'cbi-dropdown',
960 'multiple': this.options
.multiple
? '' : null,
961 'optional': this.options
.optional
? '' : null,
964 var keys
= Object
.keys(this.choices
);
966 if (this.options
.sort
=== true)
968 else if (Array
.isArray(this.options
.sort
))
969 keys
= this.options
.sort
;
971 if (this.options
.create
)
972 for (var i
= 0; i
< this.values
.length
; i
++)
973 if (!this.choices
.hasOwnProperty(this.values
[i
]))
974 keys
.push(this.values
[i
]);
976 for (var i
= 0; i
< keys
.length
; i
++) {
977 var label
= this.choices
[keys
[i
]];
979 if (L
.dom
.elem(label
))
980 label
= label
.cloneNode(true);
982 sb
.lastElementChild
.appendChild(E('li', {
983 'data-value': keys
[i
],
984 'selected': (this.values
.indexOf(keys
[i
]) > -1) ? '' : null
985 }, [ label
|| keys
[i
] ]));
988 if (this.options
.create
) {
989 var createEl
= E('input', {
991 'class': 'create-item-input',
992 'readonly': this.options
.readonly
? '' : null,
993 'maxlength': this.options
.maxlength
,
994 'placeholder': this.options
.custom_placeholder
|| this.options
.placeholder
997 if (this.options
.datatype
|| this.options
.validate
)
998 L
.ui
.addValidator(createEl
, this.options
.datatype
|| 'string',
999 true, this.options
.validate
, 'blur', 'keyup');
1001 sb
.lastElementChild
.appendChild(E('li', { 'data-value': '-' }, createEl
));
1004 if (this.options
.create_markup
)
1005 sb
.appendChild(E('script', { type
: 'item-template' },
1006 this.options
.create_markup
));
1008 return this.bind(sb
);
1012 bind: function(sb
) {
1013 var o
= this.options
;
1015 o
.multiple
= sb
.hasAttribute('multiple');
1016 o
.optional
= sb
.hasAttribute('optional');
1017 o
.placeholder
= sb
.getAttribute('placeholder') || o
.placeholder
;
1018 o
.display_items
= parseInt(sb
.getAttribute('display-items') || o
.display_items
);
1019 o
.dropdown_items
= parseInt(sb
.getAttribute('dropdown-items') || o
.dropdown_items
);
1020 o
.create_query
= sb
.getAttribute('item-create') || o
.create_query
;
1021 o
.create_template
= sb
.getAttribute('item-template') || o
.create_template
;
1023 var ul
= sb
.querySelector('ul'),
1024 more
= sb
.appendChild(E('span', { class: 'more', tabindex
: -1 }, '···')),
1025 open
= sb
.appendChild(E('span', { class: 'open', tabindex
: -1 }, '▾')),
1026 canary
= sb
.appendChild(E('div')),
1027 create
= sb
.querySelector(this.options
.create_query
),
1028 ndisplay
= this.options
.display_items
,
1031 if (this.options
.multiple
) {
1032 var items
= ul
.querySelectorAll('li');
1034 for (var i
= 0; i
< items
.length
; i
++) {
1035 this.transformItem(sb
, items
[i
]);
1037 if (items
[i
].hasAttribute('selected') && ndisplay
-- > 0)
1038 items
[i
].setAttribute('display', n
++);
1042 if (this.options
.optional
&& !ul
.querySelector('li[data-value=""]')) {
1043 var placeholder
= E('li', { placeholder
: '' },
1044 this.options
.select_placeholder
|| this.options
.placeholder
);
1047 ? ul
.insertBefore(placeholder
, ul
.firstChild
)
1048 : ul
.appendChild(placeholder
);
1051 var items
= ul
.querySelectorAll('li'),
1052 sel
= sb
.querySelectorAll('[selected]');
1054 sel
.forEach(function(s
) {
1055 s
.removeAttribute('selected');
1058 var s
= sel
[0] || items
[0];
1060 s
.setAttribute('selected', '');
1061 s
.setAttribute('display', n
++);
1067 this.saveValues(sb
, ul
);
1069 ul
.setAttribute('tabindex', -1);
1070 sb
.setAttribute('tabindex', 0);
1073 sb
.setAttribute('more', '')
1075 sb
.removeAttribute('more');
1077 if (ndisplay
== this.options
.display_items
)
1078 sb
.setAttribute('empty', '')
1080 sb
.removeAttribute('empty');
1082 L
.dom
.content(more
, (ndisplay
== this.options
.display_items
)
1083 ? (this.options
.select_placeholder
|| this.options
.placeholder
) : '···');
1086 sb
.addEventListener('click', this.handleClick
.bind(this));
1087 sb
.addEventListener('keydown', this.handleKeydown
.bind(this));
1088 sb
.addEventListener('cbi-dropdown-close', this.handleDropdownClose
.bind(this));
1089 sb
.addEventListener('cbi-dropdown-select', this.handleDropdownSelect
.bind(this));
1091 if ('ontouchstart' in window
) {
1092 sb
.addEventListener('touchstart', function(ev
) { ev
.stopPropagation(); });
1093 window
.addEventListener('touchstart', this.closeAllDropdowns
);
1096 sb
.addEventListener('mouseover', this.handleMouseover
.bind(this));
1097 sb
.addEventListener('focus', this.handleFocus
.bind(this));
1099 canary
.addEventListener('focus', this.handleCanaryFocus
.bind(this));
1101 window
.addEventListener('mouseover', this.setFocus
);
1102 window
.addEventListener('click', this.closeAllDropdowns
);
1106 create
.addEventListener('keydown', this.handleCreateKeydown
.bind(this));
1107 create
.addEventListener('focus', this.handleCreateFocus
.bind(this));
1108 create
.addEventListener('blur', this.handleCreateBlur
.bind(this));
1110 var li
= findParent(create
, 'li');
1112 li
.setAttribute('unselectable', '');
1113 li
.addEventListener('click', this.handleCreateClick
.bind(this));
1118 this.setUpdateEvents(sb
, 'cbi-dropdown-open', 'cbi-dropdown-close');
1119 this.setChangeEvents(sb
, 'cbi-dropdown-change', 'cbi-dropdown-close');
1121 L
.dom
.bindClassInstance(sb
, this);
1127 openDropdown: function(sb
) {
1128 var st
= window
.getComputedStyle(sb
, null),
1129 ul
= sb
.querySelector('ul'),
1130 li
= ul
.querySelectorAll('li'),
1131 fl
= findParent(sb
, '.cbi-value-field'),
1132 sel
= ul
.querySelector('[selected]'),
1133 rect
= sb
.getBoundingClientRect(),
1134 items
= Math
.min(this.options
.dropdown_items
, li
.length
);
1136 document
.querySelectorAll('.cbi-dropdown[open]').forEach(function(s
) {
1137 s
.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1140 sb
.setAttribute('open', '');
1142 var pv
= ul
.cloneNode(true);
1143 pv
.classList
.add('preview');
1146 fl
.classList
.add('cbi-dropdown-open');
1148 if ('ontouchstart' in window
) {
1149 var vpWidth
= Math
.max(document
.documentElement
.clientWidth
, window
.innerWidth
|| 0),
1150 vpHeight
= Math
.max(document
.documentElement
.clientHeight
, window
.innerHeight
|| 0),
1153 ul
.style
.top
= sb
.offsetHeight
+ 'px';
1154 ul
.style
.left
= -rect
.left
+ 'px';
1155 ul
.style
.right
= (rect
.right
- vpWidth
) + 'px';
1156 ul
.style
.maxHeight
= (vpHeight
* 0.5) + 'px';
1157 ul
.style
.WebkitOverflowScrolling
= 'touch';
1159 function getScrollParent(element
) {
1160 var parent
= element
,
1161 style
= getComputedStyle(element
),
1162 excludeStaticParent
= (style
.position
=== 'absolute');
1164 if (style
.position
=== 'fixed')
1165 return document
.body
;
1167 while ((parent
= parent
.parentElement
) != null) {
1168 style
= getComputedStyle(parent
);
1170 if (excludeStaticParent
&& style
.position
=== 'static')
1173 if (/(auto|scroll)/.test(style
.overflow
+ style
.overflowY
+ style
.overflowX
))
1177 return document
.body
;
1180 var scrollParent
= getScrollParent(sb
),
1181 scrollFrom
= scrollParent
.scrollTop
,
1182 scrollTo
= scrollFrom
+ rect
.top
- vpHeight
* 0.5;
1184 var scrollStep = function(timestamp
) {
1187 ul
.scrollTop
= sel
? Math
.max(sel
.offsetTop
- sel
.offsetHeight
, 0) : 0;
1190 var duration
= Math
.max(timestamp
- start
, 1);
1191 if (duration
< 100) {
1192 scrollParent
.scrollTop
= scrollFrom
+ (scrollTo
- scrollFrom
) * (duration
/ 100);
1193 window
.requestAnimationFrame(scrollStep
);
1196 scrollParent
.scrollTop
= scrollTo
;
1200 window
.requestAnimationFrame(scrollStep
);
1203 ul
.style
.maxHeight
= '1px';
1204 ul
.style
.top
= ul
.style
.bottom
= '';
1206 window
.requestAnimationFrame(function() {
1207 var itemHeight
= li
[Math
.max(0, li
.length
- 2)].getBoundingClientRect().height
,
1209 spaceAbove
= rect
.top
,
1210 spaceBelow
= window
.innerHeight
- rect
.height
- rect
.top
;
1212 for (var i
= 0; i
< (items
== -1 ? li
.length
: items
); i
++)
1213 fullHeight
+= li
[i
].getBoundingClientRect().height
;
1215 if (fullHeight
<= spaceBelow
) {
1216 ul
.style
.top
= rect
.height
+ 'px';
1217 ul
.style
.maxHeight
= spaceBelow
+ 'px';
1219 else if (fullHeight
<= spaceAbove
) {
1220 ul
.style
.bottom
= rect
.height
+ 'px';
1221 ul
.style
.maxHeight
= spaceAbove
+ 'px';
1223 else if (spaceBelow
>= spaceAbove
) {
1224 ul
.style
.top
= rect
.height
+ 'px';
1225 ul
.style
.maxHeight
= (spaceBelow
- (spaceBelow
% itemHeight
)) + 'px';
1228 ul
.style
.bottom
= rect
.height
+ 'px';
1229 ul
.style
.maxHeight
= (spaceAbove
- (spaceAbove
% itemHeight
)) + 'px';
1232 ul
.scrollTop
= sel
? Math
.max(sel
.offsetTop
- sel
.offsetHeight
, 0) : 0;
1236 var cboxes
= ul
.querySelectorAll('[selected] input[type="checkbox"]');
1237 for (var i
= 0; i
< cboxes
.length
; i
++) {
1238 cboxes
[i
].checked
= true;
1239 cboxes
[i
].disabled
= (cboxes
.length
== 1 && !this.options
.optional
);
1242 ul
.classList
.add('dropdown');
1244 sb
.insertBefore(pv
, ul
.nextElementSibling
);
1246 li
.forEach(function(l
) {
1247 l
.setAttribute('tabindex', 0);
1250 sb
.lastElementChild
.setAttribute('tabindex', 0);
1252 this.setFocus(sb
, sel
|| li
[0], true);
1256 closeDropdown: function(sb
, no_focus
) {
1257 if (!sb
.hasAttribute('open'))
1260 var pv
= sb
.querySelector('ul.preview'),
1261 ul
= sb
.querySelector('ul.dropdown'),
1262 li
= ul
.querySelectorAll('li'),
1263 fl
= findParent(sb
, '.cbi-value-field');
1265 li
.forEach(function(l
) { l
.removeAttribute('tabindex'); });
1266 sb
.lastElementChild
.removeAttribute('tabindex');
1269 sb
.removeAttribute('open');
1270 sb
.style
.width
= sb
.style
.height
= '';
1272 ul
.classList
.remove('dropdown');
1273 ul
.style
.top
= ul
.style
.bottom
= ul
.style
.maxHeight
= '';
1276 fl
.classList
.remove('cbi-dropdown-open');
1279 this.setFocus(sb
, sb
);
1281 this.saveValues(sb
, ul
);
1285 toggleItem: function(sb
, li
, force_state
) {
1286 if (li
.hasAttribute('unselectable'))
1289 if (this.options
.multiple
) {
1290 var cbox
= li
.querySelector('input[type="checkbox"]'),
1291 items
= li
.parentNode
.querySelectorAll('li'),
1292 label
= sb
.querySelector('ul.preview'),
1293 sel
= li
.parentNode
.querySelectorAll('[selected]').length
,
1294 more
= sb
.querySelector('.more'),
1295 ndisplay
= this.options
.display_items
,
1298 if (li
.hasAttribute('selected')) {
1299 if (force_state
!== true) {
1300 if (sel
> 1 || this.options
.optional
) {
1301 li
.removeAttribute('selected');
1302 cbox
.checked
= cbox
.disabled
= false;
1306 cbox
.disabled
= true;
1311 if (force_state
!== false) {
1312 li
.setAttribute('selected', '');
1313 cbox
.checked
= true;
1314 cbox
.disabled
= false;
1319 while (label
&& label
.firstElementChild
)
1320 label
.removeChild(label
.firstElementChild
);
1322 for (var i
= 0; i
< items
.length
; i
++) {
1323 items
[i
].removeAttribute('display');
1324 if (items
[i
].hasAttribute('selected')) {
1325 if (ndisplay
-- > 0) {
1326 items
[i
].setAttribute('display', n
++);
1328 label
.appendChild(items
[i
].cloneNode(true));
1330 var c
= items
[i
].querySelector('input[type="checkbox"]');
1332 c
.disabled
= (sel
== 1 && !this.options
.optional
);
1337 sb
.setAttribute('more', '');
1339 sb
.removeAttribute('more');
1341 if (ndisplay
=== this.options
.display_items
)
1342 sb
.setAttribute('empty', '');
1344 sb
.removeAttribute('empty');
1346 L
.dom
.content(more
, (ndisplay
=== this.options
.display_items
)
1347 ? (this.options
.select_placeholder
|| this.options
.placeholder
) : '···');
1350 var sel
= li
.parentNode
.querySelector('[selected]');
1352 sel
.removeAttribute('display');
1353 sel
.removeAttribute('selected');
1356 li
.setAttribute('display', 0);
1357 li
.setAttribute('selected', '');
1359 this.closeDropdown(sb
, true);
1362 this.saveValues(sb
, li
.parentNode
);
1366 transformItem: function(sb
, li
) {
1367 var cbox
= E('form', {}, E('input', { type
: 'checkbox', tabindex
: -1, onclick
: 'event.preventDefault()' })),
1370 while (li
.firstChild
)
1371 label
.appendChild(li
.firstChild
);
1373 li
.appendChild(cbox
);
1374 li
.appendChild(label
);
1378 saveValues: function(sb
, ul
) {
1379 var sel
= ul
.querySelectorAll('li[selected]'),
1380 div
= sb
.lastElementChild
,
1381 name
= this.options
.name
,
1385 while (div
.lastElementChild
)
1386 div
.removeChild(div
.lastElementChild
);
1388 sel
.forEach(function (s
) {
1389 if (s
.hasAttribute('placeholder'))
1394 value
: s
.hasAttribute('data-value') ? s
.getAttribute('data-value') : s
.innerText
,
1398 div
.appendChild(E('input', {
1406 strval
+= strval
.length
? ' ' + v
.value
: v
.value
;
1414 if (this.options
.multiple
)
1415 detail
.values
= values
;
1417 detail
.value
= values
.length
? values
[0] : null;
1421 sb
.dispatchEvent(new CustomEvent('cbi-dropdown-change', {
1428 setValues: function(sb
, values
) {
1429 var ul
= sb
.querySelector('ul');
1431 if (this.options
.create
) {
1432 for (var value
in values
) {
1433 this.createItems(sb
, value
);
1435 if (!this.options
.multiple
)
1440 if (this.options
.multiple
) {
1441 var lis
= ul
.querySelectorAll('li[data-value]');
1442 for (var i
= 0; i
< lis
.length
; i
++) {
1443 var value
= lis
[i
].getAttribute('data-value');
1444 if (values
=== null || !(value
in values
))
1445 this.toggleItem(sb
, lis
[i
], false);
1447 this.toggleItem(sb
, lis
[i
], true);
1451 var ph
= ul
.querySelector('li[placeholder]');
1453 this.toggleItem(sb
, ph
);
1455 var lis
= ul
.querySelectorAll('li[data-value]');
1456 for (var i
= 0; i
< lis
.length
; i
++) {
1457 var value
= lis
[i
].getAttribute('data-value');
1458 if (values
!== null && (value
in values
))
1459 this.toggleItem(sb
, lis
[i
]);
1465 setFocus: function(sb
, elem
, scroll
) {
1466 if (sb
&& sb
.hasAttribute
&& sb
.hasAttribute('locked-in'))
1469 if (sb
.target
&& findParent(sb
.target
, 'ul.dropdown'))
1472 document
.querySelectorAll('.focus').forEach(function(e
) {
1473 if (!matchesElem(e
, 'input')) {
1474 e
.classList
.remove('focus');
1481 elem
.classList
.add('focus');
1484 elem
.parentNode
.scrollTop
= elem
.offsetTop
- elem
.parentNode
.offsetTop
;
1489 createChoiceElement: function(sb
, value
, label
) {
1490 var tpl
= sb
.querySelector(this.options
.create_template
),
1494 markup
= (tpl
.textContent
|| tpl
.innerHTML
|| tpl
.firstChild
.data
).replace(/^<!--|-->$/, '').trim();
1496 markup
= '<li data-value="{{value}}"><span data-label-placeholder="true" /></li>';
1498 var new_item
= E(markup
.replace(/{{value}}/g, '%h'.format(value
))),
1499 placeholder
= new_item
.querySelector('[data-label-placeholder]');
1502 var content
= E('span', {}, label
|| this.choices
[value
] || [ value
]);
1504 while (content
.firstChild
)
1505 placeholder
.parentNode
.insertBefore(content
.firstChild
, placeholder
);
1507 placeholder
.parentNode
.removeChild(placeholder
);
1510 if (this.options
.multiple
)
1511 this.transformItem(sb
, new_item
);
1517 createItems: function(sb
, value
) {
1519 val
= (value
|| '').trim(),
1520 ul
= sb
.querySelector('ul');
1522 if (!sbox
.options
.multiple
)
1523 val
= val
.length
? [ val
] : [];
1525 val
= val
.length
? val
.split(/\s+/) : [];
1527 val
.forEach(function(item
) {
1528 var new_item
= null;
1530 ul
.childNodes
.forEach(function(li
) {
1531 if (li
.getAttribute
&& li
.getAttribute('data-value') === item
)
1536 new_item
= sbox
.createChoiceElement(sb
, item
);
1538 if (!sbox
.options
.multiple
) {
1539 var old
= ul
.querySelector('li[created]');
1541 ul
.removeChild(old
);
1543 new_item
.setAttribute('created', '');
1546 new_item
= ul
.insertBefore(new_item
, ul
.lastElementChild
);
1549 sbox
.toggleItem(sb
, new_item
, true);
1550 sbox
.setFocus(sb
, new_item
, true);
1555 * Remove all existing choices from the dropdown menu.
1557 * This function removes all preexisting dropdown choices from the widget,
1558 * keeping only choices currently being selected unless `reset_values` is
1559 * given, in which case all choices and deselected and removed.
1562 * @memberof LuCI.ui.Dropdown
1563 * @param {boolean} [reset_value=false]
1564 * If set to `true`, deselect and remove selected choices as well instead
1567 clearChoices: function(reset_value
) {
1568 var ul
= this.node
.querySelector('ul'),
1569 lis
= ul
? ul
.querySelectorAll('li[data-value]') : [],
1570 len
= lis
.length
- (this.options
.create
? 1 : 0),
1571 val
= reset_value
? null : this.getValue();
1573 for (var i
= 0; i
< len
; i
++) {
1574 var lival
= lis
[i
].getAttribute('data-value');
1576 (!this.options
.multiple
&& val
!= lival
) ||
1577 (this.options
.multiple
&& val
.indexOf(lival
) == -1))
1578 ul
.removeChild(lis
[i
]);
1582 this.setValues(this.node
, {});
1586 * Add new choices to the dropdown menu.
1588 * This function adds further choices to an existing dropdown menu,
1589 * ignoring choice values which are already present.
1592 * @memberof LuCI.ui.Dropdown
1593 * @param {string[]} values
1594 * The choice values to add to the dropdown widget.
1596 * @param {Object<string, *>} labels
1597 * The choice label values to use when adding dropdown choices. If no
1598 * label is found for a particular choice value, the value itself is used
1599 * as label text. Choice labels may be any valid value accepted by
1600 * {@link LuCI.dom#content}.
1602 addChoices: function(values
, labels
) {
1604 ul
= sb
.querySelector('ul'),
1605 lis
= ul
? ul
.querySelectorAll('li[data-value]') : [];
1607 if (!Array
.isArray(values
))
1608 values
= L
.toArray(values
);
1610 if (!L
.isObject(labels
))
1613 for (var i
= 0; i
< values
.length
; i
++) {
1616 for (var j
= 0; j
< lis
.length
; j
++) {
1617 if (lis
[j
].getAttribute('data-value') === values
[i
]) {
1627 this.createChoiceElement(sb
, values
[i
], labels
[values
[i
]]),
1628 ul
.lastElementChild
);
1633 * Close all open dropdown widgets in the current document.
1635 closeAllDropdowns: function() {
1636 document
.querySelectorAll('.cbi-dropdown[open]').forEach(function(s
) {
1637 s
.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1642 handleClick: function(ev
) {
1643 var sb
= ev
.currentTarget
;
1645 if (!sb
.hasAttribute('open')) {
1646 if (!matchesElem(ev
.target
, 'input'))
1647 this.openDropdown(sb
);
1650 var li
= findParent(ev
.target
, 'li');
1651 if (li
&& li
.parentNode
.classList
.contains('dropdown'))
1652 this.toggleItem(sb
, li
);
1653 else if (li
&& li
.parentNode
.classList
.contains('preview'))
1654 this.closeDropdown(sb
);
1655 else if (matchesElem(ev
.target
, 'span.open, span.more'))
1656 this.closeDropdown(sb
);
1659 ev
.preventDefault();
1660 ev
.stopPropagation();
1664 handleKeydown: function(ev
) {
1665 var sb
= ev
.currentTarget
;
1667 if (matchesElem(ev
.target
, 'input'))
1670 if (!sb
.hasAttribute('open')) {
1671 switch (ev
.keyCode
) {
1676 this.openDropdown(sb
);
1677 ev
.preventDefault();
1681 var active
= findParent(document
.activeElement
, 'li');
1683 switch (ev
.keyCode
) {
1685 this.closeDropdown(sb
);
1690 if (!active
.hasAttribute('selected'))
1691 this.toggleItem(sb
, active
);
1692 this.closeDropdown(sb
);
1693 ev
.preventDefault();
1699 this.toggleItem(sb
, active
);
1700 ev
.preventDefault();
1705 if (active
&& active
.previousElementSibling
) {
1706 this.setFocus(sb
, active
.previousElementSibling
);
1707 ev
.preventDefault();
1712 if (active
&& active
.nextElementSibling
) {
1713 this.setFocus(sb
, active
.nextElementSibling
);
1714 ev
.preventDefault();
1722 handleDropdownClose: function(ev
) {
1723 var sb
= ev
.currentTarget
;
1725 this.closeDropdown(sb
, true);
1729 handleDropdownSelect: function(ev
) {
1730 var sb
= ev
.currentTarget
,
1731 li
= findParent(ev
.target
, 'li');
1736 this.toggleItem(sb
, li
);
1737 this.closeDropdown(sb
, true);
1741 handleMouseover: function(ev
) {
1742 var sb
= ev
.currentTarget
;
1744 if (!sb
.hasAttribute('open'))
1747 var li
= findParent(ev
.target
, 'li');
1749 if (li
&& li
.parentNode
.classList
.contains('dropdown'))
1750 this.setFocus(sb
, li
);
1754 handleFocus: function(ev
) {
1755 var sb
= ev
.currentTarget
;
1757 document
.querySelectorAll('.cbi-dropdown[open]').forEach(function(s
) {
1758 if (s
!== sb
|| sb
.hasAttribute('open'))
1759 s
.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1764 handleCanaryFocus: function(ev
) {
1765 this.closeDropdown(ev
.currentTarget
.parentNode
);
1769 handleCreateKeydown: function(ev
) {
1770 var input
= ev
.currentTarget
,
1771 sb
= findParent(input
, '.cbi-dropdown');
1773 switch (ev
.keyCode
) {
1775 ev
.preventDefault();
1777 if (input
.classList
.contains('cbi-input-invalid'))
1780 this.createItems(sb
, input
.value
);
1788 handleCreateFocus: function(ev
) {
1789 var input
= ev
.currentTarget
,
1790 cbox
= findParent(input
, 'li').querySelector('input[type="checkbox"]'),
1791 sb
= findParent(input
, '.cbi-dropdown');
1794 cbox
.checked
= true;
1796 sb
.setAttribute('locked-in', '');
1800 handleCreateBlur: function(ev
) {
1801 var input
= ev
.currentTarget
,
1802 cbox
= findParent(input
, 'li').querySelector('input[type="checkbox"]'),
1803 sb
= findParent(input
, '.cbi-dropdown');
1806 cbox
.checked
= false;
1808 sb
.removeAttribute('locked-in');
1812 handleCreateClick: function(ev
) {
1813 ev
.currentTarget
.querySelector(this.options
.create_query
).focus();
1817 setValue: function(values
) {
1818 if (this.options
.multiple
) {
1819 if (!Array
.isArray(values
))
1820 values
= (values
!= null && values
!= '') ? [ values
] : [];
1824 for (var i
= 0; i
< values
.length
; i
++)
1825 v
[values
[i
]] = true;
1827 this.setValues(this.node
, v
);
1832 if (values
!= null) {
1833 if (Array
.isArray(values
))
1834 v
[values
[0]] = true;
1839 this.setValues(this.node
, v
);
1844 getValue: function() {
1845 var div
= this.node
.lastElementChild
,
1846 h
= div
.querySelectorAll('input[type="hidden"]'),
1849 for (var i
= 0; i
< h
.length
; i
++)
1852 return this.options
.multiple
? v
: v
[0];
1857 * Instantiate a rich dropdown choice widget allowing custom values.
1859 * @constructor Combobox
1861 * @augments LuCI.ui.Dropdown
1865 * The `Combobox` class implements a rich, stylable dropdown menu which allows
1866 * to enter custom values. Historically, comboboxes used to be a dedicated
1867 * widget type in LuCI but nowadays they are direct aliases of dropdown widgets
1868 * with a set of enforced default properties for easier instantiation.
1870 * UI widget instances are usually not supposed to be created by view code
1871 * directly, instead they're implicitely created by `LuCI.form` when
1872 * instantiating CBI forms.
1874 * This class is automatically instantiated as part of `LuCI.ui`. To use it
1875 * in views, use `'require ui'` and refer to `ui.Combobox`. To import it in
1876 * external JavaScript, use `L.require("ui").then(...)` and access the
1877 * `Combobox` property of the class instance value.
1879 * @param {string|string[]} [value=null]
1880 * The initial input value(s).
1882 * @param {Object<string, *>} choices
1883 * Object containing the selectable choices of the widget. The object keys
1884 * serve as values for the different choices while the values are used as
1887 * @param {LuCI.ui.Combobox.InitOptions} [options]
1888 * Object describing the widget specific options to initialize the dropdown.
1890 var UICombobox
= UIDropdown
.extend(/** @lends LuCI.ui.Combobox.prototype */ {
1892 * Comboboxes support the same properties as
1893 * [Dropdown.InitOptions]{@link LuCI.ui.Dropdown.InitOptions} but enforce
1894 * specific values for the following properties:
1896 * @typedef {LuCI.ui.Dropdown.InitOptions} InitOptions
1897 * @memberof LuCI.ui.Combobox
1899 * @property {boolean} multiple=false
1900 * Since Comboboxes never allow selecting multiple values, this property
1901 * is forcibly set to `false`.
1903 * @property {boolean} create=true
1904 * Since Comboboxes always allow custom choice values, this property is
1905 * forcibly set to `true`.
1907 * @property {boolean} optional=true
1908 * Since Comboboxes are always optional, this property is forcibly set to
1911 __init__: function(value
, choices
, options
) {
1912 this.super('__init__', [ value
, choices
, Object
.assign({
1913 select_placeholder
: _('-- Please choose --'),
1914 custom_placeholder
: _('-- custom --'),
1926 * Instantiate a combo button widget offering multiple action choices.
1928 * @constructor ComboButton
1930 * @augments LuCI.ui.Dropdown
1934 * The `ComboButton` class implements a button element which can be expanded
1935 * into a dropdown to chose from a set of different action choices.
1937 * UI widget instances are usually not supposed to be created by view code
1938 * directly, instead they're implicitely created by `LuCI.form` when
1939 * instantiating CBI forms.
1941 * This class is automatically instantiated as part of `LuCI.ui`. To use it
1942 * in views, use `'require ui'` and refer to `ui.ComboButton`. To import it in
1943 * external JavaScript, use `L.require("ui").then(...)` and access the
1944 * `ComboButton` property of the class instance value.
1946 * @param {string|string[]} [value=null]
1947 * The initial input value(s).
1949 * @param {Object<string, *>} choices
1950 * Object containing the selectable choices of the widget. The object keys
1951 * serve as values for the different choices while the values are used as
1954 * @param {LuCI.ui.ComboButton.InitOptions} [options]
1955 * Object describing the widget specific options to initialize the button.
1957 var UIComboButton
= UIDropdown
.extend(/** @lends LuCI.ui.ComboButton.prototype */ {
1959 * ComboButtons support the same properties as
1960 * [Dropdown.InitOptions]{@link LuCI.ui.Dropdown.InitOptions} but enforce
1961 * specific values for some properties and add aditional button specific
1964 * @typedef {LuCI.ui.Dropdown.InitOptions} InitOptions
1965 * @memberof LuCI.ui.ComboButton
1967 * @property {boolean} multiple=false
1968 * Since ComboButtons never allow selecting multiple actions, this property
1969 * is forcibly set to `false`.
1971 * @property {boolean} create=false
1972 * Since ComboButtons never allow creating custom choices, this property
1973 * is forcibly set to `false`.
1975 * @property {boolean} optional=false
1976 * Since ComboButtons must always select one action, this property is
1977 * forcibly set to `false`.
1979 * @property {Object<string, string>} [classes]
1980 * Specifies a mapping of choice values to CSS class names. If an action
1981 * choice is selected by the user and if a corresponding entry exists in
1982 * the `classes` object, the class names corresponding to the selected
1983 * value are set on the button element.
1985 * This is useful to apply different button styles, such as colors, to the
1986 * combined button depending on the selected action.
1988 * @property {function} [click]
1989 * Specifies a handler function to invoke when the user clicks the button.
1990 * This function will be called with the button DOM node as `this` context
1991 * and receive the DOM click event as first as well as the selected action
1992 * choice value as second argument.
1994 __init__: function(value
, choices
, options
) {
1995 this.super('__init__', [ value
, choices
, Object
.assign({
2005 render: function(/* ... */) {
2006 var node
= UIDropdown
.prototype.render
.apply(this, arguments
),
2007 val
= this.getValue();
2009 if (L
.isObject(this.options
.classes
) && this.options
.classes
.hasOwnProperty(val
))
2010 node
.setAttribute('class', 'cbi-dropdown ' + this.options
.classes
[val
]);
2016 handleClick: function(ev
) {
2017 var sb
= ev
.currentTarget
,
2020 if (sb
.hasAttribute('open') || L
.dom
.matches(t
, '.cbi-dropdown > span.open'))
2021 return UIDropdown
.prototype.handleClick
.apply(this, arguments
);
2023 if (this.options
.click
)
2024 return this.options
.click
.call(sb
, ev
, this.getValue());
2028 toggleItem: function(sb
/*, ... */) {
2029 var rv
= UIDropdown
.prototype.toggleItem
.apply(this, arguments
),
2030 val
= this.getValue();
2032 if (L
.isObject(this.options
.classes
) && this.options
.classes
.hasOwnProperty(val
))
2033 sb
.setAttribute('class', 'cbi-dropdown ' + this.options
.classes
[val
]);
2035 sb
.setAttribute('class', 'cbi-dropdown');
2042 * Instantiate a dynamic list widget.
2044 * @constructor DynamicList
2046 * @augments LuCI.ui.AbstractElement
2050 * The `DynamicList` class implements a widget which allows the user to specify
2051 * an arbitrary amount of input values, either from free formed text input or
2052 * from a set of predefined choices.
2054 * UI widget instances are usually not supposed to be created by view code
2055 * directly, instead they're implicitely created by `LuCI.form` when
2056 * instantiating CBI forms.
2058 * This class is automatically instantiated as part of `LuCI.ui`. To use it
2059 * in views, use `'require ui'` and refer to `ui.DynamicList`. To import it in
2060 * external JavaScript, use `L.require("ui").then(...)` and access the
2061 * `DynamicList` property of the class instance value.
2063 * @param {string|string[]} [value=null]
2064 * The initial input value(s).
2066 * @param {Object<string, *>} [choices]
2067 * Object containing the selectable choices of the widget. The object keys
2068 * serve as values for the different choices while the values are used as
2069 * choice labels. If omitted, no default choices are presented to the user,
2070 * instead a plain text input field is rendered allowing the user to add
2071 * arbitrary values to the dynamic list.
2073 * @param {LuCI.ui.DynamicList.InitOptions} [options]
2074 * Object describing the widget specific options to initialize the dynamic list.
2076 var UIDynamicList
= UIElement
.extend(/** @lends LuCI.ui.DynamicList.prototype */ {
2078 * In case choices are passed to the dynamic list contructor, the widget
2079 * supports the same properties as [Dropdown.InitOptions]{@link LuCI.ui.Dropdown.InitOptions}
2080 * but enforces specific values for some dropdown properties.
2082 * @typedef {LuCI.ui.Dropdown.InitOptions} InitOptions
2083 * @memberof LuCI.ui.DynamicList
2085 * @property {boolean} multiple=false
2086 * Since dynamic lists never allow selecting multiple choices when adding
2087 * another list item, this property is forcibly set to `false`.
2089 * @property {boolean} optional=true
2090 * Since dynamic lists use an embedded dropdown to present a list of
2091 * predefined choice values, the dropdown must be made optional to allow
2092 * it to remain unselected.
2094 __init__: function(values
, choices
, options
) {
2095 if (!Array
.isArray(values
))
2096 values
= (values
!= null && values
!= '') ? [ values
] : [];
2098 if (typeof(choices
) != 'object')
2101 this.values
= values
;
2102 this.choices
= choices
;
2103 this.options
= Object
.assign({}, options
, {
2110 render: function() {
2112 'id': this.options
.id
,
2113 'class': 'cbi-dynlist'
2114 }, E('div', { 'class': 'add-item' }));
2117 if (this.options
.placeholder
!= null)
2118 this.options
.select_placeholder
= this.options
.placeholder
;
2120 var cbox
= new UICombobox(null, this.choices
, this.options
);
2122 dl
.lastElementChild
.appendChild(cbox
.render());
2125 var inputEl
= E('input', {
2126 'id': this.options
.id
? 'widget.' + this.options
.id
: null,
2128 'class': 'cbi-input-text',
2129 'placeholder': this.options
.placeholder
2132 dl
.lastElementChild
.appendChild(inputEl
);
2133 dl
.lastElementChild
.appendChild(E('div', { 'class': 'btn cbi-button cbi-button-add' }, '+'));
2135 if (this.options
.datatype
|| this.options
.validate
)
2136 L
.ui
.addValidator(inputEl
, this.options
.datatype
|| 'string',
2137 true, this.options
.validate
, 'blur', 'keyup');
2140 for (var i
= 0; i
< this.values
.length
; i
++) {
2141 var label
= this.choices
? this.choices
[this.values
[i
]] : null;
2143 if (L
.dom
.elem(label
))
2144 label
= label
.cloneNode(true);
2146 this.addItem(dl
, this.values
[i
], label
);
2149 return this.bind(dl
);
2153 bind: function(dl
) {
2154 dl
.addEventListener('click', L
.bind(this.handleClick
, this));
2155 dl
.addEventListener('keydown', L
.bind(this.handleKeydown
, this));
2156 dl
.addEventListener('cbi-dropdown-change', L
.bind(this.handleDropdownChange
, this));
2160 this.setUpdateEvents(dl
, 'cbi-dynlist-change');
2161 this.setChangeEvents(dl
, 'cbi-dynlist-change');
2163 L
.dom
.bindClassInstance(dl
, this);
2169 addItem: function(dl
, value
, text
, flash
) {
2171 new_item
= E('div', { 'class': flash
? 'item flash' : 'item', 'tabindex': 0 }, [
2172 E('span', {}, [ text
|| value
]),
2175 'name': this.options
.name
,
2176 'value': value
})]);
2178 dl
.querySelectorAll('.item').forEach(function(item
) {
2182 var hidden
= item
.querySelector('input[type="hidden"]');
2184 if (hidden
&& hidden
.parentNode
!== item
)
2187 if (hidden
&& hidden
.value
=== value
)
2192 var ai
= dl
.querySelector('.add-item');
2193 ai
.parentNode
.insertBefore(new_item
, ai
);
2196 dl
.dispatchEvent(new CustomEvent('cbi-dynlist-change', {
2208 removeItem: function(dl
, item
) {
2209 var value
= item
.querySelector('input[type="hidden"]').value
;
2210 var sb
= dl
.querySelector('.cbi-dropdown');
2212 sb
.querySelectorAll('ul > li').forEach(function(li
) {
2213 if (li
.getAttribute('data-value') === value
) {
2214 if (li
.hasAttribute('dynlistcustom'))
2215 li
.parentNode
.removeChild(li
);
2217 li
.removeAttribute('unselectable');
2221 item
.parentNode
.removeChild(item
);
2223 dl
.dispatchEvent(new CustomEvent('cbi-dynlist-change', {
2235 handleClick: function(ev
) {
2236 var dl
= ev
.currentTarget
,
2237 item
= findParent(ev
.target
, '.item');
2240 this.removeItem(dl
, item
);
2242 else if (matchesElem(ev
.target
, '.cbi-button-add')) {
2243 var input
= ev
.target
.previousElementSibling
;
2244 if (input
.value
.length
&& !input
.classList
.contains('cbi-input-invalid')) {
2245 this.addItem(dl
, input
.value
, null, true);
2252 handleDropdownChange: function(ev
) {
2253 var dl
= ev
.currentTarget
,
2254 sbIn
= ev
.detail
.instance
,
2255 sbEl
= ev
.detail
.element
,
2256 sbVal
= ev
.detail
.value
;
2261 sbIn
.setValues(sbEl
, null);
2262 sbVal
.element
.setAttribute('unselectable', '');
2264 if (sbVal
.element
.hasAttribute('created')) {
2265 sbVal
.element
.removeAttribute('created');
2266 sbVal
.element
.setAttribute('dynlistcustom', '');
2269 var label
= sbVal
.text
;
2271 if (sbVal
.element
) {
2274 for (var i
= 0; i
< sbVal
.element
.childNodes
.length
; i
++)
2275 label
.appendChild(sbVal
.element
.childNodes
[i
].cloneNode(true));
2278 this.addItem(dl
, sbVal
.value
, label
, true);
2282 handleKeydown: function(ev
) {
2283 var dl
= ev
.currentTarget
,
2284 item
= findParent(ev
.target
, '.item');
2287 switch (ev
.keyCode
) {
2288 case 8: /* backspace */
2289 if (item
.previousElementSibling
)
2290 item
.previousElementSibling
.focus();
2292 this.removeItem(dl
, item
);
2295 case 46: /* delete */
2296 if (item
.nextElementSibling
) {
2297 if (item
.nextElementSibling
.classList
.contains('item'))
2298 item
.nextElementSibling
.focus();
2300 item
.nextElementSibling
.firstElementChild
.focus();
2303 this.removeItem(dl
, item
);
2307 else if (matchesElem(ev
.target
, '.cbi-input-text')) {
2308 switch (ev
.keyCode
) {
2309 case 13: /* enter */
2310 if (ev
.target
.value
.length
&& !ev
.target
.classList
.contains('cbi-input-invalid')) {
2311 this.addItem(dl
, ev
.target
.value
, null, true);
2312 ev
.target
.value
= '';
2317 ev
.preventDefault();
2324 getValue: function() {
2325 var items
= this.node
.querySelectorAll('.item > input[type="hidden"]'),
2326 input
= this.node
.querySelector('.add-item > input[type="text"]'),
2329 for (var i
= 0; i
< items
.length
; i
++)
2330 v
.push(items
[i
].value
);
2332 if (input
&& input
.value
!= null && input
.value
.match(/\S/) &&
2333 input
.classList
.contains('cbi-input-invalid') == false &&
2334 v
.filter(function(s
) { return s
== input
.value
}).length
== 0)
2335 v
.push(input
.value
);
2341 setValue: function(values
) {
2342 if (!Array
.isArray(values
))
2343 values
= (values
!= null && values
!= '') ? [ values
] : [];
2345 var items
= this.node
.querySelectorAll('.item');
2347 for (var i
= 0; i
< items
.length
; i
++)
2348 if (items
[i
].parentNode
=== this.node
)
2349 this.removeItem(this.node
, items
[i
]);
2351 for (var i
= 0; i
< values
.length
; i
++)
2352 this.addItem(this.node
, values
[i
],
2353 this.choices
? this.choices
[values
[i
]] : null);
2357 * Add new suggested choices to the dynamic list.
2359 * This function adds further choices to an existing dynamic list,
2360 * ignoring choice values which are already present.
2363 * @memberof LuCI.ui.DynamicList
2364 * @param {string[]} values
2365 * The choice values to add to the dynamic lists suggestion dropdown.
2367 * @param {Object<string, *>} labels
2368 * The choice label values to use when adding suggested choices. If no
2369 * label is found for a particular choice value, the value itself is used
2370 * as label text. Choice labels may be any valid value accepted by
2371 * {@link LuCI.dom#content}.
2373 addChoices: function(values
, labels
) {
2374 var dl
= this.node
.lastElementChild
.firstElementChild
;
2375 L
.dom
.callClassMethod(dl
, 'addChoices', values
, labels
);
2379 * Remove all existing choices from the dynamic list.
2381 * This function removes all preexisting suggested choices from the widget.
2384 * @memberof LuCI.ui.DynamicList
2386 clearChoices: function() {
2387 var dl
= this.node
.lastElementChild
.firstElementChild
;
2388 L
.dom
.callClassMethod(dl
, 'clearChoices');
2393 * Instantiate a hidden input field widget.
2395 * @constructor Hiddenfield
2397 * @augments LuCI.ui.AbstractElement
2401 * The `Hiddenfield` class implements an HTML `<input type="hidden">` field
2402 * which allows to store form data without exposing it to the user.
2404 * UI widget instances are usually not supposed to be created by view code
2405 * directly, instead they're implicitely created by `LuCI.form` when
2406 * instantiating CBI forms.
2408 * This class is automatically instantiated as part of `LuCI.ui`. To use it
2409 * in views, use `'require ui'` and refer to `ui.Hiddenfield`. To import it in
2410 * external JavaScript, use `L.require("ui").then(...)` and access the
2411 * `Hiddenfield` property of the class instance value.
2413 * @param {string|string[]} [value=null]
2414 * The initial input value.
2416 * @param {LuCI.ui.AbstractElement.InitOptions} [options]
2417 * Object describing the widget specific options to initialize the hidden input.
2419 var UIHiddenfield
= UIElement
.extend(/** @lends LuCI.ui.Hiddenfield.prototype */ {
2420 __init__: function(value
, options
) {
2422 this.options
= Object
.assign({
2428 render: function() {
2429 var hiddenEl
= E('input', {
2430 'id': this.options
.id
,
2435 return this.bind(hiddenEl
);
2439 bind: function(hiddenEl
) {
2440 this.node
= hiddenEl
;
2442 L
.dom
.bindClassInstance(hiddenEl
, this);
2448 getValue: function() {
2449 return this.node
.value
;
2453 setValue: function(value
) {
2454 this.node
.value
= value
;
2459 * Instantiate a file upload widget.
2461 * @constructor FileUpload
2463 * @augments LuCI.ui.AbstractElement
2467 * The `FileUpload` class implements a widget which allows the user to upload,
2468 * browse, select and delete files beneath a predefined remote directory.
2470 * UI widget instances are usually not supposed to be created by view code
2471 * directly, instead they're implicitely created by `LuCI.form` when
2472 * instantiating CBI forms.
2474 * This class is automatically instantiated as part of `LuCI.ui`. To use it
2475 * in views, use `'require ui'` and refer to `ui.FileUpload`. To import it in
2476 * external JavaScript, use `L.require("ui").then(...)` and access the
2477 * `FileUpload` property of the class instance value.
2479 * @param {string|string[]} [value=null]
2480 * The initial input value.
2482 * @param {LuCI.ui.DynamicList.InitOptions} [options]
2483 * Object describing the widget specific options to initialize the file
2486 var UIFileUpload
= UIElement
.extend(/** @lends LuCI.ui.FileUpload.prototype */ {
2488 * In addition to the [AbstractElement.InitOptions]{@link LuCI.ui.AbstractElement.InitOptions}
2489 * the following properties are recognized:
2491 * @typedef {LuCI.ui.AbstractElement.InitOptions} InitOptions
2492 * @memberof LuCI.ui.FileUpload
2494 * @property {boolean} [show_hidden=false]
2495 * Specifies whether hidden files should be displayed when browsing remote
2496 * files. Note that this is not a security feature, hidden files are always
2497 * present in the remote file listings received, this option merely controls
2498 * whether they're displayed or not.
2500 * @property {boolean} [enable_upload=true]
2501 * Specifies whether the widget allows the user to upload files. If set to
2502 * `false`, only existing files may be selected. Note that this is not a
2503 * security feature. Whether file upload requests are accepted remotely
2504 * depends on the ACL setup for the current session. This option merely
2505 * controls whether the upload controls are rendered or not.
2507 * @property {boolean} [enable_remove=true]
2508 * Specifies whether the widget allows the user to delete remove files.
2509 * If set to `false`, existing files may not be removed. Note that this is
2510 * not a security feature. Whether file delete requests are accepted
2511 * remotely depends on the ACL setup for the current session. This option
2512 * merely controls whether the file remove controls are rendered or not.
2514 * @property {string} [root_directory=/etc/luci-uploads]
2515 * Specifies the remote directory the upload and file browsing actions take
2516 * place in. Browsing to directories outside of the root directory is
2517 * prevented by the widget. Note that this is not a security feature.
2518 * Whether remote directories are browseable or not solely depends on the
2519 * ACL setup for the current session.
2521 __init__: function(value
, options
) {
2523 this.options
= Object
.assign({
2525 enable_upload
: true,
2526 enable_remove
: true,
2527 root_directory
: '/etc/luci-uploads'
2532 bind: function(browserEl
) {
2533 this.node
= browserEl
;
2535 this.setUpdateEvents(browserEl
, 'cbi-fileupload-select', 'cbi-fileupload-cancel');
2536 this.setChangeEvents(browserEl
, 'cbi-fileupload-select', 'cbi-fileupload-cancel');
2538 L
.dom
.bindClassInstance(browserEl
, this);
2544 render: function() {
2545 return L
.resolveDefault(this.value
!= null ? fs
.stat(this.value
) : null).then(L
.bind(function(stat
) {
2548 if (L
.isObject(stat
) && stat
.type
!= 'directory')
2551 if (this.stat
!= null)
2552 label
= [ this.iconForType(this.stat
.type
), ' %s (%1000mB)'.format(this.truncatePath(this.stat
.path
), this.stat
.size
) ];
2553 else if (this.value
!= null)
2554 label
= [ this.iconForType('file'), ' %s (%s)'.format(this.truncatePath(this.value
), _('File not accessible')) ];
2556 label
= [ _('Select file…') ];
2558 return this.bind(E('div', { 'id': this.options
.id
}, [
2561 'click': L
.ui
.createHandlerFn(this, 'handleFileBrowser')
2564 'class': 'cbi-filebrowser'
2568 'name': this.options
.name
,
2576 truncatePath: function(path
) {
2577 if (path
.length
> 50)
2578 path
= path
.substring(0, 25) + '…' + path
.substring(path
.length
- 25);
2584 iconForType: function(type
) {
2588 'src': L
.resource('cbi/link.gif'),
2589 'title': _('Symbolic link'),
2595 'src': L
.resource('cbi/folder.gif'),
2596 'title': _('Directory'),
2602 'src': L
.resource('cbi/file.gif'),
2610 canonicalizePath: function(path
) {
2611 return path
.replace(/\/{2,}/, '/')
2612 .replace(/\/\.(\/|$)/g, '/')
2613 .replace(/[^\/]+\/\.\.(\/|$)/g, '/')
2614 .replace(/\/$/, '');
2618 splitPath: function(path
) {
2619 var croot
= this.canonicalizePath(this.options
.root_directory
|| '/'),
2620 cpath
= this.canonicalizePath(path
|| '/');
2622 if (cpath
.length
<= croot
.length
)
2625 if (cpath
.charAt(croot
.length
) != '/')
2628 var parts
= cpath
.substring(croot
.length
+ 1).split(/\//);
2630 parts
.unshift(croot
);
2636 handleUpload: function(path
, list
, ev
) {
2637 var form
= ev
.target
.parentNode
,
2638 fileinput
= form
.querySelector('input[type="file"]'),
2639 nameinput
= form
.querySelector('input[type="text"]'),
2640 filename
= (nameinput
.value
!= null ? nameinput
.value
: '').trim();
2642 ev
.preventDefault();
2644 if (filename
== '' || filename
.match(/\//) || fileinput
.files
[0] == null)
2647 var existing
= list
.filter(function(e
) { return e
.name
== filename
})[0];
2649 if (existing
!= null && existing
.type
== 'directory')
2650 return alert(_('A directory with the same name already exists.'));
2651 else if (existing
!= null && !confirm(_('Overwrite existing file "%s" ?').format(filename
)))
2654 var data
= new FormData();
2656 data
.append('sessionid', L
.env
.sessionid
);
2657 data
.append('filename', path
+ '/' + filename
);
2658 data
.append('filedata', fileinput
.files
[0]);
2660 return L
.Request
.post(L
.env
.cgi_base
+ '/cgi-upload', data
, {
2661 progress
: L
.bind(function(btn
, ev
) {
2662 btn
.firstChild
.data
= '%.2f%%'.format((ev
.loaded
/ ev
.total
) * 100);
2664 }).then(L
.bind(function(path
, ev
, res
) {
2665 var reply
= res
.json();
2667 if (L
.isObject(reply
) && reply
.failure
)
2668 alert(_('Upload request failed: %s').format(reply
.message
));
2670 return this.handleSelect(path
, null, ev
);
2671 }, this, path
, ev
));
2675 handleDelete: function(path
, fileStat
, ev
) {
2676 var parent
= path
.replace(/\/[^\/]+$/, '') || '/',
2677 name
= path
.replace(/^.+\//, ''),
2680 ev
.preventDefault();
2682 if (fileStat
.type
== 'directory')
2683 msg
= _('Do you really want to recursively delete the directory "%s" ?').format(name
);
2685 msg
= _('Do you really want to delete "%s" ?').format(name
);
2688 var button
= this.node
.firstElementChild
,
2689 hidden
= this.node
.lastElementChild
;
2691 if (path
== hidden
.value
) {
2692 L
.dom
.content(button
, _('Select file…'));
2696 return fs
.remove(path
).then(L
.bind(function(parent
, ev
) {
2697 return this.handleSelect(parent
, null, ev
);
2698 }, this, parent
, ev
)).catch(function(err
) {
2699 alert(_('Delete request failed: %s').format(err
.message
));
2705 renderUpload: function(path
, list
) {
2706 if (!this.options
.enable_upload
)
2712 'class': 'btn cbi-button-positive',
2713 'click': function(ev
) {
2714 var uploadForm
= ev
.target
.nextElementSibling
,
2715 fileInput
= uploadForm
.querySelector('input[type="file"]');
2717 ev
.target
.style
.display
= 'none';
2718 uploadForm
.style
.display
= '';
2721 }, _('Upload file…')),
2722 E('div', { 'class': 'upload', 'style': 'display:none' }, [
2725 'style': 'display:none',
2726 'change': function(ev
) {
2727 var nameinput
= ev
.target
.parentNode
.querySelector('input[type="text"]'),
2728 uploadbtn
= ev
.target
.parentNode
.querySelector('button.cbi-button-save');
2730 nameinput
.value
= ev
.target
.value
.replace(/^.+[\/\\]/, '');
2731 uploadbtn
.disabled
= false;
2736 'click': function(ev
) {
2737 ev
.preventDefault();
2738 ev
.target
.previousElementSibling
.click();
2740 }, [ _('Browse…') ]),
2741 E('div', {}, E('input', { 'type': 'text', 'placeholder': _('Filename') })),
2743 'class': 'btn cbi-button-save',
2744 'click': L
.ui
.createHandlerFn(this, 'handleUpload', path
, list
),
2746 }, [ _('Upload file') ])
2752 renderListing: function(container
, path
, list
) {
2753 var breadcrumb
= E('p'),
2756 list
.sort(function(a
, b
) {
2757 var isDirA
= (a
.type
== 'directory'),
2758 isDirB
= (b
.type
== 'directory');
2760 if (isDirA
!= isDirB
)
2761 return isDirA
< isDirB
;
2763 return a
.name
> b
.name
;
2766 for (var i
= 0; i
< list
.length
; i
++) {
2767 if (!this.options
.show_hidden
&& list
[i
].name
.charAt(0) == '.')
2770 var entrypath
= this.canonicalizePath(path
+ '/' + list
[i
].name
),
2771 selected
= (entrypath
== this.node
.lastElementChild
.value
),
2772 mtime
= new Date(list
[i
].mtime
* 1000);
2774 rows
.appendChild(E('li', [
2775 E('div', { 'class': 'name' }, [
2776 this.iconForType(list
[i
].type
),
2780 'style': selected
? 'font-weight:bold' : null,
2781 'click': L
.ui
.createHandlerFn(this, 'handleSelect',
2782 entrypath
, list
[i
].type
!= 'directory' ? list
[i
] : null)
2783 }, '%h'.format(list
[i
].name
))
2785 E('div', { 'class': 'mtime hide-xs' }, [
2786 ' %04d-%02d-%02d %02d:%02d:%02d '.format(
2787 mtime
.getFullYear(),
2788 mtime
.getMonth() + 1,
2795 selected
? E('button', {
2797 'click': L
.ui
.createHandlerFn(this, 'handleReset')
2798 }, [ _('Deselect') ]) : '',
2799 this.options
.enable_remove
? E('button', {
2800 'class': 'btn cbi-button-negative',
2801 'click': L
.ui
.createHandlerFn(this, 'handleDelete', entrypath
, list
[i
])
2802 }, [ _('Delete') ]) : ''
2807 if (!rows
.firstElementChild
)
2808 rows
.appendChild(E('em', _('No entries in this directory')));
2810 var dirs
= this.splitPath(path
),
2813 for (var i
= 0; i
< dirs
.length
; i
++) {
2814 cur
= cur
? cur
+ '/' + dirs
[i
] : dirs
[i
];
2815 L
.dom
.append(breadcrumb
, [
2819 'click': L
.ui
.createHandlerFn(this, 'handleSelect', cur
|| '/', null)
2820 }, dirs
[i
] != '' ? '%h'.format(dirs
[i
]) : E('em', '(root)')),
2824 L
.dom
.content(container
, [
2827 E('div', { 'class': 'right' }, [
2828 this.renderUpload(path
, list
),
2832 'click': L
.ui
.createHandlerFn(this, 'handleCancel')
2839 handleCancel: function(ev
) {
2840 var button
= this.node
.firstElementChild
,
2841 browser
= button
.nextElementSibling
;
2843 browser
.classList
.remove('open');
2844 button
.style
.display
= '';
2846 this.node
.dispatchEvent(new CustomEvent('cbi-fileupload-cancel', {}));
2848 ev
.preventDefault();
2852 handleReset: function(ev
) {
2853 var button
= this.node
.firstElementChild
,
2854 hidden
= this.node
.lastElementChild
;
2857 L
.dom
.content(button
, _('Select file…'));
2859 this.handleCancel(ev
);
2863 handleSelect: function(path
, fileStat
, ev
) {
2864 var browser
= L
.dom
.parent(ev
.target
, '.cbi-filebrowser'),
2865 ul
= browser
.querySelector('ul');
2867 if (fileStat
== null) {
2868 L
.dom
.content(ul
, E('em', { 'class': 'spinning' }, _('Loading directory contents…')));
2869 L
.resolveDefault(fs
.list(path
), []).then(L
.bind(this.renderListing
, this, browser
, path
));
2872 var button
= this.node
.firstElementChild
,
2873 hidden
= this.node
.lastElementChild
;
2875 path
= this.canonicalizePath(path
);
2877 L
.dom
.content(button
, [
2878 this.iconForType(fileStat
.type
),
2879 ' %s (%1000mB)'.format(this.truncatePath(path
), fileStat
.size
)
2882 browser
.classList
.remove('open');
2883 button
.style
.display
= '';
2884 hidden
.value
= path
;
2886 this.stat
= Object
.assign({ path
: path
}, fileStat
);
2887 this.node
.dispatchEvent(new CustomEvent('cbi-fileupload-select', { detail
: this.stat
}));
2892 handleFileBrowser: function(ev
) {
2893 var button
= ev
.target
,
2894 browser
= button
.nextElementSibling
,
2895 path
= this.stat
? this.stat
.path
.replace(/\/[^\/]+$/, '') : (this.options
.initial_directory
|| this.options
.root_directory
);
2897 if (path
.indexOf(this.options
.root_directory
) != 0)
2898 path
= this.options
.root_directory
;
2900 ev
.preventDefault();
2902 return L
.resolveDefault(fs
.list(path
), []).then(L
.bind(function(button
, browser
, path
, list
) {
2903 document
.querySelectorAll('.cbi-filebrowser.open').forEach(function(browserEl
) {
2904 L
.dom
.findClassInstance(browserEl
).handleCancel(ev
);
2907 button
.style
.display
= 'none';
2908 browser
.classList
.add('open');
2910 return this.renderListing(browser
, path
, list
);
2911 }, this, button
, browser
, path
));
2915 getValue: function() {
2916 return this.node
.lastElementChild
.value
;
2920 setValue: function(value
) {
2921 this.node
.lastElementChild
.value
= value
;
2931 * Provides high level UI helper functionality.
2932 * To import the class in views, use `'require ui'`, to import it in
2933 * external JavaScript, use `L.require("ui").then(...)`.
2935 return L
.Class
.extend(/** @lends LuCI.ui.prototype */ {
2936 __init__: function() {
2937 modalDiv
= document
.body
.appendChild(
2938 L
.dom
.create('div', { id
: 'modal_overlay' },
2939 L
.dom
.create('div', { class: 'modal', role
: 'dialog', 'aria-modal': true })));
2941 tooltipDiv
= document
.body
.appendChild(
2942 L
.dom
.create('div', { class: 'cbi-tooltip' }));
2944 /* setup old aliases */
2945 L
.showModal
= this.showModal
;
2946 L
.hideModal
= this.hideModal
;
2947 L
.showTooltip
= this.showTooltip
;
2948 L
.hideTooltip
= this.hideTooltip
;
2949 L
.itemlist
= this.itemlist
;
2951 document
.addEventListener('mouseover', this.showTooltip
.bind(this), true);
2952 document
.addEventListener('mouseout', this.hideTooltip
.bind(this), true);
2953 document
.addEventListener('focus', this.showTooltip
.bind(this), true);
2954 document
.addEventListener('blur', this.hideTooltip
.bind(this), true);
2956 document
.addEventListener('luci-loaded', this.tabs
.init
.bind(this.tabs
));
2957 document
.addEventListener('luci-loaded', this.changes
.init
.bind(this.changes
));
2958 document
.addEventListener('uci-loaded', this.changes
.init
.bind(this.changes
));
2962 * Display a modal overlay dialog with the specified contents.
2964 * The modal overlay dialog covers the current view preventing interaction
2965 * with the underlying view contents. Only one modal dialog instance can
2966 * be opened. Invoking showModal() while a modal dialog is already open will
2967 * replace the open dialog with a new one having the specified contents.
2969 * Additional CSS class names may be passed to influence the appearence of
2970 * the dialog. Valid values for the classes depend on the underlying theme.
2972 * @see LuCI.dom.content
2974 * @param {string} [title]
2975 * The title of the dialog. If `null`, no title element will be rendered.
2977 * @param {*} contents
2978 * The contents to add to the modal dialog. This should be a DOM node or
2979 * a document fragment in most cases. The value is passed as-is to the
2980 * `L.dom.content()` function - refer to its documentation for applicable
2983 * @param {...string} [classes]
2984 * A number of extra CSS class names which are set on the modal dialog
2988 * Returns a DOM Node representing the modal dialog element.
2990 showModal: function(title
, children
/* , ... */) {
2991 var dlg
= modalDiv
.firstElementChild
;
2993 dlg
.setAttribute('class', 'modal');
2995 for (var i
= 2; i
< arguments
.length
; i
++)
2996 dlg
.classList
.add(arguments
[i
]);
2998 L
.dom
.content(dlg
, L
.dom
.create('h4', {}, title
));
2999 L
.dom
.append(dlg
, children
);
3001 document
.body
.classList
.add('modal-overlay-active');
3007 * Close the open modal overlay dialog.
3009 * This function will close an open modal dialog and restore the normal view
3010 * behaviour. It has no effect if no modal dialog is currently open.
3012 * Note that this function is stand-alone, it does not rely on `this` and
3013 * will not invoke other class functions so it suitable to be used as event
3014 * handler as-is without the need to bind it first.
3016 hideModal: function() {
3017 document
.body
.classList
.remove('modal-overlay-active');
3021 showTooltip: function(ev
) {
3022 var target
= findParent(ev
.target
, '[data-tooltip]');
3027 if (tooltipTimeout
!== null) {
3028 window
.clearTimeout(tooltipTimeout
);
3029 tooltipTimeout
= null;
3032 var rect
= target
.getBoundingClientRect(),
3033 x
= rect
.left
+ window
.pageXOffset
,
3034 y
= rect
.top
+ rect
.height
+ window
.pageYOffset
;
3036 tooltipDiv
.className
= 'cbi-tooltip';
3037 tooltipDiv
.innerHTML
= '▲ ';
3038 tooltipDiv
.firstChild
.data
+= target
.getAttribute('data-tooltip');
3040 if (target
.hasAttribute('data-tooltip-style'))
3041 tooltipDiv
.classList
.add(target
.getAttribute('data-tooltip-style'));
3043 if ((y
+ tooltipDiv
.offsetHeight
) > (window
.innerHeight
+ window
.pageYOffset
)) {
3044 y
-= (tooltipDiv
.offsetHeight
+ target
.offsetHeight
);
3045 tooltipDiv
.firstChild
.data
= '▼ ' + tooltipDiv
.firstChild
.data
.substr(2);
3048 tooltipDiv
.style
.top
= y
+ 'px';
3049 tooltipDiv
.style
.left
= x
+ 'px';
3050 tooltipDiv
.style
.opacity
= 1;
3052 tooltipDiv
.dispatchEvent(new CustomEvent('tooltip-open', {
3054 detail
: { target
: target
}
3059 hideTooltip: function(ev
) {
3060 if (ev
.target
=== tooltipDiv
|| ev
.relatedTarget
=== tooltipDiv
||
3061 tooltipDiv
.contains(ev
.target
) || tooltipDiv
.contains(ev
.relatedTarget
))
3064 if (tooltipTimeout
!== null) {
3065 window
.clearTimeout(tooltipTimeout
);
3066 tooltipTimeout
= null;
3069 tooltipDiv
.style
.opacity
= 0;
3070 tooltipTimeout
= window
.setTimeout(function() { tooltipDiv
.removeAttribute('style'); }, 250);
3072 tooltipDiv
.dispatchEvent(new CustomEvent('tooltip-close', { bubbles
: true }));
3076 * Add a notification banner at the top of the current view.
3078 * A notification banner is an alert message usually displayed at the
3079 * top of the current view, spanning the entire availibe width.
3080 * Notification banners will stay in place until dismissed by the user.
3081 * Multiple banners may be shown at the same time.
3083 * Additional CSS class names may be passed to influence the appearence of
3084 * the banner. Valid values for the classes depend on the underlying theme.
3086 * @see LuCI.dom.content
3088 * @param {string} [title]
3089 * The title of the notification banner. If `null`, no title element
3092 * @param {*} contents
3093 * The contents to add to the notification banner. This should be a DOM
3094 * node or a document fragment in most cases. The value is passed as-is
3095 * to the `L.dom.content()` function - refer to its documentation for
3096 * applicable values.
3098 * @param {...string} [classes]
3099 * A number of extra CSS class names which are set on the notification
3103 * Returns a DOM Node representing the notification banner element.
3105 addNotification: function(title
, children
/*, ... */) {
3106 var mc
= document
.querySelector('#maincontent') || document
.body
;
3107 var msg
= E('div', {
3108 'class': 'alert-message fade-in',
3109 'style': 'display:flex',
3110 'transitionend': function(ev
) {
3111 var node
= ev
.currentTarget
;
3112 if (node
.parentNode
&& node
.classList
.contains('fade-out'))
3113 node
.parentNode
.removeChild(node
);
3116 E('div', { 'style': 'flex:10' }),
3117 E('div', { 'style': 'flex:1 1 auto; display:flex' }, [
3120 'style': 'margin-left:auto; margin-top:auto',
3121 'click': function(ev
) {
3122 L
.dom
.parent(ev
.target
, '.alert-message').classList
.add('fade-out');
3125 }, [ _('Dismiss') ])
3130 L
.dom
.append(msg
.firstElementChild
, E('h4', {}, title
));
3132 L
.dom
.append(msg
.firstElementChild
, children
);
3134 for (var i
= 2; i
< arguments
.length
; i
++)
3135 msg
.classList
.add(arguments
[i
]);
3137 mc
.insertBefore(msg
, mc
.firstElementChild
);
3143 * Display or update an header area indicator.
3145 * An indicator is a small label displayed in the header area of the screen
3146 * providing few amounts of status information such as item counts or state
3147 * toggle indicators.
3149 * Multiple indicators may be shown at the same time and indicator labels
3150 * may be made clickable to display extended information or to initiate
3153 * Indicators can either use a default `active` or a less accented `inactive`
3154 * style which is useful for indicators representing state toggles.
3156 * @param {string} id
3157 * The ID of the indicator. If an indicator with the given ID already exists,
3158 * it is updated with the given label and style.
3160 * @param {string} label
3161 * The text to display in the indicator label.
3163 * @param {function} [handler]
3164 * A handler function to invoke when the indicator label is clicked/touched
3165 * by the user. If omitted, the indicator is not clickable/touchable.
3167 * Note that this parameter only applies to new indicators, when updating
3168 * existing labels it is ignored.
3170 * @param {string} [style=active]
3171 * The indicator style to use. May be either `active` or `inactive`.
3173 * @returns {boolean}
3174 * Returns `true` when the indicator has been updated or `false` when no
3175 * changes were made.
3177 showIndicator: function(id
, label
, handler
, style
) {
3178 if (indicatorDiv
== null) {
3179 indicatorDiv
= document
.body
.querySelector('#indicators');
3181 if (indicatorDiv
== null)
3185 var handlerFn
= (typeof(handler
) == 'function') ? handler
: null,
3186 indicatorElem
= indicatorDiv
.querySelector('span[data-indicator="%s"]'.format(id
)) ||
3187 indicatorDiv
.appendChild(E('span', {
3188 'data-indicator': id
,
3189 'data-clickable': handlerFn
? true : null,
3193 if (label
== indicatorElem
.firstChild
.data
&& style
== indicatorElem
.getAttribute('data-style'))
3196 indicatorElem
.firstChild
.data
= label
;
3197 indicatorElem
.setAttribute('data-style', (style
== 'inactive') ? 'inactive' : 'active');
3202 * Remove an header area indicator.
3204 * This function removes the given indicator label from the header indicator
3205 * area. When the given indicator is not found, this function does nothing.
3207 * @param {string} id
3208 * The ID of the indicator to remove.
3210 * @returns {boolean}
3211 * Returns `true` when the indicator has been removed or `false` when the
3212 * requested indicator was not found.
3214 hideIndicator: function(id
) {
3215 var indicatorElem
= indicatorDiv
? indicatorDiv
.querySelector('span[data-indicator="%s"]'.format(id
)) : null;
3217 if (indicatorElem
== null)
3220 indicatorDiv
.removeChild(indicatorElem
);
3225 * Formats a series of label/value pairs into list-like markup.
3227 * This function transforms a flat array of alternating label and value
3228 * elements into a list-like markup, using the values in `separators` as
3229 * separators and appends the resulting nodes to the given parent DOM node.
3231 * Each label is suffixed with `: ` and wrapped into a `<strong>` tag, the
3232 * `<strong>` element and the value corresponding to the label are
3233 * subsequently wrapped into a `<span class="nowrap">` element.
3235 * The resulting `<span>` element tuples are joined by the given separators
3236 * to form the final markup which is appened to the given parent DOM node.
3238 * @param {Node} node
3239 * The parent DOM node to append the markup to. Any previous child elements
3242 * @param {Array<*>} items
3243 * An alternating array of labels and values. The label values will be
3244 * converted to plain strings, the values are used as-is and may be of
3245 * any type accepted by `LuCI.dom.content()`.
3247 * @param {*|Array<*>} [separators=[E('br')]]
3248 * A single value or an array of separator values to separate each
3249 * label/value pair with. The function will cycle through the separators
3250 * when joining the pairs. If omitted, the default separator is a sole HTML
3251 * `<br>` element. Separator values are used as-is and may be of any type
3252 * accepted by `LuCI.dom.content()`.
3255 * Returns the parent DOM node the formatted markup has been added to.
3257 itemlist: function(node
, items
, separators
) {
3260 if (!Array
.isArray(separators
))
3261 separators
= [ separators
|| E('br') ];
3263 for (var i
= 0; i
< items
.length
; i
+= 2) {
3264 if (items
[i
+1] !== null && items
[i
+1] !== undefined) {
3265 var sep
= separators
[(i
/2) % separators
.length
],
3268 children
.push(E('span', { class: 'nowrap' }, [
3269 items
[i
] ? E('strong', items
[i
] + ': ') : '',
3273 if ((i
+2) < items
.length
)
3274 children
.push(L
.dom
.elem(sep
) ? sep
.cloneNode(true) : sep
);
3278 L
.dom
.content(node
, children
);
3289 * The `tabs` class handles tab menu groups used throughout the view area.
3290 * It takes care of setting up tab groups, tracking their state and handling
3293 * This class is automatically instantiated as part of `LuCI.ui`. To use it
3294 * in views, use `'require ui'` and refer to `ui.tabs`. To import it in
3295 * external JavaScript, use `L.require("ui").then(...)` and access the
3296 * `tabs` property of the class instance value.
3298 tabs
: L
.Class
.singleton(/* @lends LuCI.ui.tabs.prototype */ {
3301 var groups
= [], prevGroup
= null, currGroup
= null;
3303 document
.querySelectorAll('[data-tab]').forEach(function(tab
) {
3304 var parent
= tab
.parentNode
;
3306 if (L
.dom
.matches(tab
, 'li') && L
.dom
.matches(parent
, 'ul.cbi-tabmenu'))
3309 if (!parent
.hasAttribute('data-tab-group'))
3310 parent
.setAttribute('data-tab-group', groups
.length
);
3312 currGroup
= +parent
.getAttribute('data-tab-group');
3314 if (currGroup
!== prevGroup
) {
3315 prevGroup
= currGroup
;
3317 if (!groups
[currGroup
])
3318 groups
[currGroup
] = [];
3321 groups
[currGroup
].push(tab
);
3324 for (var i
= 0; i
< groups
.length
; i
++)
3325 this.initTabGroup(groups
[i
]);
3327 document
.addEventListener('dependency-update', this.updateTabs
.bind(this));
3333 * Initializes a new tab group from the given tab pane collection.
3335 * This function cycles through the given tab pane DOM nodes, extracts
3336 * their tab IDs, titles and active states, renders a corresponding
3337 * tab menu and prepends it to the tab panes common parent DOM node.
3339 * The tab menu labels will be set to the value of the `data-tab-title`
3340 * attribute of each corresponding pane. The last pane with the
3341 * `data-tab-active` attribute set to `true` will be selected by default.
3343 * If no pane is marked as active, the first one will be preselected.
3346 * @memberof LuCI.ui.tabs
3347 * @param {Array<Node>|NodeList} panes
3348 * A collection of tab panes to build a tab group menu for. May be a
3349 * plain array of DOM nodes or a NodeList collection, such as the result
3350 * of a `querySelectorAll()` call or the `.childNodes` property of a
3353 initTabGroup: function(panes
) {
3354 if (typeof(panes
) != 'object' || !('length' in panes
) || panes
.length
=== 0)
3357 var menu
= E('ul', { 'class': 'cbi-tabmenu' }),
3358 group
= panes
[0].parentNode
,
3359 groupId
= +group
.getAttribute('data-tab-group'),
3362 if (group
.getAttribute('data-initialized') === 'true')
3365 for (var i
= 0, pane
; pane
= panes
[i
]; i
++) {
3366 var name
= pane
.getAttribute('data-tab'),
3367 title
= pane
.getAttribute('data-tab-title'),
3368 active
= pane
.getAttribute('data-tab-active') === 'true';
3370 menu
.appendChild(E('li', {
3371 'style': this.isEmptyPane(pane
) ? 'display:none' : null,
3372 'class': active
? 'cbi-tab' : 'cbi-tab-disabled',
3376 'click': this.switchTab
.bind(this)
3383 group
.parentNode
.insertBefore(menu
, group
);
3384 group
.setAttribute('data-initialized', true);
3386 if (selected
=== null) {
3387 selected
= this.getActiveTabId(panes
[0]);
3389 if (selected
< 0 || selected
>= panes
.length
|| this.isEmptyPane(panes
[selected
])) {
3390 for (var i
= 0; i
< panes
.length
; i
++) {
3391 if (!this.isEmptyPane(panes
[i
])) {
3398 menu
.childNodes
[selected
].classList
.add('cbi-tab');
3399 menu
.childNodes
[selected
].classList
.remove('cbi-tab-disabled');
3400 panes
[selected
].setAttribute('data-tab-active', 'true');
3402 this.setActiveTabId(panes
[selected
], selected
);
3405 panes
[selected
].dispatchEvent(new CustomEvent('cbi-tab-active', {
3406 detail
: { tab
: panes
[selected
].getAttribute('data-tab') }
3409 this.updateTabs(group
);
3413 * Checks whether the given tab pane node is empty.
3416 * @memberof LuCI.ui.tabs
3417 * @param {Node} pane
3418 * The tab pane to check.
3420 * @returns {boolean}
3421 * Returns `true` if the pane is empty, else `false`.
3423 isEmptyPane: function(pane
) {
3424 return L
.dom
.isEmpty(pane
, function(n
) { return n
.classList
.contains('cbi-tab-descr') });
3428 getPathForPane: function(pane
) {
3429 var path
= [], node
= null;
3431 for (node
= pane
? pane
.parentNode
: null;
3432 node
!= null && node
.hasAttribute
!= null;
3433 node
= node
.parentNode
)
3435 if (node
.hasAttribute('data-tab'))
3436 path
.unshift(node
.getAttribute('data-tab'));
3437 else if (node
.hasAttribute('data-section-id'))
3438 path
.unshift(node
.getAttribute('data-section-id'));
3441 return path
.join('/');
3445 getActiveTabState: function() {
3446 var page
= document
.body
.getAttribute('data-page');
3449 var val
= JSON
.parse(window
.sessionStorage
.getItem('tab'));
3450 if (val
.page
=== page
&& L
.isObject(val
.paths
))
3455 window
.sessionStorage
.removeItem('tab');
3456 return { page
: page
, paths
: {} };
3460 getActiveTabId: function(pane
) {
3461 var path
= this.getPathForPane(pane
);
3462 return +this.getActiveTabState().paths
[path
] || 0;
3466 setActiveTabId: function(pane
, tabIndex
) {
3467 var path
= this.getPathForPane(pane
);
3470 var state
= this.getActiveTabState();
3471 state
.paths
[path
] = tabIndex
;
3473 window
.sessionStorage
.setItem('tab', JSON
.stringify(state
));
3475 catch (e
) { return false; }
3481 updateTabs: function(ev
, root
) {
3482 (root
|| document
).querySelectorAll('[data-tab-title]').forEach(L
.bind(function(pane
) {
3483 var menu
= pane
.parentNode
.previousElementSibling
,
3484 tab
= menu
? menu
.querySelector('[data-tab="%s"]'.format(pane
.getAttribute('data-tab'))) : null,
3485 n_errors
= pane
.querySelectorAll('.cbi-input-invalid').length
;
3490 if (this.isEmptyPane(pane
)) {
3491 tab
.style
.display
= 'none';
3492 tab
.classList
.remove('flash');
3494 else if (tab
.style
.display
=== 'none') {
3495 tab
.style
.display
= '';
3496 requestAnimationFrame(function() { tab
.classList
.add('flash') });
3500 tab
.setAttribute('data-errors', n_errors
);
3501 tab
.setAttribute('data-tooltip', _('%d invalid field(s)').format(n_errors
));
3502 tab
.setAttribute('data-tooltip-style', 'error');
3505 tab
.removeAttribute('data-errors');
3506 tab
.removeAttribute('data-tooltip');
3512 switchTab: function(ev
) {
3513 var tab
= ev
.target
.parentNode
,
3514 name
= tab
.getAttribute('data-tab'),
3515 menu
= tab
.parentNode
,
3516 group
= menu
.nextElementSibling
,
3517 groupId
= +group
.getAttribute('data-tab-group'),
3520 ev
.preventDefault();
3522 if (!tab
.classList
.contains('cbi-tab-disabled'))
3525 menu
.querySelectorAll('[data-tab]').forEach(function(tab
) {
3526 tab
.classList
.remove('cbi-tab');
3527 tab
.classList
.remove('cbi-tab-disabled');
3529 tab
.getAttribute('data-tab') === name
? 'cbi-tab' : 'cbi-tab-disabled');
3532 group
.childNodes
.forEach(function(pane
) {
3533 if (L
.dom
.matches(pane
, '[data-tab]')) {
3534 if (pane
.getAttribute('data-tab') === name
) {
3535 pane
.setAttribute('data-tab-active', 'true');
3536 pane
.dispatchEvent(new CustomEvent('cbi-tab-active', { detail
: { tab
: name
} }));
3537 L
.ui
.tabs
.setActiveTabId(pane
, index
);
3540 pane
.setAttribute('data-tab-active', 'false');
3550 * @typedef {Object} FileUploadReply
3553 * @property {string} name - Name of the uploaded file without directory components
3554 * @property {number} size - Size of the uploaded file in bytes
3555 * @property {string} checksum - The MD5 checksum of the received file data
3556 * @property {string} sha256sum - The SHA256 checksum of the received file data
3560 * Display a modal file upload prompt.
3562 * This function opens a modal dialog prompting the user to select and
3563 * upload a file to a predefined remote destination path.
3565 * @param {string} path
3566 * The remote file path to upload the local file to.
3568 * @param {Node} [progessStatusNode]
3569 * An optional DOM text node whose content text is set to the progress
3570 * percentage value during file upload.
3572 * @returns {Promise<LuCI.ui.FileUploadReply>}
3573 * Returns a promise resolving to a file upload status object on success
3574 * or rejecting with an error in case the upload failed or has been
3575 * cancelled by the user.
3577 uploadFile: function(path
, progressStatusNode
) {
3578 return new Promise(function(resolveFn
, rejectFn
) {
3579 L
.ui
.showModal(_('Uploading file…'), [
3580 E('p', _('Please select the file to upload.')),
3581 E('div', { 'style': 'display:flex' }, [
3582 E('div', { 'class': 'left', 'style': 'flex:1' }, [
3585 style
: 'display:none',
3586 change: function(ev
) {
3587 var modal
= L
.dom
.parent(ev
.target
, '.modal'),
3588 body
= modal
.querySelector('p'),
3589 upload
= modal
.querySelector('.cbi-button-action.important'),
3590 file
= ev
.currentTarget
.files
[0];
3595 L
.dom
.content(body
, [
3597 E('li', {}, [ '%s: %s'.format(_('Name'), file
.name
.replace(/^.*[\\\/]/, '')) ]),
3598 E('li', {}, [ '%s: %1024mB'.format(_('Size'), file
.size
) ])
3602 upload
.disabled
= false;
3608 'click': function(ev
) {
3609 ev
.target
.previousElementSibling
.click();
3611 }, [ _('Browse…') ])
3613 E('div', { 'class': 'right', 'style': 'flex:1' }, [
3616 'click': function() {
3618 rejectFn(new Error('Upload has been cancelled'));
3620 }, [ _('Cancel') ]),
3623 'class': 'btn cbi-button-action important',
3625 'click': function(ev
) {
3626 var input
= L
.dom
.parent(ev
.target
, '.modal').querySelector('input[type="file"]');
3628 if (!input
.files
[0])
3631 var progress
= E('div', { 'class': 'cbi-progressbar', 'title': '0%' }, E('div', { 'style': 'width:0' }));
3633 L
.ui
.showModal(_('Uploading file…'), [ progress
]);
3635 var data
= new FormData();
3637 data
.append('sessionid', rpc
.getSessionID());
3638 data
.append('filename', path
);
3639 data
.append('filedata', input
.files
[0]);
3641 var filename
= input
.files
[0].name
;
3643 L
.Request
.post(L
.env
.cgi_base
+ '/cgi-upload', data
, {
3645 progress: function(pev
) {
3646 var percent
= (pev
.loaded
/ pev
.total
) * 100;
3648 if (progressStatusNode
)
3649 progressStatusNode
.data
= '%.2f%%'.format(percent
);
3651 progress
.setAttribute('title', '%.2f%%'.format(percent
));
3652 progress
.firstElementChild
.style
.width
= '%.2f%%'.format(percent
);
3654 }).then(function(res
) {
3655 var reply
= res
.json();
3659 if (L
.isObject(reply
) && reply
.failure
) {
3660 L
.ui
.addNotification(null, E('p', _('Upload request failed: %s').format(reply
.message
)));
3661 rejectFn(new Error(reply
.failure
));
3664 reply
.name
= filename
;
3680 * Perform a device connectivity test.
3682 * Attempt to fetch a well known ressource from the remote device via HTTP
3683 * in order to test connectivity. This function is mainly useful to wait
3684 * for the router to come back online after a reboot or reconfiguration.
3686 * @param {string} [proto=http]
3687 * The protocol to use for fetching the resource. May be either `http`
3688 * (the default) or `https`.
3690 * @param {string} [host=window.location.host]
3691 * Override the host address to probe. By default the current host as seen
3692 * in the address bar is probed.
3694 * @returns {Promise<Event>}
3695 * Returns a promise resolving to a `load` event in case the device is
3696 * reachable or rejecting with an `error` event in case it is not reachable
3697 * or rejecting with `null` when the connectivity check timed out.
3699 pingDevice: function(proto
, ipaddr
) {
3700 var target
= '%s://%s%s?%s'.format(proto
|| 'http', ipaddr
|| window
.location
.host
, L
.resource('icons/loading.gif'), Math
.random());
3702 return new Promise(function(resolveFn
, rejectFn
) {
3703 var img
= new Image();
3705 img
.onload
= resolveFn
;
3706 img
.onerror
= rejectFn
;
3708 window
.setTimeout(rejectFn
, 1000);
3715 * Wait for device to come back online and reconnect to it.
3717 * Poll each given hostname or IP address and navigate to it as soon as
3718 * one of the addresses becomes reachable.
3720 * @param {...string} [hosts=[window.location.host]]
3721 * The list of IP addresses and host names to check for reachability.
3722 * If omitted, the current value of `window.location.host` is used by
3725 awaitReconnect: function(/* ... */) {
3726 var ipaddrs
= arguments
.length
? arguments
: [ window
.location
.host
];
3728 window
.setTimeout(L
.bind(function() {
3729 L
.Poll
.add(L
.bind(function() {
3730 var tasks
= [], reachable
= false;
3732 for (var i
= 0; i
< 2; i
++)
3733 for (var j
= 0; j
< ipaddrs
.length
; j
++)
3734 tasks
.push(this.pingDevice(i
? 'https' : 'http', ipaddrs
[j
])
3735 .then(function(ev
) { reachable
= ev
.target
.src
.replace(/^(https?:\/\/[^\/]+).*$/, '$1/') }, function() {}));
3737 return Promise
.all(tasks
).then(function() {
3740 window
.location
= reachable
;
3753 * The `changes` class encapsulates logic for visualizing, applying,
3754 * confirming and reverting staged UCI changesets.
3756 * This class is automatically instantiated as part of `LuCI.ui`. To use it
3757 * in views, use `'require ui'` and refer to `ui.changes`. To import it in
3758 * external JavaScript, use `L.require("ui").then(...)` and access the
3759 * `changes` property of the class instance value.
3761 changes
: L
.Class
.singleton(/* @lends LuCI.ui.changes.prototype */ {
3763 if (!L
.env
.sessionid
)
3766 return uci
.changes().then(L
.bind(this.renderChangeIndicator
, this));
3770 * Set the change count indicator.
3772 * This function updates or hides the UCI change count indicator,
3773 * depending on the passed change count. When the count is greater
3774 * than 0, the change indicator is displayed or updated, otherwise it
3778 * @memberof LuCI.ui.changes
3779 * @param {number} numChanges
3780 * The number of changes to indicate.
3782 setIndicator: function(n
) {
3783 var i
= document
.querySelector('.uci_change_indicator');
3785 var poll
= document
.getElementById('xhr_poll_status');
3786 i
= poll
.parentNode
.insertBefore(E('a', {
3788 'class': 'uci_change_indicator label notice',
3789 'click': L
.bind(this.displayChanges
, this)
3794 L
.dom
.content(i
, [ _('Unsaved Changes'), ': ', n
]);
3795 i
.classList
.add('flash');
3796 i
.style
.display
= '';
3797 document
.dispatchEvent(new CustomEvent('uci-new-changes'));
3800 i
.classList
.remove('flash');
3801 i
.style
.display
= 'none';
3802 document
.dispatchEvent(new CustomEvent('uci-clear-changes'));
3807 * Update the change count indicator.
3809 * This function updates the UCI change count indicator from the given
3810 * UCI changeset structure.
3813 * @memberof LuCI.ui.changes
3814 * @param {Object<string, Array<LuCI.uci.ChangeRecord>>} changes
3815 * The UCI changeset to count.
3817 renderChangeIndicator: function(changes
) {
3820 for (var config
in changes
)
3821 if (changes
.hasOwnProperty(config
))
3822 n_changes
+= changes
[config
].length
;
3824 this.changes
= changes
;
3825 this.setIndicator(n_changes
);
3830 'add-3': '<ins>uci add %0 <strong>%3</strong> # =%2</ins>',
3831 'set-3': '<ins>uci set %0.<strong>%2</strong>=%3</ins>',
3832 'set-4': '<var><ins>uci set %0.%2.%3=<strong>%4</strong></ins></var>',
3833 'remove-2': '<del>uci del %0.<strong>%2</strong></del>',
3834 'remove-3': '<var><del>uci del %0.%2.<strong>%3</strong></del></var>',
3835 'order-3': '<var>uci reorder %0.%2=<strong>%3</strong></var>',
3836 'list-add-4': '<var><ins>uci add_list %0.%2.%3=<strong>%4</strong></ins></var>',
3837 'list-del-4': '<var><del>uci del_list %0.%2.%3=<strong>%4</strong></del></var>',
3838 'rename-3': '<var>uci rename %0.%2=<strong>%3</strong></var>',
3839 'rename-4': '<var>uci rename %0.%2.%3=<strong>%4</strong></var>'
3843 * Display the current changelog.
3845 * Open a modal dialog visualizing the currently staged UCI changes
3846 * and offer options to revert or apply the shown changes.
3849 * @memberof LuCI.ui.changes
3851 displayChanges: function() {
3852 var list
= E('div', { 'class': 'uci-change-list' }),
3853 dlg
= L
.ui
.showModal(_('Configuration') + ' / ' + _('Changes'), [
3854 E('div', { 'class': 'cbi-section' }, [
3855 E('strong', _('Legend:')),
3856 E('div', { 'class': 'uci-change-legend' }, [
3857 E('div', { 'class': 'uci-change-legend-label' }, [
3858 E('ins', ' '), ' ', _('Section added') ]),
3859 E('div', { 'class': 'uci-change-legend-label' }, [
3860 E('del', ' '), ' ', _('Section removed') ]),
3861 E('div', { 'class': 'uci-change-legend-label' }, [
3862 E('var', {}, E('ins', ' ')), ' ', _('Option changed') ]),
3863 E('div', { 'class': 'uci-change-legend-label' }, [
3864 E('var', {}, E('del', ' ')), ' ', _('Option removed') ])]),
3866 E('div', { 'class': 'right' }, [
3869 'click': L
.ui
.hideModal
3870 }, [ _('Dismiss') ]), ' ',
3872 'class': 'cbi-button cbi-button-positive important',
3873 'click': L
.bind(this.apply
, this, true)
3874 }, [ _('Save & Apply') ]), ' ',
3876 'class': 'cbi-button cbi-button-reset',
3877 'click': L
.bind(this.revert
, this)
3878 }, [ _('Revert') ])])])
3881 for (var config
in this.changes
) {
3882 if (!this.changes
.hasOwnProperty(config
))
3885 list
.appendChild(E('h5', '# /etc/config/%s'.format(config
)));
3887 for (var i
= 0, added
= null; i
< this.changes
[config
].length
; i
++) {
3888 var chg
= this.changes
[config
][i
],
3889 tpl
= this.changeTemplates
['%s-%d'.format(chg
[0], chg
.length
)];
3891 list
.appendChild(E(tpl
.replace(/%([01234])/g, function(m0
, m1
) {
3897 if (added
!= null && chg
[1] == added
[0])
3898 return '@' + added
[1] + '[-1]';
3903 return "'%h'".format(chg
[3].replace(/'/g, "'\"'\"'"));
3910 if (chg[0] == 'add')
3911 added = [ chg[1], chg[2] ];
3915 list.appendChild(E('br'));
3916 dlg.classList.add('uci-dialog');
3920 displayStatus: function(type, content) {
3922 var message = L.ui.showModal('', '');
3924 message.classList.add('alert-message');
3925 DOMTokenList.prototype.add.apply(message.classList, type.split(/\s+/));
3928 L.dom.content(message, content);
3930 if (!this.was_polling) {
3931 this.was_polling = L.Request.poll.active();
3932 L.Request.poll.stop();
3938 if (this.was_polling)
3939 L.Request.poll.start();
3944 rollback: function(checked) {
3946 this.displayStatus('warning spinning',
3947 E('p', _('Failed to confirm apply within %ds, waiting for rollback…')
3948 .format(L.env.apply_rollback)));
3950 var call = function(r, data, duration) {
3951 if (r.status === 204) {
3952 L.ui.changes.displayStatus('warning', [
3953 E('h4', _('Configuration changes have been rolled back!')),
3954 E('p', _('The device could not be reached within %d seconds after applying the pending changes, which caused the configuration to be rolled back for safety reasons. If you believe that the configuration changes are correct nonetheless, perform an unchecked configuration apply. Alternatively, you can dismiss this warning and edit changes before attempting to apply again, or revert all pending changes to keep the currently working configuration state.').format(L.env.apply_rollback)),
3955 E('div', { 'class': 'right' }, [
3958 'click': L.bind(L.ui.changes.displayStatus, L.ui.changes, false)
3959 }, [ _('Dismiss') ]), ' ',
3961 'class': 'btn cbi-button-action important',
3962 'click': L.bind(L.ui.changes.revert, L.ui.changes)
3963 }, [ _('Revert changes') ]), ' ',
3965 'class': 'btn cbi-button-negative important',
3966 'click': L.bind(L.ui.changes.apply, L.ui.changes, false)
3967 }, [ _('Apply unchecked') ])
3974 var delay = isNaN(duration) ? 0 : Math.max(1000 - duration, 0);
3975 window.setTimeout(function() {
3976 L.Request.request(L.url('admin/uci/confirm'), {
3978 timeout: L.env.apply_timeout * 1000,
3979 query: { sid: L.env.sessionid, token: L.env.token }
3984 call({ status: 0 });
3987 this.displayStatus('warning', [
3988 E('h4', _('Device unreachable!')),
3989 E('p', _('Could not regain access to the device after applying the configuration changes. You might need to reconnect if you modified network related settings such as the IP address or wireless security credentials.'))
3995 confirm: function(checked, deadline, override_token) {
3997 var ts = Date.now();
3999 this.displayStatus('notice');
4002 this.confirm_auth = { token: override_token };
4004 var call = function(r, data, duration) {
4005 if (Date.now() >= deadline) {
4006 window.clearTimeout(tt);
4007 L.ui.changes.rollback(checked);
4010 else if (r && (r.status === 200 || r.status === 204)) {
4011 document.dispatchEvent(new CustomEvent('uci-applied'));
4013 L.ui.changes.setIndicator(0);
4014 L.ui.changes.displayStatus('notice',
4015 E('p', _('Configuration changes applied.')));
4017 window.clearTimeout(tt);
4018 window.setTimeout(function() {
4019 //L.ui.changes.displayStatus(false);
4020 window.location = window.location.href.split('#')[0];
4021 }, L.env.apply_display * 1000);
4026 var delay = isNaN(duration) ? 0 : Math.max(1000 - duration, 0);
4027 window.setTimeout(function() {
4028 L.Request.request(L.url('admin/uci/confirm'), {
4030 timeout: L.env.apply_timeout * 1000,
4031 query: L.ui.changes.confirm_auth
4032 }).then(call, call);
4036 var tick = function() {
4037 var now = Date.now();
4039 L.ui.changes.displayStatus('notice spinning',
4040 E('p', _('Applying configuration changes… %ds')
4041 .format(Math.max(Math.floor((deadline - Date.now()) / 1000), 0))));
4043 if (now >= deadline)
4046 tt = window.setTimeout(tick, 1000 - (now - ts));
4052 /* wait a few seconds for the settings to become effective */
4053 window.setTimeout(call, Math.max(L.env.apply_holdoff * 1000 - ((ts + L.env.apply_rollback * 1000) - deadline), 1));
4057 * Apply the staged configuration changes.
4059 * Start applying staged configuration changes and open a modal dialog
4060 * with a progress indication to prevent interaction with the view
4061 * during the apply process. The modal dialog will be automatically
4062 * closed and the current view reloaded once the apply process is
4066 * @memberof LuCI.ui.changes
4067 * @param {boolean} [checked=false]
4068 * Whether to perform a checked (`true`) configuration apply or an
4069 * unchecked (`false`) one.
4071 * In case of a checked apply, the configuration changes must be
4072 * confirmed within a specific time interval, otherwise the device
4073 * will begin to roll back the changes in order to restore the previous
4076 apply: function(checked) {
4077 this.displayStatus('notice spinning',
4078 E('p', _('Starting configuration apply…')));
4080 L.Request.request(L.url('admin/uci', checked ? 'apply_rollback' : 'apply_unchecked'), {
4082 query: { sid: L.env.sessionid, token: L.env.token }
4083 }).then(function(r) {
4084 if (r.status === (checked ? 200 : 204)) {
4085 var tok = null; try { tok = r.json(); } catch(e) {}
4086 if (checked && tok !== null && typeof(tok) === 'object' && typeof(tok.token) === 'string')
4087 L.ui.changes.confirm_auth = tok;
4089 L.ui.changes.confirm(checked, Date.now() + L.env.apply_rollback * 1000);
4091 else if (checked && r.status === 204) {
4092 L.ui.changes.displayStatus('notice',
4093 E('p', _('There are no changes to apply')));
4095 window.setTimeout(function() {
4096 L.ui.changes.displayStatus(false);
4097 }, L.env.apply_display * 1000);
4100 L.ui.changes.displayStatus('warning',
4101 E('p', _('Apply request failed with status <code>%h</code>')
4102 .format(r.responseText || r.statusText || r.status)));
4104 window.setTimeout(function() {
4105 L.ui.changes.displayStatus(false);
4106 }, L.env.apply_display * 1000);
4112 * Revert the staged configuration changes.
4114 * Start reverting staged configuration changes and open a modal dialog
4115 * with a progress indication to prevent interaction with the view
4116 * during the revert process. The modal dialog will be automatically
4117 * closed and the current view reloaded once the revert process is
4121 * @memberof LuCI.ui.changes
4123 revert: function() {
4124 this.displayStatus('notice spinning',
4125 E('p', _('Reverting configuration…')));
4127 L.Request.request(L.url('admin/uci/revert'), {
4129 query: { sid: L.env.sessionid, token: L.env.token }
4130 }).then(function(r) {
4131 if (r.status === 200) {
4132 document.dispatchEvent(new CustomEvent('uci-reverted'));
4134 L.ui.changes.setIndicator(0);
4135 L.ui.changes.displayStatus('notice',
4136 E('p', _('Changes have been reverted.')));
4138 window.setTimeout(function() {
4139 //L.ui.changes.displayStatus(false);
4140 window.location = window.location.href.split('#')[0];
4141 }, L.env.apply_display * 1000);
4144 L.ui.changes.displayStatus('warning',
4145 E('p', _('Revert request failed with status <code>%h</code>')
4146 .format(r.statusText || r.status)));
4148 window.setTimeout(function() {
4149 L.ui.changes.displayStatus(false);
4150 }, L.env.apply_display * 1000);
4157 * Add validation constraints to an input element.
4159 * Compile the given type expression and optional validator function into
4160 * a validation function and bind it to the specified input element events.
4162 * @param {Node} field
4163 * The DOM input element node to bind the validation constraints to.
4165 * @param {string} type
4166 * The datatype specification to describe validation constraints.
4167 * Refer to the `LuCI.validation` class documentation for details.
4169 * @param {boolean} [optional=false]
4170 * Specifies whether empty values are allowed (`true`) or not (`false`).
4171 * If an input element is not marked optional it must not be empty,
4172 * otherwise it will be marked as invalid.
4174 * @param {function} [vfunc]
4175 * Specifies a custom validation function which is invoked after the
4176 * other validation constraints are applied. The validation must return
4177 * `true` to accept the passed value. Any other return type is converted
4178 * to a string and treated as validation error message.
4180 * @param {...string} [events=blur, keyup]
4181 * The list of events to bind. Each received event will trigger a field
4182 * validation. If omitted, the `keyup` and `blur` events are bound by
4185 * @returns {function}
4186 * Returns the compiled validator function which can be used to manually
4187 * trigger field validation or to bind it to further events.
4189 * @see LuCI.validation
4191 addValidator: function(field, type, optional, vfunc /*, ... */) {
4195 var events = this.varargs(arguments, 3);
4196 if (events.length == 0)
4197 events.push('blur', 'keyup');
4200 var cbiValidator = L.validation.create(field, type, optional, vfunc),
4201 validatorFn = cbiValidator.validate.bind(cbiValidator);
4203 for (var i = 0; i < events.length; i++)
4204 field.addEventListener(events[i], validatorFn);
4214 * Create a pre-bound event handler function.
4216 * Generate and bind a function suitable for use in event handlers. The
4217 * generated function automatically disables the event source element
4218 * and adds an active indication to it by adding appropriate CSS classes.
4220 * It will also await any promises returned by the wrapped function and
4221 * re-enable the source element after the promises ran to completion.
4224 * The `this` context to use for the wrapped function.
4226 * @param {function|string} fn
4227 * Specifies the function to wrap. In case of a function value, the
4228 * function is used as-is. If a string is specified instead, it is looked
4229 * up in `ctx` to obtain the function to wrap. In both cases the bound
4230 * function will be invoked with `ctx` as `this` context
4232 * @param {...*} extra_args
4233 * Any further parameter as passed as-is to the bound event handler
4234 * function in the same order as passed to `createHandlerFn()`.
4236 * @returns {function|null}
4237 * Returns the pre-bound handler function which is suitable to be passed
4238 * to `addEventListener()`. Returns `null` if the given `fn` argument is
4239 * a string which could not be found in `ctx` or if `ctx[fn]` is not a
4240 * valid function value.
4242 createHandlerFn: function(ctx, fn /*, ... */) {
4243 if (typeof(fn) == 'string')
4246 if (typeof(fn) != 'function')
4249 var arg_offset = arguments.length - 2;
4251 return Function.prototype.bind.apply(function() {
4252 var t = arguments[arg_offset].currentTarget;
4254 t.classList.add('spinning');
4260 Promise.resolve(fn.apply(ctx, arguments)).finally(function() {
4261 t.classList.remove('spinning');
4264 }, this.varargs(arguments, 2, ctx));
4267 AbstractElement: UIElement,
4270 Textfield: UITextfield,
4271 Textarea: UITextarea,
4272 Checkbox: UICheckbox,
4274 Dropdown: UIDropdown,
4275 DynamicList: UIDynamicList,
4276 Combobox: UICombobox,
4277 ComboButton: UIComboButton,
4278 Hiddenfield: UIHiddenfield,
4279 FileUpload: UIFileUpload