5 <title>JSDoc: Source: luci.js
</title>
7 <script src=
"scripts/prettify/prettify.js"> </script>
8 <script src=
"scripts/prettify/lang-css.js"> </script>
10 <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
12 <link type=
"text/css" rel=
"stylesheet" href=
"styles/prettify-tomorrow.css">
13 <link type=
"text/css" rel=
"stylesheet" href=
"styles/jsdoc-default.css">
20 <h1 class=
"page-title">Source: luci.js
</h1>
29 <pre class=
"prettyprint source linenums"><code>/**
33 * This is the LuCI base class. It is automatically instantiated and
34 * accessible using the global `L` variable.
37 * The environment settings to use for the LuCI runtime.
40 (function(window, document, undefined) {
43 /* Object.assign polyfill for IE */
44 if (typeof Object.assign !== 'function') {
45 Object.defineProperty(Object, 'assign', {
46 value: function assign(target, varArgs) {
48 throw new TypeError('Cannot convert undefined or null to object');
50 var to = Object(target);
52 for (var index =
1; index
< arguments.length; index++)
53 if (arguments[index] != null)
54 for (var nextKey in arguments[index])
55 if (Object.prototype.hasOwnProperty.call(arguments[index], nextKey))
56 to[nextKey] = arguments[index][nextKey];
65 /* Promise.finally polyfill */
66 if (typeof Promise.prototype.finally !== 'function') {
67 Promise.prototype.finally = function(fn) {
68 var onFinally = function(cb) {
69 return Promise.resolve(fn.call(this)).then(cb);
73 function(result) { return onFinally.call(this, function() { return result }) },
74 function(reason) { return onFinally.call(this, function() { return Promise.reject(reason) }) }
80 * Class declaration and inheritance helper
83 var toCamelCase = function(s) {
84 return s.replace(/(?:^|[\. -])(.)/g, function(m0, m1) { return m1.toUpperCase() });
93 * `LuCI.Class` is the abstract base class all LuCI classes inherit from.
95 * It provides simple means to create subclasses of given classes and
96 * implements prototypal inheritance.
98 var superContext = null, Class = Object.assign(function() {}, {
100 * Extends this base class with the properties described in
101 * `properties` and returns a new subclassed Class instance
103 * @memberof LuCI.Class
105 * @param {Object
<string, *
>} properties
106 * An object describing the properties to add to the new
109 * @returns {LuCI.Class}
110 * Returns a new LuCI.Class sublassed from this class, extended
111 * by the given properties and with its prototype set to this base
112 * class to enable inheritance. The resulting value represents a
113 * class constructor and can be instantiated with `new`.
115 extend: function(properties) {
117 __base__: { value: this.prototype },
118 __name__: { value: properties.__name__ || 'anonymous' }
121 var ClassConstructor = function() {
122 if (!(this instanceof ClassConstructor))
123 throw new TypeError('Constructor must not be called without
"new"');
125 if (Object.getPrototypeOf(this).hasOwnProperty('__init__')) {
126 if (typeof(this.__init__) != 'function')
127 throw new TypeError('Class __init__ member is not a function');
129 this.__init__.apply(this, arguments)
132 this.super('__init__', arguments);
136 for (var key in properties)
137 if (!props[key]
&& properties.hasOwnProperty(key))
138 props[key] = { value: properties[key], writable: true };
140 ClassConstructor.prototype = Object.create(this.prototype, props);
141 ClassConstructor.prototype.constructor = ClassConstructor;
142 Object.assign(ClassConstructor, this);
143 ClassConstructor.displayName = toCamelCase(props.__name__.value + 'Class');
145 return ClassConstructor;
149 * Extends this base class with the properties described in
150 * `properties`, instantiates the resulting subclass using
151 * the additional optional arguments passed to this function
152 * and returns the resulting subclassed Class instance.
154 * This function serves as a convenience shortcut for
155 * {@link LuCI.Class.extend Class.extend()} and subsequent
158 * @memberof LuCI.Class
160 * @param {Object
<string, *
>} properties
161 * An object describing the properties to add to the new
164 * @param {...*} [new_args]
165 * Specifies arguments to be passed to the subclass constructor
166 * as-is in order to instantiate the new subclass.
168 * @returns {LuCI.Class}
169 * Returns a new LuCI.Class instance extended by the given
170 * properties with its prototype set to this base class to
171 * enable inheritance.
173 singleton: function(properties /*, ... */) {
174 return Class.extend(properties)
175 .instantiate(Class.prototype.varargs(arguments,
1));
179 * Calls the class constructor using `new` with the given argument
180 * array being passed as variadic parameters to the constructor.
182 * @memberof LuCI.Class
184 * @param {Array
<*
>} params
185 * An array of arbitrary values which will be passed as arguments
186 * to the constructor function.
188 * @param {...*} [new_args]
189 * Specifies arguments to be passed to the subclass constructor
190 * as-is in order to instantiate the new subclass.
192 * @returns {LuCI.Class}
193 * Returns a new LuCI.Class instance extended by the given
194 * properties with its prototype set to this base class to
195 * enable inheritance.
197 instantiate: function(args) {
198 return new (Function.prototype.bind.apply(this,
199 Class.prototype.varargs(args,
0, null)))();
203 call: function(self, method) {
204 if (typeof(this.prototype[method]) != 'function')
205 throw new ReferenceError(method + ' is not defined in class');
207 return this.prototype[method].apply(self, self.varargs(arguments,
1));
211 * Checks whether the given class value is a subclass of this class.
213 * @memberof LuCI.Class
215 * @param {LuCI.Class} classValue
216 * The class object to test.
219 * Returns `true` when the given `classValue` is a subclass of this
220 * class or `false` if the given value is not a valid class or not
221 * a subclass of this class'.
223 isSubclass: function(classValue) {
224 return (classValue != null
&&
225 typeof(classValue) == 'function'
&&
226 classValue.prototype instanceof this);
231 * Extract all values from the given argument array beginning from
232 * `offset` and prepend any further given optional parameters to
233 * the beginning of the resulting array copy.
235 * @memberof LuCI.Class
238 * @param {Array
<*
>} args
239 * The array to extract the values from.
241 * @param {number} offset
242 * The offset from which to extract the values. An offset of `
0`
243 * would copy all values till the end.
245 * @param {...*} [extra_args]
246 * Extra arguments to add to prepend to the resultung array.
248 * @returns {Array
<*
>}
249 * Returns a new array consisting of the optional extra arguments
250 * and the values extracted from the `args` array beginning with
253 varargs: function(args, offset /*, ... */) {
254 return Array.prototype.slice.call(arguments,
2)
255 .concat(Array.prototype.slice.call(args, offset));
259 * Walks up the parent class chain and looks for a class member
260 * called `key` in any of the parent classes this class inherits
261 * from. Returns the member value of the superclass or calls the
262 * member as function and returns its return value when the
263 * optional `callArgs` array is given.
265 * This function has two signatures and is sensitive to the
266 * amount of arguments passed to it:
268 * Returns the value of `key` when found within one of the
270 * - `super('key', ['arg1', 'arg2'])` -
271 * Calls the `key()` method with parameters `arg1` and `arg2`
272 * when found within one of the parent classes.
274 * @memberof LuCI.Class
277 * @param {string} key
278 * The name of the superclass member to retrieve.
280 * @param {Array
<*
>} [callArgs]
281 * An optional array of function call parameters to use. When
282 * this parameter is specified, the found member value is called
283 * as function using the values of this array as arguments.
285 * @throws {ReferenceError}
286 * Throws a `ReferenceError` when `callArgs` are specified and
287 * the found member named by `key` is not a function value.
290 * Returns the value of the found member or the return value of
291 * the call to the found method. Returns `null` when no member
292 * was found in the parent class chain or when the call to the
293 * superclass method returned `null`.
295 super: function(key, callArgs) {
296 for (superContext = Object.getPrototypeOf(superContext ||
297 Object.getPrototypeOf(this));
298 superContext
&& !superContext.hasOwnProperty(key);
299 superContext = Object.getPrototypeOf(superContext)) { }
304 var res = superContext[key];
306 if (arguments.length
> 1) {
307 if (typeof(res) != 'function')
308 throw new ReferenceError(key + ' is not a function in base class');
310 if (typeof(callArgs) != 'object')
311 callArgs = this.varargs(arguments,
1);
313 res = res.apply(this, callArgs);
322 * Returns a string representation of this class.
325 * Returns a string representation of this class containing the
326 * constructor functions `displayName` and describing the class
327 * members and their respective types.
329 toString: function() {
330 var s = '[' + this.constructor.displayName + ']', f = true;
331 for (var k in this) {
332 if (this.hasOwnProperty(k)) {
333 s += (f ? ' {\n' : '') + ' ' + k + ': ' + typeof(this[k]) + '\n';
337 return s + (f ? '' : '}');
349 * The `Headers` class is an internal utility class exposed in HTTP
350 * response objects using the `response.headers` property.
352 var Headers = Class.extend(/** @lends LuCI.Headers.prototype */ {
353 __name__: 'LuCI.XHR.Headers',
354 __init__: function(xhr) {
355 var hdrs = this.headers = {};
356 xhr.getAllResponseHeaders().split(/\r\n/).forEach(function(line) {
357 var m = /^([^:]+):(.*)$/.exec(line);
359 hdrs[m[
1].trim().toLowerCase()] = m[
2].trim();
364 * Checks whether the given header name is present.
365 * Note: Header-Names are case-insensitive.
368 * @memberof LuCI.Headers
369 * @param {string} name
370 * The header name to check
373 * Returns `true` if the header name is present, `false` otherwise
375 has: function(name) {
376 return this.headers.hasOwnProperty(String(name).toLowerCase());
380 * Returns the value of the given header name.
381 * Note: Header-Names are case-insensitive.
384 * @memberof LuCI.Headers
385 * @param {string} name
386 * The header name to read
388 * @returns {string|null}
389 * The value of the given header name or `null` if the header isn't present.
391 get: function(name) {
392 var key = String(name).toLowerCase();
393 return this.headers.hasOwnProperty(key) ? this.headers[key] : null;
403 * The `Response` class is an internal utility class representing HTTP responses.
405 var Response = Class.extend({
406 __name__: 'LuCI.XHR.Response',
407 __init__: function(xhr, url, duration, headers, content) {
409 * Describes whether the response is successful (status codes `
200.
.299`) or not
411 * @memberof LuCI.Response
415 this.ok = (xhr.status
>=
200 && xhr.status
<=
299);
418 * The numeric HTTP status code of the response
420 * @memberof LuCI.Response
424 this.status = xhr.status;
427 * The HTTP status description message of the response
429 * @memberof LuCI.Response
433 this.statusText = xhr.statusText;
436 * The HTTP headers of the response
438 * @memberof LuCI.Response
440 * @type {LuCI.Headers}
442 this.headers = (headers != null) ? headers : new Headers(xhr);
445 * The total duration of the HTTP request in milliseconds
447 * @memberof LuCI.Response
451 this.duration = duration;
454 * The final URL of the request, i.e. after following redirects.
456 * @memberof LuCI.Response
465 if (content != null
&& typeof(content) == 'object') {
466 this.responseJSON = content;
467 this.responseText = null;
469 else if (content != null) {
470 this.responseJSON = null;
471 this.responseText = String(content);
474 this.responseJSON = null;
475 this.responseText = xhr.responseText;
480 * Clones the given response object, optionally overriding the content
481 * of the cloned instance.
484 * @memberof LuCI.Response
485 * @param {*} [content]
486 * Override the content of the cloned response. Object values will be
487 * treated as JSON response data, all other types will be converted
488 * using `String()` and treated as response text.
490 * @returns {LuCI.Response}
491 * The cloned `Response` instance.
493 clone: function(content) {
494 var copy = new Response(this.xhr, this.url, this.duration, this.headers, content);
497 copy.status = this.status;
498 copy.statusText = this.statusText;
504 * Access the response content as JSON data.
507 * @memberof LuCI.Response
508 * @throws {SyntaxError}
509 * Throws `SyntaxError` if the content isn't valid JSON.
512 * The parsed JSON data.
515 if (this.responseJSON == null)
516 this.responseJSON = JSON.parse(this.responseText);
518 return this.responseJSON;
522 * Access the response content as string.
525 * @memberof LuCI.Response
527 * The response content.
530 if (this.responseText == null
&& this.responseJSON != null)
531 this.responseText = JSON.stringify(this.responseJSON);
533 return this.responseText;
538 var requestQueue = [];
540 function isQueueableRequest(opt) {
544 if (opt.method != 'POST' || typeof(opt.content) != 'object')
547 if (opt.nobatch === true)
550 var rpcBaseURL = Request.expandURL(classes.rpc.getBaseURL());
552 return (rpcBaseURL != null
&& opt.url.indexOf(rpcBaseURL) ==
0);
555 function flushRequestQueue() {
556 if (!requestQueue.length)
559 var reqopt = Object.assign({}, requestQueue[
0][
0], { content: [], nobatch: true }),
562 for (var i =
0; i
< requestQueue.length; i++) {
563 batch[i] = requestQueue[i];
564 reqopt.content[i] = batch[i][
0].content;
567 requestQueue.length =
0;
569 Request.request(rpcBaseURL, reqopt).then(function(reply) {
570 var json = null, req = null;
572 try { json = reply.json() }
575 while ((req = batch.shift()) != null)
576 if (Array.isArray(json)
&& json.length)
577 req[
2].call(reqopt, reply.clone(json.shift()));
579 req[
1].call(reqopt, new Error('No related RPC reply'));
580 }).catch(function(error) {
583 while ((req = batch.shift()) != null)
584 req[
1].call(reqopt, error);
594 * The `Request` class allows initiating HTTP requests and provides utilities
595 * for dealing with responses.
597 var Request = Class.singleton(/** @lends LuCI.Request.prototype */ {
598 __name__: 'LuCI.Request',
603 * Turn the given relative URL into an absolute URL if necessary.
606 * @memberof LuCI.Request
607 * @param {string} url
608 * The URL to convert.
611 * The absolute URL derived from the given one, or the original URL
612 * if it already was absolute.
614 expandURL: function(url) {
615 if (!/^(?:[^/]+:)?\/\//.test(url))
616 url = location.protocol + '//' + location.host + url;
622 * @typedef {Object} RequestOptions
623 * @memberof LuCI.Request
625 * @property {string} [method=GET]
626 * The HTTP method to use, e.g. `GET` or `POST`.
628 * @property {Object
<string, Object|string
>} [query]
629 * Query string data to append to the URL. Non-string values of the
630 * given object will be converted to JSON.
632 * @property {boolean} [cache=false]
633 * Specifies whether the HTTP response may be retrieved from cache.
635 * @property {string} [username]
636 * Provides a username for HTTP basic authentication.
638 * @property {string} [password]
639 * Provides a password for HTTP basic authentication.
641 * @property {number} [timeout]
642 * Specifies the request timeout in seconds.
644 * @property {boolean} [credentials=false]
645 * Whether to include credentials such as cookies in the request.
647 * @property {*} [content]
648 * Specifies the HTTP message body to send along with the request.
649 * If the value is a function, it is invoked and the return value
650 * used as content, if it is a FormData instance, it is used as-is,
651 * if it is an object, it will be converted to JSON, in all other
652 * cases it is converted to a string.
654 * @property {Object
<string, string
>} [header]
655 * Specifies HTTP headers to set for the request.
657 * @property {function} [progress]
658 * An optional request callback function which receives ProgressEvent
659 * instances as sole argument during the HTTP request transfer.
663 * Initiate an HTTP request to the given target.
666 * @memberof LuCI.Request
667 * @param {string} target
668 * The URL to request.
670 * @param {LuCI.Request.RequestOptions} [options]
671 * Additional options to configure the request.
673 * @returns {Promise
<LuCI.Response
>}
674 * The resulting HTTP response.
676 request: function(target, options) {
677 var state = { xhr: new XMLHttpRequest(), url: this.expandURL(target), start: Date.now() },
678 opt = Object.assign({}, options, state),
681 callback = this.handleReadyStateChange;
683 return new Promise(function(resolveFn, rejectFn) {
684 opt.xhr.onreadystatechange = callback.bind(opt, resolveFn, rejectFn);
685 opt.method = String(opt.method || 'GET').toUpperCase();
687 if ('query' in opt) {
688 var q = (opt.query != null) ? Object.keys(opt.query).map(function(k) {
689 if (opt.query[k] != null) {
690 var v = (typeof(opt.query[k]) == 'object')
691 ? JSON.stringify(opt.query[k])
692 : String(opt.query[k]);
694 return '%s=%s'.format(encodeURIComponent(k), encodeURIComponent(v));
697 return encodeURIComponent(k);
699 }).join('
&') : '';
702 switch (opt.method) {
706 opt.url += ((/\?/).test(opt.url) ? '
&' : '?') + q;
710 if (content == null) {
712 contenttype = 'application/x-www-form-urlencoded';
719 opt.url += ((/\?/).test(opt.url) ? '
&' : '?') + (new Date()).getTime();
721 if (isQueueableRequest(opt)) {
722 requestQueue.push([opt, rejectFn, resolveFn]);
723 requestAnimationFrame(flushRequestQueue);
727 if ('username' in opt
&& 'password' in opt)
728 opt.xhr.open(opt.method, opt.url, true, opt.username, opt.password);
730 opt.xhr.open(opt.method, opt.url, true);
732 opt.xhr.responseType = 'text';
734 if ('overrideMimeType' in opt.xhr)
735 opt.xhr.overrideMimeType('application/octet-stream');
737 if ('timeout' in opt)
738 opt.xhr.timeout = +opt.timeout;
740 if ('credentials' in opt)
741 opt.xhr.withCredentials = !!opt.credentials;
743 if (opt.content != null) {
744 switch (typeof(opt.content)) {
746 content = opt.content(xhr);
750 if (!(opt.content instanceof FormData)) {
751 content = JSON.stringify(opt.content);
752 contenttype = 'application/json';
755 content = opt.content;
760 content = String(opt.content);
764 if ('headers' in opt)
765 for (var header in opt.headers)
766 if (opt.headers.hasOwnProperty(header)) {
767 if (header.toLowerCase() != 'content-type')
768 opt.xhr.setRequestHeader(header, opt.headers[header]);
770 contenttype = opt.headers[header];
773 if ('progress' in opt
&& 'upload' in opt.xhr)
774 opt.xhr.upload.addEventListener('progress', opt.progress);
776 if (contenttype != null)
777 opt.xhr.setRequestHeader('Content-Type', contenttype);
780 opt.xhr.send(content);
783 rejectFn.call(opt, e);
788 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
790 duration = Date.now() - this.start;
792 if (xhr.readyState !==
4)
795 if (xhr.status ===
0 && xhr.statusText === '') {
796 if (duration
>= this.timeout)
797 rejectFn.call(this, new Error('XHR request timed out'));
799 rejectFn.call(this, new Error('XHR request aborted by browser'));
802 var response = new Response(
803 xhr, xhr.responseURL || this.url, duration);
805 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
806 .then(resolveFn.bind(this, response))
807 .catch(rejectFn.bind(this));
812 * Initiate an HTTP GET request to the given target.
815 * @memberof LuCI.Request
816 * @param {string} target
817 * The URL to request.
819 * @param {LuCI.Request.RequestOptions} [options]
820 * Additional options to configure the request.
822 * @returns {Promise
<LuCI.Response
>}
823 * The resulting HTTP response.
825 get: function(url, options) {
826 return this.request(url, Object.assign({ method: 'GET' }, options));
830 * Initiate an HTTP POST request to the given target.
833 * @memberof LuCI.Request
834 * @param {string} target
835 * The URL to request.
838 * The request data to send, see {@link LuCI.Request.RequestOptions} for details.
840 * @param {LuCI.Request.RequestOptions} [options]
841 * Additional options to configure the request.
843 * @returns {Promise
<LuCI.Response
>}
844 * The resulting HTTP response.
846 post: function(url, data, options) {
847 return this.request(url, Object.assign({ method: 'POST', content: data }, options));
851 * Interceptor functions are invoked whenever an HTTP reply is received, in the order
852 * these functions have been registered.
853 * @callback LuCI.Request.interceptorFn
854 * @param {LuCI.Response} res
855 * The HTTP response object
859 * Register an HTTP response interceptor function. Interceptor
860 * functions are useful to perform default actions on incoming HTTP
861 * responses, such as checking for expired authentication or for
862 * implementing request retries before returning a failure.
865 * @memberof LuCI.Request
866 * @param {LuCI.Request.interceptorFn} interceptorFn
867 * The interceptor function to register.
869 * @returns {LuCI.Request.interceptorFn}
870 * The registered function.
872 addInterceptor: function(interceptorFn) {
873 if (typeof(interceptorFn) == 'function')
874 this.interceptors.push(interceptorFn);
875 return interceptorFn;
879 * Remove an HTTP response interceptor function. The passed function
880 * value must be the very same value that was used to register the
884 * @memberof LuCI.Request
885 * @param {LuCI.Request.interceptorFn} interceptorFn
886 * The interceptor function to remove.
889 * Returns `true` if any function has been removed, else `false`.
891 removeInterceptor: function(interceptorFn) {
892 var oldlen = this.interceptors.length, i = oldlen;
894 if (this.interceptors[i] === interceptorFn)
895 this.interceptors.splice(i,
1);
896 return (this.interceptors.length
< oldlen);
901 * @memberof LuCI.Request
905 * The `Request.poll` class provides some convience wrappers around
906 * {@link LuCI.Poll} mainly to simplify registering repeating HTTP
907 * request calls as polling functions.
911 * The callback function is invoked whenever an HTTP reply to a
912 * polled request is received or when the polled request timed
915 * @callback LuCI.Request.poll~callbackFn
916 * @param {LuCI.Response} res
917 * The HTTP response object.
920 * The response JSON if the response could be parsed as such,
923 * @param {number} duration
924 * The total duration of the request in milliseconds.
928 * Register a repeating HTTP request with an optional callback
929 * to invoke whenever a response for the request is received.
932 * @memberof LuCI.Request.poll
933 * @param {number} interval
934 * The poll interval in seconds.
936 * @param {string} url
937 * The URL to request on each poll.
939 * @param {LuCI.Request.RequestOptions} [options]
940 * Additional options to configure the request.
942 * @param {LuCI.Request.poll~callbackFn} [callback]
943 * {@link LuCI.Request.poll~callbackFn Callback} function to
944 * invoke for each HTTP reply.
946 * @throws {TypeError}
947 * Throws `TypeError` when an invalid interval was passed.
949 * @returns {function}
950 * Returns the internally created poll function.
952 add: function(interval, url, options, callback) {
953 if (isNaN(interval) || interval
<=
0)
954 throw new TypeError('Invalid poll interval');
956 var ival = interval
>>> 0,
957 opts = Object.assign({}, options, { timeout: ival *
1000 -
5 });
959 var fn = function() {
960 return Request.request(url, options).then(function(res) {
965 callback(res, res.json(), res.duration);
968 callback(res, null, res.duration);
973 return (Poll.add(fn, ival) ? fn : null);
977 * Remove a polling request that has been previously added using `add()`.
978 * This function is essentially a wrapper around
979 * {@link LuCI.Poll.remove LuCI.Poll.remove()}.
982 * @memberof LuCI.Request.poll
983 * @param {function} entry
984 * The poll function returned by {@link LuCI.Request.poll#add add()}.
987 * Returns `true` if any function has been removed, else `false`.
989 remove: function(entry) { return Poll.remove(entry) },
992 * Alias for {@link LuCI.Poll.start LuCI.Poll.start()}.
995 * @memberof LuCI.Request.poll
997 start: function() { return Poll.start() },
1000 * Alias for {@link LuCI.Poll.stop LuCI.Poll.stop()}.
1003 * @memberof LuCI.Request.poll
1005 stop: function() { return Poll.stop() },
1008 * Alias for {@link LuCI.Poll.active LuCI.Poll.active()}.
1011 * @memberof LuCI.Request.poll
1013 active: function() { return Poll.active() }
1023 * The `Poll` class allows registering and unregistering poll actions,
1024 * as well as starting, stopping and querying the state of the polling
1027 var Poll = Class.singleton(/** @lends LuCI.Poll.prototype */ {
1028 __name__: 'LuCI.Poll',
1033 * Add a new operation to the polling loop. If the polling loop is not
1034 * already started at this point, it will be implicitely started.
1037 * @memberof LuCI.Poll
1038 * @param {function} fn
1039 * The function to invoke on each poll interval.
1041 * @param {number} interval
1042 * The poll interval in seconds.
1044 * @throws {TypeError}
1045 * Throws `TypeError` when an invalid interval was passed.
1047 * @returns {boolean}
1048 * Returns `true` if the function has been added or `false` if it
1049 * already is registered.
1051 add: function(fn, interval) {
1052 if (interval == null || interval
<=
0)
1053 interval = window.L ? window.L.env.pollinterval : null;
1055 if (isNaN(interval) || typeof(fn) != 'function')
1056 throw new TypeError('Invalid argument to LuCI.Poll.add()');
1058 for (var i =
0; i
< this.queue.length; i++)
1059 if (this.queue[i].fn === fn)
1070 if (this.tick != null
&& !this.active())
1077 * Remove an operation from the polling loop. If no further operatons
1078 * are registered, the polling loop is implicitely stopped.
1081 * @memberof LuCI.Poll
1082 * @param {function} fn
1083 * The function to remove.
1085 * @throws {TypeError}
1086 * Throws `TypeError` when the given argument isn't a function.
1088 * @returns {boolean}
1089 * Returns `true` if the function has been removed or `false` if it
1092 remove: function(fn) {
1093 if (typeof(fn) != 'function')
1094 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
1096 var len = this.queue.length;
1098 for (var i = len; i
> 0; i--)
1099 if (this.queue[i-
1].fn === fn)
1100 this.queue.splice(i-
1,
1);
1102 if (!this.queue.length
&& this.stop())
1105 return (this.queue.length != len);
1109 * (Re)start the polling loop. Dispatches a custom `poll-start` event
1110 * to the `document` object upon successful start.
1113 * @memberof LuCI.Poll
1114 * @returns {boolean}
1115 * Returns `true` if polling has been started (or if no functions
1116 * where registered) or `false` when the polling loop already runs.
1124 if (this.queue.length) {
1125 this.timer = window.setInterval(this.step,
1000);
1127 document.dispatchEvent(new CustomEvent('poll-start'));
1134 * Stop the polling loop. Dispatches a custom `poll-stop` event
1135 * to the `document` object upon successful stop.
1138 * @memberof LuCI.Poll
1139 * @returns {boolean}
1140 * Returns `true` if polling has been stopped or `false` if it din't
1141 * run to begin with.
1147 document.dispatchEvent(new CustomEvent('poll-stop'));
1148 window.clearInterval(this.timer);
1156 for (var i =
0, e = null; (e = Poll.queue[i]) != null; i++) {
1157 if ((Poll.tick % e.i) !=
0)
1165 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
1168 Poll.tick = (Poll.tick +
1) % Math.pow(
2,
32);
1172 * Test whether the polling loop is running.
1175 * @memberof LuCI.Poll
1176 * @returns {boolean} - Returns `true` if polling is active, else `false`.
1178 active: function() {
1179 return (this.timer != null);
1184 var dummyElem = null,
1186 originalCBIInit = null,
1191 var LuCI = Class.extend(/** @lends LuCI.prototype */ {
1193 __init__: function(env) {
1195 document.querySelectorAll('script[src*=
"/luci.js"]').forEach(function(s) {
1196 if (env.base_url == null || env.base_url == '') {
1197 var m = (s.getAttribute('src') || '').match(/^(.*)\/luci\.js(?:\?v=([^?]+))?$/);
1199 env.base_url = m[
1];
1200 env.resource_version = m[
2];
1205 if (env.base_url == null)
1206 this.error('InternalError', 'Cannot find url of luci.js');
1208 Object.assign(this.env, env);
1210 document.addEventListener('poll-start', function(ev) {
1211 document.querySelectorAll('[id^=
"xhr_poll_status"]').forEach(function(e) {
1212 e.style.display = (e.id == 'xhr_poll_status_off') ? 'none' : '';
1216 document.addEventListener('poll-stop', function(ev) {
1217 document.querySelectorAll('[id^=
"xhr_poll_status"]').forEach(function(e) {
1218 e.style.display = (e.id == 'xhr_poll_status_on') ? 'none' : '';
1222 var domReady = new Promise(function(resolveFn, rejectFn) {
1223 document.addEventListener('DOMContentLoaded', resolveFn);
1229 this.require('rpc'),
1230 this.require('form'),
1231 this.probeRPCBaseURL()
1232 ]).then(this.setupDOM.bind(this)).catch(this.error);
1234 originalCBIInit = window.cbi_init;
1235 window.cbi_init = function() {};
1239 * Captures the current stack trace and throws an error of the
1240 * specified type as a new exception. Also logs the exception as
1241 * error to the debug console if it is available.
1246 * @param {Error|string} [type=Error]
1247 * Either a string specifying the type of the error to throw or an
1248 * existing `Error` instance to copy.
1250 * @param {string} [fmt=Unspecified error]
1251 * A format string which is used to form the error message, together
1252 * with all subsequent optional arguments.
1254 * @param {...*} [args]
1255 * Zero or more variable arguments to the supplied format string.
1258 * Throws the created error object with the captured stack trace
1259 * appended to the message and the type set to the given type
1260 * argument or copied from the given error instance.
1262 raise: function(type, fmt /*, ...*/) {
1264 msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments,
2)) : null,
1267 if (type instanceof Error) {
1271 e.message = msg + ': ' + e.message;
1274 try { throw new Error('stacktrace') }
1275 catch (e2) { stack = (e2.stack || '').split(/\n/) }
1277 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
1278 e.name = type || 'Error';
1281 stack = (stack || []).map(function(frame) {
1282 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $
1 ($
2:$
3:$
4)').trim();
1283 return frame ? ' ' + frame : '';
1286 if (!/^ at /.test(stack[
0]))
1289 if (/\braise /.test(stack[
0]))
1292 if (/\berror /.test(stack[
0]))
1296 e.message += '\n' + stack.join('\n');
1298 if (window.console
&& console.debug)
1305 * A wrapper around {@link LuCI#raise raise()} which also renders
1306 * the error either as modal overlay when `ui.js` is already loaed
1307 * or directly into the view body.
1312 * @param {Error|string} [type=Error]
1313 * Either a string specifying the type of the error to throw or an
1314 * existing `Error` instance to copy.
1316 * @param {string} [fmt=Unspecified error]
1317 * A format string which is used to form the error message, together
1318 * with all subsequent optional arguments.
1320 * @param {...*} [args]
1321 * Zero or more variable arguments to the supplied format string.
1324 * Throws the created error object with the captured stack trace
1325 * appended to the message and the type set to the given type
1326 * argument or copied from the given error instance.
1328 error: function(type, fmt /*, ...*/) {
1330 L.raise.apply(L, Array.prototype.slice.call(arguments));
1335 L.ui.addNotification(e.name || _('Runtime error'),
1336 E('pre', {}, e.message), 'danger');
1338 L.dom.content(document.querySelector('#maincontent'),
1339 E('pre', { 'class': 'alert-message error' }, e.message));
1349 * Return a bound function using the given `self` as `this` context
1350 * and any further arguments as parameters to the bound function.
1355 * @param {function} fn
1356 * The function to bind.
1359 * The value to bind as `this` context to the specified function.
1361 * @param {...*} [args]
1362 * Zero or more variable arguments which are bound to the function
1365 * @returns {function}
1366 * Returns the bound function.
1368 bind: function(fn, self /*, ... */) {
1369 return Function.prototype.bind.apply(fn, this.varargs(arguments,
2, self));
1373 * Load an additional LuCI JavaScript class and its dependencies,
1374 * instantiate it and return the resulting class instance. Each
1375 * class is only loaded once. Subsequent attempts to load the same
1376 * class will return the already instantiated class.
1381 * @param {string} name
1382 * The name of the class to load in dotted notation. Dots will
1383 * be replaced by spaces and joined with the runtime-determined
1384 * base URL of LuCI.js to form an absolute URL to load the class
1387 * @throws {DependencyError}
1388 * Throws a `DependencyError` when the class to load includes
1389 * circular dependencies.
1391 * @throws {NetworkError}
1392 * Throws `NetworkError` when the underlying {@link LuCI.Request}
1395 * @throws {SyntaxError}
1396 * Throws `SyntaxError` when the loaded class file code cannot
1397 * be interpreted by `eval`.
1399 * @throws {TypeError}
1400 * Throws `TypeError` when the class file could be loaded and
1401 * interpreted, but when invoking its code did not yield a valid
1404 * @returns {Promise
<LuCI#Class
>}
1405 * Returns the instantiated class.
1407 require: function(name, from) {
1408 var L = this, url = null, from = from || [];
1410 /* Class already loaded */
1411 if (classes[name] != null) {
1412 /* Circular dependency */
1413 if (from.indexOf(name) != -
1)
1414 L.raise('DependencyError',
1415 'Circular dependency: class
"%s" depends on
"%s"',
1416 name, from.join('
" which depends on "'));
1418 return Promise.resolve(classes[name]);
1421 url = '%s/%s.js%s'.format(L.env.base_url, name.replace(/\./g, '/'), (L.env.resource_version ? '?v=' + L.env.resource_version : ''));
1422 from = [ name ].concat(from);
1424 var compileClass = function(res) {
1426 L.raise('NetworkError',
1427 'HTTP error %d while loading class file
"%s"', res.status, url);
1429 var source = res.text(),
1430 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
1431 strictmatch = /^use[ \t]+strict$/,
1435 /* find require statements in source */
1436 for (var i =
0, off = -
1, quote = -
1, esc = false; i
< source.length; i++) {
1437 var chr = source.charCodeAt(i);
1442 else if (chr ==
92) {
1445 else if (chr == quote) {
1446 var s = source.substring(off, i),
1447 m = requirematch.exec(s);
1450 var dep = m[
1], as = m[
2] || dep.replace(/[^a-zA-Z0-
9_]/g, '_');
1451 depends.push(L.require(dep, from));
1454 else if (!strictmatch.exec(s)) {
1461 else if (quote == -
1 && (chr ==
34 || chr ==
39)) {
1467 /* load dependencies and instantiate class */
1468 return Promise.all(depends).then(function(instances) {
1469 var _factory, _class;
1473 '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
1474 .format(args, source, res.url));
1477 L.raise('SyntaxError', '%s\n in %s:%s',
1478 error.message, res.url, error.lineNumber || '?');
1481 _factory.displayName = toCamelCase(name + 'ClassFactory');
1482 _class = _factory.apply(_factory, [window, document, L].concat(instances));
1484 if (!Class.isSubclass(_class))
1485 L.error('TypeError', '
"%s" factory yields invalid constructor', name);
1487 if (_class.displayName == 'AnonymousClass')
1488 _class.displayName = toCamelCase(name + 'Class');
1490 var ptr = Object.getPrototypeOf(L),
1491 parts = name.split(/\./),
1492 instance = new _class();
1494 for (var i =
0; ptr
&& i
< parts.length -
1; i++)
1495 ptr = ptr[parts[i]];
1498 ptr[parts[i]] = instance;
1500 classes[name] = instance;
1506 /* Request class file */
1507 classes[name] = Request.get(url, { cache: true }).then(compileClass);
1509 return classes[name];
1513 probeRPCBaseURL: function() {
1514 if (rpcBaseURL == null) {
1516 rpcBaseURL = window.sessionStorage.getItem('rpcBaseURL');
1521 if (rpcBaseURL == null) {
1522 var rpcFallbackURL = this.url('admin/ubus');
1524 rpcBaseURL = Request.get('/ubus/').then(function(res) {
1525 return (rpcBaseURL = (res.status ==
400) ? '/ubus/' : rpcFallbackURL);
1527 return (rpcBaseURL = rpcFallbackURL);
1528 }).then(function(url) {
1530 window.sessionStorage.setItem('rpcBaseURL', url);
1538 return Promise.resolve(rpcBaseURL);
1541 probeSystemFeatures: function() {
1542 var sessionid = classes.rpc.getSessionID();
1544 if (sysFeatures == null) {
1546 var data = JSON.parse(window.sessionStorage.getItem('sysFeatures'));
1548 if (this.isObject(data)
&& this.isObject(data[sessionid]))
1549 sysFeatures = data[sessionid];
1554 if (!this.isObject(sysFeatures)) {
1555 sysFeatures = classes.rpc.declare({
1557 method: 'getFeatures',
1559 })().then(function(features) {
1562 data[sessionid] = features;
1564 window.sessionStorage.setItem('sysFeatures', JSON.stringify(data));
1568 sysFeatures = features;
1574 return Promise.resolve(sysFeatures);
1578 * Test whether a particular system feature is available, such as
1579 * hostapd SAE support or an installed firewall. The features are
1580 * queried once at the beginning of the LuCI session and cached in
1581 * `SessionStorage` throughout the lifetime of the associated tab or
1587 * @param {string} feature
1588 * The feature to test. For detailed list of known feature flags,
1589 * see `/modules/luci-base/root/usr/libexec/rpcd/luci`.
1591 * @param {string} [subfeature]
1592 * Some feature classes like `hostapd` provide sub-feature flags,
1593 * such as `sae` or `
11w` support. The `subfeature` argument can
1594 * be used to query these.
1596 * @return {boolean|null}
1597 * Return `true` if the queried feature (and sub-feature) is available
1598 * or `false` if the requested feature isn't present or known.
1599 * Return `null` when a sub-feature was queried for a feature which
1600 * has no sub-features.
1602 hasSystemFeature: function() {
1603 var ft = sysFeatures[arguments[
0]];
1605 if (arguments.length ==
2)
1606 return this.isObject(ft) ? ft[arguments[
1]] : null;
1608 return (ft != null
&& ft != false);
1612 notifySessionExpiry: function() {
1615 L.ui.showModal(_('Session expired'), [
1616 E('div', { class: 'alert-message warning' },
1617 _('A new login is required since the authentication session expired.')),
1618 E('div', { class: 'right' },
1620 class: 'btn primary',
1622 var loc = window.location;
1623 window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
1625 }, _('To login…')))
1628 L.raise('SessionError', 'Login session is expired');
1632 setupDOM: function(res) {
1637 rpcBaseURL = res[
4];
1639 rpcClass.setBaseURL(rpcBaseURL);
1641 rpcClass.addInterceptor(function(msg, req) {
1642 if (!L.isObject(msg) || !L.isObject(msg.error) || msg.error.code != -
32002)
1645 if (!L.isObject(req) || (req.object == 'session'
&& req.method == 'access'))
1648 return rpcClass.declare({
1649 'object': 'session',
1651 'params': [ 'scope', 'object', 'function' ],
1652 'expect': { access: true }
1653 })('uci', 'luci', 'read').catch(L.notifySessionExpiry);
1656 Request.addInterceptor(function(res) {
1657 var isDenied = false;
1659 if (res.status ==
403 && res.headers.get('X-LuCI-Login-Required') == 'yes')
1665 L.notifySessionExpiry();
1668 return this.probeSystemFeatures().finally(this.initDOM);
1672 initDOM: function() {
1675 document.dispatchEvent(new CustomEvent('luci-loaded'));
1679 * The `env` object holds environment settings used by LuCI, such
1680 * as request timeouts, base URLs etc.
1688 * Construct a relative URL path from the given prefix and parts.
1689 * The resulting URL is guaranteed to only contain the characters
1690 * `a-z`, `A-Z`, `
0-
9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1691 * as `/` for the path separator.
1696 * @param {string} [prefix]
1697 * The prefix to join the given parts with. If the `prefix` is
1698 * omitted, it defaults to an empty string.
1700 * @param {string[]} [parts]
1701 * An array of parts to join into an URL path. Parts may contain
1702 * slashes and any of the other characters mentioned above.
1705 * Return the joined URL path.
1707 path: function(prefix, parts) {
1708 var url = [ prefix || '' ];
1710 for (var i =
0; i
< parts.length; i++)
1711 if (/^(?:[a-zA-Z0-
9_.%,;-]+\/)*[a-zA-Z0-
9_.%,;-]+$/.test(parts[i]))
1712 url.push('/', parts[i]);
1714 if (url.length ===
1)
1717 return url.join('');
1721 * Construct an URL pathrelative to the script path of the server
1722 * side LuCI application (usually `/cgi-bin/luci`).
1724 * The resulting URL is guaranteed to only contain the characters
1725 * `a-z`, `A-Z`, `
0-
9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1726 * as `/` for the path separator.
1731 * @param {string[]} [parts]
1732 * An array of parts to join into an URL path. Parts may contain
1733 * slashes and any of the other characters mentioned above.
1736 * Returns the resulting URL path.
1739 return this.path(this.env.scriptname, arguments);
1743 * Construct an URL path relative to the global static resource path
1744 * of the LuCI ui (usually `/luci-static/resources`).
1746 * The resulting URL is guaranteed to only contain the characters
1747 * `a-z`, `A-Z`, `
0-
9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1748 * as `/` for the path separator.
1753 * @param {string[]} [parts]
1754 * An array of parts to join into an URL path. Parts may contain
1755 * slashes and any of the other characters mentioned above.
1758 * Returns the resulting URL path.
1760 resource: function() {
1761 return this.path(this.env.resource, arguments);
1765 * Return the complete URL path to the current view.
1771 * Returns the URL path to the current view.
1773 location: function() {
1774 return this.path(this.env.scriptname, this.env.requestpath);
1779 * Tests whether the passed argument is a JavaScript object.
1780 * This function is meant to be an object counterpart to the
1781 * standard `Array.isArray()` function.
1790 * Returns `true` if the given value is of type object and
1791 * not `null`, else returns `false`.
1793 isObject: function(val) {
1794 return (val != null
&& typeof(val) == 'object');
1798 * Return an array of sorted object keys, optionally sorted by
1799 * a different key or a different sorting mode.
1804 * @param {object} obj
1805 * The object to extract the keys from. If the given value is
1806 * not an object, the function will return an empty array.
1808 * @param {string} [key]
1809 * Specifies the key to order by. This is mainly useful for
1810 * nested objects of objects or objects of arrays when sorting
1811 * shall not be performed by the primary object keys but by
1812 * some other key pointing to a value within the nested values.
1814 * @param {string} [sortmode]
1815 * May be either `addr` or `num` to override the natural
1816 * lexicographic sorting with a sorting suitable for IP/MAC style
1817 * addresses or numeric values respectively.
1819 * @return {string[]}
1820 * Returns an array containing the sorted keys of the given object.
1822 sortedKeys: function(obj, key, sortmode) {
1823 if (obj == null || typeof(obj) != 'object')
1826 return Object.keys(obj).map(function(e) {
1827 var v = (key != null) ? obj[e][key] : e;
1831 v = (v != null) ? v.replace(/(?:^|[.:])([
0-
9a-fA-F]{
1,
4})/g,
1832 function(m0, m1) { return ('
000' + m1.toLowerCase()).substr(-
4) }) : null;
1836 v = (v != null) ? +v : null;
1841 }).filter(function(e) {
1842 return (e[
1] != null);
1843 }).sort(function(a, b) {
1844 return (a[
1]
> b[
1]);
1845 }).map(function(e) {
1851 * Converts the given value to an array. If the given value is of
1852 * type array, it is returned as-is, values of type object are
1853 * returned as one-element array containing the object, empty
1854 * strings and `null` values are returned as empty array, all other
1855 * values are converted using `String()`, trimmed, split on white
1856 * space and returned as array.
1862 * The value to convert into an array.
1864 * @return {Array
<*
>}
1865 * Returns the resulting array.
1867 toArray: function(val) {
1870 else if (Array.isArray(val))
1872 else if (typeof(val) == 'object')
1875 var s = String(val).trim();
1880 return s.split(/\s+/);
1884 * Returns a promise resolving with either the given value or or with
1885 * the given default in case the input value is a rejecting promise.
1891 * The value to resolve the promise with.
1893 * @param {*} defvalue
1894 * The default value to resolve the promise with in case the given
1895 * input value is a rejecting promise.
1897 * @returns {Promise
<*
>}
1898 * Returns a new promise resolving either to the given input value or
1899 * to the given default value on error.
1901 resolveDefault: function(value, defvalue) {
1902 return Promise.resolve(value).catch(function() { return defvalue });
1906 * The request callback function is invoked whenever an HTTP
1907 * reply to a request made using the `L.get()`, `L.post()` or
1908 * `L.poll()` function is timed out or received successfully.
1913 * @callback LuCI.requestCallbackFn
1914 * @param {XMLHTTPRequest} xhr
1915 * The XMLHTTPRequest instance used to make the request.
1918 * The response JSON if the response could be parsed as such,
1921 * @param {number} duration
1922 * The total duration of the request in milliseconds.
1926 * Issues a GET request to the given url and invokes the specified
1927 * callback function. The function is a wrapper around
1928 * {@link LuCI.Request#request Request.request()}.
1934 * @param {string} url
1935 * The URL to request.
1937 * @param {Object
<string, string
>} [args]
1938 * Additional query string arguments to append to the URL.
1940 * @param {LuCI.requestCallbackFn} cb
1941 * The callback function to invoke when the request finishes.
1943 * @return {Promise
<null
>}
1944 * Returns a promise resolving to `null` when concluded.
1946 get: function(url, args, cb) {
1947 return this.poll(null, url, args, cb, false);
1951 * Issues a POST request to the given url and invokes the specified
1952 * callback function. The function is a wrapper around
1953 * {@link LuCI.Request#request Request.request()}. The request is
1954 * sent using `application/x-www-form-urlencoded` encoding and will
1955 * contain a field `token` with the current value of `LuCI.env.token`
1962 * @param {string} url
1963 * The URL to request.
1965 * @param {Object
<string, string
>} [args]
1966 * Additional post arguments to append to the request body.
1968 * @param {LuCI.requestCallbackFn} cb
1969 * The callback function to invoke when the request finishes.
1971 * @return {Promise
<null
>}
1972 * Returns a promise resolving to `null` when concluded.
1974 post: function(url, args, cb) {
1975 return this.poll(null, url, args, cb, true);
1979 * Register a polling HTTP request that invokes the specified
1980 * callback function. The function is a wrapper around
1981 * {@link LuCI.Request.poll#add Request.poll.add()}.
1987 * @param {number} interval
1988 * The poll interval to use. If set to a value less than or equal
1989 * to `
0`, it will default to the global poll interval configured
1990 * in `LuCI.env.pollinterval`.
1992 * @param {string} url
1993 * The URL to request.
1995 * @param {Object
<string, string
>} [args]
1996 * Specifies additional arguments for the request. For GET requests,
1997 * the arguments are appended to the URL as query string, for POST
1998 * requests, they'll be added to the request body.
2000 * @param {LuCI.requestCallbackFn} cb
2001 * The callback function to invoke whenever a request finishes.
2003 * @param {boolean} [post=false]
2004 * When set to `false` or not specified, poll requests will be made
2005 * using the GET method. When set to `true`, POST requests will be
2006 * issued. In case of POST requests, the request body will contain
2007 * an argument `token` with the current value of `LuCI.env.token` by
2008 * default, regardless of the parameters specified with `args`.
2010 * @return {function}
2011 * Returns the internally created function that has been passed to
2012 * {@link LuCI.Request.poll#add Request.poll.add()}. This value can
2013 * be passed to {@link LuCI.Poll.remove Poll.remove()} to remove the
2016 poll: function(interval, url, args, cb, post) {
2017 if (interval !== null
&& interval
<=
0)
2018 interval = this.env.pollinterval;
2020 var data = post ? { token: this.env.token } : null,
2021 method = post ? 'POST' : 'GET';
2023 if (!/^(?:\/|\S+:\/\/)/.test(url))
2024 url = this.url(url);
2027 data = Object.assign(data || {}, args);
2029 if (interval !== null)
2030 return Request.poll.add(interval, url, { method: method, query: data }, cb);
2032 return Request.request(url, { method: method, query: data })
2033 .then(function(res) {
2035 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
2036 try { json = res.json() } catch(e) {}
2037 cb(res.xhr, json, res.duration);
2042 * Deprecated wrapper around {@link LuCI.Poll.remove Poll.remove()}.
2048 * @param {function} entry
2049 * The polling function to remove.
2052 * Returns `true` when the function has been removed or `false` if
2053 * it could not be found.
2055 stop: function(entry) { return Poll.remove(entry) },
2058 * Deprecated wrapper around {@link LuCI.Poll.stop Poll.stop()}.
2065 * Returns `true` when the polling loop has been stopped or `false`
2066 * when it didn't run to begin with.
2068 halt: function() { return Poll.stop() },
2071 * Deprecated wrapper around {@link LuCI.Poll.start Poll.start()}.
2078 * Returns `true` when the polling loop has been started or `false`
2079 * when it was already running.
2081 run: function() { return Poll.start() },
2090 * The `dom` class provides convenience method for creating and
2091 * manipulating DOM elements.
2093 dom: Class.singleton(/* @lends LuCI.dom.prototype */ {
2094 __name__: 'LuCI.DOM',
2097 * Tests whether the given argument is a valid DOM `Node`.
2100 * @memberof LuCI.dom
2102 * The value to test.
2104 * @returns {boolean}
2105 * Returns `true` if the value is a DOM `Node`, else `false`.
2108 return (e != null
&& typeof(e) == 'object'
&& 'nodeType' in e);
2112 * Parses a given string as HTML and returns the first child node.
2115 * @memberof LuCI.dom
2117 * A string containing an HTML fragment to parse. Note that only
2118 * the first result of the resulting structure is returned, so an
2119 * input value of `
<div
>foo
</div
> <div
>bar
</div
>` will only return
2120 * the first `div` element node.
2123 * Returns the first DOM `Node` extracted from the HTML fragment or
2124 * `null` on parsing failures or if no element could be found.
2126 parse: function(s) {
2130 domParser = domParser || new DOMParser();
2131 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
2137 dummyElem = dummyElem || document.createElement('div');
2138 dummyElem.innerHTML = s;
2139 elem = dummyElem.firstChild;
2144 return elem || null;
2148 * Tests whether a given `Node` matches the given query selector.
2150 * This function is a convenience wrapper around the standard
2151 * `Node.matches(
"selector")` function with the added benefit that
2152 * the `node` argument may be a non-`Node` value, in which case
2153 * this function simply returns `false`.
2156 * @memberof LuCI.dom
2158 * The `Node` argument to test the selector against.
2160 * @param {string} [selector]
2161 * The query selector expression to test against the given node.
2163 * @returns {boolean}
2164 * Returns `true` if the given node matches the specified selector
2165 * or `false` when the node argument is no valid DOM `Node` or the
2166 * selector didn't match.
2168 matches: function(node, selector) {
2169 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
2170 return m ? m.call(node, selector) : false;
2174 * Returns the closest parent node that matches the given query
2175 * selector expression.
2177 * This function is a convenience wrapper around the standard
2178 * `Node.closest(
"selector")` function with the added benefit that
2179 * the `node` argument may be a non-`Node` value, in which case
2180 * this function simply returns `null`.
2183 * @memberof LuCI.dom
2185 * The `Node` argument to find the closest parent for.
2187 * @param {string} [selector]
2188 * The query selector expression to test against each parent.
2190 * @returns {Node|null}
2191 * Returns the closest parent node matching the selector or
2192 * `null` when the node argument is no valid DOM `Node` or the
2193 * selector didn't match any parent.
2195 parent: function(node, selector) {
2196 if (this.elem(node)
&& node.closest)
2197 return node.closest(selector);
2199 while (this.elem(node))
2200 if (this.matches(node, selector))
2203 node = node.parentNode;
2209 * Appends the given children data to the given node.
2212 * @memberof LuCI.dom
2214 * The `Node` argument to append the children to.
2216 * @param {*} [children]
2217 * The childrens to append to the given node.
2219 * When `children` is an array, then each item of the array
2220 * will be either appended as child element or text node,
2221 * depending on whether the item is a DOM `Node` instance or
2222 * some other non-`null` value. Non-`Node`, non-`null` values
2223 * will be converted to strings first before being passed as
2224 * argument to `createTextNode()`.
2226 * When `children` is a function, it will be invoked with
2227 * the passed `node` argument as sole parameter and the `append`
2228 * function will be invoked again, with the given `node` argument
2229 * as first and the return value of the `children` function as
2232 * When `children` is is a DOM `Node` instance, it will be
2233 * appended to the given `node`.
2235 * When `children` is any other non-`null` value, it will be
2236 * converted to a string and appened to the `innerHTML` property
2237 * of the given `node`.
2239 * @returns {Node|null}
2240 * Returns the last children `Node` appended to the node or `null`
2241 * if either the `node` argument was no valid DOM `node` or if the
2242 * `children` was `null` or didn't result in further DOM nodes.
2244 append: function(node, children) {
2245 if (!this.elem(node))
2248 if (Array.isArray(children)) {
2249 for (var i =
0; i
< children.length; i++)
2250 if (this.elem(children[i]))
2251 node.appendChild(children[i]);
2252 else if (children !== null
&& children !== undefined)
2253 node.appendChild(document.createTextNode('' + children[i]));
2255 return node.lastChild;
2257 else if (typeof(children) === 'function') {
2258 return this.append(node, children(node));
2260 else if (this.elem(children)) {
2261 return node.appendChild(children);
2263 else if (children !== null
&& children !== undefined) {
2264 node.innerHTML = '' + children;
2265 return node.lastChild;
2272 * Replaces the content of the given node with the given children.
2274 * This function first removes any children of the given DOM
2275 * `Node` and then adds the given given children following the
2276 * rules outlined below.
2279 * @memberof LuCI.dom
2281 * The `Node` argument to replace the children of.
2283 * @param {*} [children]
2284 * The childrens to replace into the given node.
2286 * When `children` is an array, then each item of the array
2287 * will be either appended as child element or text node,
2288 * depending on whether the item is a DOM `Node` instance or
2289 * some other non-`null` value. Non-`Node`, non-`null` values
2290 * will be converted to strings first before being passed as
2291 * argument to `createTextNode()`.
2293 * When `children` is a function, it will be invoked with
2294 * the passed `node` argument as sole parameter and the `append`
2295 * function will be invoked again, with the given `node` argument
2296 * as first and the return value of the `children` function as
2299 * When `children` is is a DOM `Node` instance, it will be
2300 * appended to the given `node`.
2302 * When `children` is any other non-`null` value, it will be
2303 * converted to a string and appened to the `innerHTML` property
2304 * of the given `node`.
2306 * @returns {Node|null}
2307 * Returns the last children `Node` appended to the node or `null`
2308 * if either the `node` argument was no valid DOM `node` or if the
2309 * `children` was `null` or didn't result in further DOM nodes.
2311 content: function(node, children) {
2312 if (!this.elem(node))
2315 var dataNodes = node.querySelectorAll('[data-idref]');
2317 for (var i =
0; i
< dataNodes.length; i++)
2318 delete this.registry[dataNodes[i].getAttribute('data-idref')];
2320 while (node.firstChild)
2321 node.removeChild(node.firstChild);
2323 return this.append(node, children);
2327 * Sets attributes or registers event listeners on element nodes.
2330 * @memberof LuCI.dom
2332 * The `Node` argument to set the attributes or add the event
2333 * listeners for. When the given `node` value is not a valid
2334 * DOM `Node`, the function returns and does nothing.
2336 * @param {string|Object
<string, *
>} key
2337 * Specifies either the attribute or event handler name to use,
2338 * or an object containing multiple key, value pairs which are
2339 * each added to the node as either attribute or event handler,
2340 * depending on the respective value.
2343 * Specifies the attribute value or event handler function to add.
2344 * If the `key` parameter is an `Object`, this parameter will be
2347 * When `val` is of type function, it will be registered as event
2348 * handler on the given `node` with the `key` parameter being the
2351 * When `val` is of type object, it will be serialized as JSON and
2352 * added as attribute to the given `node`, using the given `key`
2353 * as attribute name.
2355 * When `val` is of any other type, it will be added as attribute
2356 * to the given `node` as-is, with the underlying `setAttribute()`
2357 * call implicitely turning it into a string.
2359 attr: function(node, key, val) {
2360 if (!this.elem(node))
2365 if (typeof(key) === 'object'
&& key !== null)
2367 else if (typeof(key) === 'string')
2368 attr = {}, attr[key] = val;
2371 if (!attr.hasOwnProperty(key) || attr[key] == null)
2374 switch (typeof(attr[key])) {
2376 node.addEventListener(key, attr[key]);
2380 node.setAttribute(key, JSON.stringify(attr[key]));
2384 node.setAttribute(key, attr[key]);
2390 * Creates a new DOM `Node` from the given `html`, `attr` and
2391 * `data` parameters.
2393 * This function has multiple signatures, it can be either invoked
2394 * in the form `create(html[, attr[, data]])` or in the form
2395 * `create(html[, data])`. The used variant is determined from the
2396 * type of the second argument.
2399 * @memberof LuCI.dom
2401 * Describes the node to create.
2403 * When the value of `html` is of type array, a `DocumentFragment`
2404 * node is created and each item of the array is first converted
2405 * to a DOM `Node` by passing it through `create()` and then added
2406 * as child to the fragment.
2408 * When the value of `html` is a DOM `Node` instance, no new
2409 * element will be created but the node will be used as-is.
2411 * When the value of `html` is a string starting with `
<`, it will
2412 * be passed to `dom.parse()` and the resulting value is used.
2414 * When the value of `html` is any other string, it will be passed
2415 * to `document.createElement()` for creating a new DOM `Node` of
2418 * @param {Object
<string, *
>} [attr]
2419 * Specifies an Object of key, value pairs to set as attributes
2420 * or event handlers on the created node. Refer to
2421 * {@link LuCI.dom#attr dom.attr()} for details.
2424 * Specifies children to append to the newly created element.
2425 * Refer to {@link LuCI.dom#append dom.append()} for details.
2427 * @throws {InvalidCharacterError}
2428 * Throws an `InvalidCharacterError` when the given `html`
2429 * argument contained malformed markup (such as not escaped
2430 * `
&` characters in XHTML mode) or when the given node name
2431 * in `html` contains characters which are not legal in DOM
2432 * element names, such as spaces.
2435 * Returns the newly created `Node`.
2437 create: function() {
2438 var html = arguments[
0],
2439 attr = arguments[
1],
2440 data = arguments[
2],
2443 if (!(attr instanceof Object) || Array.isArray(attr))
2444 data = attr, attr = null;
2446 if (Array.isArray(html)) {
2447 elem = document.createDocumentFragment();
2448 for (var i =
0; i
< html.length; i++)
2449 elem.appendChild(this.create(html[i]));
2451 else if (this.elem(html)) {
2454 else if (html.charCodeAt(
0) ===
60) {
2455 elem = this.parse(html);
2458 elem = document.createElement(html);
2464 this.attr(elem, attr);
2465 this.append(elem, data);
2473 * Attaches or detaches arbitrary data to and from a DOM `Node`.
2475 * This function is useful to attach non-string values or runtime
2476 * data that is not serializable to DOM nodes. To decouple data
2477 * from the DOM, values are not added directly to nodes, but
2478 * inserted into a registry instead which is then referenced by a
2479 * string key stored as `data-idref` attribute in the node.
2481 * This function has multiple signatures and is sensitive to the
2482 * number of arguments passed to it.
2484 * - `dom.data(node)` -
2485 * Fetches all data associated with the given node.
2486 * - `dom.data(node, key)` -
2487 * Fetches a specific key associated with the given node.
2488 * - `dom.data(node, key, val)` -
2489 * Sets a specific key to the given value associated with the
2491 * - `dom.data(node, null)` -
2492 * Clears any data associated with the node.
2493 * - `dom.data(node, key, null)` -
2494 * Clears the given key associated with the node.
2497 * @memberof LuCI.dom
2498 * @param {Node} node
2499 * The DOM `Node` instance to set or retrieve the data for.
2501 * @param {string|null} [key]
2502 * This is either a string specifying the key to retrieve, or
2503 * `null` to unset the entire node data.
2505 * @param {*|null} [val]
2506 * This is either a non-`null` value to set for a given key or
2507 * `null` to remove the given `key` from the specified node.
2510 * Returns the get or set value, or `null` when no value could
2513 data: function(node, key, val) {
2514 var id = node.getAttribute('data-idref');
2516 /* clear all data */
2517 if (arguments.length
> 1 && key == null) {
2519 node.removeAttribute('data-idref');
2520 val = this.registry[id]
2521 delete this.registry[id];
2529 else if (arguments.length
> 2 && key != null
&& val == null) {
2531 val = this.registry[id][key];
2532 delete this.registry[id][key];
2540 else if (arguments.length
> 2 && key != null
&& val != null) {
2542 do { id = Math.floor(Math.random() *
0xffffffff).toString(
16) }
2543 while (this.registry.hasOwnProperty(id));
2545 node.setAttribute('data-idref', id);
2546 this.registry[id] = {};
2549 return (this.registry[id][key] = val);
2553 else if (arguments.length ==
1) {
2555 return this.registry[id];
2561 else if (arguments.length ==
2) {
2563 return this.registry[id][key];
2570 * Binds the given class instance ot the specified DOM `Node`.
2572 * This function uses the `dom.data()` facility to attach the
2573 * passed instance of a Class to a node. This is needed for
2574 * complex widget elements or similar where the corresponding
2575 * class instance responsible for the element must be retrieved
2576 * from DOM nodes obtained by `querySelector()` or similar means.
2579 * @memberof LuCI.dom
2580 * @param {Node} node
2581 * The DOM `Node` instance to bind the class to.
2583 * @param {Class} inst
2584 * The Class instance to bind to the node.
2586 * @throws {TypeError}
2587 * Throws a `TypeError` when the given instance argument isn't
2588 * a valid Class instance.
2591 * Returns the bound class instance.
2593 bindClassInstance: function(node, inst) {
2594 if (!(inst instanceof Class))
2595 L.error('TypeError', 'Argument must be a class instance');
2597 return this.data(node, '_class', inst);
2601 * Finds a bound class instance on the given node itself or the
2602 * first bound instance on its closest parent node.
2605 * @memberof LuCI.dom
2606 * @param {Node} node
2607 * The DOM `Node` instance to start from.
2609 * @returns {Class|null}
2610 * Returns the founds class instance if any or `null` if no bound
2611 * class could be found on the node itself or any of its parents.
2613 findClassInstance: function(node) {
2617 inst = this.data(node, '_class');
2618 node = node.parentNode;
2620 while (!(inst instanceof Class)
&& node != null);
2626 * Finds a bound class instance on the given node itself or the
2627 * first bound instance on its closest parent node and invokes
2628 * the specified method name on the found class instance.
2631 * @memberof LuCI.dom
2632 * @param {Node} node
2633 * The DOM `Node` instance to start from.
2635 * @param {string} method
2636 * The name of the method to invoke on the found class instance.
2638 * @param {...*} params
2639 * Additional arguments to pass to the invoked method as-is.
2642 * Returns the return value of the invoked method if a class
2643 * instance and method has been found. Returns `null` if either
2644 * no bound class instance could be found, or if the found
2645 * instance didn't have the requested `method`.
2647 callClassMethod: function(node, method /*, ... */) {
2648 var inst = this.findClassInstance(node);
2650 if (inst == null || typeof(inst[method]) != 'function')
2653 return inst[method].apply(inst, inst.varargs(arguments,
2));
2657 * The ignore callback function is invoked by `isEmpty()` for each
2658 * child node to decide whether to ignore a child node or not.
2660 * When this function returns `false`, the node passed to it is
2661 * ignored, else not.
2663 * @callback LuCI.dom~ignoreCallbackFn
2664 * @param {Node} node
2665 * The child node to test.
2667 * @returns {boolean}
2668 * Boolean indicating whether to ignore the node or not.
2672 * Tests whether a given DOM `Node` instance is empty or appears
2675 * Any element child nodes which have the CSS class `hidden` set
2676 * or for which the optionally passed `ignoreFn` callback function
2677 * returns `false` are ignored.
2680 * @memberof LuCI.dom
2681 * @param {Node} node
2682 * The DOM `Node` instance to test.
2684 * @param {LuCI.dom~ignoreCallbackFn} [ignoreFn]
2685 * Specifies an optional function which is invoked for each child
2686 * node to decide whether the child node should be ignored or not.
2688 * @returns {boolean}
2689 * Returns `true` if the node does not have any children or if
2690 * any children node either has a `hidden` CSS class or a `false`
2691 * result when testing it using the given `ignoreFn`.
2693 isEmpty: function(node, ignoreFn) {
2694 for (var child = node.firstElementChild; child != null; child = child.nextElementSibling)
2695 if (!child.classList.contains('hidden')
&& (!ignoreFn || !ignoreFn(child)))
2712 * The `view` class forms the basis of views and provides a standard
2713 * set of methods to inherit from.
2715 view: Class.extend(/* @lends LuCI.view.prototype */ {
2716 __name__: 'LuCI.View',
2718 __init__: function() {
2719 var vp = document.getElementById('view');
2721 L.dom.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
2723 return Promise.resolve(this.load())
2724 .then(L.bind(this.render, this))
2725 .then(L.bind(function(nodes) {
2726 var vp = document.getElementById('view');
2728 L.dom.content(vp, nodes);
2729 L.dom.append(vp, this.addFooter());
2730 }, this)).catch(L.error);
2734 * The load function is invoked before the view is rendered.
2736 * The invocation of this function is wrapped by
2737 * `Promise.resolve()` so it may return Promises if needed.
2739 * The return value of the function (or the resolved values
2740 * of the promise returned by it) will be passed as first
2741 * argument to `render()`.
2743 * This function is supposed to be overwritten by subclasses,
2744 * the default implementation does nothing.
2748 * @memberof LuCI.view
2750 * @returns {*|Promise
<*
>}
2751 * May return any value or a Promise resolving to any value.
2753 load: function() {},
2756 * The render function is invoked after the
2757 * {@link LuCI.view#load load()} function and responsible
2758 * for setting up the view contents. It must return a DOM
2759 * `Node` or `DocumentFragment` holding the contents to
2760 * insert into the view area.
2762 * The invocation of this function is wrapped by
2763 * `Promise.resolve()` so it may return Promises if needed.
2765 * The return value of the function (or the resolved values
2766 * of the promise returned by it) will be inserted into the
2767 * main content area using
2768 * {@link LuCI.dom#append dom.append()}.
2770 * This function is supposed to be overwritten by subclasses,
2771 * the default implementation does nothing.
2775 * @memberof LuCI.view
2776 * @param {*|null} load_results
2777 * This function will receive the return value of the
2778 * {@link LuCI.view#load view.load()} function as first
2781 * @returns {Node|Promise
<Node
>}
2782 * Should return a DOM `Node` value or a `Promise` resolving
2783 * to a `Node` value.
2785 render: function() {},
2788 * The handleSave function is invoked when the user clicks
2789 * the `Save` button in the page action footer.
2791 * The default implementation should be sufficient for most
2792 * views using {@link form#Map form.Map()} based forms - it
2793 * will iterate all forms present in the view and invoke
2794 * the {@link form#Map#save Map.save()} method on each form.
2796 * Views not using `Map` instances or requiring other special
2797 * logic should overwrite `handleSave()` with a custom
2800 * To disable the `Save` page footer button, views extending
2801 * this base class should overwrite the `handleSave` function
2804 * The invocation of this function is wrapped by
2805 * `Promise.resolve()` so it may return Promises if needed.
2808 * @memberof LuCI.view
2810 * The DOM event that triggered the function.
2812 * @returns {*|Promise
<*
>}
2813 * Any return values of this function are discarded, but
2814 * passed through `Promise.resolve()` to ensure that any
2815 * returned promise runs to completion before the button
2818 handleSave: function(ev) {
2821 document.getElementById('maincontent')
2822 .querySelectorAll('.cbi-map').forEach(function(map) {
2823 tasks.push(L.dom.callClassMethod(map, 'save'));
2826 return Promise.all(tasks);
2830 * The handleSaveApply function is invoked when the user clicks
2831 * the `Save
& Apply` button in the page action footer.
2833 * The default implementation should be sufficient for most
2834 * views using {@link form#Map form.Map()} based forms - it
2836 * {@link LuCI.view.handleSave view.handleSave()} and then
2837 * call {@link ui#changes#apply ui.changes.apply()} to start the
2838 * modal config apply and page reload flow.
2840 * Views not using `Map` instances or requiring other special
2841 * logic should overwrite `handleSaveApply()` with a custom
2844 * To disable the `Save
& Apply` page footer button, views
2845 * extending this base class should overwrite the
2846 * `handleSaveApply` function with `null`.
2848 * The invocation of this function is wrapped by
2849 * `Promise.resolve()` so it may return Promises if needed.
2852 * @memberof LuCI.view
2854 * The DOM event that triggered the function.
2856 * @returns {*|Promise
<*
>}
2857 * Any return values of this function are discarded, but
2858 * passed through `Promise.resolve()` to ensure that any
2859 * returned promise runs to completion before the button
2862 handleSaveApply: function(ev) {
2863 return this.handleSave(ev).then(function() {
2864 L.ui.changes.apply(true);
2869 * The handleReset function is invoked when the user clicks
2870 * the `Reset` button in the page action footer.
2872 * The default implementation should be sufficient for most
2873 * views using {@link form#Map form.Map()} based forms - it
2874 * will iterate all forms present in the view and invoke
2875 * the {@link form#Map#save Map.reset()} method on each form.
2877 * Views not using `Map` instances or requiring other special
2878 * logic should overwrite `handleReset()` with a custom
2881 * To disable the `Reset` page footer button, views extending
2882 * this base class should overwrite the `handleReset` function
2885 * The invocation of this function is wrapped by
2886 * `Promise.resolve()` so it may return Promises if needed.
2889 * @memberof LuCI.view
2891 * The DOM event that triggered the function.
2893 * @returns {*|Promise
<*
>}
2894 * Any return values of this function are discarded, but
2895 * passed through `Promise.resolve()` to ensure that any
2896 * returned promise runs to completion before the button
2899 handleReset: function(ev) {
2902 document.getElementById('maincontent')
2903 .querySelectorAll('.cbi-map').forEach(function(map) {
2904 tasks.push(L.dom.callClassMethod(map, 'reset'));
2907 return Promise.all(tasks);
2911 * Renders a standard page action footer if any of the
2912 * `handleSave()`, `handleSaveApply()` or `handleReset()`
2913 * functions are defined.
2915 * The default implementation should be sufficient for most
2916 * views - it will render a standard page footer with action
2917 * buttons labeled `Save`, `Save
& Apply` and `Reset`
2918 * triggering the `handleSave()`, `handleSaveApply()` and
2919 * `handleReset()` functions respectively.
2921 * When any of these `handle*()` functions is overwritten
2922 * with `null` by a view extending this class, the
2923 * corresponding button will not be rendered.
2926 * @memberof LuCI.view
2927 * @returns {DocumentFragment}
2928 * Returns a `DocumentFragment` containing the footer bar
2929 * with buttons for each corresponding `handle*()` action
2930 * or an empty `DocumentFragment` if all three `handle*()`
2931 * methods are overwritten with `null`.
2933 addFooter: function() {
2936 if (this.handleSaveApply || this.handleSave || this.handleReset) {
2937 footer.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
2938 this.handleSaveApply ? E('button', {
2939 'class': 'cbi-button cbi-button-apply',
2940 'click': L.ui.createHandlerFn(this, 'handleSaveApply')
2941 }, [ _('Save
& Apply') ]) : '', ' ',
2942 this.handleSave ? E('button', {
2943 'class': 'cbi-button cbi-button-save',
2944 'click': L.ui.createHandlerFn(this, 'handleSave')
2945 }, [ _('Save') ]) : '', ' ',
2946 this.handleReset ? E('button', {
2947 'class': 'cbi-button cbi-button-reset',
2948 'click': L.ui.createHandlerFn(this, 'handleReset')
2949 }, [ _('Reset') ]) : ''
2964 * The `LuCI.XHR` class is a legacy compatibility shim for the
2965 * functionality formerly provided by `xhr.js`. It is registered as global
2966 * `window.XHR` symbol for compatibility with legacy code.
2968 * New code should use {@link LuCI.Request} instead to implement HTTP
2971 var XHR = Class.extend(/** @lends LuCI.XHR.prototype */ {
2972 __name__: 'LuCI.XHR',
2973 __init__: function() {
2974 if (window.console
&& console.debug)
2975 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
2978 _response: function(cb, res, json, duration) {
2980 cb(res, json, duration);
2985 * This function is a legacy wrapper around
2986 * {@link LuCI#get LuCI.get()}.
2990 * @memberof LuCI.XHR
2992 * @param {string} url
2993 * The URL to request
2995 * @param {Object} [data]
2996 * Additional query string data
2998 * @param {LuCI.requestCallbackFn} [callback]
2999 * Callback function to invoke on completion
3001 * @param {number} [timeout]
3002 * Request timeout to use
3004 * @return {Promise
<null
>}
3006 get: function(url, data, callback, timeout) {
3008 L.get(url, data, this._response.bind(this, callback), timeout);
3012 * This function is a legacy wrapper around
3013 * {@link LuCI#post LuCI.post()}.
3017 * @memberof LuCI.XHR
3019 * @param {string} url
3020 * The URL to request
3022 * @param {Object} [data]
3023 * Additional data to append to the request body.
3025 * @param {LuCI.requestCallbackFn} [callback]
3026 * Callback function to invoke on completion
3028 * @param {number} [timeout]
3029 * Request timeout to use
3031 * @return {Promise
<null
>}
3033 post: function(url, data, callback, timeout) {
3035 L.post(url, data, this._response.bind(this, callback), timeout);
3039 * Cancels a running request.
3041 * This function does not actually cancel the underlying
3042 * `XMLHTTPRequest` request but it sets a flag which prevents the
3043 * invocation of the callback function when the request eventually
3044 * finishes or timed out.
3048 * @memberof LuCI.XHR
3050 cancel: function() { delete this.active },
3053 * Checks the running state of the request.
3057 * @memberof LuCI.XHR
3059 * @returns {boolean}
3060 * Returns `true` if the request is still running or `false` if it
3061 * already completed.
3063 busy: function() { return (this.active === true) },
3066 * Ignored for backwards compatibility.
3068 * This function does nothing.
3072 * @memberof LuCI.XHR
3074 abort: function() {},
3077 * Existing for backwards compatibility.
3079 * This function simply throws an `InternalError` when invoked.
3083 * @memberof LuCI.XHR
3085 * @throws {InternalError}
3086 * Throws an `InternalError` with the message `Not implemented`
3089 send_form: function() { L.error('InternalError', 'Not implemented') },
3092 XHR.get = function() { return window.L.get.apply(window.L, arguments) };
3093 XHR.post = function() { return window.L.post.apply(window.L, arguments) };
3094 XHR.poll = function() { return window.L.poll.apply(window.L, arguments) };
3095 XHR.stop = Request.poll.remove.bind(Request.poll);
3096 XHR.halt = Request.poll.stop.bind(Request.poll);
3097 XHR.run = Request.poll.start.bind(Request.poll);
3098 XHR.running = Request.poll.active.bind(Request.poll);
3102 })(window, document);
3113 <h2><a href=
"index.html">Home
</a></h2><h3>Classes
</h3><ul><li><a href=
"LuCI.html">LuCI
</a></li><li><a href=
"LuCI.Class.html">Class
</a></li><li><a href=
"LuCI.dom.html">dom
</a></li><li><a href=
"LuCI.fs.html">fs
</a></li><li><a href=
"LuCI.Headers.html">Headers
</a></li><li><a href=
"LuCI.Network.html">Network
</a></li><li><a href=
"LuCI.Network.Device.html">Device
</a></li><li><a href=
"LuCI.Network.Hosts.html">Hosts
</a></li><li><a href=
"LuCI.Network.Protocol.html">Protocol
</a></li><li><a href=
"LuCI.Network.WifiDevice.html">WifiDevice
</a></li><li><a href=
"LuCI.Network.WifiNetwork.html">WifiNetwork
</a></li><li><a href=
"LuCI.Poll.html">Poll
</a></li><li><a href=
"LuCI.Request.html">Request
</a></li><li><a href=
"LuCI.Request.poll.html">poll
</a></li><li><a href=
"LuCI.Response.html">Response
</a></li><li><a href=
"LuCI.rpc.html">rpc
</a></li><li><a href=
"LuCI.uci.html">uci
</a></li><li><a href=
"LuCI.view.html">view
</a></li><li><a href=
"LuCI.XHR.html">XHR
</a></li></ul>
3119 Documentation generated by
<a href=
"https://github.com/jsdoc/jsdoc">JSDoc
3.6.3</a> on Tue Nov
05 2019 09:
33:
05 GMT+
0100 (Central European Standard Time)
3122 <script> prettyPrint();
</script>
3123 <script src=
"scripts/linenumber.js"> </script>