5 * This is the LuCI base class. It is automatically instantiated and
6 * accessible using the global `L` variable.
9 * The environment settings to use for the LuCI runtime.
12 (function(window, document, undefined) {
15 /* Object.assign polyfill for IE */
16 if (typeof Object.assign !== 'function') {
17 Object.defineProperty(Object, 'assign', {
18 value: function assign(target, varArgs) {
20 throw new TypeError('Cannot convert undefined or null to object');
22 var to = Object(target);
24 for (var index = 1; index < arguments.length; index++)
25 if (arguments[index] != null)
26 for (var nextKey in arguments[index])
27 if (Object.prototype.hasOwnProperty.call(arguments[index], nextKey))
28 to[nextKey] = arguments[index][nextKey];
37 /* Promise.finally polyfill */
38 if (typeof Promise.prototype.finally !== 'function') {
39 Promise.prototype.finally = function(fn) {
40 var onFinally = function(cb) {
41 return Promise.resolve(fn.call(this)).then(cb);
45 function(result) { return onFinally.call(this, function() { return result }) },
46 function(reason) { return onFinally.call(this, function() { return Promise.reject(reason) }) }
52 * Class declaration and inheritance helper
55 var toCamelCase = function(s) {
56 return s.replace(/(?:^|[\. -])(.)/g, function(m0, m1) { return m1.toUpperCase() });
65 * `LuCI.baseclass` is the abstract base class all LuCI classes inherit from.
67 * It provides simple means to create subclasses of given classes and
68 * implements prototypal inheritance.
70 var superContext = {}, classIndex = 0, Class = Object.assign(function() {}, {
72 * Extends this base class with the properties described in
73 * `properties` and returns a new subclassed Class instance
75 * @memberof LuCI.baseclass
77 * @param {Object<string, *>} properties
78 * An object describing the properties to add to the new
81 * @returns {LuCI.baseclass}
82 * Returns a new LuCI.baseclass sublassed from this class, extended
83 * by the given properties and with its prototype set to this base
84 * class to enable inheritance. The resulting value represents a
85 * class constructor and can be instantiated with `new`.
87 extend: function(properties) {
89 __id__: { value: classIndex },
90 __base__: { value: this.prototype },
91 __name__: { value: properties.__name__ || 'anonymous' + classIndex++ }
94 var ClassConstructor = function() {
95 if (!(this instanceof ClassConstructor))
96 throw new TypeError('Constructor must not be called without "new"');
98 if (Object.getPrototypeOf(this).hasOwnProperty('__init__')) {
99 if (typeof(this.__init__) != 'function')
100 throw new TypeError('Class __init__ member is not a function');
102 this.__init__.apply(this, arguments)
105 this.super('__init__', arguments);
109 for (var key in properties)
110 if (!props[key] && properties.hasOwnProperty(key))
111 props[key] = { value: properties[key], writable: true };
113 ClassConstructor.prototype = Object.create(this.prototype, props);
114 ClassConstructor.prototype.constructor = ClassConstructor;
115 Object.assign(ClassConstructor, this);
116 ClassConstructor.displayName = toCamelCase(props.__name__.value + 'Class');
118 return ClassConstructor;
122 * Extends this base class with the properties described in
123 * `properties`, instantiates the resulting subclass using
124 * the additional optional arguments passed to this function
125 * and returns the resulting subclassed Class instance.
127 * This function serves as a convenience shortcut for
128 * {@link LuCI.baseclass.extend Class.extend()} and subsequent
131 * @memberof LuCI.baseclass
133 * @param {Object<string, *>} properties
134 * An object describing the properties to add to the new
137 * @param {...*} [new_args]
138 * Specifies arguments to be passed to the subclass constructor
139 * as-is in order to instantiate the new subclass.
141 * @returns {LuCI.baseclass}
142 * Returns a new LuCI.baseclass instance extended by the given
143 * properties with its prototype set to this base class to
144 * enable inheritance.
146 singleton: function(properties /*, ... */) {
147 return Class.extend(properties)
148 .instantiate(Class.prototype.varargs(arguments, 1));
152 * Calls the class constructor using `new` with the given argument
153 * array being passed as variadic parameters to the constructor.
155 * @memberof LuCI.baseclass
157 * @param {Array<*>} params
158 * An array of arbitrary values which will be passed as arguments
159 * to the constructor function.
161 * @param {...*} [new_args]
162 * Specifies arguments to be passed to the subclass constructor
163 * as-is in order to instantiate the new subclass.
165 * @returns {LuCI.baseclass}
166 * Returns a new LuCI.baseclass instance extended by the given
167 * properties with its prototype set to this base class to
168 * enable inheritance.
170 instantiate: function(args) {
171 return new (Function.prototype.bind.apply(this,
172 Class.prototype.varargs(args, 0, null)))();
176 call: function(self, method) {
177 if (typeof(this.prototype[method]) != 'function')
178 throw new ReferenceError(method + ' is not defined in class');
180 return this.prototype[method].apply(self, self.varargs(arguments, 1));
184 * Checks whether the given class value is a subclass of this class.
186 * @memberof LuCI.baseclass
188 * @param {LuCI.baseclass} classValue
189 * The class object to test.
192 * Returns `true` when the given `classValue` is a subclass of this
193 * class or `false` if the given value is not a valid class or not
194 * a subclass of this class'.
196 isSubclass: function(classValue) {
197 return (classValue != null &&
198 typeof(classValue) == 'function' &&
199 classValue.prototype instanceof this);
204 * Extract all values from the given argument array beginning from
205 * `offset` and prepend any further given optional parameters to
206 * the beginning of the resulting array copy.
208 * @memberof LuCI.baseclass
211 * @param {Array<*>} args
212 * The array to extract the values from.
214 * @param {number} offset
215 * The offset from which to extract the values. An offset of `0`
216 * would copy all values till the end.
218 * @param {...*} [extra_args]
219 * Extra arguments to add to prepend to the resultung array.
221 * @returns {Array<*>}
222 * Returns a new array consisting of the optional extra arguments
223 * and the values extracted from the `args` array beginning with
226 varargs: function(args, offset /*, ... */) {
227 return Array.prototype.slice.call(arguments, 2)
228 .concat(Array.prototype.slice.call(args, offset));
232 * Walks up the parent class chain and looks for a class member
233 * called `key` in any of the parent classes this class inherits
234 * from. Returns the member value of the superclass or calls the
235 * member as function and returns its return value when the
236 * optional `callArgs` array is given.
238 * This function has two signatures and is sensitive to the
239 * amount of arguments passed to it:
241 * Returns the value of `key` when found within one of the
243 * - `super('key', ['arg1', 'arg2'])` -
244 * Calls the `key()` method with parameters `arg1` and `arg2`
245 * when found within one of the parent classes.
247 * @memberof LuCI.baseclass
250 * @param {string} key
251 * The name of the superclass member to retrieve.
253 * @param {Array<*>} [callArgs]
254 * An optional array of function call parameters to use. When
255 * this parameter is specified, the found member value is called
256 * as function using the values of this array as arguments.
258 * @throws {ReferenceError}
259 * Throws a `ReferenceError` when `callArgs` are specified and
260 * the found member named by `key` is not a function value.
263 * Returns the value of the found member or the return value of
264 * the call to the found method. Returns `null` when no member
265 * was found in the parent class chain or when the call to the
266 * superclass method returned `null`.
268 super: function(key, callArgs) {
272 var slotIdx = this.__id__ + '.' + key,
273 symStack = superContext[slotIdx],
276 for (protoCtx = Object.getPrototypeOf(symStack ? symStack[0] : Object.getPrototypeOf(this));
277 protoCtx != null && !protoCtx.hasOwnProperty(key);
278 protoCtx = Object.getPrototypeOf(protoCtx)) {}
280 if (protoCtx == null)
283 var res = protoCtx[key];
285 if (arguments.length > 1) {
286 if (typeof(res) != 'function')
287 throw new ReferenceError(key + ' is not a function in base class');
289 if (typeof(callArgs) != 'object')
290 callArgs = this.varargs(arguments, 1);
293 symStack.unshift(protoCtx);
295 superContext[slotIdx] = [ protoCtx ];
297 res = res.apply(this, callArgs);
299 if (symStack && symStack.length > 1)
300 symStack.shift(protoCtx);
302 delete superContext[slotIdx];
309 * Returns a string representation of this class.
312 * Returns a string representation of this class containing the
313 * constructor functions `displayName` and describing the class
314 * members and their respective types.
316 toString: function() {
317 var s = '[' + this.constructor.displayName + ']', f = true;
318 for (var k in this) {
319 if (this.hasOwnProperty(k)) {
320 s += (f ? ' {\n' : '') + ' ' + k + ': ' + typeof(this[k]) + '\n';
324 return s + (f ? '' : '}');
336 * The `Headers` class is an internal utility class exposed in HTTP
337 * response objects using the `response.headers` property.
339 var Headers = Class.extend(/** @lends LuCI.headers.prototype */ {
340 __name__: 'LuCI.headers',
341 __init__: function(xhr) {
342 var hdrs = this.headers = {};
343 xhr.getAllResponseHeaders().split(/\r\n/).forEach(function(line) {
344 var m = /^([^:]+):(.*)$/.exec(line);
346 hdrs[m[1].trim().toLowerCase()] = m[2].trim();
351 * Checks whether the given header name is present.
352 * Note: Header-Names are case-insensitive.
355 * @memberof LuCI.headers
356 * @param {string} name
357 * The header name to check
360 * Returns `true` if the header name is present, `false` otherwise
362 has: function(name) {
363 return this.headers.hasOwnProperty(String(name).toLowerCase());
367 * Returns the value of the given header name.
368 * Note: Header-Names are case-insensitive.
371 * @memberof LuCI.headers
372 * @param {string} name
373 * The header name to read
375 * @returns {string|null}
376 * The value of the given header name or `null` if the header isn't present.
378 get: function(name) {
379 var key = String(name).toLowerCase();
380 return this.headers.hasOwnProperty(key) ? this.headers[key] : null;
390 * The `Response` class is an internal utility class representing HTTP responses.
392 var Response = Class.extend({
393 __name__: 'LuCI.response',
394 __init__: function(xhr, url, duration, headers, content) {
396 * Describes whether the response is successful (status codes `200..299`) or not
398 * @memberof LuCI.response
402 this.ok = (xhr.status >= 200 && xhr.status <= 299);
405 * The numeric HTTP status code of the response
407 * @memberof LuCI.response
411 this.status = xhr.status;
414 * The HTTP status description message of the response
416 * @memberof LuCI.response
420 this.statusText = xhr.statusText;
423 * The HTTP headers of the response
425 * @memberof LuCI.response
427 * @type {LuCI.headers}
429 this.headers = (headers != null) ? headers : new Headers(xhr);
432 * The total duration of the HTTP request in milliseconds
434 * @memberof LuCI.response
438 this.duration = duration;
441 * The final URL of the request, i.e. after following redirects.
443 * @memberof LuCI.response
452 if (content instanceof Blob) {
453 this.responseBlob = content;
454 this.responseJSON = null;
455 this.responseText = null;
457 else if (content != null && typeof(content) == 'object') {
458 this.responseBlob = null;
459 this.responseJSON = content;
460 this.responseText = null;
462 else if (content != null) {
463 this.responseBlob = null;
464 this.responseJSON = null;
465 this.responseText = String(content);
468 this.responseJSON = null;
470 if (xhr.responseType == 'blob') {
471 this.responseBlob = xhr.response;
472 this.responseText = null;
475 this.responseBlob = null;
476 this.responseText = xhr.responseText;
482 * Clones the given response object, optionally overriding the content
483 * of the cloned instance.
486 * @memberof LuCI.response
487 * @param {*} [content]
488 * Override the content of the cloned response. Object values will be
489 * treated as JSON response data, all other types will be converted
490 * using `String()` and treated as response text.
492 * @returns {LuCI.response}
493 * The cloned `Response` instance.
495 clone: function(content) {
496 var copy = new Response(this.xhr, this.url, this.duration, this.headers, content);
499 copy.status = this.status;
500 copy.statusText = this.statusText;
506 * Access the response content as JSON data.
509 * @memberof LuCI.response
510 * @throws {SyntaxError}
511 * Throws `SyntaxError` if the content isn't valid JSON.
514 * The parsed JSON data.
517 if (this.responseJSON == null)
518 this.responseJSON = JSON.parse(this.responseText);
520 return this.responseJSON;
524 * Access the response content as string.
527 * @memberof LuCI.response
529 * The response content.
532 if (this.responseText == null && this.responseJSON != null)
533 this.responseText = JSON.stringify(this.responseJSON);
535 return this.responseText;
539 * Access the response content as blob.
542 * @memberof LuCI.response
544 * The response content as blob.
547 return this.responseBlob;
552 var requestQueue = [];
554 function isQueueableRequest(opt) {
558 if (opt.method != 'POST' || typeof(opt.content) != 'object')
561 if (opt.nobatch === true)
564 var rpcBaseURL = Request.expandURL(classes.rpc.getBaseURL());
566 return (rpcBaseURL != null && opt.url.indexOf(rpcBaseURL) == 0);
569 function flushRequestQueue() {
570 if (!requestQueue.length)
573 var reqopt = Object.assign({}, requestQueue[0][0], { content: [], nobatch: true }),
576 for (var i = 0; i < requestQueue.length; i++) {
577 batch[i] = requestQueue[i];
578 reqopt.content[i] = batch[i][0].content;
581 requestQueue.length = 0;
583 Request.request(rpcBaseURL, reqopt).then(function(reply) {
584 var json = null, req = null;
586 try { json = reply.json() }
589 while ((req = batch.shift()) != null)
590 if (Array.isArray(json) && json.length)
591 req[2].call(reqopt, reply.clone(json.shift()));
593 req[1].call(reqopt, new Error('No related RPC reply'));
594 }).catch(function(error) {
597 while ((req = batch.shift()) != null)
598 req[1].call(reqopt, error);
608 * The `Request` class allows initiating HTTP requests and provides utilities
609 * for dealing with responses.
611 var Request = Class.singleton(/** @lends LuCI.request.prototype */ {
612 __name__: 'LuCI.request',
617 * Turn the given relative URL into an absolute URL if necessary.
620 * @memberof LuCI.request
621 * @param {string} url
622 * The URL to convert.
625 * The absolute URL derived from the given one, or the original URL
626 * if it already was absolute.
628 expandURL: function(url) {
629 if (!/^(?:[^/]+:)?\/\//.test(url))
630 url = location.protocol + '//' + location.host + url;
636 * @typedef {Object} RequestOptions
637 * @memberof LuCI.request
639 * @property {string} [method=GET]
640 * The HTTP method to use, e.g. `GET` or `POST`.
642 * @property {Object<string, Object|string>} [query]
643 * Query string data to append to the URL. Non-string values of the
644 * given object will be converted to JSON.
646 * @property {boolean} [cache=false]
647 * Specifies whether the HTTP response may be retrieved from cache.
649 * @property {string} [username]
650 * Provides a username for HTTP basic authentication.
652 * @property {string} [password]
653 * Provides a password for HTTP basic authentication.
655 * @property {number} [timeout]
656 * Specifies the request timeout in seconds.
658 * @property {boolean} [credentials=false]
659 * Whether to include credentials such as cookies in the request.
661 * @property {string} [responseType=text]
662 * Overrides the request response type. Valid values or `text` to
663 * interpret the response as UTF-8 string or `blob` to handle the
664 * response as binary `Blob` data.
666 * @property {*} [content]
667 * Specifies the HTTP message body to send along with the request.
668 * If the value is a function, it is invoked and the return value
669 * used as content, if it is a FormData instance, it is used as-is,
670 * if it is an object, it will be converted to JSON, in all other
671 * cases it is converted to a string.
673 * @property {Object<string, string>} [header]
674 * Specifies HTTP headers to set for the request.
676 * @property {function} [progress]
677 * An optional request callback function which receives ProgressEvent
678 * instances as sole argument during the HTTP request transfer.
682 * Initiate an HTTP request to the given target.
685 * @memberof LuCI.request
686 * @param {string} target
687 * The URL to request.
689 * @param {LuCI.request.RequestOptions} [options]
690 * Additional options to configure the request.
692 * @returns {Promise<LuCI.response>}
693 * The resulting HTTP response.
695 request: function(target, options) {
696 var state = { xhr: new XMLHttpRequest(), url: this.expandURL(target), start: Date.now() },
697 opt = Object.assign({}, options, state),
700 callback = this.handleReadyStateChange;
702 return new Promise(function(resolveFn, rejectFn) {
703 opt.xhr.onreadystatechange = callback.bind(opt, resolveFn, rejectFn);
704 opt.method = String(opt.method || 'GET').toUpperCase();
706 if ('query' in opt) {
707 var q = (opt.query != null) ? Object.keys(opt.query).map(function(k) {
708 if (opt.query[k] != null) {
709 var v = (typeof(opt.query[k]) == 'object')
710 ? JSON.stringify(opt.query[k])
711 : String(opt.query[k]);
713 return '%s=%s'.format(encodeURIComponent(k), encodeURIComponent(v));
716 return encodeURIComponent(k);
721 switch (opt.method) {
725 opt.url += ((/\?/).test(opt.url) ? '&' : '?') + q;
729 if (content == null) {
731 contenttype = 'application/x-www-form-urlencoded';
738 opt.url += ((/\?/).test(opt.url) ? '&' : '?') + (new Date()).getTime();
740 if (isQueueableRequest(opt)) {
741 requestQueue.push([opt, rejectFn, resolveFn]);
742 requestAnimationFrame(flushRequestQueue);
746 if ('username' in opt && 'password' in opt)
747 opt.xhr.open(opt.method, opt.url, true, opt.username, opt.password);
749 opt.xhr.open(opt.method, opt.url, true);
751 opt.xhr.responseType = opt.responseType || 'text';
753 if ('overrideMimeType' in opt.xhr)
754 opt.xhr.overrideMimeType('application/octet-stream');
756 if ('timeout' in opt)
757 opt.xhr.timeout = +opt.timeout;
759 if ('credentials' in opt)
760 opt.xhr.withCredentials = !!opt.credentials;
762 if (opt.content != null) {
763 switch (typeof(opt.content)) {
765 content = opt.content(xhr);
769 if (!(opt.content instanceof FormData)) {
770 content = JSON.stringify(opt.content);
771 contenttype = 'application/json';
774 content = opt.content;
779 content = String(opt.content);
783 if ('headers' in opt)
784 for (var header in opt.headers)
785 if (opt.headers.hasOwnProperty(header)) {
786 if (header.toLowerCase() != 'content-type')
787 opt.xhr.setRequestHeader(header, opt.headers[header]);
789 contenttype = opt.headers[header];
792 if ('progress' in opt && 'upload' in opt.xhr)
793 opt.xhr.upload.addEventListener('progress', opt.progress);
795 if (contenttype != null)
796 opt.xhr.setRequestHeader('Content-Type', contenttype);
799 opt.xhr.send(content);
802 rejectFn.call(opt, e);
807 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
809 duration = Date.now() - this.start;
811 if (xhr.readyState !== 4)
814 if (xhr.status === 0 && xhr.statusText === '') {
815 if (duration >= this.timeout)
816 rejectFn.call(this, new Error('XHR request timed out'));
818 rejectFn.call(this, new Error('XHR request aborted by browser'));
821 var response = new Response(
822 xhr, xhr.responseURL || this.url, duration);
824 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
825 .then(resolveFn.bind(this, response))
826 .catch(rejectFn.bind(this));
831 * Initiate an HTTP GET request to the given target.
834 * @memberof LuCI.request
835 * @param {string} target
836 * The URL to request.
838 * @param {LuCI.request.RequestOptions} [options]
839 * Additional options to configure the request.
841 * @returns {Promise<LuCI.response>}
842 * The resulting HTTP response.
844 get: function(url, options) {
845 return this.request(url, Object.assign({ method: 'GET' }, options));
849 * Initiate an HTTP POST request to the given target.
852 * @memberof LuCI.request
853 * @param {string} target
854 * The URL to request.
857 * The request data to send, see {@link LuCI.request.RequestOptions} for details.
859 * @param {LuCI.request.RequestOptions} [options]
860 * Additional options to configure the request.
862 * @returns {Promise<LuCI.response>}
863 * The resulting HTTP response.
865 post: function(url, data, options) {
866 return this.request(url, Object.assign({ method: 'POST', content: data }, options));
870 * Interceptor functions are invoked whenever an HTTP reply is received, in the order
871 * these functions have been registered.
872 * @callback LuCI.request.interceptorFn
873 * @param {LuCI.response} res
874 * The HTTP response object
878 * Register an HTTP response interceptor function. Interceptor
879 * functions are useful to perform default actions on incoming HTTP
880 * responses, such as checking for expired authentication or for
881 * implementing request retries before returning a failure.
884 * @memberof LuCI.request
885 * @param {LuCI.request.interceptorFn} interceptorFn
886 * The interceptor function to register.
888 * @returns {LuCI.request.interceptorFn}
889 * The registered function.
891 addInterceptor: function(interceptorFn) {
892 if (typeof(interceptorFn) == 'function')
893 this.interceptors.push(interceptorFn);
894 return interceptorFn;
898 * Remove an HTTP response interceptor function. The passed function
899 * value must be the very same value that was used to register the
903 * @memberof LuCI.request
904 * @param {LuCI.request.interceptorFn} interceptorFn
905 * The interceptor function to remove.
908 * Returns `true` if any function has been removed, else `false`.
910 removeInterceptor: function(interceptorFn) {
911 var oldlen = this.interceptors.length, i = oldlen;
913 if (this.interceptors[i] === interceptorFn)
914 this.interceptors.splice(i, 1);
915 return (this.interceptors.length < oldlen);
920 * @memberof LuCI.request
924 * The `Request.poll` class provides some convience wrappers around
925 * {@link LuCI.poll} mainly to simplify registering repeating HTTP
926 * request calls as polling functions.
930 * The callback function is invoked whenever an HTTP reply to a
931 * polled request is received or when the polled request timed
934 * @callback LuCI.request.poll~callbackFn
935 * @param {LuCI.response} res
936 * The HTTP response object.
939 * The response JSON if the response could be parsed as such,
942 * @param {number} duration
943 * The total duration of the request in milliseconds.
947 * Register a repeating HTTP request with an optional callback
948 * to invoke whenever a response for the request is received.
951 * @memberof LuCI.request.poll
952 * @param {number} interval
953 * The poll interval in seconds.
955 * @param {string} url
956 * The URL to request on each poll.
958 * @param {LuCI.request.RequestOptions} [options]
959 * Additional options to configure the request.
961 * @param {LuCI.request.poll~callbackFn} [callback]
962 * {@link LuCI.request.poll~callbackFn Callback} function to
963 * invoke for each HTTP reply.
965 * @throws {TypeError}
966 * Throws `TypeError` when an invalid interval was passed.
968 * @returns {function}
969 * Returns the internally created poll function.
971 add: function(interval, url, options, callback) {
972 if (isNaN(interval) || interval <= 0)
973 throw new TypeError('Invalid poll interval');
975 var ival = interval >>> 0,
976 opts = Object.assign({}, options, { timeout: ival * 1000 - 5 });
978 var fn = function() {
979 return Request.request(url, options).then(function(res) {
984 callback(res, res.json(), res.duration);
987 callback(res, null, res.duration);
992 return (Poll.add(fn, ival) ? fn : null);
996 * Remove a polling request that has been previously added using `add()`.
997 * This function is essentially a wrapper around
998 * {@link LuCI.poll.remove LuCI.poll.remove()}.
1001 * @memberof LuCI.request.poll
1002 * @param {function} entry
1003 * The poll function returned by {@link LuCI.request.poll#add add()}.
1005 * @returns {boolean}
1006 * Returns `true` if any function has been removed, else `false`.
1008 remove: function(entry) { return Poll.remove(entry) },
1011 * Alias for {@link LuCI.poll.start LuCI.poll.start()}.
1014 * @memberof LuCI.request.poll
1016 start: function() { return Poll.start() },
1019 * Alias for {@link LuCI.poll.stop LuCI.poll.stop()}.
1022 * @memberof LuCI.request.poll
1024 stop: function() { return Poll.stop() },
1027 * Alias for {@link LuCI.poll.active LuCI.poll.active()}.
1030 * @memberof LuCI.request.poll
1032 active: function() { return Poll.active() }
1042 * The `Poll` class allows registering and unregistering poll actions,
1043 * as well as starting, stopping and querying the state of the polling
1046 var Poll = Class.singleton(/** @lends LuCI.poll.prototype */ {
1047 __name__: 'LuCI.poll',
1052 * Add a new operation to the polling loop. If the polling loop is not
1053 * already started at this point, it will be implicitely started.
1056 * @memberof LuCI.poll
1057 * @param {function} fn
1058 * The function to invoke on each poll interval.
1060 * @param {number} interval
1061 * The poll interval in seconds.
1063 * @throws {TypeError}
1064 * Throws `TypeError` when an invalid interval was passed.
1066 * @returns {boolean}
1067 * Returns `true` if the function has been added or `false` if it
1068 * already is registered.
1070 add: function(fn, interval) {
1071 if (interval == null || interval <= 0)
1072 interval = window.L ? window.L.env.pollinterval : null;
1074 if (isNaN(interval) || typeof(fn) != 'function')
1075 throw new TypeError('Invalid argument to LuCI.poll.add()');
1077 for (var i = 0; i < this.queue.length; i++)
1078 if (this.queue[i].fn === fn)
1089 if (this.tick != null && !this.active())
1096 * Remove an operation from the polling loop. If no further operatons
1097 * are registered, the polling loop is implicitely stopped.
1100 * @memberof LuCI.poll
1101 * @param {function} fn
1102 * The function to remove.
1104 * @throws {TypeError}
1105 * Throws `TypeError` when the given argument isn't a function.
1107 * @returns {boolean}
1108 * Returns `true` if the function has been removed or `false` if it
1111 remove: function(fn) {
1112 if (typeof(fn) != 'function')
1113 throw new TypeError('Invalid argument to LuCI.poll.remove()');
1115 var len = this.queue.length;
1117 for (var i = len; i > 0; i--)
1118 if (this.queue[i-1].fn === fn)
1119 this.queue.splice(i-1, 1);
1121 if (!this.queue.length && this.stop())
1124 return (this.queue.length != len);
1128 * (Re)start the polling loop. Dispatches a custom `poll-start` event
1129 * to the `document` object upon successful start.
1132 * @memberof LuCI.poll
1133 * @returns {boolean}
1134 * Returns `true` if polling has been started (or if no functions
1135 * where registered) or `false` when the polling loop already runs.
1143 if (this.queue.length) {
1144 this.timer = window.setInterval(this.step, 1000);
1146 document.dispatchEvent(new CustomEvent('poll-start'));
1153 * Stop the polling loop. Dispatches a custom `poll-stop` event
1154 * to the `document` object upon successful stop.
1157 * @memberof LuCI.poll
1158 * @returns {boolean}
1159 * Returns `true` if polling has been stopped or `false` if it din't
1160 * run to begin with.
1166 document.dispatchEvent(new CustomEvent('poll-stop'));
1167 window.clearInterval(this.timer);
1175 for (var i = 0, e = null; (e = Poll.queue[i]) != null; i++) {
1176 if ((Poll.tick % e.i) != 0)
1184 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
1187 Poll.tick = (Poll.tick + 1) % Math.pow(2, 32);
1191 * Test whether the polling loop is running.
1194 * @memberof LuCI.poll
1195 * @returns {boolean} - Returns `true` if polling is active, else `false`.
1197 active: function() {
1198 return (this.timer != null);
1208 * The `dom` class provides convenience method for creating and
1209 * manipulating DOM elements.
1211 * To import the class in views, use `'require dom'`, to import it in
1212 * external JavaScript, use `L.require("dom").then(...)`.
1214 var DOM = Class.singleton(/* @lends LuCI.dom.prototype */ {
1215 __name__: 'LuCI.dom',
1218 * Tests whether the given argument is a valid DOM `Node`.
1221 * @memberof LuCI.dom
1223 * The value to test.
1225 * @returns {boolean}
1226 * Returns `true` if the value is a DOM `Node`, else `false`.
1229 return (e != null && typeof(e) == 'object' && 'nodeType' in e);
1233 * Parses a given string as HTML and returns the first child node.
1236 * @memberof LuCI.dom
1238 * A string containing an HTML fragment to parse. Note that only
1239 * the first result of the resulting structure is returned, so an
1240 * input value of `<div>foo</div> <div>bar</div>` will only return
1241 * the first `div` element node.
1244 * Returns the first DOM `Node` extracted from the HTML fragment or
1245 * `null` on parsing failures or if no element could be found.
1247 parse: function(s) {
1251 domParser = domParser || new DOMParser();
1252 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1258 dummyElem = dummyElem || document.createElement('div');
1259 dummyElem.innerHTML = s;
1260 elem = dummyElem.firstChild;
1265 return elem || null;
1269 * Tests whether a given `Node` matches the given query selector.
1271 * This function is a convenience wrapper around the standard
1272 * `Node.matches("selector")` function with the added benefit that
1273 * the `node` argument may be a non-`Node` value, in which case
1274 * this function simply returns `false`.
1277 * @memberof LuCI.dom
1279 * The `Node` argument to test the selector against.
1281 * @param {string} [selector]
1282 * The query selector expression to test against the given node.
1284 * @returns {boolean}
1285 * Returns `true` if the given node matches the specified selector
1286 * or `false` when the node argument is no valid DOM `Node` or the
1287 * selector didn't match.
1289 matches: function(node, selector) {
1290 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
1291 return m ? m.call(node, selector) : false;
1295 * Returns the closest parent node that matches the given query
1296 * selector expression.
1298 * This function is a convenience wrapper around the standard
1299 * `Node.closest("selector")` function with the added benefit that
1300 * the `node` argument may be a non-`Node` value, in which case
1301 * this function simply returns `null`.
1304 * @memberof LuCI.dom
1306 * The `Node` argument to find the closest parent for.
1308 * @param {string} [selector]
1309 * The query selector expression to test against each parent.
1311 * @returns {Node|null}
1312 * Returns the closest parent node matching the selector or
1313 * `null` when the node argument is no valid DOM `Node` or the
1314 * selector didn't match any parent.
1316 parent: function(node, selector) {
1317 if (this.elem(node) && node.closest)
1318 return node.closest(selector);
1320 while (this.elem(node))
1321 if (this.matches(node, selector))
1324 node = node.parentNode;
1330 * Appends the given children data to the given node.
1333 * @memberof LuCI.dom
1335 * The `Node` argument to append the children to.
1337 * @param {*} [children]
1338 * The childrens to append to the given node.
1340 * When `children` is an array, then each item of the array
1341 * will be either appended as child element or text node,
1342 * depending on whether the item is a DOM `Node` instance or
1343 * some other non-`null` value. Non-`Node`, non-`null` values
1344 * will be converted to strings first before being passed as
1345 * argument to `createTextNode()`.
1347 * When `children` is a function, it will be invoked with
1348 * the passed `node` argument as sole parameter and the `append`
1349 * function will be invoked again, with the given `node` argument
1350 * as first and the return value of the `children` function as
1353 * When `children` is is a DOM `Node` instance, it will be
1354 * appended to the given `node`.
1356 * When `children` is any other non-`null` value, it will be
1357 * converted to a string and appened to the `innerHTML` property
1358 * of the given `node`.
1360 * @returns {Node|null}
1361 * Returns the last children `Node` appended to the node or `null`
1362 * if either the `node` argument was no valid DOM `node` or if the
1363 * `children` was `null` or didn't result in further DOM nodes.
1365 append: function(node, children) {
1366 if (!this.elem(node))
1369 if (Array.isArray(children)) {
1370 for (var i = 0; i < children.length; i++)
1371 if (this.elem(children[i]))
1372 node.appendChild(children[i]);
1373 else if (children !== null && children !== undefined)
1374 node.appendChild(document.createTextNode('' + children[i]));
1376 return node.lastChild;
1378 else if (typeof(children) === 'function') {
1379 return this.append(node, children(node));
1381 else if (this.elem(children)) {
1382 return node.appendChild(children);
1384 else if (children !== null && children !== undefined) {
1385 node.innerHTML = '' + children;
1386 return node.lastChild;
1393 * Replaces the content of the given node with the given children.
1395 * This function first removes any children of the given DOM
1396 * `Node` and then adds the given given children following the
1397 * rules outlined below.
1400 * @memberof LuCI.dom
1402 * The `Node` argument to replace the children of.
1404 * @param {*} [children]
1405 * The childrens to replace into the given node.
1407 * When `children` is an array, then each item of the array
1408 * will be either appended as child element or text node,
1409 * depending on whether the item is a DOM `Node` instance or
1410 * some other non-`null` value. Non-`Node`, non-`null` values
1411 * will be converted to strings first before being passed as
1412 * argument to `createTextNode()`.
1414 * When `children` is a function, it will be invoked with
1415 * the passed `node` argument as sole parameter and the `append`
1416 * function will be invoked again, with the given `node` argument
1417 * as first and the return value of the `children` function as
1420 * When `children` is is a DOM `Node` instance, it will be
1421 * appended to the given `node`.
1423 * When `children` is any other non-`null` value, it will be
1424 * converted to a string and appened to the `innerHTML` property
1425 * of the given `node`.
1427 * @returns {Node|null}
1428 * Returns the last children `Node` appended to the node or `null`
1429 * if either the `node` argument was no valid DOM `node` or if the
1430 * `children` was `null` or didn't result in further DOM nodes.
1432 content: function(node, children) {
1433 if (!this.elem(node))
1436 var dataNodes = node.querySelectorAll('[data-idref]');
1438 for (var i = 0; i < dataNodes.length; i++)
1439 delete this.registry[dataNodes[i].getAttribute('data-idref')];
1441 while (node.firstChild)
1442 node.removeChild(node.firstChild);
1444 return this.append(node, children);
1448 * Sets attributes or registers event listeners on element nodes.
1451 * @memberof LuCI.dom
1453 * The `Node` argument to set the attributes or add the event
1454 * listeners for. When the given `node` value is not a valid
1455 * DOM `Node`, the function returns and does nothing.
1457 * @param {string|Object<string, *>} key
1458 * Specifies either the attribute or event handler name to use,
1459 * or an object containing multiple key, value pairs which are
1460 * each added to the node as either attribute or event handler,
1461 * depending on the respective value.
1464 * Specifies the attribute value or event handler function to add.
1465 * If the `key` parameter is an `Object`, this parameter will be
1468 * When `val` is of type function, it will be registered as event
1469 * handler on the given `node` with the `key` parameter being the
1472 * When `val` is of type object, it will be serialized as JSON and
1473 * added as attribute to the given `node`, using the given `key`
1474 * as attribute name.
1476 * When `val` is of any other type, it will be added as attribute
1477 * to the given `node` as-is, with the underlying `setAttribute()`
1478 * call implicitely turning it into a string.
1480 attr: function(node, key, val) {
1481 if (!this.elem(node))
1486 if (typeof(key) === 'object' && key !== null)
1488 else if (typeof(key) === 'string')
1489 attr = {}, attr[key] = val;
1492 if (!attr.hasOwnProperty(key) || attr[key] == null)
1495 switch (typeof(attr[key])) {
1497 node.addEventListener(key, attr[key]);
1501 node.setAttribute(key, JSON.stringify(attr[key]));
1505 node.setAttribute(key, attr[key]);
1511 * Creates a new DOM `Node` from the given `html`, `attr` and
1512 * `data` parameters.
1514 * This function has multiple signatures, it can be either invoked
1515 * in the form `create(html[, attr[, data]])` or in the form
1516 * `create(html[, data])`. The used variant is determined from the
1517 * type of the second argument.
1520 * @memberof LuCI.dom
1522 * Describes the node to create.
1524 * When the value of `html` is of type array, a `DocumentFragment`
1525 * node is created and each item of the array is first converted
1526 * to a DOM `Node` by passing it through `create()` and then added
1527 * as child to the fragment.
1529 * When the value of `html` is a DOM `Node` instance, no new
1530 * element will be created but the node will be used as-is.
1532 * When the value of `html` is a string starting with `<`, it will
1533 * be passed to `dom.parse()` and the resulting value is used.
1535 * When the value of `html` is any other string, it will be passed
1536 * to `document.createElement()` for creating a new DOM `Node` of
1539 * @param {Object<string, *>} [attr]
1540 * Specifies an Object of key, value pairs to set as attributes
1541 * or event handlers on the created node. Refer to
1542 * {@link LuCI.dom#attr dom.attr()} for details.
1545 * Specifies children to append to the newly created element.
1546 * Refer to {@link LuCI.dom#append dom.append()} for details.
1548 * @throws {InvalidCharacterError}
1549 * Throws an `InvalidCharacterError` when the given `html`
1550 * argument contained malformed markup (such as not escaped
1551 * `&` characters in XHTML mode) or when the given node name
1552 * in `html` contains characters which are not legal in DOM
1553 * element names, such as spaces.
1556 * Returns the newly created `Node`.
1558 create: function() {
1559 var html = arguments[0],
1560 attr = arguments[1],
1561 data = arguments[2],
1564 if (!(attr instanceof Object) || Array.isArray(attr))
1565 data = attr, attr = null;
1567 if (Array.isArray(html)) {
1568 elem = document.createDocumentFragment();
1569 for (var i = 0; i < html.length; i++)
1570 elem.appendChild(this.create(html[i]));
1572 else if (this.elem(html)) {
1575 else if (html.charCodeAt(0) === 60) {
1576 elem = this.parse(html);
1579 elem = document.createElement(html);
1585 this.attr(elem, attr);
1586 this.append(elem, data);
1594 * Attaches or detaches arbitrary data to and from a DOM `Node`.
1596 * This function is useful to attach non-string values or runtime
1597 * data that is not serializable to DOM nodes. To decouple data
1598 * from the DOM, values are not added directly to nodes, but
1599 * inserted into a registry instead which is then referenced by a
1600 * string key stored as `data-idref` attribute in the node.
1602 * This function has multiple signatures and is sensitive to the
1603 * number of arguments passed to it.
1605 * - `dom.data(node)` -
1606 * Fetches all data associated with the given node.
1607 * - `dom.data(node, key)` -
1608 * Fetches a specific key associated with the given node.
1609 * - `dom.data(node, key, val)` -
1610 * Sets a specific key to the given value associated with the
1612 * - `dom.data(node, null)` -
1613 * Clears any data associated with the node.
1614 * - `dom.data(node, key, null)` -
1615 * Clears the given key associated with the node.
1618 * @memberof LuCI.dom
1619 * @param {Node} node
1620 * The DOM `Node` instance to set or retrieve the data for.
1622 * @param {string|null} [key]
1623 * This is either a string specifying the key to retrieve, or
1624 * `null` to unset the entire node data.
1626 * @param {*|null} [val]
1627 * This is either a non-`null` value to set for a given key or
1628 * `null` to remove the given `key` from the specified node.
1631 * Returns the get or set value, or `null` when no value could
1634 data: function(node, key, val) {
1635 if (!node || !node.getAttribute)
1638 var id = node.getAttribute('data-idref');
1640 /* clear all data */
1641 if (arguments.length > 1 && key == null) {
1643 node.removeAttribute('data-idref');
1644 val = this.registry[id]
1645 delete this.registry[id];
1653 else if (arguments.length > 2 && key != null && val == null) {
1655 val = this.registry[id][key];
1656 delete this.registry[id][key];
1664 else if (arguments.length > 2 && key != null && val != null) {
1666 do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
1667 while (this.registry.hasOwnProperty(id));
1669 node.setAttribute('data-idref', id);
1670 this.registry[id] = {};
1673 return (this.registry[id][key] = val);
1677 else if (arguments.length == 1) {
1679 return this.registry[id];
1685 else if (arguments.length == 2) {
1687 return this.registry[id][key];
1694 * Binds the given class instance ot the specified DOM `Node`.
1696 * This function uses the `dom.data()` facility to attach the
1697 * passed instance of a Class to a node. This is needed for
1698 * complex widget elements or similar where the corresponding
1699 * class instance responsible for the element must be retrieved
1700 * from DOM nodes obtained by `querySelector()` or similar means.
1703 * @memberof LuCI.dom
1704 * @param {Node} node
1705 * The DOM `Node` instance to bind the class to.
1707 * @param {Class} inst
1708 * The Class instance to bind to the node.
1710 * @throws {TypeError}
1711 * Throws a `TypeError` when the given instance argument isn't
1712 * a valid Class instance.
1715 * Returns the bound class instance.
1717 bindClassInstance: function(node, inst) {
1718 if (!(inst instanceof Class))
1719 L.error('TypeError', 'Argument must be a class instance');
1721 return this.data(node, '_class', inst);
1725 * Finds a bound class instance on the given node itself or the
1726 * first bound instance on its closest parent node.
1729 * @memberof LuCI.dom
1730 * @param {Node} node
1731 * The DOM `Node` instance to start from.
1733 * @returns {Class|null}
1734 * Returns the founds class instance if any or `null` if no bound
1735 * class could be found on the node itself or any of its parents.
1737 findClassInstance: function(node) {
1741 inst = this.data(node, '_class');
1742 node = node.parentNode;
1744 while (!(inst instanceof Class) && node != null);
1750 * Finds a bound class instance on the given node itself or the
1751 * first bound instance on its closest parent node and invokes
1752 * the specified method name on the found class instance.
1755 * @memberof LuCI.dom
1756 * @param {Node} node
1757 * The DOM `Node` instance to start from.
1759 * @param {string} method
1760 * The name of the method to invoke on the found class instance.
1762 * @param {...*} params
1763 * Additional arguments to pass to the invoked method as-is.
1766 * Returns the return value of the invoked method if a class
1767 * instance and method has been found. Returns `null` if either
1768 * no bound class instance could be found, or if the found
1769 * instance didn't have the requested `method`.
1771 callClassMethod: function(node, method /*, ... */) {
1772 var inst = this.findClassInstance(node);
1774 if (inst == null || typeof(inst[method]) != 'function')
1777 return inst[method].apply(inst, inst.varargs(arguments, 2));
1781 * The ignore callback function is invoked by `isEmpty()` for each
1782 * child node to decide whether to ignore a child node or not.
1784 * When this function returns `false`, the node passed to it is
1785 * ignored, else not.
1787 * @callback LuCI.dom~ignoreCallbackFn
1788 * @param {Node} node
1789 * The child node to test.
1791 * @returns {boolean}
1792 * Boolean indicating whether to ignore the node or not.
1796 * Tests whether a given DOM `Node` instance is empty or appears
1799 * Any element child nodes which have the CSS class `hidden` set
1800 * or for which the optionally passed `ignoreFn` callback function
1801 * returns `false` are ignored.
1804 * @memberof LuCI.dom
1805 * @param {Node} node
1806 * The DOM `Node` instance to test.
1808 * @param {LuCI.dom~ignoreCallbackFn} [ignoreFn]
1809 * Specifies an optional function which is invoked for each child
1810 * node to decide whether the child node should be ignored or not.
1812 * @returns {boolean}
1813 * Returns `true` if the node does not have any children or if
1814 * any children node either has a `hidden` CSS class or a `false`
1815 * result when testing it using the given `ignoreFn`.
1817 isEmpty: function(node, ignoreFn) {
1818 for (var child = node.firstElementChild; child != null; child = child.nextElementSibling)
1819 if (!child.classList.contains('hidden') && (!ignoreFn || !ignoreFn(child)))
1832 * The `view` class forms the basis of views and provides a standard
1833 * set of methods to inherit from.
1835 var View = Class.extend(/* @lends LuCI.view.prototype */ {
1836 __name__: 'LuCI.view',
1838 __init__: function() {
1839 var vp = document.getElementById('view');
1841 DOM.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
1843 return Promise.resolve(this.load())
1844 .then(L.bind(this.render, this))
1845 .then(L.bind(function(nodes) {
1846 var vp = document.getElementById('view');
1848 DOM.content(vp, nodes);
1849 DOM.append(vp, this.addFooter());
1850 }, this)).catch(L.error);
1854 * The load function is invoked before the view is rendered.
1856 * The invocation of this function is wrapped by
1857 * `Promise.resolve()` so it may return Promises if needed.
1859 * The return value of the function (or the resolved values
1860 * of the promise returned by it) will be passed as first
1861 * argument to `render()`.
1863 * This function is supposed to be overwritten by subclasses,
1864 * the default implementation does nothing.
1868 * @memberof LuCI.view
1870 * @returns {*|Promise<*>}
1871 * May return any value or a Promise resolving to any value.
1873 load: function() {},
1876 * The render function is invoked after the
1877 * {@link LuCI.view#load load()} function and responsible
1878 * for setting up the view contents. It must return a DOM
1879 * `Node` or `DocumentFragment` holding the contents to
1880 * insert into the view area.
1882 * The invocation of this function is wrapped by
1883 * `Promise.resolve()` so it may return Promises if needed.
1885 * The return value of the function (or the resolved values
1886 * of the promise returned by it) will be inserted into the
1887 * main content area using
1888 * {@link LuCI.dom#append dom.append()}.
1890 * This function is supposed to be overwritten by subclasses,
1891 * the default implementation does nothing.
1895 * @memberof LuCI.view
1896 * @param {*|null} load_results
1897 * This function will receive the return value of the
1898 * {@link LuCI.view#load view.load()} function as first
1901 * @returns {Node|Promise<Node>}
1902 * Should return a DOM `Node` value or a `Promise` resolving
1903 * to a `Node` value.
1905 render: function() {},
1908 * The handleSave function is invoked when the user clicks
1909 * the `Save` button in the page action footer.
1911 * The default implementation should be sufficient for most
1912 * views using {@link form#Map form.Map()} based forms - it
1913 * will iterate all forms present in the view and invoke
1914 * the {@link form#Map#save Map.save()} method on each form.
1916 * Views not using `Map` instances or requiring other special
1917 * logic should overwrite `handleSave()` with a custom
1920 * To disable the `Save` page footer button, views extending
1921 * this base class should overwrite the `handleSave` function
1924 * The invocation of this function is wrapped by
1925 * `Promise.resolve()` so it may return Promises if needed.
1928 * @memberof LuCI.view
1930 * The DOM event that triggered the function.
1932 * @returns {*|Promise<*>}
1933 * Any return values of this function are discarded, but
1934 * passed through `Promise.resolve()` to ensure that any
1935 * returned promise runs to completion before the button
1938 handleSave: function(ev) {
1941 document.getElementById('maincontent')
1942 .querySelectorAll('.cbi-map').forEach(function(map) {
1943 tasks.push(DOM.callClassMethod(map, 'save'));
1946 return Promise.all(tasks);
1950 * The handleSaveApply function is invoked when the user clicks
1951 * the `Save & Apply` button in the page action footer.
1953 * The default implementation should be sufficient for most
1954 * views using {@link form#Map form.Map()} based forms - it
1956 * {@link LuCI.view.handleSave view.handleSave()} and then
1957 * call {@link ui#changes#apply ui.changes.apply()} to start the
1958 * modal config apply and page reload flow.
1960 * Views not using `Map` instances or requiring other special
1961 * logic should overwrite `handleSaveApply()` with a custom
1964 * To disable the `Save & Apply` page footer button, views
1965 * extending this base class should overwrite the
1966 * `handleSaveApply` function with `null`.
1968 * The invocation of this function is wrapped by
1969 * `Promise.resolve()` so it may return Promises if needed.
1972 * @memberof LuCI.view
1974 * The DOM event that triggered the function.
1976 * @returns {*|Promise<*>}
1977 * Any return values of this function are discarded, but
1978 * passed through `Promise.resolve()` to ensure that any
1979 * returned promise runs to completion before the button
1982 handleSaveApply: function(ev, mode) {
1983 return this.handleSave(ev).then(function() {
1984 L.ui.changes.apply(mode == '0');
1989 * The handleReset function is invoked when the user clicks
1990 * the `Reset` button in the page action footer.
1992 * The default implementation should be sufficient for most
1993 * views using {@link form#Map form.Map()} based forms - it
1994 * will iterate all forms present in the view and invoke
1995 * the {@link form#Map#save Map.reset()} method on each form.
1997 * Views not using `Map` instances or requiring other special
1998 * logic should overwrite `handleReset()` with a custom
2001 * To disable the `Reset` page footer button, views extending
2002 * this base class should overwrite the `handleReset` function
2005 * The invocation of this function is wrapped by
2006 * `Promise.resolve()` so it may return Promises if needed.
2009 * @memberof LuCI.view
2011 * The DOM event that triggered the function.
2013 * @returns {*|Promise<*>}
2014 * Any return values of this function are discarded, but
2015 * passed through `Promise.resolve()` to ensure that any
2016 * returned promise runs to completion before the button
2019 handleReset: function(ev) {
2022 document.getElementById('maincontent')
2023 .querySelectorAll('.cbi-map').forEach(function(map) {
2024 tasks.push(DOM.callClassMethod(map, 'reset'));
2027 return Promise.all(tasks);
2031 * Renders a standard page action footer if any of the
2032 * `handleSave()`, `handleSaveApply()` or `handleReset()`
2033 * functions are defined.
2035 * The default implementation should be sufficient for most
2036 * views - it will render a standard page footer with action
2037 * buttons labeled `Save`, `Save & Apply` and `Reset`
2038 * triggering the `handleSave()`, `handleSaveApply()` and
2039 * `handleReset()` functions respectively.
2041 * When any of these `handle*()` functions is overwritten
2042 * with `null` by a view extending this class, the
2043 * corresponding button will not be rendered.
2046 * @memberof LuCI.view
2047 * @returns {DocumentFragment}
2048 * Returns a `DocumentFragment` containing the footer bar
2049 * with buttons for each corresponding `handle*()` action
2050 * or an empty `DocumentFragment` if all three `handle*()`
2051 * methods are overwritten with `null`.
2053 addFooter: function() {
2056 var saveApplyBtn = this.handleSaveApply ? new L.ui.ComboButton('0', {
2057 0: [ _('Save & Apply') ],
2058 1: [ _('Apply unchecked') ]
2061 0: 'btn cbi-button cbi-button-apply important',
2062 1: 'btn cbi-button cbi-button-negative important'
2064 click: L.ui.createHandlerFn(this, 'handleSaveApply')
2065 }).render() : E([]);
2067 if (this.handleSaveApply || this.handleSave || this.handleReset) {
2068 footer.appendChild(E('div', { 'class': 'cbi-page-actions control-group' }, [
2070 this.handleSave ? E('button', {
2071 'class': 'cbi-button cbi-button-save',
2072 'click': L.ui.createHandlerFn(this, 'handleSave')
2073 }, [ _('Save') ]) : '', ' ',
2074 this.handleReset ? E('button', {
2075 'class': 'cbi-button cbi-button-reset',
2076 'click': L.ui.createHandlerFn(this, 'handleReset')
2077 }, [ _('Reset') ]) : ''
2086 var dummyElem = null,
2088 originalCBIInit = null,
2091 preloadClasses = null;
2093 /* "preload" builtin classes to make the available via require */
2102 var LuCI = Class.extend(/** @lends LuCI.prototype */ {
2104 __init__: function(env) {
2106 document.querySelectorAll('script[src*="/luci.js"]').forEach(function(s) {
2107 if (env.base_url == null || env.base_url == '') {
2108 var m = (s.getAttribute('src') || '').match(/^(.*)\/luci\.js(?:\?v=([^?]+))?$/);
2110 env.base_url = m[1];
2111 env.resource_version = m[2];
2116 if (env.base_url == null)
2117 this.error('InternalError', 'Cannot find url of luci.js');
2119 env.cgi_base = env.scriptname.replace(/\/[^\/]+$/, '');
2121 Object.assign(this.env, env);
2123 document.addEventListener('poll-start', function(ev) {
2124 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
2125 e.style.display = (e.id == 'xhr_poll_status_off') ? 'none' : '';
2129 document.addEventListener('poll-stop', function(ev) {
2130 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
2131 e.style.display = (e.id == 'xhr_poll_status_on') ? 'none' : '';
2135 var domReady = new Promise(function(resolveFn, rejectFn) {
2136 document.addEventListener('DOMContentLoaded', resolveFn);
2142 this.require('rpc'),
2143 this.require('form'),
2144 this.probeRPCBaseURL()
2145 ]).then(this.setupDOM.bind(this)).catch(this.error);
2147 originalCBIInit = window.cbi_init;
2148 window.cbi_init = function() {};
2152 * Captures the current stack trace and throws an error of the
2153 * specified type as a new exception. Also logs the exception as
2154 * error to the debug console if it is available.
2159 * @param {Error|string} [type=Error]
2160 * Either a string specifying the type of the error to throw or an
2161 * existing `Error` instance to copy.
2163 * @param {string} [fmt=Unspecified error]
2164 * A format string which is used to form the error message, together
2165 * with all subsequent optional arguments.
2167 * @param {...*} [args]
2168 * Zero or more variable arguments to the supplied format string.
2171 * Throws the created error object with the captured stack trace
2172 * appended to the message and the type set to the given type
2173 * argument or copied from the given error instance.
2175 raise: function(type, fmt /*, ...*/) {
2177 msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
2180 if (type instanceof Error) {
2184 e.message = msg + ': ' + e.message;
2187 try { throw new Error('stacktrace') }
2188 catch (e2) { stack = (e2.stack || '').split(/\n/) }
2190 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
2191 e.name = type || 'Error';
2194 stack = (stack || []).map(function(frame) {
2195 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
2196 return frame ? ' ' + frame : '';
2199 if (!/^ at /.test(stack[0]))
2202 if (/\braise /.test(stack[0]))
2205 if (/\berror /.test(stack[0]))
2209 e.message += '\n' + stack.join('\n');
2211 if (window.console && console.debug)
2218 * A wrapper around {@link LuCI#raise raise()} which also renders
2219 * the error either as modal overlay when `ui.js` is already loaed
2220 * or directly into the view body.
2225 * @param {Error|string} [type=Error]
2226 * Either a string specifying the type of the error to throw or an
2227 * existing `Error` instance to copy.
2229 * @param {string} [fmt=Unspecified error]
2230 * A format string which is used to form the error message, together
2231 * with all subsequent optional arguments.
2233 * @param {...*} [args]
2234 * Zero or more variable arguments to the supplied format string.
2237 * Throws the created error object with the captured stack trace
2238 * appended to the message and the type set to the given type
2239 * argument or copied from the given error instance.
2241 error: function(type, fmt /*, ...*/) {
2243 L.raise.apply(L, Array.prototype.slice.call(arguments));
2248 L.ui.addNotification(e.name || _('Runtime error'),
2249 E('pre', {}, e.message), 'danger');
2251 DOM.content(document.querySelector('#maincontent'),
2252 E('pre', { 'class': 'alert-message error' }, e.message));
2262 * Return a bound function using the given `self` as `this` context
2263 * and any further arguments as parameters to the bound function.
2268 * @param {function} fn
2269 * The function to bind.
2272 * The value to bind as `this` context to the specified function.
2274 * @param {...*} [args]
2275 * Zero or more variable arguments which are bound to the function
2278 * @returns {function}
2279 * Returns the bound function.
2281 bind: function(fn, self /*, ... */) {
2282 return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
2286 * Load an additional LuCI JavaScript class and its dependencies,
2287 * instantiate it and return the resulting class instance. Each
2288 * class is only loaded once. Subsequent attempts to load the same
2289 * class will return the already instantiated class.
2294 * @param {string} name
2295 * The name of the class to load in dotted notation. Dots will
2296 * be replaced by spaces and joined with the runtime-determined
2297 * base URL of LuCI.js to form an absolute URL to load the class
2300 * @throws {DependencyError}
2301 * Throws a `DependencyError` when the class to load includes
2302 * circular dependencies.
2304 * @throws {NetworkError}
2305 * Throws `NetworkError` when the underlying {@link LuCI.request}
2308 * @throws {SyntaxError}
2309 * Throws `SyntaxError` when the loaded class file code cannot
2310 * be interpreted by `eval`.
2312 * @throws {TypeError}
2313 * Throws `TypeError` when the class file could be loaded and
2314 * interpreted, but when invoking its code did not yield a valid
2317 * @returns {Promise<LuCI.baseclass>}
2318 * Returns the instantiated class.
2320 require: function(name, from) {
2321 var L = this, url = null, from = from || [];
2323 /* Class already loaded */
2324 if (classes[name] != null) {
2325 /* Circular dependency */
2326 if (from.indexOf(name) != -1)
2327 L.raise('DependencyError',
2328 'Circular dependency: class "%s" depends on "%s"',
2329 name, from.join('" which depends on "'));
2331 return Promise.resolve(classes[name]);
2334 url = '%s/%s.js%s'.format(L.env.base_url, name.replace(/\./g, '/'), (L.env.resource_version ? '?v=' + L.env.resource_version : ''));
2335 from = [ name ].concat(from);
2337 var compileClass = function(res) {
2339 L.raise('NetworkError',
2340 'HTTP error %d while loading class file "%s"', res.status, url);
2342 var source = res.text(),
2343 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
2344 strictmatch = /^use[ \t]+strict$/,
2348 /* find require statements in source */
2349 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
2350 var chr = source.charCodeAt(i);
2355 else if (chr == 92) {
2358 else if (chr == quote) {
2359 var s = source.substring(off, i),
2360 m = requirematch.exec(s);
2363 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
2364 depends.push(L.require(dep, from));
2367 else if (!strictmatch.exec(s)) {
2374 else if (quote == -1 && (chr == 34 || chr == 39)) {
2380 /* load dependencies and instantiate class */
2381 return Promise.all(depends).then(function(instances) {
2382 var _factory, _class;
2386 '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
2387 .format(args, source, res.url));
2390 L.raise('SyntaxError', '%s\n in %s:%s',
2391 error.message, res.url, error.lineNumber || '?');
2394 _factory.displayName = toCamelCase(name + 'ClassFactory');
2395 _class = _factory.apply(_factory, [window, document, L].concat(instances));
2397 if (!Class.isSubclass(_class))
2398 L.error('TypeError', '"%s" factory yields invalid constructor', name);
2400 if (_class.displayName == 'AnonymousClass')
2401 _class.displayName = toCamelCase(name + 'Class');
2403 var ptr = Object.getPrototypeOf(L),
2404 parts = name.split(/\./),
2405 instance = new _class();
2407 for (var i = 0; ptr && i < parts.length - 1; i++)
2408 ptr = ptr[parts[i]];
2411 ptr[parts[i]] = instance;
2413 classes[name] = instance;
2419 /* Request class file */
2420 classes[name] = Request.get(url, { cache: true }).then(compileClass);
2422 return classes[name];
2426 probeRPCBaseURL: function() {
2427 if (rpcBaseURL == null) {
2429 rpcBaseURL = window.sessionStorage.getItem('rpcBaseURL');
2434 if (rpcBaseURL == null) {
2435 var rpcFallbackURL = this.url('admin/ubus');
2437 rpcBaseURL = Request.get('/ubus/').then(function(res) {
2438 return (rpcBaseURL = (res.status == 400) ? '/ubus/' : rpcFallbackURL);
2440 return (rpcBaseURL = rpcFallbackURL);
2441 }).then(function(url) {
2443 window.sessionStorage.setItem('rpcBaseURL', url);
2451 return Promise.resolve(rpcBaseURL);
2454 probeSystemFeatures: function() {
2455 var sessionid = classes.rpc.getSessionID();
2457 if (sysFeatures == null) {
2459 var data = JSON.parse(window.sessionStorage.getItem('sysFeatures'));
2461 if (this.isObject(data) && this.isObject(data[sessionid]))
2462 sysFeatures = data[sessionid];
2467 if (!this.isObject(sysFeatures)) {
2468 sysFeatures = classes.rpc.declare({
2470 method: 'getFeatures',
2472 })().then(function(features) {
2475 data[sessionid] = features;
2477 window.sessionStorage.setItem('sysFeatures', JSON.stringify(data));
2481 sysFeatures = features;
2487 return Promise.resolve(sysFeatures);
2490 probePreloadClasses: function() {
2491 var sessionid = classes.rpc.getSessionID();
2493 if (preloadClasses == null) {
2495 var data = JSON.parse(window.sessionStorage.getItem('preloadClasses'));
2497 if (this.isObject(data) && this.isObject(data[sessionid]))
2498 preloadClasses = data[sessionid];
2503 if (!Array.isArray(preloadClasses)) {
2504 preloadClasses = this.resolveDefault(classes.rpc.declare({
2508 expect: { 'entries': [] }
2509 })(this.fspath(this.resource('preload'))), []).then(function(entries) {
2512 for (var i = 0; i < entries.length; i++) {
2513 if (entries[i].type != 'file')
2516 var m = entries[i].name.match(/(.+)\.js$/);
2519 classes.push('preload.%s'.format(m[1]));
2524 data[sessionid] = classes;
2526 window.sessionStorage.setItem('preloadClasses', JSON.stringify(data));
2530 preloadClasses = classes;
2536 return Promise.resolve(preloadClasses);
2540 * Test whether a particular system feature is available, such as
2541 * hostapd SAE support or an installed firewall. The features are
2542 * queried once at the beginning of the LuCI session and cached in
2543 * `SessionStorage` throughout the lifetime of the associated tab or
2549 * @param {string} feature
2550 * The feature to test. For detailed list of known feature flags,
2551 * see `/modules/luci-base/root/usr/libexec/rpcd/luci`.
2553 * @param {string} [subfeature]
2554 * Some feature classes like `hostapd` provide sub-feature flags,
2555 * such as `sae` or `11w` support. The `subfeature` argument can
2556 * be used to query these.
2558 * @return {boolean|null}
2559 * Return `true` if the queried feature (and sub-feature) is available
2560 * or `false` if the requested feature isn't present or known.
2561 * Return `null` when a sub-feature was queried for a feature which
2562 * has no sub-features.
2564 hasSystemFeature: function() {
2565 var ft = sysFeatures[arguments[0]];
2567 if (arguments.length == 2)
2568 return this.isObject(ft) ? ft[arguments[1]] : null;
2570 return (ft != null && ft != false);
2574 notifySessionExpiry: function() {
2577 L.ui.showModal(_('Session expired'), [
2578 E('div', { class: 'alert-message warning' },
2579 _('A new login is required since the authentication session expired.')),
2580 E('div', { class: 'right' },
2582 class: 'btn primary',
2584 var loc = window.location;
2585 window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
2587 }, _('To login…')))
2590 L.raise('SessionError', 'Login session is expired');
2594 setupDOM: function(res) {
2599 rpcBaseURL = res[4];
2601 rpcClass.setBaseURL(rpcBaseURL);
2603 rpcClass.addInterceptor(function(msg, req) {
2604 if (!L.isObject(msg) || !L.isObject(msg.error) || msg.error.code != -32002)
2607 if (!L.isObject(req) || (req.object == 'session' && req.method == 'access'))
2610 return rpcClass.declare({
2611 'object': 'session',
2613 'params': [ 'scope', 'object', 'function' ],
2614 'expect': { access: true }
2615 })('uci', 'luci', 'read').catch(L.notifySessionExpiry);
2618 Request.addInterceptor(function(res) {
2619 var isDenied = false;
2621 if (res.status == 403 && res.headers.get('X-LuCI-Login-Required') == 'yes')
2627 L.notifySessionExpiry();
2630 return Promise.all([
2631 this.probeSystemFeatures(),
2632 this.probePreloadClasses()
2633 ]).finally(L.bind(function() {
2636 if (Array.isArray(preloadClasses))
2637 for (var i = 0; i < preloadClasses.length; i++)
2638 tasks.push(this.require(preloadClasses[i]));
2640 return Promise.all(tasks);
2641 }, this)).finally(this.initDOM);
2645 initDOM: function() {
2648 document.dispatchEvent(new CustomEvent('luci-loaded'));
2652 * The `env` object holds environment settings used by LuCI, such
2653 * as request timeouts, base URLs etc.
2661 * Construct an absolute filesystem path relative to the server
2667 * @param {...string} [parts]
2668 * An array of parts to join into a path.
2671 * Return the joined path.
2673 fspath: function(/* ... */) {
2674 var path = this.env.documentroot;
2676 for (var i = 0; i < arguments.length; i++)
2677 path += '/' + arguments[i];
2679 var p = path.replace(/\/+$/, '').replace(/\/+/g, '/').split(/\//),
2682 for (var i = 0; i < p.length; i++)
2685 else if (p[i] != '.')
2688 return res.join('/');
2692 * Construct a relative URL path from the given prefix and parts.
2693 * The resulting URL is guaranteed to only contain the characters
2694 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2695 * as `/` for the path separator.
2700 * @param {string} [prefix]
2701 * The prefix to join the given parts with. If the `prefix` is
2702 * omitted, it defaults to an empty string.
2704 * @param {string[]} [parts]
2705 * An array of parts to join into an URL path. Parts may contain
2706 * slashes and any of the other characters mentioned above.
2709 * Return the joined URL path.
2711 path: function(prefix, parts) {
2712 var url = [ prefix || '' ];
2714 for (var i = 0; i < parts.length; i++)
2715 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
2716 url.push('/', parts[i]);
2718 if (url.length === 1)
2721 return url.join('');
2725 * Construct an URL pathrelative to the script path of the server
2726 * side LuCI application (usually `/cgi-bin/luci`).
2728 * The resulting URL is guaranteed to only contain the characters
2729 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2730 * as `/` for the path separator.
2735 * @param {string[]} [parts]
2736 * An array of parts to join into an URL path. Parts may contain
2737 * slashes and any of the other characters mentioned above.
2740 * Returns the resulting URL path.
2743 return this.path(this.env.scriptname, arguments);
2747 * Construct an URL path relative to the global static resource path
2748 * of the LuCI ui (usually `/luci-static/resources`).
2750 * The resulting URL is guaranteed to only contain the characters
2751 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2752 * as `/` for the path separator.
2757 * @param {string[]} [parts]
2758 * An array of parts to join into an URL path. Parts may contain
2759 * slashes and any of the other characters mentioned above.
2762 * Returns the resulting URL path.
2764 resource: function() {
2765 return this.path(this.env.resource, arguments);
2769 * Construct an URL path relative to the media resource path of the
2770 * LuCI ui (usually `/luci-static/$theme_name`).
2772 * The resulting URL is guaranteed to only contain the characters
2773 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2774 * as `/` for the path separator.
2779 * @param {string[]} [parts]
2780 * An array of parts to join into an URL path. Parts may contain
2781 * slashes and any of the other characters mentioned above.
2784 * Returns the resulting URL path.
2787 return this.path(this.env.media, arguments);
2791 * Return the complete URL path to the current view.
2797 * Returns the URL path to the current view.
2799 location: function() {
2800 return this.path(this.env.scriptname, this.env.requestpath);
2805 * Tests whether the passed argument is a JavaScript object.
2806 * This function is meant to be an object counterpart to the
2807 * standard `Array.isArray()` function.
2816 * Returns `true` if the given value is of type object and
2817 * not `null`, else returns `false`.
2819 isObject: function(val) {
2820 return (val != null && typeof(val) == 'object');
2824 * Return an array of sorted object keys, optionally sorted by
2825 * a different key or a different sorting mode.
2830 * @param {object} obj
2831 * The object to extract the keys from. If the given value is
2832 * not an object, the function will return an empty array.
2834 * @param {string} [key]
2835 * Specifies the key to order by. This is mainly useful for
2836 * nested objects of objects or objects of arrays when sorting
2837 * shall not be performed by the primary object keys but by
2838 * some other key pointing to a value within the nested values.
2840 * @param {string} [sortmode]
2841 * May be either `addr` or `num` to override the natural
2842 * lexicographic sorting with a sorting suitable for IP/MAC style
2843 * addresses or numeric values respectively.
2845 * @return {string[]}
2846 * Returns an array containing the sorted keys of the given object.
2848 sortedKeys: function(obj, key, sortmode) {
2849 if (obj == null || typeof(obj) != 'object')
2852 return Object.keys(obj).map(function(e) {
2853 var v = (key != null) ? obj[e][key] : e;
2857 v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
2858 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
2862 v = (v != null) ? +v : null;
2867 }).filter(function(e) {
2868 return (e[1] != null);
2869 }).sort(function(a, b) {
2870 return (a[1] > b[1]);
2871 }).map(function(e) {
2877 * Converts the given value to an array. If the given value is of
2878 * type array, it is returned as-is, values of type object are
2879 * returned as one-element array containing the object, empty
2880 * strings and `null` values are returned as empty array, all other
2881 * values are converted using `String()`, trimmed, split on white
2882 * space and returned as array.
2888 * The value to convert into an array.
2890 * @return {Array<*>}
2891 * Returns the resulting array.
2893 toArray: function(val) {
2896 else if (Array.isArray(val))
2898 else if (typeof(val) == 'object')
2901 var s = String(val).trim();
2906 return s.split(/\s+/);
2910 * Returns a promise resolving with either the given value or or with
2911 * the given default in case the input value is a rejecting promise.
2917 * The value to resolve the promise with.
2919 * @param {*} defvalue
2920 * The default value to resolve the promise with in case the given
2921 * input value is a rejecting promise.
2923 * @returns {Promise<*>}
2924 * Returns a new promise resolving either to the given input value or
2925 * to the given default value on error.
2927 resolveDefault: function(value, defvalue) {
2928 return Promise.resolve(value).catch(function() { return defvalue });
2932 * The request callback function is invoked whenever an HTTP
2933 * reply to a request made using the `L.get()`, `L.post()` or
2934 * `L.poll()` function is timed out or received successfully.
2939 * @callback LuCI.requestCallbackFn
2940 * @param {XMLHTTPRequest} xhr
2941 * The XMLHTTPRequest instance used to make the request.
2944 * The response JSON if the response could be parsed as such,
2947 * @param {number} duration
2948 * The total duration of the request in milliseconds.
2952 * Issues a GET request to the given url and invokes the specified
2953 * callback function. The function is a wrapper around
2954 * {@link LuCI.request#request Request.request()}.
2960 * @param {string} url
2961 * The URL to request.
2963 * @param {Object<string, string>} [args]
2964 * Additional query string arguments to append to the URL.
2966 * @param {LuCI.requestCallbackFn} cb
2967 * The callback function to invoke when the request finishes.
2969 * @return {Promise<null>}
2970 * Returns a promise resolving to `null` when concluded.
2972 get: function(url, args, cb) {
2973 return this.poll(null, url, args, cb, false);
2977 * Issues a POST request to the given url and invokes the specified
2978 * callback function. The function is a wrapper around
2979 * {@link LuCI.request#request Request.request()}. The request is
2980 * sent using `application/x-www-form-urlencoded` encoding and will
2981 * contain a field `token` with the current value of `LuCI.env.token`
2988 * @param {string} url
2989 * The URL to request.
2991 * @param {Object<string, string>} [args]
2992 * Additional post arguments to append to the request body.
2994 * @param {LuCI.requestCallbackFn} cb
2995 * The callback function to invoke when the request finishes.
2997 * @return {Promise<null>}
2998 * Returns a promise resolving to `null` when concluded.
3000 post: function(url, args, cb) {
3001 return this.poll(null, url, args, cb, true);
3005 * Register a polling HTTP request that invokes the specified
3006 * callback function. The function is a wrapper around
3007 * {@link LuCI.request.poll#add Request.poll.add()}.
3013 * @param {number} interval
3014 * The poll interval to use. If set to a value less than or equal
3015 * to `0`, it will default to the global poll interval configured
3016 * in `LuCI.env.pollinterval`.
3018 * @param {string} url
3019 * The URL to request.
3021 * @param {Object<string, string>} [args]
3022 * Specifies additional arguments for the request. For GET requests,
3023 * the arguments are appended to the URL as query string, for POST
3024 * requests, they'll be added to the request body.
3026 * @param {LuCI.requestCallbackFn} cb
3027 * The callback function to invoke whenever a request finishes.
3029 * @param {boolean} [post=false]
3030 * When set to `false` or not specified, poll requests will be made
3031 * using the GET method. When set to `true`, POST requests will be
3032 * issued. In case of POST requests, the request body will contain
3033 * an argument `token` with the current value of `LuCI.env.token` by
3034 * default, regardless of the parameters specified with `args`.
3036 * @return {function}
3037 * Returns the internally created function that has been passed to
3038 * {@link LuCI.request.poll#add Request.poll.add()}. This value can
3039 * be passed to {@link LuCI.poll.remove Poll.remove()} to remove the
3042 poll: function(interval, url, args, cb, post) {
3043 if (interval !== null && interval <= 0)
3044 interval = this.env.pollinterval;
3046 var data = post ? { token: this.env.token } : null,
3047 method = post ? 'POST' : 'GET';
3049 if (!/^(?:\/|\S+:\/\/)/.test(url))
3050 url = this.url(url);
3053 data = Object.assign(data || {}, args);
3055 if (interval !== null)
3056 return Request.poll.add(interval, url, { method: method, query: data }, cb);
3058 return Request.request(url, { method: method, query: data })
3059 .then(function(res) {
3061 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
3062 try { json = res.json() } catch(e) {}
3063 cb(res.xhr, json, res.duration);
3068 * Deprecated wrapper around {@link LuCI.poll.remove Poll.remove()}.
3074 * @param {function} entry
3075 * The polling function to remove.
3078 * Returns `true` when the function has been removed or `false` if
3079 * it could not be found.
3081 stop: function(entry) { return Poll.remove(entry) },
3084 * Deprecated wrapper around {@link LuCI.poll.stop Poll.stop()}.
3091 * Returns `true` when the polling loop has been stopped or `false`
3092 * when it didn't run to begin with.
3094 halt: function() { return Poll.stop() },
3097 * Deprecated wrapper around {@link LuCI.poll.start Poll.start()}.
3104 * Returns `true` when the polling loop has been started or `false`
3105 * when it was already running.
3107 run: function() { return Poll.start() },
3110 * Legacy `L.dom` class alias. New view code should use `'require dom';`
3111 * to request the `LuCI.dom` class.
3120 * Legacy `L.view` class alias. New view code should use `'require view';`
3121 * to request the `LuCI.view` class.
3130 * Legacy `L.Poll` class alias. New view code should use `'require poll';`
3131 * to request the `LuCI.poll` class.
3140 * Legacy `L.Request` class alias. New view code should use `'require request';`
3141 * to request the `LuCI.request` class.
3150 * Legacy `L.Class` class alias. New view code should use `'require baseclass';`
3151 * to request the `LuCI.baseclass` class.
3166 * The `LuCI.xhr` class is a legacy compatibility shim for the
3167 * functionality formerly provided by `xhr.js`. It is registered as global
3168 * `window.XHR` symbol for compatibility with legacy code.
3170 * New code should use {@link LuCI.request} instead to implement HTTP
3173 var XHR = Class.extend(/** @lends LuCI.xhr.prototype */ {
3174 __name__: 'LuCI.xhr',
3175 __init__: function() {
3176 if (window.console && console.debug)
3177 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
3180 _response: function(cb, res, json, duration) {
3182 cb(res, json, duration);
3187 * This function is a legacy wrapper around
3188 * {@link LuCI#get LuCI.get()}.
3192 * @memberof LuCI.xhr
3194 * @param {string} url
3195 * The URL to request
3197 * @param {Object} [data]
3198 * Additional query string data
3200 * @param {LuCI.requestCallbackFn} [callback]
3201 * Callback function to invoke on completion
3203 * @param {number} [timeout]
3204 * Request timeout to use
3206 * @return {Promise<null>}
3208 get: function(url, data, callback, timeout) {
3210 L.get(url, data, this._response.bind(this, callback), timeout);
3214 * This function is a legacy wrapper around
3215 * {@link LuCI#post LuCI.post()}.
3219 * @memberof LuCI.xhr
3221 * @param {string} url
3222 * The URL to request
3224 * @param {Object} [data]
3225 * Additional data to append to the request body.
3227 * @param {LuCI.requestCallbackFn} [callback]
3228 * Callback function to invoke on completion
3230 * @param {number} [timeout]
3231 * Request timeout to use
3233 * @return {Promise<null>}
3235 post: function(url, data, callback, timeout) {
3237 L.post(url, data, this._response.bind(this, callback), timeout);
3241 * Cancels a running request.
3243 * This function does not actually cancel the underlying
3244 * `XMLHTTPRequest` request but it sets a flag which prevents the
3245 * invocation of the callback function when the request eventually
3246 * finishes or timed out.
3250 * @memberof LuCI.xhr
3252 cancel: function() { delete this.active },
3255 * Checks the running state of the request.
3259 * @memberof LuCI.xhr
3261 * @returns {boolean}
3262 * Returns `true` if the request is still running or `false` if it
3263 * already completed.
3265 busy: function() { return (this.active === true) },
3268 * Ignored for backwards compatibility.
3270 * This function does nothing.
3274 * @memberof LuCI.xhr
3276 abort: function() {},
3279 * Existing for backwards compatibility.
3281 * This function simply throws an `InternalError` when invoked.
3285 * @memberof LuCI.xhr
3287 * @throws {InternalError}
3288 * Throws an `InternalError` with the message `Not implemented`
3291 send_form: function() { L.error('InternalError', 'Not implemented') },
3294 XHR.get = function() { return window.L.get.apply(window.L, arguments) };
3295 XHR.post = function() { return window.L.post.apply(window.L, arguments) };
3296 XHR.poll = function() { return window.L.poll.apply(window.L, arguments) };
3297 XHR.stop = Request.poll.remove.bind(Request.poll);
3298 XHR.halt = Request.poll.stop.bind(Request.poll);
3299 XHR.run = Request.poll.start.bind(Request.poll);
3300 XHR.running = Request.poll.active.bind(Request.poll);
3304 })(window, document);