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+/);
1856 * Returns a promise resolving with either the given value or or with
1857 * the given default in case the input value is a rejecting promise.
1863 * The value to resolve the promise with.
1865 * @param {*} defvalue
1866 * The default value to resolve the promise with in case the given
1867 * input value is a rejecting promise.
1869 * @returns {Promise<*>}
1870 * Returns a new promise resolving either to the given input value or
1871 * to the given default value on error.
1873 resolveDefault: function(value
, defvalue
) {
1874 return Promise
.resolve(value
).catch(function() { return defvalue
});
1878 * The request callback function is invoked whenever an HTTP
1879 * reply to a request made using the `L.get()`, `L.post()` or
1880 * `L.poll()` function is timed out or received successfully.
1885 * @callback LuCI.requestCallbackFn
1886 * @param {XMLHTTPRequest} xhr
1887 * The XMLHTTPRequest instance used to make the request.
1890 * The response JSON if the response could be parsed as such,
1893 * @param {number} duration
1894 * The total duration of the request in milliseconds.
1898 * Issues a GET request to the given url and invokes the specified
1899 * callback function. The function is a wrapper around
1900 * {@link LuCI.Request#request Request.request()}.
1906 * @param {string} url
1907 * The URL to request.
1909 * @param {Object<string, string>} [args]
1910 * Additional query string arguments to append to the URL.
1912 * @param {LuCI.requestCallbackFn} cb
1913 * The callback function to invoke when the request finishes.
1915 * @return {Promise<null>}
1916 * Returns a promise resolving to `null` when concluded.
1918 get: function(url
, args
, cb
) {
1919 return this.poll(null, url
, args
, cb
, false);
1923 * Issues a POST request to the given url and invokes the specified
1924 * callback function. The function is a wrapper around
1925 * {@link LuCI.Request#request Request.request()}. The request is
1926 * sent using `application/x-www-form-urlencoded` encoding and will
1927 * contain a field `token` with the current value of `LuCI.env.token`
1934 * @param {string} url
1935 * The URL to request.
1937 * @param {Object<string, string>} [args]
1938 * Additional post arguments to append to the request body.
1940 * @param {LuCI.requestCallbackFn} cb
1941 * The callback function to invoke when the request finishes.
1943 * @return {Promise<null>}
1944 * Returns a promise resolving to `null` when concluded.
1946 post: function(url
, args
, cb
) {
1947 return this.poll(null, url
, args
, cb
, true);
1951 * Register a polling HTTP request that invokes the specified
1952 * callback function. The function is a wrapper around
1953 * {@link LuCI.Request.poll#add Request.poll.add()}.
1959 * @param {number} interval
1960 * The poll interval to use. If set to a value less than or equal
1961 * to `0`, it will default to the global poll interval configured
1962 * in `LuCI.env.pollinterval`.
1964 * @param {string} url
1965 * The URL to request.
1967 * @param {Object<string, string>} [args]
1968 * Specifies additional arguments for the request. For GET requests,
1969 * the arguments are appended to the URL as query string, for POST
1970 * requests, they'll be added to the request body.
1972 * @param {LuCI.requestCallbackFn} cb
1973 * The callback function to invoke whenever a request finishes.
1975 * @param {boolean} [post=false]
1976 * When set to `false` or not specified, poll requests will be made
1977 * using the GET method. When set to `true`, POST requests will be
1978 * issued. In case of POST requests, the request body will contain
1979 * an argument `token` with the current value of `LuCI.env.token` by
1980 * default, regardless of the parameters specified with `args`.
1982 * @return {function}
1983 * Returns the internally created function that has been passed to
1984 * {@link LuCI.Request.poll#add Request.poll.add()}. This value can
1985 * be passed to {@link LuCI.Poll.remove Poll.remove()} to remove the
1988 poll: function(interval
, url
, args
, cb
, post
) {
1989 if (interval
!== null && interval
<= 0)
1990 interval
= this.env
.pollinterval
;
1992 var data
= post
? { token
: this.env
.token
} : null,
1993 method
= post
? 'POST' : 'GET';
1995 if (!/^(?:\/|\S+:\/\/)/.test(url
))
1996 url
= this.url(url
);
1999 data
= Object
.assign(data
|| {}, args
);
2001 if (interval
!== null)
2002 return Request
.poll
.add(interval
, url
, { method
: method
, query
: data
}, cb
);
2004 return Request
.request(url
, { method
: method
, query
: data
})
2005 .then(function(res
) {
2007 if (/^application\/json\b/.test(res
.headers
.get('Content-Type')))
2008 try { json
= res
.json() } catch(e
) {}
2009 cb(res
.xhr
, json
, res
.duration
);
2014 * Deprecated wrapper around {@link LuCI.Poll.remove Poll.remove()}.
2020 * @param {function} entry
2021 * The polling function to remove.
2024 * Returns `true` when the function has been removed or `false` if
2025 * it could not be found.
2027 stop: function(entry
) { return Poll
.remove(entry
) },
2030 * Deprecated wrapper around {@link LuCI.Poll.stop Poll.stop()}.
2037 * Returns `true` when the polling loop has been stopped or `false`
2038 * when it didn't run to begin with.
2040 halt: function() { return Poll
.stop() },
2043 * Deprecated wrapper around {@link LuCI.Poll.start Poll.start()}.
2050 * Returns `true` when the polling loop has been started or `false`
2051 * when it was already running.
2053 run: function() { return Poll
.start() },
2062 * The `dom` class provides convenience method for creating and
2063 * manipulating DOM elements.
2065 dom
: Class
.singleton(/* @lends LuCI.dom.prototype */ {
2066 __name__
: 'LuCI.DOM',
2069 * Tests whether the given argument is a valid DOM `Node`.
2072 * @memberof LuCI.dom
2074 * The value to test.
2076 * @returns {boolean}
2077 * Returns `true` if the value is a DOM `Node`, else `false`.
2080 return (e
!= null && typeof(e
) == 'object' && 'nodeType' in e
);
2084 * Parses a given string as HTML and returns the first child node.
2087 * @memberof LuCI.dom
2089 * A string containing an HTML fragment to parse. Note that only
2090 * the first result of the resulting structure is returned, so an
2091 * input value of `<div>foo</div> <div>bar</div>` will only return
2092 * the first `div` element node.
2095 * Returns the first DOM `Node` extracted from the HTML fragment or
2096 * `null` on parsing failures or if no element could be found.
2098 parse: function(s
) {
2102 domParser
= domParser
|| new DOMParser();
2103 elem
= domParser
.parseFromString(s
, 'text/html').body
.firstChild
;
2109 dummyElem
= dummyElem
|| document
.createElement('div');
2110 dummyElem
.innerHTML
= s
;
2111 elem
= dummyElem
.firstChild
;
2116 return elem
|| null;
2120 * Tests whether a given `Node` matches the given query selector.
2122 * This function is a convenience wrapper around the standard
2123 * `Node.matches("selector")` function with the added benefit that
2124 * the `node` argument may be a non-`Node` value, in which case
2125 * this function simply returns `false`.
2128 * @memberof LuCI.dom
2130 * The `Node` argument to test the selector against.
2132 * @param {string} [selector]
2133 * The query selector expression to test against the given node.
2135 * @returns {boolean}
2136 * Returns `true` if the given node matches the specified selector
2137 * or `false` when the node argument is no valid DOM `Node` or the
2138 * selector didn't match.
2140 matches: function(node
, selector
) {
2141 var m
= this.elem(node
) ? node
.matches
|| node
.msMatchesSelector
: null;
2142 return m
? m
.call(node
, selector
) : false;
2146 * Returns the closest parent node that matches the given query
2147 * selector expression.
2149 * This function is a convenience wrapper around the standard
2150 * `Node.closest("selector")` function with the added benefit that
2151 * the `node` argument may be a non-`Node` value, in which case
2152 * this function simply returns `null`.
2155 * @memberof LuCI.dom
2157 * The `Node` argument to find the closest parent for.
2159 * @param {string} [selector]
2160 * The query selector expression to test against each parent.
2162 * @returns {Node|null}
2163 * Returns the closest parent node matching the selector or
2164 * `null` when the node argument is no valid DOM `Node` or the
2165 * selector didn't match any parent.
2167 parent: function(node
, selector
) {
2168 if (this.elem(node
) && node
.closest
)
2169 return node
.closest(selector
);
2171 while (this.elem(node
))
2172 if (this.matches(node
, selector
))
2175 node
= node
.parentNode
;
2181 * Appends the given children data to the given node.
2184 * @memberof LuCI.dom
2186 * The `Node` argument to append the children to.
2188 * @param {*} [children]
2189 * The childrens to append to the given node.
2191 * When `children` is an array, then each item of the array
2192 * will be either appended as child element or text node,
2193 * depending on whether the item is a DOM `Node` instance or
2194 * some other non-`null` value. Non-`Node`, non-`null` values
2195 * will be converted to strings first before being passed as
2196 * argument to `createTextNode()`.
2198 * When `children` is a function, it will be invoked with
2199 * the passed `node` argument as sole parameter and the `append`
2200 * function will be invoked again, with the given `node` argument
2201 * as first and the return value of the `children` function as
2204 * When `children` is is a DOM `Node` instance, it will be
2205 * appended to the given `node`.
2207 * When `children` is any other non-`null` value, it will be
2208 * converted to a string and appened to the `innerHTML` property
2209 * of the given `node`.
2211 * @returns {Node|null}
2212 * Returns the last children `Node` appended to the node or `null`
2213 * if either the `node` argument was no valid DOM `node` or if the
2214 * `children` was `null` or didn't result in further DOM nodes.
2216 append: function(node
, children
) {
2217 if (!this.elem(node
))
2220 if (Array
.isArray(children
)) {
2221 for (var i
= 0; i
< children
.length
; i
++)
2222 if (this.elem(children
[i
]))
2223 node
.appendChild(children
[i
]);
2224 else if (children
!== null && children
!== undefined)
2225 node
.appendChild(document
.createTextNode('' + children
[i
]));
2227 return node
.lastChild
;
2229 else if (typeof(children
) === 'function') {
2230 return this.append(node
, children(node
));
2232 else if (this.elem(children
)) {
2233 return node
.appendChild(children
);
2235 else if (children
!== null && children
!== undefined) {
2236 node
.innerHTML
= '' + children
;
2237 return node
.lastChild
;
2244 * Replaces the content of the given node with the given children.
2246 * This function first removes any children of the given DOM
2247 * `Node` and then adds the given given children following the
2248 * rules outlined below.
2251 * @memberof LuCI.dom
2253 * The `Node` argument to replace the children of.
2255 * @param {*} [children]
2256 * The childrens to replace into the given node.
2258 * When `children` is an array, then each item of the array
2259 * will be either appended as child element or text node,
2260 * depending on whether the item is a DOM `Node` instance or
2261 * some other non-`null` value. Non-`Node`, non-`null` values
2262 * will be converted to strings first before being passed as
2263 * argument to `createTextNode()`.
2265 * When `children` is a function, it will be invoked with
2266 * the passed `node` argument as sole parameter and the `append`
2267 * function will be invoked again, with the given `node` argument
2268 * as first and the return value of the `children` function as
2271 * When `children` is is a DOM `Node` instance, it will be
2272 * appended to the given `node`.
2274 * When `children` is any other non-`null` value, it will be
2275 * converted to a string and appened to the `innerHTML` property
2276 * of the given `node`.
2278 * @returns {Node|null}
2279 * Returns the last children `Node` appended to the node or `null`
2280 * if either the `node` argument was no valid DOM `node` or if the
2281 * `children` was `null` or didn't result in further DOM nodes.
2283 content: function(node
, children
) {
2284 if (!this.elem(node
))
2287 var dataNodes
= node
.querySelectorAll('[data-idref]');
2289 for (var i
= 0; i
< dataNodes
.length
; i
++)
2290 delete this.registry
[dataNodes
[i
].getAttribute('data-idref')];
2292 while (node
.firstChild
)
2293 node
.removeChild(node
.firstChild
);
2295 return this.append(node
, children
);
2299 * Sets attributes or registers event listeners on element nodes.
2302 * @memberof LuCI.dom
2304 * The `Node` argument to set the attributes or add the event
2305 * listeners for. When the given `node` value is not a valid
2306 * DOM `Node`, the function returns and does nothing.
2308 * @param {string|Object<string, *>} key
2309 * Specifies either the attribute or event handler name to use,
2310 * or an object containing multiple key, value pairs which are
2311 * each added to the node as either attribute or event handler,
2312 * depending on the respective value.
2315 * Specifies the attribute value or event handler function to add.
2316 * If the `key` parameter is an `Object`, this parameter will be
2319 * When `val` is of type function, it will be registered as event
2320 * handler on the given `node` with the `key` parameter being the
2323 * When `val` is of type object, it will be serialized as JSON and
2324 * added as attribute to the given `node`, using the given `key`
2325 * as attribute name.
2327 * When `val` is of any other type, it will be added as attribute
2328 * to the given `node` as-is, with the underlying `setAttribute()`
2329 * call implicitely turning it into a string.
2331 attr: function(node
, key
, val
) {
2332 if (!this.elem(node
))
2337 if (typeof(key
) === 'object' && key
!== null)
2339 else if (typeof(key
) === 'string')
2340 attr
= {}, attr
[key
] = val
;
2343 if (!attr
.hasOwnProperty(key
) || attr
[key
] == null)
2346 switch (typeof(attr
[key
])) {
2348 node
.addEventListener(key
, attr
[key
]);
2352 node
.setAttribute(key
, JSON
.stringify(attr
[key
]));
2356 node
.setAttribute(key
, attr
[key
]);
2362 * Creates a new DOM `Node` from the given `html`, `attr` and
2363 * `data` parameters.
2365 * This function has multiple signatures, it can be either invoked
2366 * in the form `create(html[, attr[, data]])` or in the form
2367 * `create(html[, data])`. The used variant is determined from the
2368 * type of the second argument.
2371 * @memberof LuCI.dom
2373 * Describes the node to create.
2375 * When the value of `html` is of type array, a `DocumentFragment`
2376 * node is created and each item of the array is first converted
2377 * to a DOM `Node` by passing it through `create()` and then added
2378 * as child to the fragment.
2380 * When the value of `html` is a DOM `Node` instance, no new
2381 * element will be created but the node will be used as-is.
2383 * When the value of `html` is a string starting with `<`, it will
2384 * be passed to `dom.parse()` and the resulting value is used.
2386 * When the value of `html` is any other string, it will be passed
2387 * to `document.createElement()` for creating a new DOM `Node` of
2390 * @param {Object<string, *>} [attr]
2391 * Specifies an Object of key, value pairs to set as attributes
2392 * or event handlers on the created node. Refer to
2393 * {@link LuCI.dom#attr dom.attr()} for details.
2396 * Specifies children to append to the newly created element.
2397 * Refer to {@link LuCI.dom#append dom.append()} for details.
2399 * @throws {InvalidCharacterError}
2400 * Throws an `InvalidCharacterError` when the given `html`
2401 * argument contained malformed markup (such as not escaped
2402 * `&` characters in XHTML mode) or when the given node name
2403 * in `html` contains characters which are not legal in DOM
2404 * element names, such as spaces.
2407 * Returns the newly created `Node`.
2409 create: function() {
2410 var html
= arguments
[0],
2411 attr
= arguments
[1],
2412 data
= arguments
[2],
2415 if (!(attr
instanceof Object
) || Array
.isArray(attr
))
2416 data
= attr
, attr
= null;
2418 if (Array
.isArray(html
)) {
2419 elem
= document
.createDocumentFragment();
2420 for (var i
= 0; i
< html
.length
; i
++)
2421 elem
.appendChild(this.create(html
[i
]));
2423 else if (this.elem(html
)) {
2426 else if (html
.charCodeAt(0) === 60) {
2427 elem
= this.parse(html
);
2430 elem
= document
.createElement(html
);
2436 this.attr(elem
, attr
);
2437 this.append(elem
, data
);
2445 * Attaches or detaches arbitrary data to and from a DOM `Node`.
2447 * This function is useful to attach non-string values or runtime
2448 * data that is not serializable to DOM nodes. To decouple data
2449 * from the DOM, values are not added directly to nodes, but
2450 * inserted into a registry instead which is then referenced by a
2451 * string key stored as `data-idref` attribute in the node.
2453 * This function has multiple signatures and is sensitive to the
2454 * number of arguments passed to it.
2456 * - `dom.data(node)` -
2457 * Fetches all data associated with the given node.
2458 * - `dom.data(node, key)` -
2459 * Fetches a specific key associated with the given node.
2460 * - `dom.data(node, key, val)` -
2461 * Sets a specific key to the given value associated with the
2463 * - `dom.data(node, null)` -
2464 * Clears any data associated with the node.
2465 * - `dom.data(node, key, null)` -
2466 * Clears the given key associated with the node.
2469 * @memberof LuCI.dom
2470 * @param {Node} node
2471 * The DOM `Node` instance to set or retrieve the data for.
2473 * @param {string|null} [key]
2474 * This is either a string specifying the key to retrieve, or
2475 * `null` to unset the entire node data.
2477 * @param {*|null} [val]
2478 * This is either a non-`null` value to set for a given key or
2479 * `null` to remove the given `key` from the specified node.
2482 * Returns the get or set value, or `null` when no value could
2485 data: function(node
, key
, val
) {
2486 var id
= node
.getAttribute('data-idref');
2488 /* clear all data */
2489 if (arguments
.length
> 1 && key
== null) {
2491 node
.removeAttribute('data-idref');
2492 val
= this.registry
[id
]
2493 delete this.registry
[id
];
2501 else if (arguments
.length
> 2 && key
!= null && val
== null) {
2503 val
= this.registry
[id
][key
];
2504 delete this.registry
[id
][key
];
2512 else if (arguments
.length
> 2 && key
!= null && val
!= null) {
2514 do { id
= Math
.floor(Math
.random() * 0xffffffff).toString(16) }
2515 while (this.registry
.hasOwnProperty(id
));
2517 node
.setAttribute('data-idref', id
);
2518 this.registry
[id
] = {};
2521 return (this.registry
[id
][key
] = val
);
2525 else if (arguments
.length
== 1) {
2527 return this.registry
[id
];
2533 else if (arguments
.length
== 2) {
2535 return this.registry
[id
][key
];
2542 * Binds the given class instance ot the specified DOM `Node`.
2544 * This function uses the `dom.data()` facility to attach the
2545 * passed instance of a Class to a node. This is needed for
2546 * complex widget elements or similar where the corresponding
2547 * class instance responsible for the element must be retrieved
2548 * from DOM nodes obtained by `querySelector()` or similar means.
2551 * @memberof LuCI.dom
2552 * @param {Node} node
2553 * The DOM `Node` instance to bind the class to.
2555 * @param {Class} inst
2556 * The Class instance to bind to the node.
2558 * @throws {TypeError}
2559 * Throws a `TypeError` when the given instance argument isn't
2560 * a valid Class instance.
2563 * Returns the bound class instance.
2565 bindClassInstance: function(node
, inst
) {
2566 if (!(inst
instanceof Class
))
2567 L
.error('TypeError', 'Argument must be a class instance');
2569 return this.data(node
, '_class', inst
);
2573 * Finds a bound class instance on the given node itself or the
2574 * first bound instance on its closest parent node.
2577 * @memberof LuCI.dom
2578 * @param {Node} node
2579 * The DOM `Node` instance to start from.
2581 * @returns {Class|null}
2582 * Returns the founds class instance if any or `null` if no bound
2583 * class could be found on the node itself or any of its parents.
2585 findClassInstance: function(node
) {
2589 inst
= this.data(node
, '_class');
2590 node
= node
.parentNode
;
2592 while (!(inst
instanceof Class
) && node
!= null);
2598 * Finds a bound class instance on the given node itself or the
2599 * first bound instance on its closest parent node and invokes
2600 * the specified method name on the found class instance.
2603 * @memberof LuCI.dom
2604 * @param {Node} node
2605 * The DOM `Node` instance to start from.
2607 * @param {string} method
2608 * The name of the method to invoke on the found class instance.
2610 * @param {...*} params
2611 * Additional arguments to pass to the invoked method as-is.
2614 * Returns the return value of the invoked method if a class
2615 * instance and method has been found. Returns `null` if either
2616 * no bound class instance could be found, or if the found
2617 * instance didn't have the requested `method`.
2619 callClassMethod: function(node
, method
/*, ... */) {
2620 var inst
= this.findClassInstance(node
);
2622 if (inst
== null || typeof(inst
[method
]) != 'function')
2625 return inst
[method
].apply(inst
, inst
.varargs(arguments
, 2));
2629 * The ignore callback function is invoked by `isEmpty()` for each
2630 * child node to decide whether to ignore a child node or not.
2632 * When this function returns `false`, the node passed to it is
2633 * ignored, else not.
2635 * @callback LuCI.dom~ignoreCallbackFn
2636 * @param {Node} node
2637 * The child node to test.
2639 * @returns {boolean}
2640 * Boolean indicating whether to ignore the node or not.
2644 * Tests whether a given DOM `Node` instance is empty or appears
2647 * Any element child nodes which have the CSS class `hidden` set
2648 * or for which the optionally passed `ignoreFn` callback function
2649 * returns `false` are ignored.
2652 * @memberof LuCI.dom
2653 * @param {Node} node
2654 * The DOM `Node` instance to test.
2656 * @param {LuCI.dom~ignoreCallbackFn} [ignoreFn]
2657 * Specifies an optional function which is invoked for each child
2658 * node to decide whether the child node should be ignored or not.
2660 * @returns {boolean}
2661 * Returns `true` if the node does not have any children or if
2662 * any children node either has a `hidden` CSS class or a `false`
2663 * result when testing it using the given `ignoreFn`.
2665 isEmpty: function(node
, ignoreFn
) {
2666 for (var child
= node
.firstElementChild
; child
!= null; child
= child
.nextElementSibling
)
2667 if (!child
.classList
.contains('hidden') && (!ignoreFn
|| !ignoreFn(child
)))
2684 * The `view` class forms the basis of views and provides a standard
2685 * set of methods to inherit from.
2687 view
: Class
.extend(/* @lends LuCI.view.prototype */ {
2688 __name__
: 'LuCI.View',
2690 __init__: function() {
2691 var vp
= document
.getElementById('view');
2693 L
.dom
.content(vp
, E('div', { 'class': 'spinning' }, _('Loading view…')));
2695 return Promise
.resolve(this.load())
2696 .then(L
.bind(this.render
, this))
2697 .then(L
.bind(function(nodes
) {
2698 var vp
= document
.getElementById('view');
2700 L
.dom
.content(vp
, nodes
);
2701 L
.dom
.append(vp
, this.addFooter());
2702 }, this)).catch(L
.error
);
2706 * The load function is invoked before the view is rendered.
2708 * The invocation of this function is wrapped by
2709 * `Promise.resolve()` so it may return Promises if needed.
2711 * The return value of the function (or the resolved values
2712 * of the promise returned by it) will be passed as first
2713 * argument to `render()`.
2715 * This function is supposed to be overwritten by subclasses,
2716 * the default implementation does nothing.
2720 * @memberof LuCI.view
2722 * @returns {*|Promise<*>}
2723 * May return any value or a Promise resolving to any value.
2725 load: function() {},
2728 * The render function is invoked after the
2729 * {@link LuCI.view#load load()} function and responsible
2730 * for setting up the view contents. It must return a DOM
2731 * `Node` or `DocumentFragment` holding the contents to
2732 * insert into the view area.
2734 * The invocation of this function is wrapped by
2735 * `Promise.resolve()` so it may return Promises if needed.
2737 * The return value of the function (or the resolved values
2738 * of the promise returned by it) will be inserted into the
2739 * main content area using
2740 * {@link LuCI.dom#append dom.append()}.
2742 * This function is supposed to be overwritten by subclasses,
2743 * the default implementation does nothing.
2747 * @memberof LuCI.view
2748 * @param {*|null} load_results
2749 * This function will receive the return value of the
2750 * {@link LuCI.view#load view.load()} function as first
2753 * @returns {Node|Promise<Node>}
2754 * Should return a DOM `Node` value or a `Promise` resolving
2755 * to a `Node` value.
2757 render: function() {},
2760 * The handleSave function is invoked when the user clicks
2761 * the `Save` button in the page action footer.
2763 * The default implementation should be sufficient for most
2764 * views using {@link form#Map form.Map()} based forms - it
2765 * will iterate all forms present in the view and invoke
2766 * the {@link form#Map#save Map.save()} method on each form.
2768 * Views not using `Map` instances or requiring other special
2769 * logic should overwrite `handleSave()` with a custom
2772 * To disable the `Save` page footer button, views extending
2773 * this base class should overwrite the `handleSave` function
2776 * The invocation of this function is wrapped by
2777 * `Promise.resolve()` so it may return Promises if needed.
2780 * @memberof LuCI.view
2782 * The DOM event that triggered the function.
2784 * @returns {*|Promise<*>}
2785 * Any return values of this function are discarded, but
2786 * passed through `Promise.resolve()` to ensure that any
2787 * returned promise runs to completion before the button
2790 handleSave: function(ev
) {
2793 document
.getElementById('maincontent')
2794 .querySelectorAll('.cbi-map').forEach(function(map
) {
2795 tasks
.push(L
.dom
.callClassMethod(map
, 'save'));
2798 return Promise
.all(tasks
);
2802 * The handleSaveApply function is invoked when the user clicks
2803 * the `Save & Apply` button in the page action footer.
2805 * The default implementation should be sufficient for most
2806 * views using {@link form#Map form.Map()} based forms - it
2808 * {@link LuCI.view.handleSave view.handleSave()} and then
2809 * call {@link ui#changes#apply ui.changes.apply()} to start the
2810 * modal config apply and page reload flow.
2812 * Views not using `Map` instances or requiring other special
2813 * logic should overwrite `handleSaveApply()` with a custom
2816 * To disable the `Save & Apply` page footer button, views
2817 * extending this base class should overwrite the
2818 * `handleSaveApply` function with `null`.
2820 * The invocation of this function is wrapped by
2821 * `Promise.resolve()` so it may return Promises if needed.
2824 * @memberof LuCI.view
2826 * The DOM event that triggered the function.
2828 * @returns {*|Promise<*>}
2829 * Any return values of this function are discarded, but
2830 * passed through `Promise.resolve()` to ensure that any
2831 * returned promise runs to completion before the button
2834 handleSaveApply: function(ev
, mode
) {
2835 return this.handleSave(ev
).then(function() {
2836 L
.ui
.changes
.apply(mode
== '0');
2841 * The handleReset function is invoked when the user clicks
2842 * the `Reset` button in the page action footer.
2844 * The default implementation should be sufficient for most
2845 * views using {@link form#Map form.Map()} based forms - it
2846 * will iterate all forms present in the view and invoke
2847 * the {@link form#Map#save Map.reset()} method on each form.
2849 * Views not using `Map` instances or requiring other special
2850 * logic should overwrite `handleReset()` with a custom
2853 * To disable the `Reset` page footer button, views extending
2854 * this base class should overwrite the `handleReset` function
2857 * The invocation of this function is wrapped by
2858 * `Promise.resolve()` so it may return Promises if needed.
2861 * @memberof LuCI.view
2863 * The DOM event that triggered the function.
2865 * @returns {*|Promise<*>}
2866 * Any return values of this function are discarded, but
2867 * passed through `Promise.resolve()` to ensure that any
2868 * returned promise runs to completion before the button
2871 handleReset: function(ev
) {
2874 document
.getElementById('maincontent')
2875 .querySelectorAll('.cbi-map').forEach(function(map
) {
2876 tasks
.push(L
.dom
.callClassMethod(map
, 'reset'));
2879 return Promise
.all(tasks
);
2883 * Renders a standard page action footer if any of the
2884 * `handleSave()`, `handleSaveApply()` or `handleReset()`
2885 * functions are defined.
2887 * The default implementation should be sufficient for most
2888 * views - it will render a standard page footer with action
2889 * buttons labeled `Save`, `Save & Apply` and `Reset`
2890 * triggering the `handleSave()`, `handleSaveApply()` and
2891 * `handleReset()` functions respectively.
2893 * When any of these `handle*()` functions is overwritten
2894 * with `null` by a view extending this class, the
2895 * corresponding button will not be rendered.
2898 * @memberof LuCI.view
2899 * @returns {DocumentFragment}
2900 * Returns a `DocumentFragment` containing the footer bar
2901 * with buttons for each corresponding `handle*()` action
2902 * or an empty `DocumentFragment` if all three `handle*()`
2903 * methods are overwritten with `null`.
2905 addFooter: function() {
2908 var saveApplyBtn
= this.handleSaveApply
? new L
.ui
.ComboButton('0', {
2909 0: [ _('Save & Apply') ],
2910 1: [ _('Apply unchecked') ]
2913 0: 'cbi-button cbi-button-apply important',
2914 1: 'cbi-button cbi-button-negative important'
2916 click
: L
.ui
.createHandlerFn(this, 'handleSaveApply')
2917 }).render() : E([]);
2919 if (this.handleSaveApply
|| this.handleSave
|| this.handleReset
) {
2920 footer
.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
2922 this.handleSave
? E('button', {
2923 'class': 'cbi-button cbi-button-save',
2924 'click': L
.ui
.createHandlerFn(this, 'handleSave')
2925 }, [ _('Save') ]) : '', ' ',
2926 this.handleReset
? E('button', {
2927 'class': 'cbi-button cbi-button-reset',
2928 'click': L
.ui
.createHandlerFn(this, 'handleReset')
2929 }, [ _('Reset') ]) : ''
2944 * The `LuCI.XHR` class is a legacy compatibility shim for the
2945 * functionality formerly provided by `xhr.js`. It is registered as global
2946 * `window.XHR` symbol for compatibility with legacy code.
2948 * New code should use {@link LuCI.Request} instead to implement HTTP
2951 var XHR
= Class
.extend(/** @lends LuCI.XHR.prototype */ {
2952 __name__
: 'LuCI.XHR',
2953 __init__: function() {
2954 if (window
.console
&& console
.debug
)
2955 console
.debug('Direct use XHR() is deprecated, please use L.Request instead');
2958 _response: function(cb
, res
, json
, duration
) {
2960 cb(res
, json
, duration
);
2965 * This function is a legacy wrapper around
2966 * {@link LuCI#get LuCI.get()}.
2970 * @memberof LuCI.XHR
2972 * @param {string} url
2973 * The URL to request
2975 * @param {Object} [data]
2976 * Additional query string data
2978 * @param {LuCI.requestCallbackFn} [callback]
2979 * Callback function to invoke on completion
2981 * @param {number} [timeout]
2982 * Request timeout to use
2984 * @return {Promise<null>}
2986 get: function(url
, data
, callback
, timeout
) {
2988 L
.get(url
, data
, this._response
.bind(this, callback
), timeout
);
2992 * This function is a legacy wrapper around
2993 * {@link LuCI#post LuCI.post()}.
2997 * @memberof LuCI.XHR
2999 * @param {string} url
3000 * The URL to request
3002 * @param {Object} [data]
3003 * Additional data to append to the request body.
3005 * @param {LuCI.requestCallbackFn} [callback]
3006 * Callback function to invoke on completion
3008 * @param {number} [timeout]
3009 * Request timeout to use
3011 * @return {Promise<null>}
3013 post: function(url
, data
, callback
, timeout
) {
3015 L
.post(url
, data
, this._response
.bind(this, callback
), timeout
);
3019 * Cancels a running request.
3021 * This function does not actually cancel the underlying
3022 * `XMLHTTPRequest` request but it sets a flag which prevents the
3023 * invocation of the callback function when the request eventually
3024 * finishes or timed out.
3028 * @memberof LuCI.XHR
3030 cancel: function() { delete this.active
},
3033 * Checks the running state of the request.
3037 * @memberof LuCI.XHR
3039 * @returns {boolean}
3040 * Returns `true` if the request is still running or `false` if it
3041 * already completed.
3043 busy: function() { return (this.active
=== true) },
3046 * Ignored for backwards compatibility.
3048 * This function does nothing.
3052 * @memberof LuCI.XHR
3054 abort: function() {},
3057 * Existing for backwards compatibility.
3059 * This function simply throws an `InternalError` when invoked.
3063 * @memberof LuCI.XHR
3065 * @throws {InternalError}
3066 * Throws an `InternalError` with the message `Not implemented`
3069 send_form: function() { L
.error('InternalError', 'Not implemented') },
3072 XHR
.get = function() { return window
.L
.get.apply(window
.L
, arguments
) };
3073 XHR
.post = function() { return window
.L
.post
.apply(window
.L
, arguments
) };
3074 XHR
.poll = function() { return window
.L
.poll
.apply(window
.L
, arguments
) };
3075 XHR
.stop
= Request
.poll
.remove
.bind(Request
.poll
);
3076 XHR
.halt
= Request
.poll
.stop
.bind(Request
.poll
);
3077 XHR
.run
= Request
.poll
.start
.bind(Request
.poll
);
3078 XHR
.running
= Request
.poll
.active
.bind(Request
.poll
);
3082 })(window
, document
);