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.Class` 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
= null, 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.Class
77 * @param {Object<string, *>} properties
78 * An object describing the properties to add to the new
81 * @returns {LuCI.Class}
82 * Returns a new LuCI.Class 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 __base__
: { value
: this.prototype },
90 __name__
: { value
: properties
.__name__
|| 'anonymous' }
93 var ClassConstructor = function() {
94 if (!(this instanceof ClassConstructor
))
95 throw new TypeError('Constructor must not be called without "new"');
97 if (Object
.getPrototypeOf(this).hasOwnProperty('__init__')) {
98 if (typeof(this.__init__
) != 'function')
99 throw new TypeError('Class __init__ member is not a function');
101 this.__init__
.apply(this, arguments
)
104 this.super('__init__', arguments
);
108 for (var key
in properties
)
109 if (!props
[key
] && properties
.hasOwnProperty(key
))
110 props
[key
] = { value
: properties
[key
], writable
: true };
112 ClassConstructor
.prototype = Object
.create(this.prototype, props
);
113 ClassConstructor
.prototype.constructor = ClassConstructor
;
114 Object
.assign(ClassConstructor
, this);
115 ClassConstructor
.displayName
= toCamelCase(props
.__name__
.value
+ 'Class');
117 return ClassConstructor
;
121 * Extends this base class with the properties described in
122 * `properties`, instantiates the resulting subclass using
123 * the additional optional arguments passed to this function
124 * and returns the resulting subclassed Class instance.
126 * This function serves as a convenience shortcut for
127 * {@link LuCI.Class.extend Class.extend()} and subsequent
130 * @memberof LuCI.Class
132 * @param {Object<string, *>} properties
133 * An object describing the properties to add to the new
136 * @param {...*} [new_args]
137 * Specifies arguments to be passed to the subclass constructor
138 * as-is in order to instantiate the new subclass.
140 * @returns {LuCI.Class}
141 * Returns a new LuCI.Class instance extended by the given
142 * properties with its prototype set to this base class to
143 * enable inheritance.
145 singleton: function(properties
/*, ... */) {
146 return Class
.extend(properties
)
147 .instantiate(Class
.prototype.varargs(arguments
, 1));
151 * Calls the class constructor using `new` with the given argument
152 * array being passed as variadic parameters to the constructor.
154 * @memberof LuCI.Class
156 * @param {Array<*>} params
157 * An array of arbitrary values which will be passed as arguments
158 * to the constructor function.
160 * @param {...*} [new_args]
161 * Specifies arguments to be passed to the subclass constructor
162 * as-is in order to instantiate the new subclass.
164 * @returns {LuCI.Class}
165 * Returns a new LuCI.Class instance extended by the given
166 * properties with its prototype set to this base class to
167 * enable inheritance.
169 instantiate: function(args
) {
170 return new (Function
.prototype.bind
.apply(this,
171 Class
.prototype.varargs(args
, 0, null)))();
175 call: function(self
, method
) {
176 if (typeof(this.prototype[method
]) != 'function')
177 throw new ReferenceError(method
+ ' is not defined in class');
179 return this.prototype[method
].apply(self
, self
.varargs(arguments
, 1));
183 * Checks whether the given class value is a subclass of this class.
185 * @memberof LuCI.Class
187 * @param {LuCI.Class} classValue
188 * The class object to test.
191 * Returns `true` when the given `classValue` is a subclass of this
192 * class or `false` if the given value is not a valid class or not
193 * a subclass of this class'.
195 isSubclass: function(classValue
) {
196 return (classValue
!= null &&
197 typeof(classValue
) == 'function' &&
198 classValue
.prototype instanceof this);
203 * Extract all values from the given argument array beginning from
204 * `offset` and prepend any further given optional parameters to
205 * the beginning of the resulting array copy.
207 * @memberof LuCI.Class
210 * @param {Array<*>} args
211 * The array to extract the values from.
213 * @param {number} offset
214 * The offset from which to extract the values. An offset of `0`
215 * would copy all values till the end.
217 * @param {...*} [extra_args]
218 * Extra arguments to add to prepend to the resultung array.
220 * @returns {Array<*>}
221 * Returns a new array consisting of the optional extra arguments
222 * and the values extracted from the `args` array beginning with
225 varargs: function(args
, offset
/*, ... */) {
226 return Array
.prototype.slice
.call(arguments
, 2)
227 .concat(Array
.prototype.slice
.call(args
, offset
));
231 * Walks up the parent class chain and looks for a class member
232 * called `key` in any of the parent classes this class inherits
233 * from. Returns the member value of the superclass or calls the
234 * member as function and returns its return value when the
235 * optional `callArgs` array is given.
237 * This function has two signatures and is sensitive to the
238 * amount of arguments passed to it:
240 * Returns the value of `key` when found within one of the
242 * - `super('key', ['arg1', 'arg2'])` -
243 * Calls the `key()` method with parameters `arg1` and `arg2`
244 * when found within one of the parent classes.
246 * @memberof LuCI.Class
249 * @param {string} key
250 * The name of the superclass member to retrieve.
252 * @param {Array<*>} [callArgs]
253 * An optional array of function call parameters to use. When
254 * this parameter is specified, the found member value is called
255 * as function using the values of this array as arguments.
257 * @throws {ReferenceError}
258 * Throws a `ReferenceError` when `callArgs` are specified and
259 * the found member named by `key` is not a function value.
262 * Returns the value of the found member or the return value of
263 * the call to the found method. Returns `null` when no member
264 * was found in the parent class chain or when the call to the
265 * superclass method returned `null`.
267 super: function(key
, callArgs
) {
268 for (superContext
= Object
.getPrototypeOf(superContext
||
269 Object
.getPrototypeOf(this));
270 superContext
&& !superContext
.hasOwnProperty(key
);
271 superContext
= Object
.getPrototypeOf(superContext
)) { }
276 var res
= superContext
[key
];
278 if (arguments
.length
> 1) {
279 if (typeof(res
) != 'function')
280 throw new ReferenceError(key
+ ' is not a function in base class');
282 if (typeof(callArgs
) != 'object')
283 callArgs
= this.varargs(arguments
, 1);
285 res
= res
.apply(this, callArgs
);
294 * Returns a string representation of this class.
297 * Returns a string representation of this class containing the
298 * constructor functions `displayName` and describing the class
299 * members and their respective types.
301 toString: function() {
302 var s
= '[' + this.constructor.displayName
+ ']', f
= true;
303 for (var k
in this) {
304 if (this.hasOwnProperty(k
)) {
305 s
+= (f
? ' {\n' : '') + ' ' + k
+ ': ' + typeof(this[k
]) + '\n';
309 return s
+ (f
? '' : '}');
321 * The `Headers` class is an internal utility class exposed in HTTP
322 * response objects using the `response.headers` property.
324 var Headers
= Class
.extend(/** @lends LuCI.Headers.prototype */ {
325 __name__
: 'LuCI.XHR.Headers',
326 __init__: function(xhr
) {
327 var hdrs
= this.headers
= {};
328 xhr
.getAllResponseHeaders().split(/\r\n/).forEach(function(line
) {
329 var m
= /^([^:]+):(.*)$/.exec(line
);
331 hdrs
[m
[1].trim().toLowerCase()] = m
[2].trim();
336 * Checks whether the given header name is present.
337 * Note: Header-Names are case-insensitive.
340 * @memberof LuCI.Headers
341 * @param {string} name
342 * The header name to check
345 * Returns `true` if the header name is present, `false` otherwise
347 has: function(name
) {
348 return this.headers
.hasOwnProperty(String(name
).toLowerCase());
352 * Returns the value of the given header name.
353 * Note: Header-Names are case-insensitive.
356 * @memberof LuCI.Headers
357 * @param {string} name
358 * The header name to read
360 * @returns {string|null}
361 * The value of the given header name or `null` if the header isn't present.
363 get: function(name
) {
364 var key
= String(name
).toLowerCase();
365 return this.headers
.hasOwnProperty(key
) ? this.headers
[key
] : null;
375 * The `Response` class is an internal utility class representing HTTP responses.
377 var Response
= Class
.extend({
378 __name__
: 'LuCI.XHR.Response',
379 __init__: function(xhr
, url
, duration
, headers
, content
) {
381 * Describes whether the response is successful (status codes `200..299`) or not
383 * @memberof LuCI.Response
387 this.ok
= (xhr
.status
>= 200 && xhr
.status
<= 299);
390 * The numeric HTTP status code of the response
392 * @memberof LuCI.Response
396 this.status
= xhr
.status
;
399 * The HTTP status description message of the response
401 * @memberof LuCI.Response
405 this.statusText
= xhr
.statusText
;
408 * The HTTP headers of the response
410 * @memberof LuCI.Response
412 * @type {LuCI.Headers}
414 this.headers
= (headers
!= null) ? headers
: new Headers(xhr
);
417 * The total duration of the HTTP request in milliseconds
419 * @memberof LuCI.Response
423 this.duration
= duration
;
426 * The final URL of the request, i.e. after following redirects.
428 * @memberof LuCI.Response
437 if (content
!= null && typeof(content
) == 'object') {
438 this.responseJSON
= content
;
439 this.responseText
= null;
441 else if (content
!= null) {
442 this.responseJSON
= null;
443 this.responseText
= String(content
);
446 this.responseJSON
= null;
447 this.responseText
= xhr
.responseText
;
452 * Clones the given response object, optionally overriding the content
453 * of the cloned instance.
456 * @memberof LuCI.Response
457 * @param {*} [content]
458 * Override the content of the cloned response. Object values will be
459 * treated as JSON response data, all other types will be converted
460 * using `String()` and treated as response text.
462 * @returns {LuCI.Response}
463 * The cloned `Response` instance.
465 clone: function(content
) {
466 var copy
= new Response(this.xhr
, this.url
, this.duration
, this.headers
, content
);
469 copy
.status
= this.status
;
470 copy
.statusText
= this.statusText
;
476 * Access the response content as JSON data.
479 * @memberof LuCI.Response
480 * @throws {SyntaxError}
481 * Throws `SyntaxError` if the content isn't valid JSON.
484 * The parsed JSON data.
487 if (this.responseJSON
== null)
488 this.responseJSON
= JSON
.parse(this.responseText
);
490 return this.responseJSON
;
494 * Access the response content as string.
497 * @memberof LuCI.Response
499 * The response content.
502 if (this.responseText
== null && this.responseJSON
!= null)
503 this.responseText
= JSON
.stringify(this.responseJSON
);
505 return this.responseText
;
510 var requestQueue
= [];
512 function isQueueableRequest(opt
) {
516 if (opt
.method
!= 'POST' || typeof(opt
.content
) != 'object')
519 if (opt
.nobatch
=== true)
522 var rpcBaseURL
= Request
.expandURL(classes
.rpc
.getBaseURL());
524 return (rpcBaseURL
!= null && opt
.url
.indexOf(rpcBaseURL
) == 0);
527 function flushRequestQueue() {
528 if (!requestQueue
.length
)
531 var reqopt
= Object
.assign({}, requestQueue
[0][0], { content
: [], nobatch
: true }),
534 for (var i
= 0; i
< requestQueue
.length
; i
++) {
535 batch
[i
] = requestQueue
[i
];
536 reqopt
.content
[i
] = batch
[i
][0].content
;
539 requestQueue
.length
= 0;
541 Request
.request(rpcBaseURL
, reqopt
).then(function(reply
) {
542 var json
= null, req
= null;
544 try { json
= reply
.json() }
547 while ((req
= batch
.shift()) != null)
548 if (Array
.isArray(json
) && json
.length
)
549 req
[2].call(reqopt
, reply
.clone(json
.shift()));
551 req
[1].call(reqopt
, new Error('No related RPC reply'));
552 }).catch(function(error
) {
555 while ((req
= batch
.shift()) != null)
556 req
[1].call(reqopt
, error
);
566 * The `Request` class allows initiating HTTP requests and provides utilities
567 * for dealing with responses.
569 var Request
= Class
.singleton(/** @lends LuCI.Request.prototype */ {
570 __name__
: 'LuCI.Request',
575 * Turn the given relative URL into an absolute URL if necessary.
578 * @memberof LuCI.Request
579 * @param {string} url
580 * The URL to convert.
583 * The absolute URL derived from the given one, or the original URL
584 * if it already was absolute.
586 expandURL: function(url
) {
587 if (!/^(?:[^/]+:)?\/\//.test(url
))
588 url
= location
.protocol
+ '//' + location
.host
+ url
;
594 * @typedef {Object} RequestOptions
595 * @memberof LuCI.Request
597 * @property {string} [method=GET]
598 * The HTTP method to use, e.g. `GET` or `POST`.
600 * @property {Object<string, Object|string>} [query]
601 * Query string data to append to the URL. Non-string values of the
602 * given object will be converted to JSON.
604 * @property {boolean} [cache=false]
605 * Specifies whether the HTTP response may be retrieved from cache.
607 * @property {string} [username]
608 * Provides a username for HTTP basic authentication.
610 * @property {string} [password]
611 * Provides a password for HTTP basic authentication.
613 * @property {number} [timeout]
614 * Specifies the request timeout in seconds.
616 * @property {boolean} [credentials=false]
617 * Whether to include credentials such as cookies in the request.
619 * @property {*} [content]
620 * Specifies the HTTP message body to send along with the request.
621 * If the value is a function, it is invoked and the return value
622 * used as content, if it is a FormData instance, it is used as-is,
623 * if it is an object, it will be converted to JSON, in all other
624 * cases it is converted to a string.
626 * @property {Object<string, string>} [header]
627 * Specifies HTTP headers to set for the request.
629 * @property {function} [progress]
630 * An optional request callback function which receives ProgressEvent
631 * instances as sole argument during the HTTP request transfer.
635 * Initiate an HTTP request to the given target.
638 * @memberof LuCI.Request
639 * @param {string} target
640 * The URL to request.
642 * @param {LuCI.Request.RequestOptions} [options]
643 * Additional options to configure the request.
645 * @returns {Promise<LuCI.Response>}
646 * The resulting HTTP response.
648 request: function(target
, options
) {
649 var state
= { xhr
: new XMLHttpRequest(), url
: this.expandURL(target
), start
: Date
.now() },
650 opt
= Object
.assign({}, options
, state
),
653 callback
= this.handleReadyStateChange
;
655 return new Promise(function(resolveFn
, rejectFn
) {
656 opt
.xhr
.onreadystatechange
= callback
.bind(opt
, resolveFn
, rejectFn
);
657 opt
.method
= String(opt
.method
|| 'GET').toUpperCase();
659 if ('query' in opt
) {
660 var q
= (opt
.query
!= null) ? Object
.keys(opt
.query
).map(function(k
) {
661 if (opt
.query
[k
] != null) {
662 var v
= (typeof(opt
.query
[k
]) == 'object')
663 ? JSON
.stringify(opt
.query
[k
])
664 : String(opt
.query
[k
]);
666 return '%s=%s'.format(encodeURIComponent(k
), encodeURIComponent(v
));
669 return encodeURIComponent(k
);
674 switch (opt
.method
) {
678 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + q
;
682 if (content
== null) {
684 contenttype
= 'application/x-www-form-urlencoded';
691 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + (new Date()).getTime();
693 if (isQueueableRequest(opt
)) {
694 requestQueue
.push([opt
, rejectFn
, resolveFn
]);
695 requestAnimationFrame(flushRequestQueue
);
699 if ('username' in opt
&& 'password' in opt
)
700 opt
.xhr
.open(opt
.method
, opt
.url
, true, opt
.username
, opt
.password
);
702 opt
.xhr
.open(opt
.method
, opt
.url
, true);
704 opt
.xhr
.responseType
= 'text';
706 if ('overrideMimeType' in opt
.xhr
)
707 opt
.xhr
.overrideMimeType('application/octet-stream');
709 if ('timeout' in opt
)
710 opt
.xhr
.timeout
= +opt
.timeout
;
712 if ('credentials' in opt
)
713 opt
.xhr
.withCredentials
= !!opt
.credentials
;
715 if (opt
.content
!= null) {
716 switch (typeof(opt
.content
)) {
718 content
= opt
.content(xhr
);
722 if (!(opt
.content
instanceof FormData
)) {
723 content
= JSON
.stringify(opt
.content
);
724 contenttype
= 'application/json';
727 content
= opt
.content
;
732 content
= String(opt
.content
);
736 if ('headers' in opt
)
737 for (var header
in opt
.headers
)
738 if (opt
.headers
.hasOwnProperty(header
)) {
739 if (header
.toLowerCase() != 'content-type')
740 opt
.xhr
.setRequestHeader(header
, opt
.headers
[header
]);
742 contenttype
= opt
.headers
[header
];
745 if ('progress' in opt
&& 'upload' in opt
.xhr
)
746 opt
.xhr
.upload
.addEventListener('progress', opt
.progress
);
748 if (contenttype
!= null)
749 opt
.xhr
.setRequestHeader('Content-Type', contenttype
);
752 opt
.xhr
.send(content
);
755 rejectFn
.call(opt
, e
);
760 handleReadyStateChange: function(resolveFn
, rejectFn
, ev
) {
762 duration
= Date
.now() - this.start
;
764 if (xhr
.readyState
!== 4)
767 if (xhr
.status
=== 0 && xhr
.statusText
=== '') {
768 if (duration
>= this.timeout
)
769 rejectFn
.call(this, new Error('XHR request timed out'));
771 rejectFn
.call(this, new Error('XHR request aborted by browser'));
774 var response
= new Response(
775 xhr
, xhr
.responseURL
|| this.url
, duration
);
777 Promise
.all(Request
.interceptors
.map(function(fn
) { return fn(response
) }))
778 .then(resolveFn
.bind(this, response
))
779 .catch(rejectFn
.bind(this));
784 * Initiate an HTTP GET request to the given target.
787 * @memberof LuCI.Request
788 * @param {string} target
789 * The URL to request.
791 * @param {LuCI.Request.RequestOptions} [options]
792 * Additional options to configure the request.
794 * @returns {Promise<LuCI.Response>}
795 * The resulting HTTP response.
797 get: function(url
, options
) {
798 return this.request(url
, Object
.assign({ method
: 'GET' }, options
));
802 * Initiate an HTTP POST request to the given target.
805 * @memberof LuCI.Request
806 * @param {string} target
807 * The URL to request.
810 * The request data to send, see {@link LuCI.Request.RequestOptions} for details.
812 * @param {LuCI.Request.RequestOptions} [options]
813 * Additional options to configure the request.
815 * @returns {Promise<LuCI.Response>}
816 * The resulting HTTP response.
818 post: function(url
, data
, options
) {
819 return this.request(url
, Object
.assign({ method
: 'POST', content
: data
}, options
));
823 * Interceptor functions are invoked whenever an HTTP reply is received, in the order
824 * these functions have been registered.
825 * @callback LuCI.Request.interceptorFn
826 * @param {LuCI.Response} res
827 * The HTTP response object
831 * Register an HTTP response interceptor function. Interceptor
832 * functions are useful to perform default actions on incoming HTTP
833 * responses, such as checking for expired authentication or for
834 * implementing request retries before returning a failure.
837 * @memberof LuCI.Request
838 * @param {LuCI.Request.interceptorFn} interceptorFn
839 * The interceptor function to register.
841 * @returns {LuCI.Request.interceptorFn}
842 * The registered function.
844 addInterceptor: function(interceptorFn
) {
845 if (typeof(interceptorFn
) == 'function')
846 this.interceptors
.push(interceptorFn
);
847 return interceptorFn
;
851 * Remove an HTTP response interceptor function. The passed function
852 * value must be the very same value that was used to register the
856 * @memberof LuCI.Request
857 * @param {LuCI.Request.interceptorFn} interceptorFn
858 * The interceptor function to remove.
861 * Returns `true` if any function has been removed, else `false`.
863 removeInterceptor: function(interceptorFn
) {
864 var oldlen
= this.interceptors
.length
, i
= oldlen
;
866 if (this.interceptors
[i
] === interceptorFn
)
867 this.interceptors
.splice(i
, 1);
868 return (this.interceptors
.length
< oldlen
);
873 * @memberof LuCI.Request
877 * The `Request.poll` class provides some convience wrappers around
878 * {@link LuCI.Poll} mainly to simplify registering repeating HTTP
879 * request calls as polling functions.
883 * The callback function is invoked whenever an HTTP reply to a
884 * polled request is received or when the polled request timed
887 * @callback LuCI.Request.poll~callbackFn
888 * @param {LuCI.Response} res
889 * The HTTP response object.
892 * The response JSON if the response could be parsed as such,
895 * @param {number} duration
896 * The total duration of the request in milliseconds.
900 * Register a repeating HTTP request with an optional callback
901 * to invoke whenever a response for the request is received.
904 * @memberof LuCI.Request.poll
905 * @param {number} interval
906 * The poll interval in seconds.
908 * @param {string} url
909 * The URL to request on each poll.
911 * @param {LuCI.Request.RequestOptions} [options]
912 * Additional options to configure the request.
914 * @param {LuCI.Request.poll~callbackFn} [callback]
915 * {@link LuCI.Request.poll~callbackFn Callback} function to
916 * invoke for each HTTP reply.
918 * @throws {TypeError}
919 * Throws `TypeError` when an invalid interval was passed.
921 * @returns {function}
922 * Returns the internally created poll function.
924 add: function(interval
, url
, options
, callback
) {
925 if (isNaN(interval
) || interval
<= 0)
926 throw new TypeError('Invalid poll interval');
928 var ival
= interval
>>> 0,
929 opts
= Object
.assign({}, options
, { timeout
: ival
* 1000 - 5 });
931 var fn = function() {
932 return Request
.request(url
, options
).then(function(res
) {
937 callback(res
, res
.json(), res
.duration
);
940 callback(res
, null, res
.duration
);
945 return (Poll
.add(fn
, ival
) ? fn
: null);
949 * Remove a polling request that has been previously added using `add()`.
950 * This function is essentially a wrapper around
951 * {@link LuCI.Poll.remove LuCI.Poll.remove()}.
954 * @memberof LuCI.Request.poll
955 * @param {function} entry
956 * The poll function returned by {@link LuCI.Request.poll#add add()}.
959 * Returns `true` if any function has been removed, else `false`.
961 remove: function(entry
) { return Poll
.remove(entry
) },
964 * Alias for {@link LuCI.Poll.start LuCI.Poll.start()}.
967 * @memberof LuCI.Request.poll
969 start: function() { return Poll
.start() },
972 * Alias for {@link LuCI.Poll.stop LuCI.Poll.stop()}.
975 * @memberof LuCI.Request.poll
977 stop: function() { return Poll
.stop() },
980 * Alias for {@link LuCI.Poll.active LuCI.Poll.active()}.
983 * @memberof LuCI.Request.poll
985 active: function() { return Poll
.active() }
995 * The `Poll` class allows registering and unregistering poll actions,
996 * as well as starting, stopping and querying the state of the polling
999 var Poll
= Class
.singleton(/** @lends LuCI.Poll.prototype */ {
1000 __name__
: 'LuCI.Poll',
1005 * Add a new operation to the polling loop. If the polling loop is not
1006 * already started at this point, it will be implicitely started.
1009 * @memberof LuCI.Poll
1010 * @param {function} fn
1011 * The function to invoke on each poll interval.
1013 * @param {number} interval
1014 * The poll interval in seconds.
1016 * @throws {TypeError}
1017 * Throws `TypeError` when an invalid interval was passed.
1019 * @returns {boolean}
1020 * Returns `true` if the function has been added or `false` if it
1021 * already is registered.
1023 add: function(fn
, interval
) {
1024 if (interval
== null || interval
<= 0)
1025 interval
= window
.L
? window
.L
.env
.pollinterval
: null;
1027 if (isNaN(interval
) || typeof(fn
) != 'function')
1028 throw new TypeError('Invalid argument to LuCI.Poll.add()');
1030 for (var i
= 0; i
< this.queue
.length
; i
++)
1031 if (this.queue
[i
].fn
=== fn
)
1042 if (this.tick
!= null && !this.active())
1049 * Remove an operation from the polling loop. If no further operatons
1050 * are registered, the polling loop is implicitely stopped.
1053 * @memberof LuCI.Poll
1054 * @param {function} fn
1055 * The function to remove.
1057 * @throws {TypeError}
1058 * Throws `TypeError` when the given argument isn't a function.
1060 * @returns {boolean}
1061 * Returns `true` if the function has been removed or `false` if it
1064 remove: function(fn
) {
1065 if (typeof(fn
) != 'function')
1066 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
1068 var len
= this.queue
.length
;
1070 for (var i
= len
; i
> 0; i
--)
1071 if (this.queue
[i
-1].fn
=== fn
)
1072 this.queue
.splice(i
-1, 1);
1074 if (!this.queue
.length
&& this.stop())
1077 return (this.queue
.length
!= len
);
1081 * (Re)start the polling loop. Dispatches a custom `poll-start` event
1082 * to the `document` object upon successful start.
1085 * @memberof LuCI.Poll
1086 * @returns {boolean}
1087 * Returns `true` if polling has been started (or if no functions
1088 * where registered) or `false` when the polling loop already runs.
1096 if (this.queue
.length
) {
1097 this.timer
= window
.setInterval(this.step
, 1000);
1099 document
.dispatchEvent(new CustomEvent('poll-start'));
1106 * Stop the polling loop. Dispatches a custom `poll-stop` event
1107 * to the `document` object upon successful stop.
1110 * @memberof LuCI.Poll
1111 * @returns {boolean}
1112 * Returns `true` if polling has been stopped or `false` if it din't
1113 * run to begin with.
1119 document
.dispatchEvent(new CustomEvent('poll-stop'));
1120 window
.clearInterval(this.timer
);
1128 for (var i
= 0, e
= null; (e
= Poll
.queue
[i
]) != null; i
++) {
1129 if ((Poll
.tick
% e
.i
) != 0)
1137 Promise
.resolve(e
.fn()).finally((function() { this.r
= true }).bind(e
));
1140 Poll
.tick
= (Poll
.tick
+ 1) % Math
.pow(2, 32);
1144 * Test whether the polling loop is running.
1147 * @memberof LuCI.Poll
1148 * @returns {boolean} - Returns `true` if polling is active, else `false`.
1150 active: function() {
1151 return (this.timer
!= null);
1156 var dummyElem
= null,
1158 originalCBIInit
= null,
1163 var LuCI
= Class
.extend(/** @lends LuCI.prototype */ {
1165 __init__: function(env
) {
1167 document
.querySelectorAll('script[src*="/luci.js"]').forEach(function(s
) {
1168 if (env
.base_url
== null || env
.base_url
== '') {
1169 var m
= (s
.getAttribute('src') || '').match(/^(.*)\/luci\.js(?:\?v=([^?]+))?$/);
1171 env
.base_url
= m
[1];
1172 env
.resource_version
= m
[2];
1177 if (env
.base_url
== null)
1178 this.error('InternalError', 'Cannot find url of luci.js');
1180 Object
.assign(this.env
, env
);
1182 document
.addEventListener('poll-start', function(ev
) {
1183 document
.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e
) {
1184 e
.style
.display
= (e
.id
== 'xhr_poll_status_off') ? 'none' : '';
1188 document
.addEventListener('poll-stop', function(ev
) {
1189 document
.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e
) {
1190 e
.style
.display
= (e
.id
== 'xhr_poll_status_on') ? 'none' : '';
1194 var domReady
= new Promise(function(resolveFn
, rejectFn
) {
1195 document
.addEventListener('DOMContentLoaded', resolveFn
);
1201 this.require('rpc'),
1202 this.require('form'),
1203 this.probeRPCBaseURL()
1204 ]).then(this.setupDOM
.bind(this)).catch(this.error
);
1206 originalCBIInit
= window
.cbi_init
;
1207 window
.cbi_init = function() {};
1211 * Captures the current stack trace and throws an error of the
1212 * specified type as a new exception. Also logs the exception as
1213 * error to the debug console if it is available.
1218 * @param {Error|string} [type=Error]
1219 * Either a string specifying the type of the error to throw or an
1220 * existing `Error` instance to copy.
1222 * @param {string} [fmt=Unspecified error]
1223 * A format string which is used to form the error message, together
1224 * with all subsequent optional arguments.
1226 * @param {...*} [args]
1227 * Zero or more variable arguments to the supplied format string.
1230 * Throws the created error object with the captured stack trace
1231 * appended to the message and the type set to the given type
1232 * argument or copied from the given error instance.
1234 raise: function(type
, fmt
/*, ...*/) {
1236 msg
= fmt
? String
.prototype.format
.apply(fmt
, this.varargs(arguments
, 2)) : null,
1239 if (type
instanceof Error
) {
1243 e
.message
= msg
+ ': ' + e
.message
;
1246 try { throw new Error('stacktrace') }
1247 catch (e2
) { stack
= (e2
.stack
|| '').split(/\n/) }
1249 e
= new (window
[type
|| 'Error'] || Error
)(msg
|| 'Unspecified error');
1250 e
.name
= type
|| 'Error';
1253 stack
= (stack
|| []).map(function(frame
) {
1254 frame
= frame
.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
1255 return frame
? ' ' + frame
: '';
1258 if (!/^ at /.test(stack
[0]))
1261 if (/\braise /.test(stack
[0]))
1264 if (/\berror /.test(stack
[0]))
1268 e
.message
+= '\n' + stack
.join('\n');
1270 if (window
.console
&& console
.debug
)
1277 * A wrapper around {@link LuCI#raise raise()} which also renders
1278 * the error either as modal overlay when `ui.js` is already loaed
1279 * or directly into the view body.
1284 * @param {Error|string} [type=Error]
1285 * Either a string specifying the type of the error to throw or an
1286 * existing `Error` instance to copy.
1288 * @param {string} [fmt=Unspecified error]
1289 * A format string which is used to form the error message, together
1290 * with all subsequent optional arguments.
1292 * @param {...*} [args]
1293 * Zero or more variable arguments to the supplied format string.
1296 * Throws the created error object with the captured stack trace
1297 * appended to the message and the type set to the given type
1298 * argument or copied from the given error instance.
1300 error: function(type
, fmt
/*, ...*/) {
1302 L
.raise
.apply(L
, Array
.prototype.slice
.call(arguments
));
1307 L
.ui
.addNotification(e
.name
|| _('Runtime error'),
1308 E('pre', {}, e
.message
), 'danger');
1310 L
.dom
.content(document
.querySelector('#maincontent'),
1311 E('pre', { 'class': 'alert-message error' }, e
.message
));
1321 * Return a bound function using the given `self` as `this` context
1322 * and any further arguments as parameters to the bound function.
1327 * @param {function} fn
1328 * The function to bind.
1331 * The value to bind as `this` context to the specified function.
1333 * @param {...*} [args]
1334 * Zero or more variable arguments which are bound to the function
1337 * @returns {function}
1338 * Returns the bound function.
1340 bind: function(fn
, self
/*, ... */) {
1341 return Function
.prototype.bind
.apply(fn
, this.varargs(arguments
, 2, self
));
1345 * Load an additional LuCI JavaScript class and its dependencies,
1346 * instantiate it and return the resulting class instance. Each
1347 * class is only loaded once. Subsequent attempts to load the same
1348 * class will return the already instantiated class.
1353 * @param {string} name
1354 * The name of the class to load in dotted notation. Dots will
1355 * be replaced by spaces and joined with the runtime-determined
1356 * base URL of LuCI.js to form an absolute URL to load the class
1359 * @throws {DependencyError}
1360 * Throws a `DependencyError` when the class to load includes
1361 * circular dependencies.
1363 * @throws {NetworkError}
1364 * Throws `NetworkError` when the underlying {@link LuCI.Request}
1367 * @throws {SyntaxError}
1368 * Throws `SyntaxError` when the loaded class file code cannot
1369 * be interpreted by `eval`.
1371 * @throws {TypeError}
1372 * Throws `TypeError` when the class file could be loaded and
1373 * interpreted, but when invoking its code did not yield a valid
1376 * @returns {Promise<LuCI#Class>}
1377 * Returns the instantiated class.
1379 require: function(name
, from) {
1380 var L
= this, url
= null, from = from || [];
1382 /* Class already loaded */
1383 if (classes
[name
] != null) {
1384 /* Circular dependency */
1385 if (from.indexOf(name
) != -1)
1386 L
.raise('DependencyError',
1387 'Circular dependency: class "%s" depends on "%s"',
1388 name
, from.join('" which depends on "'));
1390 return Promise
.resolve(classes
[name
]);
1393 url
= '%s/%s.js%s'.format(L
.env
.base_url
, name
.replace(/\./g, '/'), (L.env.resource_version ? '?v
=' + L.env.resource_version : ''));
1394 from = [ name ].concat(from);
1396 var compileClass = function(res) {
1398 L.raise('NetworkError
',
1399 'HTTP error
%d
while loading
class file
"%s"', res.status, url);
1401 var source = res.text(),
1402 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
1403 strictmatch = /^use[ \t]+strict$/,
1407 /* find require statements in source */
1408 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
1409 var chr = source.charCodeAt(i);
1414 else if (chr == 92) {
1417 else if (chr == quote) {
1418 var s = source.substring(off, i),
1419 m = requirematch.exec(s);
1422 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_
');
1423 depends.push(L.require(dep, from));
1426 else if (!strictmatch.exec(s)) {
1433 else if (quote == -1 && (chr == 34 || chr == 39)) {
1439 /* load dependencies and instantiate class */
1440 return Promise.all(depends).then(function(instances) {
1441 var _factory, _class;
1445 '(function(window
, document
, L
%s
) { %s
})\n\n//# sourceURL=%s\n'
1446 .format(args
, source
, res
.url
));
1449 L
.raise('SyntaxError', '%s\n in %s:%s',
1450 error
.message
, res
.url
, error
.lineNumber
|| '?');
1453 _factory
.displayName
= toCamelCase(name
+ 'ClassFactory');
1454 _class
= _factory
.apply(_factory
, [window
, document
, L
].concat(instances
));
1456 if (!Class
.isSubclass(_class
))
1457 L
.error('TypeError', '"%s" factory yields invalid constructor', name
);
1459 if (_class
.displayName
== 'AnonymousClass')
1460 _class
.displayName
= toCamelCase(name
+ 'Class');
1462 var ptr
= Object
.getPrototypeOf(L
),
1463 parts
= name
.split(/\./),
1464 instance
= new _class();
1466 for (var i
= 0; ptr
&& i
< parts
.length
- 1; i
++)
1467 ptr
= ptr
[parts
[i
]];
1470 ptr
[parts
[i
]] = instance
;
1472 classes
[name
] = instance
;
1478 /* Request class file */
1479 classes
[name
] = Request
.get(url
, { cache
: true }).then(compileClass
);
1481 return classes
[name
];
1485 probeRPCBaseURL: function() {
1486 if (rpcBaseURL
== null) {
1488 rpcBaseURL
= window
.sessionStorage
.getItem('rpcBaseURL');
1493 if (rpcBaseURL
== null) {
1494 var rpcFallbackURL
= this.url('admin/ubus');
1496 rpcBaseURL
= Request
.get('/ubus/').then(function(res
) {
1497 return (rpcBaseURL
= (res
.status
== 400) ? '/ubus/' : rpcFallbackURL
);
1499 return (rpcBaseURL
= rpcFallbackURL
);
1500 }).then(function(url
) {
1502 window
.sessionStorage
.setItem('rpcBaseURL', url
);
1510 return Promise
.resolve(rpcBaseURL
);
1513 probeSystemFeatures: function() {
1514 var sessionid
= classes
.rpc
.getSessionID();
1516 if (sysFeatures
== null) {
1518 var data
= JSON
.parse(window
.sessionStorage
.getItem('sysFeatures'));
1520 if (this.isObject(data
) && this.isObject(data
[sessionid
]))
1521 sysFeatures
= data
[sessionid
];
1526 if (!this.isObject(sysFeatures
)) {
1527 sysFeatures
= classes
.rpc
.declare({
1529 method
: 'getFeatures',
1531 })().then(function(features
) {
1534 data
[sessionid
] = features
;
1536 window
.sessionStorage
.setItem('sysFeatures', JSON
.stringify(data
));
1540 sysFeatures
= features
;
1546 return Promise
.resolve(sysFeatures
);
1550 * Test whether a particular system feature is available, such as
1551 * hostapd SAE support or an installed firewall. The features are
1552 * queried once at the beginning of the LuCI session and cached in
1553 * `SessionStorage` throughout the lifetime of the associated tab or
1559 * @param {string} feature
1560 * The feature to test. For detailed list of known feature flags,
1561 * see `/modules/luci-base/root/usr/libexec/rpcd/luci`.
1563 * @param {string} [subfeature]
1564 * Some feature classes like `hostapd` provide sub-feature flags,
1565 * such as `sae` or `11w` support. The `subfeature` argument can
1566 * be used to query these.
1568 * @return {boolean|null}
1569 * Return `true` if the queried feature (and sub-feature) is available
1570 * or `false` if the requested feature isn't present or known.
1571 * Return `null` when a sub-feature was queried for a feature which
1572 * has no sub-features.
1574 hasSystemFeature: function() {
1575 var ft
= sysFeatures
[arguments
[0]];
1577 if (arguments
.length
== 2)
1578 return this.isObject(ft
) ? ft
[arguments
[1]] : null;
1580 return (ft
!= null && ft
!= false);
1584 notifySessionExpiry: function() {
1587 L
.ui
.showModal(_('Session expired'), [
1588 E('div', { class: 'alert-message warning' },
1589 _('A new login is required since the authentication session expired.')),
1590 E('div', { class: 'right' },
1592 class: 'btn primary',
1594 var loc
= window
.location
;
1595 window
.location
= loc
.protocol
+ '//' + loc
.host
+ loc
.pathname
+ loc
.search
;
1597 }, _('To login…')))
1600 L
.raise('SessionError', 'Login session is expired');
1604 setupDOM: function(res
) {
1609 rpcBaseURL
= res
[4];
1611 rpcClass
.setBaseURL(rpcBaseURL
);
1613 rpcClass
.addInterceptor(function(msg
, req
) {
1614 if (!L
.isObject(msg
) || !L
.isObject(msg
.error
) || msg
.error
.code
!= -32002)
1617 if (!L
.isObject(req
) || (req
.object
== 'session' && req
.method
== 'access'))
1620 return rpcClass
.declare({
1621 'object': 'session',
1623 'params': [ 'scope', 'object', 'function' ],
1624 'expect': { access
: true }
1625 })('uci', 'luci', 'read').catch(L
.notifySessionExpiry
);
1628 Request
.addInterceptor(function(res
) {
1629 var isDenied
= false;
1631 if (res
.status
== 403 && res
.headers
.get('X-LuCI-Login-Required') == 'yes')
1637 L
.notifySessionExpiry();
1640 return this.probeSystemFeatures().finally(this.initDOM
);
1644 initDOM: function() {
1647 document
.dispatchEvent(new CustomEvent('luci-loaded'));
1651 * The `env` object holds environment settings used by LuCI, such
1652 * as request timeouts, base URLs etc.
1660 * Construct a relative URL path from the given prefix and parts.
1661 * The resulting URL is guaranteed to only contain the characters
1662 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1663 * as `/` for the path separator.
1668 * @param {string} [prefix]
1669 * The prefix to join the given parts with. If the `prefix` is
1670 * omitted, it defaults to an empty string.
1672 * @param {string[]} [parts]
1673 * An array of parts to join into an URL path. Parts may contain
1674 * slashes and any of the other characters mentioned above.
1677 * Return the joined URL path.
1679 path: function(prefix
, parts
) {
1680 var url
= [ prefix
|| '' ];
1682 for (var i
= 0; i
< parts
.length
; i
++)
1683 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts
[i
]))
1684 url
.push('/', parts
[i
]);
1686 if (url
.length
=== 1)
1689 return url
.join('');
1693 * Construct an URL pathrelative to the script path of the server
1694 * side LuCI application (usually `/cgi-bin/luci`).
1696 * The resulting URL is guaranteed to only contain the characters
1697 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1698 * as `/` for the path separator.
1703 * @param {string[]} [parts]
1704 * An array of parts to join into an URL path. Parts may contain
1705 * slashes and any of the other characters mentioned above.
1708 * Returns the resulting URL path.
1711 return this.path(this.env
.scriptname
, arguments
);
1715 * Construct an URL path relative to the global static resource path
1716 * of the LuCI ui (usually `/luci-static/resources`).
1718 * The resulting URL is guaranteed to only contain the characters
1719 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1720 * as `/` for the path separator.
1725 * @param {string[]} [parts]
1726 * An array of parts to join into an URL path. Parts may contain
1727 * slashes and any of the other characters mentioned above.
1730 * Returns the resulting URL path.
1732 resource: function() {
1733 return this.path(this.env
.resource
, arguments
);
1737 * Return the complete URL path to the current view.
1743 * Returns the URL path to the current view.
1745 location: function() {
1746 return this.path(this.env
.scriptname
, this.env
.requestpath
);
1751 * Tests whether the passed argument is a JavaScript object.
1752 * This function is meant to be an object counterpart to the
1753 * standard `Array.isArray()` function.
1762 * Returns `true` if the given value is of type object and
1763 * not `null`, else returns `false`.
1765 isObject: function(val
) {
1766 return (val
!= null && typeof(val
) == 'object');
1770 * Return an array of sorted object keys, optionally sorted by
1771 * a different key or a different sorting mode.
1776 * @param {object} obj
1777 * The object to extract the keys from. If the given value is
1778 * not an object, the function will return an empty array.
1780 * @param {string} [key]
1781 * Specifies the key to order by. This is mainly useful for
1782 * nested objects of objects or objects of arrays when sorting
1783 * shall not be performed by the primary object keys but by
1784 * some other key pointing to a value within the nested values.
1786 * @param {string} [sortmode]
1787 * May be either `addr` or `num` to override the natural
1788 * lexicographic sorting with a sorting suitable for IP/MAC style
1789 * addresses or numeric values respectively.
1791 * @return {string[]}
1792 * Returns an array containing the sorted keys of the given object.
1794 sortedKeys: function(obj
, key
, sortmode
) {
1795 if (obj
== null || typeof(obj
) != 'object')
1798 return Object
.keys(obj
).map(function(e
) {
1799 var v
= (key
!= null) ? obj
[e
][key
] : e
;
1803 v
= (v
!= null) ? v
.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
1804 function(m0
, m1
) { return ('000' + m1
.toLowerCase()).substr(-4) }) : null;
1808 v
= (v
!= null) ? +v
: null;
1813 }).filter(function(e
) {
1814 return (e
[1] != null);
1815 }).sort(function(a
, b
) {
1816 return (a
[1] > b
[1]);
1817 }).map(function(e
) {
1823 * Converts the given value to an array. If the given value is of
1824 * type array, it is returned as-is, values of type object are
1825 * returned as one-element array containing the object, empty
1826 * strings and `null` values are returned as empty array, all other
1827 * values are converted using `String()`, trimmed, split on white
1828 * space and returned as array.
1834 * The value to convert into an array.
1836 * @return {Array<*>}
1837 * Returns the resulting array.
1839 toArray: function(val
) {
1842 else if (Array
.isArray(val
))
1844 else if (typeof(val
) == 'object')
1847 var s
= String(val
).trim();
1852 return s
.split(/\s+/);
1857 * The request callback function is invoked whenever an HTTP
1858 * reply to a request made using the `L.get()`, `L.post()` or
1859 * `L.poll()` function is timed out or received successfully.
1864 * @callback LuCI.requestCallbackFn
1865 * @param {XMLHTTPRequest} xhr
1866 * The XMLHTTPRequest instance used to make the request.
1869 * The response JSON if the response could be parsed as such,
1872 * @param {number} duration
1873 * The total duration of the request in milliseconds.
1877 * Issues a GET request to the given url and invokes the specified
1878 * callback function. The function is a wrapper around
1879 * {@link LuCI.Request#request Request.request()}.
1885 * @param {string} url
1886 * The URL to request.
1888 * @param {Object<string, string>} [args]
1889 * Additional query string arguments to append to the URL.
1891 * @param {LuCI.requestCallbackFn} cb
1892 * The callback function to invoke when the request finishes.
1894 * @return {Promise<null>}
1895 * Returns a promise resolving to `null` when concluded.
1897 get: function(url
, args
, cb
) {
1898 return this.poll(null, url
, args
, cb
, false);
1902 * Issues a POST request to the given url and invokes the specified
1903 * callback function. The function is a wrapper around
1904 * {@link LuCI.Request#request Request.request()}. The request is
1905 * sent using `application/x-www-form-urlencoded` encoding and will
1906 * contain a field `token` with the current value of `LuCI.env.token`
1913 * @param {string} url
1914 * The URL to request.
1916 * @param {Object<string, string>} [args]
1917 * Additional post arguments to append to the request body.
1919 * @param {LuCI.requestCallbackFn} cb
1920 * The callback function to invoke when the request finishes.
1922 * @return {Promise<null>}
1923 * Returns a promise resolving to `null` when concluded.
1925 post: function(url
, args
, cb
) {
1926 return this.poll(null, url
, args
, cb
, true);
1930 * Register a polling HTTP request that invokes the specified
1931 * callback function. The function is a wrapper around
1932 * {@link LuCI.Request.poll#add Request.poll.add()}.
1938 * @param {number} interval
1939 * The poll interval to use. If set to a value less than or equal
1940 * to `0`, it will default to the global poll interval configured
1941 * in `LuCI.env.pollinterval`.
1943 * @param {string} url
1944 * The URL to request.
1946 * @param {Object<string, string>} [args]
1947 * Specifies additional arguments for the request. For GET requests,
1948 * the arguments are appended to the URL as query string, for POST
1949 * requests, they'll be added to the request body.
1951 * @param {LuCI.requestCallbackFn} cb
1952 * The callback function to invoke whenever a request finishes.
1954 * @param {boolean} [post=false]
1955 * When set to `false` or not specified, poll requests will be made
1956 * using the GET method. When set to `true`, POST requests will be
1957 * issued. In case of POST requests, the request body will contain
1958 * an argument `token` with the current value of `LuCI.env.token` by
1959 * default, regardless of the parameters specified with `args`.
1961 * @return {function}
1962 * Returns the internally created function that has been passed to
1963 * {@link LuCI.Request.poll#add Request.poll.add()}. This value can
1964 * be passed to {@link LuCI.Poll.remove Poll.remove()} to remove the
1967 poll: function(interval
, url
, args
, cb
, post
) {
1968 if (interval
!== null && interval
<= 0)
1969 interval
= this.env
.pollinterval
;
1971 var data
= post
? { token
: this.env
.token
} : null,
1972 method
= post
? 'POST' : 'GET';
1974 if (!/^(?:\/|\S+:\/\/)/.test(url
))
1975 url
= this.url(url
);
1978 data
= Object
.assign(data
|| {}, args
);
1980 if (interval
!== null)
1981 return Request
.poll
.add(interval
, url
, { method
: method
, query
: data
}, cb
);
1983 return Request
.request(url
, { method
: method
, query
: data
})
1984 .then(function(res
) {
1986 if (/^application\/json\b/.test(res
.headers
.get('Content-Type')))
1987 try { json
= res
.json() } catch(e
) {}
1988 cb(res
.xhr
, json
, res
.duration
);
1993 * Deprecated wrapper around {@link LuCI.Poll.remove Poll.remove()}.
1999 * @param {function} entry
2000 * The polling function to remove.
2003 * Returns `true` when the function has been removed or `false` if
2004 * it could not be found.
2006 stop: function(entry
) { return Poll
.remove(entry
) },
2009 * Deprecated wrapper around {@link LuCI.Poll.stop Poll.stop()}.
2016 * Returns `true` when the polling loop has been stopped or `false`
2017 * when it didn't run to begin with.
2019 halt: function() { return Poll
.stop() },
2022 * Deprecated wrapper around {@link LuCI.Poll.start Poll.start()}.
2029 * Returns `true` when the polling loop has been started or `false`
2030 * when it was already running.
2032 run: function() { return Poll
.start() },
2041 * The `dom` class provides convenience method for creating and
2042 * manipulating DOM elements.
2044 dom
: Class
.singleton(/* @lends LuCI.dom.prototype */ {
2045 __name__
: 'LuCI.DOM',
2048 * Tests whether the given argument is a valid DOM `Node`.
2051 * @memberof LuCI.dom
2053 * The value to test.
2055 * @returns {boolean}
2056 * Returns `true` if the value is a DOM `Node`, else `false`.
2059 return (e
!= null && typeof(e
) == 'object' && 'nodeType' in e
);
2063 * Parses a given string as HTML and returns the first child node.
2066 * @memberof LuCI.dom
2068 * A string containing an HTML fragment to parse. Note that only
2069 * the first result of the resulting structure is returned, so an
2070 * input value of `<div>foo</div> <div>bar</div>` will only return
2071 * the first `div` element node.
2074 * Returns the first DOM `Node` extracted from the HTML fragment or
2075 * `null` on parsing failures or if no element could be found.
2077 parse: function(s
) {
2081 domParser
= domParser
|| new DOMParser();
2082 elem
= domParser
.parseFromString(s
, 'text/html').body
.firstChild
;
2088 dummyElem
= dummyElem
|| document
.createElement('div');
2089 dummyElem
.innerHTML
= s
;
2090 elem
= dummyElem
.firstChild
;
2095 return elem
|| null;
2099 * Tests whether a given `Node` matches the given query selector.
2101 * This function is a convenience wrapper around the standard
2102 * `Node.matches("selector")` function with the added benefit that
2103 * the `node` argument may be a non-`Node` value, in which case
2104 * this function simply returns `false`.
2107 * @memberof LuCI.dom
2109 * The `Node` argument to test the selector against.
2111 * @param {string} [selector]
2112 * The query selector expression to test against the given node.
2114 * @returns {boolean}
2115 * Returns `true` if the given node matches the specified selector
2116 * or `false` when the node argument is no valid DOM `Node` or the
2117 * selector didn't match.
2119 matches: function(node
, selector
) {
2120 var m
= this.elem(node
) ? node
.matches
|| node
.msMatchesSelector
: null;
2121 return m
? m
.call(node
, selector
) : false;
2125 * Returns the closest parent node that matches the given query
2126 * selector expression.
2128 * This function is a convenience wrapper around the standard
2129 * `Node.closest("selector")` function with the added benefit that
2130 * the `node` argument may be a non-`Node` value, in which case
2131 * this function simply returns `null`.
2134 * @memberof LuCI.dom
2136 * The `Node` argument to find the closest parent for.
2138 * @param {string} [selector]
2139 * The query selector expression to test against each parent.
2141 * @returns {Node|null}
2142 * Returns the closest parent node matching the selector or
2143 * `null` when the node argument is no valid DOM `Node` or the
2144 * selector didn't match any parent.
2146 parent: function(node
, selector
) {
2147 if (this.elem(node
) && node
.closest
)
2148 return node
.closest(selector
);
2150 while (this.elem(node
))
2151 if (this.matches(node
, selector
))
2154 node
= node
.parentNode
;
2160 * Appends the given children data to the given node.
2163 * @memberof LuCI.dom
2165 * The `Node` argument to append the children to.
2167 * @param {*} [children]
2168 * The childrens to append to the given node.
2170 * When `children` is an array, then each item of the array
2171 * will be either appended as child element or text node,
2172 * depending on whether the item is a DOM `Node` instance or
2173 * some other non-`null` value. Non-`Node`, non-`null` values
2174 * will be converted to strings first before being passed as
2175 * argument to `createTextNode()`.
2177 * When `children` is a function, it will be invoked with
2178 * the passed `node` argument as sole parameter and the `append`
2179 * function will be invoked again, with the given `node` argument
2180 * as first and the return value of the `children` function as
2183 * When `children` is is a DOM `Node` instance, it will be
2184 * appended to the given `node`.
2186 * When `children` is any other non-`null` value, it will be
2187 * converted to a string and appened to the `innerHTML` property
2188 * of the given `node`.
2190 * @returns {Node|null}
2191 * Returns the last children `Node` appended to the node or `null`
2192 * if either the `node` argument was no valid DOM `node` or if the
2193 * `children` was `null` or didn't result in further DOM nodes.
2195 append: function(node
, children
) {
2196 if (!this.elem(node
))
2199 if (Array
.isArray(children
)) {
2200 for (var i
= 0; i
< children
.length
; i
++)
2201 if (this.elem(children
[i
]))
2202 node
.appendChild(children
[i
]);
2203 else if (children
!== null && children
!== undefined)
2204 node
.appendChild(document
.createTextNode('' + children
[i
]));
2206 return node
.lastChild
;
2208 else if (typeof(children
) === 'function') {
2209 return this.append(node
, children(node
));
2211 else if (this.elem(children
)) {
2212 return node
.appendChild(children
);
2214 else if (children
!== null && children
!== undefined) {
2215 node
.innerHTML
= '' + children
;
2216 return node
.lastChild
;
2223 * Replaces the content of the given node with the given children.
2225 * This function first removes any children of the given DOM
2226 * `Node` and then adds the given given children following the
2227 * rules outlined below.
2230 * @memberof LuCI.dom
2232 * The `Node` argument to replace the children of.
2234 * @param {*} [children]
2235 * The childrens to replace into the given node.
2237 * When `children` is an array, then each item of the array
2238 * will be either appended as child element or text node,
2239 * depending on whether the item is a DOM `Node` instance or
2240 * some other non-`null` value. Non-`Node`, non-`null` values
2241 * will be converted to strings first before being passed as
2242 * argument to `createTextNode()`.
2244 * When `children` is a function, it will be invoked with
2245 * the passed `node` argument as sole parameter and the `append`
2246 * function will be invoked again, with the given `node` argument
2247 * as first and the return value of the `children` function as
2250 * When `children` is is a DOM `Node` instance, it will be
2251 * appended to the given `node`.
2253 * When `children` is any other non-`null` value, it will be
2254 * converted to a string and appened to the `innerHTML` property
2255 * of the given `node`.
2257 * @returns {Node|null}
2258 * Returns the last children `Node` appended to the node or `null`
2259 * if either the `node` argument was no valid DOM `node` or if the
2260 * `children` was `null` or didn't result in further DOM nodes.
2262 content: function(node
, children
) {
2263 if (!this.elem(node
))
2266 var dataNodes
= node
.querySelectorAll('[data-idref]');
2268 for (var i
= 0; i
< dataNodes
.length
; i
++)
2269 delete this.registry
[dataNodes
[i
].getAttribute('data-idref')];
2271 while (node
.firstChild
)
2272 node
.removeChild(node
.firstChild
);
2274 return this.append(node
, children
);
2278 * Sets attributes or registers event listeners on element nodes.
2281 * @memberof LuCI.dom
2283 * The `Node` argument to set the attributes or add the event
2284 * listeners for. When the given `node` value is not a valid
2285 * DOM `Node`, the function returns and does nothing.
2287 * @param {string|Object<string, *>} key
2288 * Specifies either the attribute or event handler name to use,
2289 * or an object containing multiple key, value pairs which are
2290 * each added to the node as either attribute or event handler,
2291 * depending on the respective value.
2294 * Specifies the attribute value or event handler function to add.
2295 * If the `key` parameter is an `Object`, this parameter will be
2298 * When `val` is of type function, it will be registered as event
2299 * handler on the given `node` with the `key` parameter being the
2302 * When `val` is of type object, it will be serialized as JSON and
2303 * added as attribute to the given `node`, using the given `key`
2304 * as attribute name.
2306 * When `val` is of any other type, it will be added as attribute
2307 * to the given `node` as-is, with the underlying `setAttribute()`
2308 * call implicitely turning it into a string.
2310 attr: function(node
, key
, val
) {
2311 if (!this.elem(node
))
2316 if (typeof(key
) === 'object' && key
!== null)
2318 else if (typeof(key
) === 'string')
2319 attr
= {}, attr
[key
] = val
;
2322 if (!attr
.hasOwnProperty(key
) || attr
[key
] == null)
2325 switch (typeof(attr
[key
])) {
2327 node
.addEventListener(key
, attr
[key
]);
2331 node
.setAttribute(key
, JSON
.stringify(attr
[key
]));
2335 node
.setAttribute(key
, attr
[key
]);
2341 * Creates a new DOM `Node` from the given `html`, `attr` and
2342 * `data` parameters.
2344 * This function has multiple signatures, it can be either invoked
2345 * in the form `create(html[, attr[, data]])` or in the form
2346 * `create(html[, data])`. The used variant is determined from the
2347 * type of the second argument.
2350 * @memberof LuCI.dom
2352 * Describes the node to create.
2354 * When the value of `html` is of type array, a `DocumentFragment`
2355 * node is created and each item of the array is first converted
2356 * to a DOM `Node` by passing it through `create()` and then added
2357 * as child to the fragment.
2359 * When the value of `html` is a DOM `Node` instance, no new
2360 * element will be created but the node will be used as-is.
2362 * When the value of `html` is a string starting with `<`, it will
2363 * be passed to `dom.parse()` and the resulting value is used.
2365 * When the value of `html` is any other string, it will be passed
2366 * to `document.createElement()` for creating a new DOM `Node` of
2369 * @param {Object<string, *>} [attr]
2370 * Specifies an Object of key, value pairs to set as attributes
2371 * or event handlers on the created node. Refer to
2372 * {@link LuCI.dom#attr dom.attr()} for details.
2375 * Specifies children to append to the newly created element.
2376 * Refer to {@link LuCI.dom#append dom.append()} for details.
2378 * @throws {InvalidCharacterError}
2379 * Throws an `InvalidCharacterError` when the given `html`
2380 * argument contained malformed markup (such as not escaped
2381 * `&` characters in XHTML mode) or when the given node name
2382 * in `html` contains characters which are not legal in DOM
2383 * element names, such as spaces.
2386 * Returns the newly created `Node`.
2388 create: function() {
2389 var html
= arguments
[0],
2390 attr
= arguments
[1],
2391 data
= arguments
[2],
2394 if (!(attr
instanceof Object
) || Array
.isArray(attr
))
2395 data
= attr
, attr
= null;
2397 if (Array
.isArray(html
)) {
2398 elem
= document
.createDocumentFragment();
2399 for (var i
= 0; i
< html
.length
; i
++)
2400 elem
.appendChild(this.create(html
[i
]));
2402 else if (this.elem(html
)) {
2405 else if (html
.charCodeAt(0) === 60) {
2406 elem
= this.parse(html
);
2409 elem
= document
.createElement(html
);
2415 this.attr(elem
, attr
);
2416 this.append(elem
, data
);
2424 * Attaches or detaches arbitrary data to and from a DOM `Node`.
2426 * This function is useful to attach non-string values or runtime
2427 * data that is not serializable to DOM nodes. To decouple data
2428 * from the DOM, values are not added directly to nodes, but
2429 * inserted into a registry instead which is then referenced by a
2430 * string key stored as `data-idref` attribute in the node.
2432 * This function has multiple signatures and is sensitive to the
2433 * number of arguments passed to it.
2435 * - `dom.data(node)` -
2436 * Fetches all data associated with the given node.
2437 * - `dom.data(node, key)` -
2438 * Fetches a specific key associated with the given node.
2439 * - `dom.data(node, key, val)` -
2440 * Sets a specific key to the given value associated with the
2442 * - `dom.data(node, null)` -
2443 * Clears any data associated with the node.
2444 * - `dom.data(node, key, null)` -
2445 * Clears the given key associated with the node.
2448 * @memberof LuCI.dom
2449 * @param {Node} node
2450 * The DOM `Node` instance to set or retrieve the data for.
2452 * @param {string|null} [key]
2453 * This is either a string specifying the key to retrieve, or
2454 * `null` to unset the entire node data.
2456 * @param {*|null} [val]
2457 * This is either a non-`null` value to set for a given key or
2458 * `null` to remove the given `key` from the specified node.
2461 * Returns the get or set value, or `null` when no value could
2464 data: function(node
, key
, val
) {
2465 var id
= node
.getAttribute('data-idref');
2467 /* clear all data */
2468 if (arguments
.length
> 1 && key
== null) {
2470 node
.removeAttribute('data-idref');
2471 val
= this.registry
[id
]
2472 delete this.registry
[id
];
2480 else if (arguments
.length
> 2 && key
!= null && val
== null) {
2482 val
= this.registry
[id
][key
];
2483 delete this.registry
[id
][key
];
2491 else if (arguments
.length
> 2 && key
!= null && val
!= null) {
2493 do { id
= Math
.floor(Math
.random() * 0xffffffff).toString(16) }
2494 while (this.registry
.hasOwnProperty(id
));
2496 node
.setAttribute('data-idref', id
);
2497 this.registry
[id
] = {};
2500 return (this.registry
[id
][key
] = val
);
2504 else if (arguments
.length
== 1) {
2506 return this.registry
[id
];
2512 else if (arguments
.length
== 2) {
2514 return this.registry
[id
][key
];
2521 * Binds the given class instance ot the specified DOM `Node`.
2523 * This function uses the `dom.data()` facility to attach the
2524 * passed instance of a Class to a node. This is needed for
2525 * complex widget elements or similar where the corresponding
2526 * class instance responsible for the element must be retrieved
2527 * from DOM nodes obtained by `querySelector()` or similar means.
2530 * @memberof LuCI.dom
2531 * @param {Node} node
2532 * The DOM `Node` instance to bind the class to.
2534 * @param {Class} inst
2535 * The Class instance to bind to the node.
2537 * @throws {TypeError}
2538 * Throws a `TypeError` when the given instance argument isn't
2539 * a valid Class instance.
2542 * Returns the bound class instance.
2544 bindClassInstance: function(node
, inst
) {
2545 if (!(inst
instanceof Class
))
2546 L
.error('TypeError', 'Argument must be a class instance');
2548 return this.data(node
, '_class', inst
);
2552 * Finds a bound class instance on the given node itself or the
2553 * first bound instance on its closest parent node.
2556 * @memberof LuCI.dom
2557 * @param {Node} node
2558 * The DOM `Node` instance to start from.
2560 * @returns {Class|null}
2561 * Returns the founds class instance if any or `null` if no bound
2562 * class could be found on the node itself or any of its parents.
2564 findClassInstance: function(node
) {
2568 inst
= this.data(node
, '_class');
2569 node
= node
.parentNode
;
2571 while (!(inst
instanceof Class
) && node
!= null);
2577 * Finds a bound class instance on the given node itself or the
2578 * first bound instance on its closest parent node and invokes
2579 * the specified method name on the found class instance.
2582 * @memberof LuCI.dom
2583 * @param {Node} node
2584 * The DOM `Node` instance to start from.
2586 * @param {string} method
2587 * The name of the method to invoke on the found class instance.
2589 * @param {...*} params
2590 * Additional arguments to pass to the invoked method as-is.
2593 * Returns the return value of the invoked method if a class
2594 * instance and method has been found. Returns `null` if either
2595 * no bound class instance could be found, or if the found
2596 * instance didn't have the requested `method`.
2598 callClassMethod: function(node
, method
/*, ... */) {
2599 var inst
= this.findClassInstance(node
);
2601 if (inst
== null || typeof(inst
[method
]) != 'function')
2604 return inst
[method
].apply(inst
, inst
.varargs(arguments
, 2));
2608 * The ignore callback function is invoked by `isEmpty()` for each
2609 * child node to decide whether to ignore a child node or not.
2611 * When this function returns `false`, the node passed to it is
2612 * ignored, else not.
2614 * @callback LuCI.dom~ignoreCallbackFn
2615 * @param {Node} node
2616 * The child node to test.
2618 * @returns {boolean}
2619 * Boolean indicating whether to ignore the node or not.
2623 * Tests whether a given DOM `Node` instance is empty or appears
2626 * Any element child nodes which have the CSS class `hidden` set
2627 * or for which the optionally passed `ignoreFn` callback function
2628 * returns `false` are ignored.
2631 * @memberof LuCI.dom
2632 * @param {Node} node
2633 * The DOM `Node` instance to test.
2635 * @param {LuCI.dom~ignoreCallbackFn} [ignoreFn]
2636 * Specifies an optional function which is invoked for each child
2637 * node to decide whether the child node should be ignored or not.
2639 * @returns {boolean}
2640 * Returns `true` if the node does not have any children or if
2641 * any children node either has a `hidden` CSS class or a `false`
2642 * result when testing it using the given `ignoreFn`.
2644 isEmpty: function(node
, ignoreFn
) {
2645 for (var child
= node
.firstElementChild
; child
!= null; child
= child
.nextElementSibling
)
2646 if (!child
.classList
.contains('hidden') && (!ignoreFn
|| !ignoreFn(child
)))
2663 * The `view` class forms the basis of views and provides a standard
2664 * set of methods to inherit from.
2666 view
: Class
.extend(/* @lends LuCI.view.prototype */ {
2667 __name__
: 'LuCI.View',
2669 __init__: function() {
2670 var vp
= document
.getElementById('view');
2672 L
.dom
.content(vp
, E('div', { 'class': 'spinning' }, _('Loading view…')));
2674 return Promise
.resolve(this.load())
2675 .then(L
.bind(this.render
, this))
2676 .then(L
.bind(function(nodes
) {
2677 var vp
= document
.getElementById('view');
2679 L
.dom
.content(vp
, nodes
);
2680 L
.dom
.append(vp
, this.addFooter());
2681 }, this)).catch(L
.error
);
2685 * The load function is invoked before the view is rendered.
2687 * The invocation of this function is wrapped by
2688 * `Promise.resolve()` so it may return Promises if needed.
2690 * The return value of the function (or the resolved values
2691 * of the promise returned by it) will be passed as first
2692 * argument to `render()`.
2694 * This function is supposed to be overwritten by subclasses,
2695 * the default implementation does nothing.
2699 * @memberof LuCI.view
2701 * @returns {*|Promise<*>}
2702 * May return any value or a Promise resolving to any value.
2704 load: function() {},
2707 * The render function is invoked after the
2708 * {@link LuCI.view#load load()} function and responsible
2709 * for setting up the view contents. It must return a DOM
2710 * `Node` or `DocumentFragment` holding the contents to
2711 * insert into the view area.
2713 * The invocation of this function is wrapped by
2714 * `Promise.resolve()` so it may return Promises if needed.
2716 * The return value of the function (or the resolved values
2717 * of the promise returned by it) will be inserted into the
2718 * main content area using
2719 * {@link LuCI.dom#append dom.append()}.
2721 * This function is supposed to be overwritten by subclasses,
2722 * the default implementation does nothing.
2726 * @memberof LuCI.view
2727 * @param {*|null} load_results
2728 * This function will receive the return value of the
2729 * {@link LuCI.view#load view.load()} function as first
2732 * @returns {Node|Promise<Node>}
2733 * Should return a DOM `Node` value or a `Promise` resolving
2734 * to a `Node` value.
2736 render: function() {},
2739 * The handleSave function is invoked when the user clicks
2740 * the `Save` button in the page action footer.
2742 * The default implementation should be sufficient for most
2743 * views using {@link form#Map form.Map()} based forms - it
2744 * will iterate all forms present in the view and invoke
2745 * the {@link form#Map#save Map.save()} method on each form.
2747 * Views not using `Map` instances or requiring other special
2748 * logic should overwrite `handleSave()` with a custom
2751 * To disable the `Save` page footer button, views extending
2752 * this base class should overwrite the `handleSave` function
2755 * The invocation of this function is wrapped by
2756 * `Promise.resolve()` so it may return Promises if needed.
2759 * @memberof LuCI.view
2761 * The DOM event that triggered the function.
2763 * @returns {*|Promise<*>}
2764 * Any return values of this function are discarded, but
2765 * passed through `Promise.resolve()` to ensure that any
2766 * returned promise runs to completion before the button
2769 handleSave: function(ev
) {
2772 document
.getElementById('maincontent')
2773 .querySelectorAll('.cbi-map').forEach(function(map
) {
2774 tasks
.push(L
.dom
.callClassMethod(map
, 'save'));
2777 return Promise
.all(tasks
);
2781 * The handleSaveApply function is invoked when the user clicks
2782 * the `Save & Apply` button in the page action footer.
2784 * The default implementation should be sufficient for most
2785 * views using {@link form#Map form.Map()} based forms - it
2787 * {@link LuCI.view.handleSave view.handleSave()} and then
2788 * call {@link ui#changes#apply ui.changes.apply()} to start the
2789 * modal config apply and page reload flow.
2791 * Views not using `Map` instances or requiring other special
2792 * logic should overwrite `handleSaveApply()` with a custom
2795 * To disable the `Save & Apply` page footer button, views
2796 * extending this base class should overwrite the
2797 * `handleSaveApply` function with `null`.
2799 * The invocation of this function is wrapped by
2800 * `Promise.resolve()` so it may return Promises if needed.
2803 * @memberof LuCI.view
2805 * The DOM event that triggered the function.
2807 * @returns {*|Promise<*>}
2808 * Any return values of this function are discarded, but
2809 * passed through `Promise.resolve()` to ensure that any
2810 * returned promise runs to completion before the button
2813 handleSaveApply: function(ev
) {
2814 return this.handleSave(ev
).then(function() {
2815 L
.ui
.changes
.apply(true);
2820 * The handleReset function is invoked when the user clicks
2821 * the `Reset` button in the page action footer.
2823 * The default implementation should be sufficient for most
2824 * views using {@link form#Map form.Map()} based forms - it
2825 * will iterate all forms present in the view and invoke
2826 * the {@link form#Map#save Map.reset()} method on each form.
2828 * Views not using `Map` instances or requiring other special
2829 * logic should overwrite `handleReset()` with a custom
2832 * To disable the `Reset` page footer button, views extending
2833 * this base class should overwrite the `handleReset` function
2836 * The invocation of this function is wrapped by
2837 * `Promise.resolve()` so it may return Promises if needed.
2840 * @memberof LuCI.view
2842 * The DOM event that triggered the function.
2844 * @returns {*|Promise<*>}
2845 * Any return values of this function are discarded, but
2846 * passed through `Promise.resolve()` to ensure that any
2847 * returned promise runs to completion before the button
2850 handleReset: function(ev
) {
2853 document
.getElementById('maincontent')
2854 .querySelectorAll('.cbi-map').forEach(function(map
) {
2855 tasks
.push(L
.dom
.callClassMethod(map
, 'reset'));
2858 return Promise
.all(tasks
);
2862 * Renders a standard page action footer if any of the
2863 * `handleSave()`, `handleSaveApply()` or `handleReset()`
2864 * functions are defined.
2866 * The default implementation should be sufficient for most
2867 * views - it will render a standard page footer with action
2868 * buttons labeled `Save`, `Save & Apply` and `Reset`
2869 * triggering the `handleSave()`, `handleSaveApply()` and
2870 * `handleReset()` functions respectively.
2872 * When any of these `handle*()` functions is overwritten
2873 * with `null` by a view extending this class, the
2874 * corresponding button will not be rendered.
2877 * @memberof LuCI.view
2878 * @returns {DocumentFragment}
2879 * Returns a `DocumentFragment` containing the footer bar
2880 * with buttons for each corresponding `handle*()` action
2881 * or an empty `DocumentFragment` if all three `handle*()`
2882 * methods are overwritten with `null`.
2884 addFooter: function() {
2887 if (this.handleSaveApply
|| this.handleSave
|| this.handleReset
) {
2888 footer
.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
2889 this.handleSaveApply
? E('button', {
2890 'class': 'cbi-button cbi-button-apply',
2891 'click': L
.ui
.createHandlerFn(this, 'handleSaveApply')
2892 }, [ _('Save & Apply') ]) : '', ' ',
2893 this.handleSave
? E('button', {
2894 'class': 'cbi-button cbi-button-save',
2895 'click': L
.ui
.createHandlerFn(this, 'handleSave')
2896 }, [ _('Save') ]) : '', ' ',
2897 this.handleReset
? E('button', {
2898 'class': 'cbi-button cbi-button-reset',
2899 'click': L
.ui
.createHandlerFn(this, 'handleReset')
2900 }, [ _('Reset') ]) : ''
2915 * The `LuCI.XHR` class is a legacy compatibility shim for the
2916 * functionality formerly provided by `xhr.js`. It is registered as global
2917 * `window.XHR` symbol for compatibility with legacy code.
2919 * New code should use {@link LuCI.Request} instead to implement HTTP
2922 var XHR
= Class
.extend(/** @lends LuCI.XHR.prototype */ {
2923 __name__
: 'LuCI.XHR',
2924 __init__: function() {
2925 if (window
.console
&& console
.debug
)
2926 console
.debug('Direct use XHR() is deprecated, please use L.Request instead');
2929 _response: function(cb
, res
, json
, duration
) {
2931 cb(res
, json
, duration
);
2936 * This function is a legacy wrapper around
2937 * {@link LuCI#get LuCI.get()}.
2941 * @memberof LuCI.XHR
2943 * @param {string} url
2944 * The URL to request
2946 * @param {Object} [data]
2947 * Additional query string data
2949 * @param {LuCI.requestCallbackFn} [callback]
2950 * Callback function to invoke on completion
2952 * @param {number} [timeout]
2953 * Request timeout to use
2955 * @return {Promise<null>}
2957 get: function(url
, data
, callback
, timeout
) {
2959 L
.get(url
, data
, this._response
.bind(this, callback
), timeout
);
2963 * This function is a legacy wrapper around
2964 * {@link LuCI#post LuCI.post()}.
2968 * @memberof LuCI.XHR
2970 * @param {string} url
2971 * The URL to request
2973 * @param {Object} [data]
2974 * Additional data to append to the request body.
2976 * @param {LuCI.requestCallbackFn} [callback]
2977 * Callback function to invoke on completion
2979 * @param {number} [timeout]
2980 * Request timeout to use
2982 * @return {Promise<null>}
2984 post: function(url
, data
, callback
, timeout
) {
2986 L
.post(url
, data
, this._response
.bind(this, callback
), timeout
);
2990 * Cancels a running request.
2992 * This function does not actually cancel the underlying
2993 * `XMLHTTPRequest` request but it sets a flag which prevents the
2994 * invocation of the callback function when the request eventually
2995 * finishes or timed out.
2999 * @memberof LuCI.XHR
3001 cancel: function() { delete this.active
},
3004 * Checks the running state of the request.
3008 * @memberof LuCI.XHR
3010 * @returns {boolean}
3011 * Returns `true` if the request is still running or `false` if it
3012 * already completed.
3014 busy: function() { return (this.active
=== true) },
3017 * Ignored for backwards compatibility.
3019 * This function does nothing.
3023 * @memberof LuCI.XHR
3025 abort: function() {},
3028 * Existing for backwards compatibility.
3030 * This function simply throws an `InternalError` when invoked.
3034 * @memberof LuCI.XHR
3036 * @throws {InternalError}
3037 * Throws an `InternalError` with the message `Not implemented`
3040 send_form: function() { L
.error('InternalError', 'Not implemented') },
3043 XHR
.get = function() { return window
.L
.get.apply(window
.L
, arguments
) };
3044 XHR
.post = function() { return window
.L
.post
.apply(window
.L
, arguments
) };
3045 XHR
.poll = function() { return window
.L
.poll
.apply(window
.L
, arguments
) };
3046 XHR
.stop
= Request
.poll
.remove
.bind(Request
.poll
);
3047 XHR
.halt
= Request
.poll
.stop
.bind(Request
.poll
);
3048 XHR
.run
= Request
.poll
.start
.bind(Request
.poll
);
3049 XHR
.running
= Request
.poll
.active
.bind(Request
.poll
);
3053 })(window
, document
);