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
= {}, classIndex
= 0, Class
= Object
.assign(function() {}, {
72 * Extends this base class with the properties described in
73 * `properties` and returns a new subclassed Class instance
75 * @memberof LuCI.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 __id__
: { value
: classIndex
},
90 __base__
: { value
: this.prototype },
91 __name__
: { value
: properties
.__name__
|| 'anonymous' + classIndex
++ }
94 var ClassConstructor = function() {
95 if (!(this instanceof ClassConstructor
))
96 throw new TypeError('Constructor must not be called without "new"');
98 if (Object
.getPrototypeOf(this).hasOwnProperty('__init__')) {
99 if (typeof(this.__init__
) != 'function')
100 throw new TypeError('Class __init__ member is not a function');
102 this.__init__
.apply(this, arguments
)
105 this.super('__init__', arguments
);
109 for (var key
in properties
)
110 if (!props
[key
] && properties
.hasOwnProperty(key
))
111 props
[key
] = { value
: properties
[key
], writable
: true };
113 ClassConstructor
.prototype = Object
.create(this.prototype, props
);
114 ClassConstructor
.prototype.constructor = ClassConstructor
;
115 Object
.assign(ClassConstructor
, this);
116 ClassConstructor
.displayName
= toCamelCase(props
.__name__
.value
+ 'Class');
118 return ClassConstructor
;
122 * Extends this base class with the properties described in
123 * `properties`, instantiates the resulting subclass using
124 * the additional optional arguments passed to this function
125 * and returns the resulting subclassed Class instance.
127 * This function serves as a convenience shortcut for
128 * {@link LuCI.Class.extend Class.extend()} and subsequent
131 * @memberof LuCI.Class
133 * @param {Object<string, *>} properties
134 * An object describing the properties to add to the new
137 * @param {...*} [new_args]
138 * Specifies arguments to be passed to the subclass constructor
139 * as-is in order to instantiate the new subclass.
141 * @returns {LuCI.Class}
142 * Returns a new LuCI.Class instance extended by the given
143 * properties with its prototype set to this base class to
144 * enable inheritance.
146 singleton: function(properties
/*, ... */) {
147 return Class
.extend(properties
)
148 .instantiate(Class
.prototype.varargs(arguments
, 1));
152 * Calls the class constructor using `new` with the given argument
153 * array being passed as variadic parameters to the constructor.
155 * @memberof LuCI.Class
157 * @param {Array<*>} params
158 * An array of arbitrary values which will be passed as arguments
159 * to the constructor function.
161 * @param {...*} [new_args]
162 * Specifies arguments to be passed to the subclass constructor
163 * as-is in order to instantiate the new subclass.
165 * @returns {LuCI.Class}
166 * Returns a new LuCI.Class instance extended by the given
167 * properties with its prototype set to this base class to
168 * enable inheritance.
170 instantiate: function(args
) {
171 return new (Function
.prototype.bind
.apply(this,
172 Class
.prototype.varargs(args
, 0, null)))();
176 call: function(self
, method
) {
177 if (typeof(this.prototype[method
]) != 'function')
178 throw new ReferenceError(method
+ ' is not defined in class');
180 return this.prototype[method
].apply(self
, self
.varargs(arguments
, 1));
184 * Checks whether the given class value is a subclass of this class.
186 * @memberof LuCI.Class
188 * @param {LuCI.Class} classValue
189 * The class object to test.
192 * Returns `true` when the given `classValue` is a subclass of this
193 * class or `false` if the given value is not a valid class or not
194 * a subclass of this class'.
196 isSubclass: function(classValue
) {
197 return (classValue
!= null &&
198 typeof(classValue
) == 'function' &&
199 classValue
.prototype instanceof this);
204 * Extract all values from the given argument array beginning from
205 * `offset` and prepend any further given optional parameters to
206 * the beginning of the resulting array copy.
208 * @memberof LuCI.Class
211 * @param {Array<*>} args
212 * The array to extract the values from.
214 * @param {number} offset
215 * The offset from which to extract the values. An offset of `0`
216 * would copy all values till the end.
218 * @param {...*} [extra_args]
219 * Extra arguments to add to prepend to the resultung array.
221 * @returns {Array<*>}
222 * Returns a new array consisting of the optional extra arguments
223 * and the values extracted from the `args` array beginning with
226 varargs: function(args
, offset
/*, ... */) {
227 return Array
.prototype.slice
.call(arguments
, 2)
228 .concat(Array
.prototype.slice
.call(args
, offset
));
232 * Walks up the parent class chain and looks for a class member
233 * called `key` in any of the parent classes this class inherits
234 * from. Returns the member value of the superclass or calls the
235 * member as function and returns its return value when the
236 * optional `callArgs` array is given.
238 * This function has two signatures and is sensitive to the
239 * amount of arguments passed to it:
241 * Returns the value of `key` when found within one of the
243 * - `super('key', ['arg1', 'arg2'])` -
244 * Calls the `key()` method with parameters `arg1` and `arg2`
245 * when found within one of the parent classes.
247 * @memberof LuCI.Class
250 * @param {string} key
251 * The name of the superclass member to retrieve.
253 * @param {Array<*>} [callArgs]
254 * An optional array of function call parameters to use. When
255 * this parameter is specified, the found member value is called
256 * as function using the values of this array as arguments.
258 * @throws {ReferenceError}
259 * Throws a `ReferenceError` when `callArgs` are specified and
260 * the found member named by `key` is not a function value.
263 * Returns the value of the found member or the return value of
264 * the call to the found method. Returns `null` when no member
265 * was found in the parent class chain or when the call to the
266 * superclass method returned `null`.
268 super: function(key
, callArgs
) {
272 var slotIdx
= this.__id__
+ '.' + key
,
273 symStack
= superContext
[slotIdx
],
276 for (protoCtx
= Object
.getPrototypeOf(symStack
? symStack
[0] : Object
.getPrototypeOf(this));
277 protoCtx
!= null && !protoCtx
.hasOwnProperty(key
);
278 protoCtx
= Object
.getPrototypeOf(protoCtx
)) {}
280 if (protoCtx
== null)
283 var res
= protoCtx
[key
];
285 if (arguments
.length
> 1) {
286 if (typeof(res
) != 'function')
287 throw new ReferenceError(key
+ ' is not a function in base class');
289 if (typeof(callArgs
) != 'object')
290 callArgs
= this.varargs(arguments
, 1);
293 symStack
.unshift(protoCtx
);
295 superContext
[slotIdx
] = [ protoCtx
];
297 res
= res
.apply(this, callArgs
);
299 if (symStack
&& symStack
.length
> 1)
300 symStack
.shift(protoCtx
);
302 delete superContext
[slotIdx
];
309 * Returns a string representation of this class.
312 * Returns a string representation of this class containing the
313 * constructor functions `displayName` and describing the class
314 * members and their respective types.
316 toString: function() {
317 var s
= '[' + this.constructor.displayName
+ ']', f
= true;
318 for (var k
in this) {
319 if (this.hasOwnProperty(k
)) {
320 s
+= (f
? ' {\n' : '') + ' ' + k
+ ': ' + typeof(this[k
]) + '\n';
324 return s
+ (f
? '' : '}');
336 * The `Headers` class is an internal utility class exposed in HTTP
337 * response objects using the `response.headers` property.
339 var Headers
= Class
.extend(/** @lends LuCI.Headers.prototype */ {
340 __name__
: 'LuCI.XHR.Headers',
341 __init__: function(xhr
) {
342 var hdrs
= this.headers
= {};
343 xhr
.getAllResponseHeaders().split(/\r\n/).forEach(function(line
) {
344 var m
= /^([^:]+):(.*)$/.exec(line
);
346 hdrs
[m
[1].trim().toLowerCase()] = m
[2].trim();
351 * Checks whether the given header name is present.
352 * Note: Header-Names are case-insensitive.
355 * @memberof LuCI.Headers
356 * @param {string} name
357 * The header name to check
360 * Returns `true` if the header name is present, `false` otherwise
362 has: function(name
) {
363 return this.headers
.hasOwnProperty(String(name
).toLowerCase());
367 * Returns the value of the given header name.
368 * Note: Header-Names are case-insensitive.
371 * @memberof LuCI.Headers
372 * @param {string} name
373 * The header name to read
375 * @returns {string|null}
376 * The value of the given header name or `null` if the header isn't present.
378 get: function(name
) {
379 var key
= String(name
).toLowerCase();
380 return this.headers
.hasOwnProperty(key
) ? this.headers
[key
] : null;
390 * The `Response` class is an internal utility class representing HTTP responses.
392 var Response
= Class
.extend({
393 __name__
: 'LuCI.XHR.Response',
394 __init__: function(xhr
, url
, duration
, headers
, content
) {
396 * Describes whether the response is successful (status codes `200..299`) or not
398 * @memberof LuCI.Response
402 this.ok
= (xhr
.status
>= 200 && xhr
.status
<= 299);
405 * The numeric HTTP status code of the response
407 * @memberof LuCI.Response
411 this.status
= xhr
.status
;
414 * The HTTP status description message of the response
416 * @memberof LuCI.Response
420 this.statusText
= xhr
.statusText
;
423 * The HTTP headers of the response
425 * @memberof LuCI.Response
427 * @type {LuCI.Headers}
429 this.headers
= (headers
!= null) ? headers
: new Headers(xhr
);
432 * The total duration of the HTTP request in milliseconds
434 * @memberof LuCI.Response
438 this.duration
= duration
;
441 * The final URL of the request, i.e. after following redirects.
443 * @memberof LuCI.Response
452 if (content
instanceof Blob
) {
453 this.responseBlob
= content
;
454 this.responseJSON
= null;
455 this.responseText
= null;
457 else if (content
!= null && typeof(content
) == 'object') {
458 this.responseBlob
= null;
459 this.responseJSON
= content
;
460 this.responseText
= null;
462 else if (content
!= null) {
463 this.responseBlob
= null;
464 this.responseJSON
= null;
465 this.responseText
= String(content
);
468 this.responseJSON
= null;
470 if (xhr
.responseType
== 'blob') {
471 this.responseBlob
= xhr
.response
;
472 this.responseText
= null;
475 this.responseBlob
= null;
476 this.responseText
= xhr
.responseText
;
482 * Clones the given response object, optionally overriding the content
483 * of the cloned instance.
486 * @memberof LuCI.Response
487 * @param {*} [content]
488 * Override the content of the cloned response. Object values will be
489 * treated as JSON response data, all other types will be converted
490 * using `String()` and treated as response text.
492 * @returns {LuCI.Response}
493 * The cloned `Response` instance.
495 clone: function(content
) {
496 var copy
= new Response(this.xhr
, this.url
, this.duration
, this.headers
, content
);
499 copy
.status
= this.status
;
500 copy
.statusText
= this.statusText
;
506 * Access the response content as JSON data.
509 * @memberof LuCI.Response
510 * @throws {SyntaxError}
511 * Throws `SyntaxError` if the content isn't valid JSON.
514 * The parsed JSON data.
517 if (this.responseJSON
== null)
518 this.responseJSON
= JSON
.parse(this.responseText
);
520 return this.responseJSON
;
524 * Access the response content as string.
527 * @memberof LuCI.Response
529 * The response content.
532 if (this.responseText
== null && this.responseJSON
!= null)
533 this.responseText
= JSON
.stringify(this.responseJSON
);
535 return this.responseText
;
539 * Access the response content as blob.
542 * @memberof LuCI.Response
544 * The response content as blob.
547 return this.responseBlob
;
552 var requestQueue
= [];
554 function isQueueableRequest(opt
) {
558 if (opt
.method
!= 'POST' || typeof(opt
.content
) != 'object')
561 if (opt
.nobatch
=== true)
564 var rpcBaseURL
= Request
.expandURL(classes
.rpc
.getBaseURL());
566 return (rpcBaseURL
!= null && opt
.url
.indexOf(rpcBaseURL
) == 0);
569 function flushRequestQueue() {
570 if (!requestQueue
.length
)
573 var reqopt
= Object
.assign({}, requestQueue
[0][0], { content
: [], nobatch
: true }),
576 for (var i
= 0; i
< requestQueue
.length
; i
++) {
577 batch
[i
] = requestQueue
[i
];
578 reqopt
.content
[i
] = batch
[i
][0].content
;
581 requestQueue
.length
= 0;
583 Request
.request(rpcBaseURL
, reqopt
).then(function(reply
) {
584 var json
= null, req
= null;
586 try { json
= reply
.json() }
589 while ((req
= batch
.shift()) != null)
590 if (Array
.isArray(json
) && json
.length
)
591 req
[2].call(reqopt
, reply
.clone(json
.shift()));
593 req
[1].call(reqopt
, new Error('No related RPC reply'));
594 }).catch(function(error
) {
597 while ((req
= batch
.shift()) != null)
598 req
[1].call(reqopt
, error
);
608 * The `Request` class allows initiating HTTP requests and provides utilities
609 * for dealing with responses.
611 var Request
= Class
.singleton(/** @lends LuCI.Request.prototype */ {
612 __name__
: 'LuCI.Request',
617 * Turn the given relative URL into an absolute URL if necessary.
620 * @memberof LuCI.Request
621 * @param {string} url
622 * The URL to convert.
625 * The absolute URL derived from the given one, or the original URL
626 * if it already was absolute.
628 expandURL: function(url
) {
629 if (!/^(?:[^/]+:)?\/\//.test(url
))
630 url
= location
.protocol
+ '//' + location
.host
+ url
;
636 * @typedef {Object} RequestOptions
637 * @memberof LuCI.Request
639 * @property {string} [method=GET]
640 * The HTTP method to use, e.g. `GET` or `POST`.
642 * @property {Object<string, Object|string>} [query]
643 * Query string data to append to the URL. Non-string values of the
644 * given object will be converted to JSON.
646 * @property {boolean} [cache=false]
647 * Specifies whether the HTTP response may be retrieved from cache.
649 * @property {string} [username]
650 * Provides a username for HTTP basic authentication.
652 * @property {string} [password]
653 * Provides a password for HTTP basic authentication.
655 * @property {number} [timeout]
656 * Specifies the request timeout in seconds.
658 * @property {boolean} [credentials=false]
659 * Whether to include credentials such as cookies in the request.
661 * @property {string} [responseType=text]
662 * Overrides the request response type. Valid values or `text` to
663 * interpret the response as UTF-8 string or `blob` to handle the
664 * response as binary `Blob` data.
666 * @property {*} [content]
667 * Specifies the HTTP message body to send along with the request.
668 * If the value is a function, it is invoked and the return value
669 * used as content, if it is a FormData instance, it is used as-is,
670 * if it is an object, it will be converted to JSON, in all other
671 * cases it is converted to a string.
673 * @property {Object<string, string>} [header]
674 * Specifies HTTP headers to set for the request.
676 * @property {function} [progress]
677 * An optional request callback function which receives ProgressEvent
678 * instances as sole argument during the HTTP request transfer.
682 * Initiate an HTTP request to the given target.
685 * @memberof LuCI.Request
686 * @param {string} target
687 * The URL to request.
689 * @param {LuCI.Request.RequestOptions} [options]
690 * Additional options to configure the request.
692 * @returns {Promise<LuCI.Response>}
693 * The resulting HTTP response.
695 request: function(target
, options
) {
696 var state
= { xhr
: new XMLHttpRequest(), url
: this.expandURL(target
), start
: Date
.now() },
697 opt
= Object
.assign({}, options
, state
),
700 callback
= this.handleReadyStateChange
;
702 return new Promise(function(resolveFn
, rejectFn
) {
703 opt
.xhr
.onreadystatechange
= callback
.bind(opt
, resolveFn
, rejectFn
);
704 opt
.method
= String(opt
.method
|| 'GET').toUpperCase();
706 if ('query' in opt
) {
707 var q
= (opt
.query
!= null) ? Object
.keys(opt
.query
).map(function(k
) {
708 if (opt
.query
[k
] != null) {
709 var v
= (typeof(opt
.query
[k
]) == 'object')
710 ? JSON
.stringify(opt
.query
[k
])
711 : String(opt
.query
[k
]);
713 return '%s=%s'.format(encodeURIComponent(k
), encodeURIComponent(v
));
716 return encodeURIComponent(k
);
721 switch (opt
.method
) {
725 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + q
;
729 if (content
== null) {
731 contenttype
= 'application/x-www-form-urlencoded';
738 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + (new Date()).getTime();
740 if (isQueueableRequest(opt
)) {
741 requestQueue
.push([opt
, rejectFn
, resolveFn
]);
742 requestAnimationFrame(flushRequestQueue
);
746 if ('username' in opt
&& 'password' in opt
)
747 opt
.xhr
.open(opt
.method
, opt
.url
, true, opt
.username
, opt
.password
);
749 opt
.xhr
.open(opt
.method
, opt
.url
, true);
751 opt
.xhr
.responseType
= opt
.responseType
|| 'text';
753 if ('overrideMimeType' in opt
.xhr
)
754 opt
.xhr
.overrideMimeType('application/octet-stream');
756 if ('timeout' in opt
)
757 opt
.xhr
.timeout
= +opt
.timeout
;
759 if ('credentials' in opt
)
760 opt
.xhr
.withCredentials
= !!opt
.credentials
;
762 if (opt
.content
!= null) {
763 switch (typeof(opt
.content
)) {
765 content
= opt
.content(xhr
);
769 if (!(opt
.content
instanceof FormData
)) {
770 content
= JSON
.stringify(opt
.content
);
771 contenttype
= 'application/json';
774 content
= opt
.content
;
779 content
= String(opt
.content
);
783 if ('headers' in opt
)
784 for (var header
in opt
.headers
)
785 if (opt
.headers
.hasOwnProperty(header
)) {
786 if (header
.toLowerCase() != 'content-type')
787 opt
.xhr
.setRequestHeader(header
, opt
.headers
[header
]);
789 contenttype
= opt
.headers
[header
];
792 if ('progress' in opt
&& 'upload' in opt
.xhr
)
793 opt
.xhr
.upload
.addEventListener('progress', opt
.progress
);
795 if (contenttype
!= null)
796 opt
.xhr
.setRequestHeader('Content-Type', contenttype
);
799 opt
.xhr
.send(content
);
802 rejectFn
.call(opt
, e
);
807 handleReadyStateChange: function(resolveFn
, rejectFn
, ev
) {
809 duration
= Date
.now() - this.start
;
811 if (xhr
.readyState
!== 4)
814 if (xhr
.status
=== 0 && xhr
.statusText
=== '') {
815 if (duration
>= this.timeout
)
816 rejectFn
.call(this, new Error('XHR request timed out'));
818 rejectFn
.call(this, new Error('XHR request aborted by browser'));
821 var response
= new Response(
822 xhr
, xhr
.responseURL
|| this.url
, duration
);
824 Promise
.all(Request
.interceptors
.map(function(fn
) { return fn(response
) }))
825 .then(resolveFn
.bind(this, response
))
826 .catch(rejectFn
.bind(this));
831 * Initiate an HTTP GET request to the given target.
834 * @memberof LuCI.Request
835 * @param {string} target
836 * The URL to request.
838 * @param {LuCI.Request.RequestOptions} [options]
839 * Additional options to configure the request.
841 * @returns {Promise<LuCI.Response>}
842 * The resulting HTTP response.
844 get: function(url
, options
) {
845 return this.request(url
, Object
.assign({ method
: 'GET' }, options
));
849 * Initiate an HTTP POST request to the given target.
852 * @memberof LuCI.Request
853 * @param {string} target
854 * The URL to request.
857 * The request data to send, see {@link LuCI.Request.RequestOptions} for details.
859 * @param {LuCI.Request.RequestOptions} [options]
860 * Additional options to configure the request.
862 * @returns {Promise<LuCI.Response>}
863 * The resulting HTTP response.
865 post: function(url
, data
, options
) {
866 return this.request(url
, Object
.assign({ method
: 'POST', content
: data
}, options
));
870 * Interceptor functions are invoked whenever an HTTP reply is received, in the order
871 * these functions have been registered.
872 * @callback LuCI.Request.interceptorFn
873 * @param {LuCI.Response} res
874 * The HTTP response object
878 * Register an HTTP response interceptor function. Interceptor
879 * functions are useful to perform default actions on incoming HTTP
880 * responses, such as checking for expired authentication or for
881 * implementing request retries before returning a failure.
884 * @memberof LuCI.Request
885 * @param {LuCI.Request.interceptorFn} interceptorFn
886 * The interceptor function to register.
888 * @returns {LuCI.Request.interceptorFn}
889 * The registered function.
891 addInterceptor: function(interceptorFn
) {
892 if (typeof(interceptorFn
) == 'function')
893 this.interceptors
.push(interceptorFn
);
894 return interceptorFn
;
898 * Remove an HTTP response interceptor function. The passed function
899 * value must be the very same value that was used to register the
903 * @memberof LuCI.Request
904 * @param {LuCI.Request.interceptorFn} interceptorFn
905 * The interceptor function to remove.
908 * Returns `true` if any function has been removed, else `false`.
910 removeInterceptor: function(interceptorFn
) {
911 var oldlen
= this.interceptors
.length
, i
= oldlen
;
913 if (this.interceptors
[i
] === interceptorFn
)
914 this.interceptors
.splice(i
, 1);
915 return (this.interceptors
.length
< oldlen
);
920 * @memberof LuCI.Request
924 * The `Request.poll` class provides some convience wrappers around
925 * {@link LuCI.Poll} mainly to simplify registering repeating HTTP
926 * request calls as polling functions.
930 * The callback function is invoked whenever an HTTP reply to a
931 * polled request is received or when the polled request timed
934 * @callback LuCI.Request.poll~callbackFn
935 * @param {LuCI.Response} res
936 * The HTTP response object.
939 * The response JSON if the response could be parsed as such,
942 * @param {number} duration
943 * The total duration of the request in milliseconds.
947 * Register a repeating HTTP request with an optional callback
948 * to invoke whenever a response for the request is received.
951 * @memberof LuCI.Request.poll
952 * @param {number} interval
953 * The poll interval in seconds.
955 * @param {string} url
956 * The URL to request on each poll.
958 * @param {LuCI.Request.RequestOptions} [options]
959 * Additional options to configure the request.
961 * @param {LuCI.Request.poll~callbackFn} [callback]
962 * {@link LuCI.Request.poll~callbackFn Callback} function to
963 * invoke for each HTTP reply.
965 * @throws {TypeError}
966 * Throws `TypeError` when an invalid interval was passed.
968 * @returns {function}
969 * Returns the internally created poll function.
971 add: function(interval
, url
, options
, callback
) {
972 if (isNaN(interval
) || interval
<= 0)
973 throw new TypeError('Invalid poll interval');
975 var ival
= interval
>>> 0,
976 opts
= Object
.assign({}, options
, { timeout
: ival
* 1000 - 5 });
978 var fn = function() {
979 return Request
.request(url
, options
).then(function(res
) {
984 callback(res
, res
.json(), res
.duration
);
987 callback(res
, null, res
.duration
);
992 return (Poll
.add(fn
, ival
) ? fn
: null);
996 * Remove a polling request that has been previously added using `add()`.
997 * This function is essentially a wrapper around
998 * {@link LuCI.Poll.remove LuCI.Poll.remove()}.
1001 * @memberof LuCI.Request.poll
1002 * @param {function} entry
1003 * The poll function returned by {@link LuCI.Request.poll#add add()}.
1005 * @returns {boolean}
1006 * Returns `true` if any function has been removed, else `false`.
1008 remove: function(entry
) { return Poll
.remove(entry
) },
1011 * Alias for {@link LuCI.Poll.start LuCI.Poll.start()}.
1014 * @memberof LuCI.Request.poll
1016 start: function() { return Poll
.start() },
1019 * Alias for {@link LuCI.Poll.stop LuCI.Poll.stop()}.
1022 * @memberof LuCI.Request.poll
1024 stop: function() { return Poll
.stop() },
1027 * Alias for {@link LuCI.Poll.active LuCI.Poll.active()}.
1030 * @memberof LuCI.Request.poll
1032 active: function() { return Poll
.active() }
1042 * The `Poll` class allows registering and unregistering poll actions,
1043 * as well as starting, stopping and querying the state of the polling
1046 var Poll
= Class
.singleton(/** @lends LuCI.Poll.prototype */ {
1047 __name__
: 'LuCI.Poll',
1052 * Add a new operation to the polling loop. If the polling loop is not
1053 * already started at this point, it will be implicitely started.
1056 * @memberof LuCI.Poll
1057 * @param {function} fn
1058 * The function to invoke on each poll interval.
1060 * @param {number} interval
1061 * The poll interval in seconds.
1063 * @throws {TypeError}
1064 * Throws `TypeError` when an invalid interval was passed.
1066 * @returns {boolean}
1067 * Returns `true` if the function has been added or `false` if it
1068 * already is registered.
1070 add: function(fn
, interval
) {
1071 if (interval
== null || interval
<= 0)
1072 interval
= window
.L
? window
.L
.env
.pollinterval
: null;
1074 if (isNaN(interval
) || typeof(fn
) != 'function')
1075 throw new TypeError('Invalid argument to LuCI.Poll.add()');
1077 for (var i
= 0; i
< this.queue
.length
; i
++)
1078 if (this.queue
[i
].fn
=== fn
)
1089 if (this.tick
!= null && !this.active())
1096 * Remove an operation from the polling loop. If no further operatons
1097 * are registered, the polling loop is implicitely stopped.
1100 * @memberof LuCI.Poll
1101 * @param {function} fn
1102 * The function to remove.
1104 * @throws {TypeError}
1105 * Throws `TypeError` when the given argument isn't a function.
1107 * @returns {boolean}
1108 * Returns `true` if the function has been removed or `false` if it
1111 remove: function(fn
) {
1112 if (typeof(fn
) != 'function')
1113 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
1115 var len
= this.queue
.length
;
1117 for (var i
= len
; i
> 0; i
--)
1118 if (this.queue
[i
-1].fn
=== fn
)
1119 this.queue
.splice(i
-1, 1);
1121 if (!this.queue
.length
&& this.stop())
1124 return (this.queue
.length
!= len
);
1128 * (Re)start the polling loop. Dispatches a custom `poll-start` event
1129 * to the `document` object upon successful start.
1132 * @memberof LuCI.Poll
1133 * @returns {boolean}
1134 * Returns `true` if polling has been started (or if no functions
1135 * where registered) or `false` when the polling loop already runs.
1143 if (this.queue
.length
) {
1144 this.timer
= window
.setInterval(this.step
, 1000);
1146 document
.dispatchEvent(new CustomEvent('poll-start'));
1153 * Stop the polling loop. Dispatches a custom `poll-stop` event
1154 * to the `document` object upon successful stop.
1157 * @memberof LuCI.Poll
1158 * @returns {boolean}
1159 * Returns `true` if polling has been stopped or `false` if it din't
1160 * run to begin with.
1166 document
.dispatchEvent(new CustomEvent('poll-stop'));
1167 window
.clearInterval(this.timer
);
1175 for (var i
= 0, e
= null; (e
= Poll
.queue
[i
]) != null; i
++) {
1176 if ((Poll
.tick
% e
.i
) != 0)
1184 Promise
.resolve(e
.fn()).finally((function() { this.r
= true }).bind(e
));
1187 Poll
.tick
= (Poll
.tick
+ 1) % Math
.pow(2, 32);
1191 * Test whether the polling loop is running.
1194 * @memberof LuCI.Poll
1195 * @returns {boolean} - Returns `true` if polling is active, else `false`.
1197 active: function() {
1198 return (this.timer
!= null);
1203 var dummyElem
= null,
1205 originalCBIInit
= null,
1210 var LuCI
= Class
.extend(/** @lends LuCI.prototype */ {
1212 __init__: function(env
) {
1214 document
.querySelectorAll('script[src*="/luci.js"]').forEach(function(s
) {
1215 if (env
.base_url
== null || env
.base_url
== '') {
1216 var m
= (s
.getAttribute('src') || '').match(/^(.*)\/luci\.js(?:\?v=([^?]+))?$/);
1218 env
.base_url
= m
[1];
1219 env
.resource_version
= m
[2];
1224 if (env
.base_url
== null)
1225 this.error('InternalError', 'Cannot find url of luci.js');
1227 env
.cgi_base
= env
.scriptname
.replace(/\/[^\/]+$/, '');
1229 Object
.assign(this.env
, env
);
1231 document
.addEventListener('poll-start', function(ev
) {
1232 document
.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e
) {
1233 e
.style
.display
= (e
.id
== 'xhr_poll_status_off') ? 'none' : '';
1237 document
.addEventListener('poll-stop', function(ev
) {
1238 document
.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e
) {
1239 e
.style
.display
= (e
.id
== 'xhr_poll_status_on') ? 'none' : '';
1243 var domReady
= new Promise(function(resolveFn
, rejectFn
) {
1244 document
.addEventListener('DOMContentLoaded', resolveFn
);
1250 this.require('rpc'),
1251 this.require('form'),
1252 this.probeRPCBaseURL()
1253 ]).then(this.setupDOM
.bind(this)).catch(this.error
);
1255 originalCBIInit
= window
.cbi_init
;
1256 window
.cbi_init = function() {};
1260 * Captures the current stack trace and throws an error of the
1261 * specified type as a new exception. Also logs the exception as
1262 * error to the debug console if it is available.
1267 * @param {Error|string} [type=Error]
1268 * Either a string specifying the type of the error to throw or an
1269 * existing `Error` instance to copy.
1271 * @param {string} [fmt=Unspecified error]
1272 * A format string which is used to form the error message, together
1273 * with all subsequent optional arguments.
1275 * @param {...*} [args]
1276 * Zero or more variable arguments to the supplied format string.
1279 * Throws the created error object with the captured stack trace
1280 * appended to the message and the type set to the given type
1281 * argument or copied from the given error instance.
1283 raise: function(type
, fmt
/*, ...*/) {
1285 msg
= fmt
? String
.prototype.format
.apply(fmt
, this.varargs(arguments
, 2)) : null,
1288 if (type
instanceof Error
) {
1292 e
.message
= msg
+ ': ' + e
.message
;
1295 try { throw new Error('stacktrace') }
1296 catch (e2
) { stack
= (e2
.stack
|| '').split(/\n/) }
1298 e
= new (window
[type
|| 'Error'] || Error
)(msg
|| 'Unspecified error');
1299 e
.name
= type
|| 'Error';
1302 stack
= (stack
|| []).map(function(frame
) {
1303 frame
= frame
.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
1304 return frame
? ' ' + frame
: '';
1307 if (!/^ at /.test(stack
[0]))
1310 if (/\braise /.test(stack
[0]))
1313 if (/\berror /.test(stack
[0]))
1317 e
.message
+= '\n' + stack
.join('\n');
1319 if (window
.console
&& console
.debug
)
1326 * A wrapper around {@link LuCI#raise raise()} which also renders
1327 * the error either as modal overlay when `ui.js` is already loaed
1328 * or directly into the view body.
1333 * @param {Error|string} [type=Error]
1334 * Either a string specifying the type of the error to throw or an
1335 * existing `Error` instance to copy.
1337 * @param {string} [fmt=Unspecified error]
1338 * A format string which is used to form the error message, together
1339 * with all subsequent optional arguments.
1341 * @param {...*} [args]
1342 * Zero or more variable arguments to the supplied format string.
1345 * Throws the created error object with the captured stack trace
1346 * appended to the message and the type set to the given type
1347 * argument or copied from the given error instance.
1349 error: function(type
, fmt
/*, ...*/) {
1351 L
.raise
.apply(L
, Array
.prototype.slice
.call(arguments
));
1356 L
.ui
.addNotification(e
.name
|| _('Runtime error'),
1357 E('pre', {}, e
.message
), 'danger');
1359 L
.dom
.content(document
.querySelector('#maincontent'),
1360 E('pre', { 'class': 'alert-message error' }, e
.message
));
1370 * Return a bound function using the given `self` as `this` context
1371 * and any further arguments as parameters to the bound function.
1376 * @param {function} fn
1377 * The function to bind.
1380 * The value to bind as `this` context to the specified function.
1382 * @param {...*} [args]
1383 * Zero or more variable arguments which are bound to the function
1386 * @returns {function}
1387 * Returns the bound function.
1389 bind: function(fn
, self
/*, ... */) {
1390 return Function
.prototype.bind
.apply(fn
, this.varargs(arguments
, 2, self
));
1394 * Load an additional LuCI JavaScript class and its dependencies,
1395 * instantiate it and return the resulting class instance. Each
1396 * class is only loaded once. Subsequent attempts to load the same
1397 * class will return the already instantiated class.
1402 * @param {string} name
1403 * The name of the class to load in dotted notation. Dots will
1404 * be replaced by spaces and joined with the runtime-determined
1405 * base URL of LuCI.js to form an absolute URL to load the class
1408 * @throws {DependencyError}
1409 * Throws a `DependencyError` when the class to load includes
1410 * circular dependencies.
1412 * @throws {NetworkError}
1413 * Throws `NetworkError` when the underlying {@link LuCI.Request}
1416 * @throws {SyntaxError}
1417 * Throws `SyntaxError` when the loaded class file code cannot
1418 * be interpreted by `eval`.
1420 * @throws {TypeError}
1421 * Throws `TypeError` when the class file could be loaded and
1422 * interpreted, but when invoking its code did not yield a valid
1425 * @returns {Promise<LuCI#Class>}
1426 * Returns the instantiated class.
1428 require: function(name
, from) {
1429 var L
= this, url
= null, from = from || [];
1431 /* Class already loaded */
1432 if (classes
[name
] != null) {
1433 /* Circular dependency */
1434 if (from.indexOf(name
) != -1)
1435 L
.raise('DependencyError',
1436 'Circular dependency: class "%s" depends on "%s"',
1437 name
, from.join('" which depends on "'));
1439 return Promise
.resolve(classes
[name
]);
1442 url
= '%s/%s.js%s'.format(L
.env
.base_url
, name
.replace(/\./g, '/'), (L.env.resource_version ? '?v
=' + L.env.resource_version : ''));
1443 from = [ name ].concat(from);
1445 var compileClass = function(res) {
1447 L.raise('NetworkError
',
1448 'HTTP error
%d
while loading
class file
"%s"', res.status, url);
1450 var source = res.text(),
1451 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
1452 strictmatch = /^use[ \t]+strict$/,
1456 /* find require statements in source */
1457 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
1458 var chr = source.charCodeAt(i);
1463 else if (chr == 92) {
1466 else if (chr == quote) {
1467 var s = source.substring(off, i),
1468 m = requirematch.exec(s);
1471 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_
');
1472 depends.push(L.require(dep, from));
1475 else if (!strictmatch.exec(s)) {
1482 else if (quote == -1 && (chr == 34 || chr == 39)) {
1488 /* load dependencies and instantiate class */
1489 return Promise.all(depends).then(function(instances) {
1490 var _factory, _class;
1494 '(function(window
, document
, L
%s
) { %s
})\n\n//# sourceURL=%s\n'
1495 .format(args
, source
, res
.url
));
1498 L
.raise('SyntaxError', '%s\n in %s:%s',
1499 error
.message
, res
.url
, error
.lineNumber
|| '?');
1502 _factory
.displayName
= toCamelCase(name
+ 'ClassFactory');
1503 _class
= _factory
.apply(_factory
, [window
, document
, L
].concat(instances
));
1505 if (!Class
.isSubclass(_class
))
1506 L
.error('TypeError', '"%s" factory yields invalid constructor', name
);
1508 if (_class
.displayName
== 'AnonymousClass')
1509 _class
.displayName
= toCamelCase(name
+ 'Class');
1511 var ptr
= Object
.getPrototypeOf(L
),
1512 parts
= name
.split(/\./),
1513 instance
= new _class();
1515 for (var i
= 0; ptr
&& i
< parts
.length
- 1; i
++)
1516 ptr
= ptr
[parts
[i
]];
1519 ptr
[parts
[i
]] = instance
;
1521 classes
[name
] = instance
;
1527 /* Request class file */
1528 classes
[name
] = Request
.get(url
, { cache
: true }).then(compileClass
);
1530 return classes
[name
];
1534 probeRPCBaseURL: function() {
1535 if (rpcBaseURL
== null) {
1537 rpcBaseURL
= window
.sessionStorage
.getItem('rpcBaseURL');
1542 if (rpcBaseURL
== null) {
1543 var rpcFallbackURL
= this.url('admin/ubus');
1545 rpcBaseURL
= Request
.get(this.env
.ubuspath
).then(function(res
) {
1546 return (rpcBaseURL
= (res
.status
== 400) ? L
.env
.ubuspath
: rpcFallbackURL
);
1548 return (rpcBaseURL
= rpcFallbackURL
);
1549 }).then(function(url
) {
1551 window
.sessionStorage
.setItem('rpcBaseURL', url
);
1559 return Promise
.resolve(rpcBaseURL
);
1562 probeSystemFeatures: function() {
1563 var sessionid
= classes
.rpc
.getSessionID();
1565 if (sysFeatures
== null) {
1567 var data
= JSON
.parse(window
.sessionStorage
.getItem('sysFeatures'));
1569 if (this.isObject(data
) && this.isObject(data
[sessionid
]))
1570 sysFeatures
= data
[sessionid
];
1575 if (!this.isObject(sysFeatures
)) {
1576 sysFeatures
= classes
.rpc
.declare({
1578 method
: 'getFeatures',
1580 })().then(function(features
) {
1583 data
[sessionid
] = features
;
1585 window
.sessionStorage
.setItem('sysFeatures', JSON
.stringify(data
));
1589 sysFeatures
= features
;
1595 return Promise
.resolve(sysFeatures
);
1599 * Test whether a particular system feature is available, such as
1600 * hostapd SAE support or an installed firewall. The features are
1601 * queried once at the beginning of the LuCI session and cached in
1602 * `SessionStorage` throughout the lifetime of the associated tab or
1608 * @param {string} feature
1609 * The feature to test. For detailed list of known feature flags,
1610 * see `/modules/luci-base/root/usr/libexec/rpcd/luci`.
1612 * @param {string} [subfeature]
1613 * Some feature classes like `hostapd` provide sub-feature flags,
1614 * such as `sae` or `11w` support. The `subfeature` argument can
1615 * be used to query these.
1617 * @return {boolean|null}
1618 * Return `true` if the queried feature (and sub-feature) is available
1619 * or `false` if the requested feature isn't present or known.
1620 * Return `null` when a sub-feature was queried for a feature which
1621 * has no sub-features.
1623 hasSystemFeature: function() {
1624 var ft
= sysFeatures
[arguments
[0]];
1626 if (arguments
.length
== 2)
1627 return this.isObject(ft
) ? ft
[arguments
[1]] : null;
1629 return (ft
!= null && ft
!= false);
1633 notifySessionExpiry: function() {
1636 L
.ui
.showModal(_('Session expired'), [
1637 E('div', { class: 'alert-message warning' },
1638 _('A new login is required since the authentication session expired.')),
1639 E('div', { class: 'right' },
1641 class: 'btn primary',
1643 var loc
= window
.location
;
1644 window
.location
= loc
.protocol
+ '//' + loc
.host
+ loc
.pathname
+ loc
.search
;
1646 }, _('To login…')))
1649 L
.raise('SessionError', 'Login session is expired');
1653 setupDOM: function(res
) {
1658 rpcBaseURL
= res
[4];
1660 rpcClass
.setBaseURL(rpcBaseURL
);
1662 rpcClass
.addInterceptor(function(msg
, req
) {
1663 if (!L
.isObject(msg
) || !L
.isObject(msg
.error
) || msg
.error
.code
!= -32002)
1666 if (!L
.isObject(req
) || (req
.object
== 'session' && req
.method
== 'access'))
1669 return rpcClass
.declare({
1670 'object': 'session',
1672 'params': [ 'scope', 'object', 'function' ],
1673 'expect': { access
: true }
1674 })('uci', 'luci', 'read').catch(L
.notifySessionExpiry
);
1677 Request
.addInterceptor(function(res
) {
1678 var isDenied
= false;
1680 if (res
.status
== 403 && res
.headers
.get('X-LuCI-Login-Required') == 'yes')
1686 L
.notifySessionExpiry();
1689 return this.probeSystemFeatures().finally(this.initDOM
);
1693 initDOM: function() {
1696 document
.dispatchEvent(new CustomEvent('luci-loaded'));
1700 * The `env` object holds environment settings used by LuCI, such
1701 * as request timeouts, base URLs etc.
1709 * Construct a relative URL path from the given prefix and parts.
1710 * The resulting URL is guaranteed to only contain the characters
1711 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1712 * as `/` for the path separator.
1717 * @param {string} [prefix]
1718 * The prefix to join the given parts with. If the `prefix` is
1719 * omitted, it defaults to an empty string.
1721 * @param {string[]} [parts]
1722 * An array of parts to join into an URL path. Parts may contain
1723 * slashes and any of the other characters mentioned above.
1726 * Return the joined URL path.
1728 path: function(prefix
, parts
) {
1729 var url
= [ prefix
|| '' ];
1731 for (var i
= 0; i
< parts
.length
; i
++)
1732 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts
[i
]))
1733 url
.push('/', parts
[i
]);
1735 if (url
.length
=== 1)
1738 return url
.join('');
1742 * Construct an URL pathrelative to the script path of the server
1743 * side LuCI application (usually `/cgi-bin/luci`).
1745 * The resulting URL is guaranteed to only contain the characters
1746 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1747 * as `/` for the path separator.
1752 * @param {string[]} [parts]
1753 * An array of parts to join into an URL path. Parts may contain
1754 * slashes and any of the other characters mentioned above.
1757 * Returns the resulting URL path.
1760 return this.path(this.env
.scriptname
, arguments
);
1764 * Construct an URL path relative to the global static resource path
1765 * of the LuCI ui (usually `/luci-static/resources`).
1767 * The resulting URL is guaranteed to only contain the characters
1768 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1769 * as `/` for the path separator.
1774 * @param {string[]} [parts]
1775 * An array of parts to join into an URL path. Parts may contain
1776 * slashes and any of the other characters mentioned above.
1779 * Returns the resulting URL path.
1781 resource: function() {
1782 return this.path(this.env
.resource
, arguments
);
1786 * Construct an URL path relative to the media resource path of the
1787 * LuCI ui (usually `/luci-static/$theme_name`).
1789 * The resulting URL is guaranteed to only contain the characters
1790 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
1791 * as `/` for the path separator.
1796 * @param {string[]} [parts]
1797 * An array of parts to join into an URL path. Parts may contain
1798 * slashes and any of the other characters mentioned above.
1801 * Returns the resulting URL path.
1804 return this.path(this.env
.media
, arguments
);
1808 * Return the complete URL path to the current view.
1814 * Returns the URL path to the current view.
1816 location: function() {
1817 return this.path(this.env
.scriptname
, this.env
.requestpath
);
1822 * Tests whether the passed argument is a JavaScript object.
1823 * This function is meant to be an object counterpart to the
1824 * standard `Array.isArray()` function.
1833 * Returns `true` if the given value is of type object and
1834 * not `null`, else returns `false`.
1836 isObject: function(val
) {
1837 return (val
!= null && typeof(val
) == 'object');
1841 * Return an array of sorted object keys, optionally sorted by
1842 * a different key or a different sorting mode.
1847 * @param {object} obj
1848 * The object to extract the keys from. If the given value is
1849 * not an object, the function will return an empty array.
1851 * @param {string} [key]
1852 * Specifies the key to order by. This is mainly useful for
1853 * nested objects of objects or objects of arrays when sorting
1854 * shall not be performed by the primary object keys but by
1855 * some other key pointing to a value within the nested values.
1857 * @param {string} [sortmode]
1858 * May be either `addr` or `num` to override the natural
1859 * lexicographic sorting with a sorting suitable for IP/MAC style
1860 * addresses or numeric values respectively.
1862 * @return {string[]}
1863 * Returns an array containing the sorted keys of the given object.
1865 sortedKeys: function(obj
, key
, sortmode
) {
1866 if (obj
== null || typeof(obj
) != 'object')
1869 return Object
.keys(obj
).map(function(e
) {
1870 var v
= (key
!= null) ? obj
[e
][key
] : e
;
1874 v
= (v
!= null) ? v
.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
1875 function(m0
, m1
) { return ('000' + m1
.toLowerCase()).substr(-4) }) : null;
1879 v
= (v
!= null) ? +v
: null;
1884 }).filter(function(e
) {
1885 return (e
[1] != null);
1886 }).sort(function(a
, b
) {
1887 return (a
[1] > b
[1]);
1888 }).map(function(e
) {
1894 * Converts the given value to an array. If the given value is of
1895 * type array, it is returned as-is, values of type object are
1896 * returned as one-element array containing the object, empty
1897 * strings and `null` values are returned as empty array, all other
1898 * values are converted using `String()`, trimmed, split on white
1899 * space and returned as array.
1905 * The value to convert into an array.
1907 * @return {Array<*>}
1908 * Returns the resulting array.
1910 toArray: function(val
) {
1913 else if (Array
.isArray(val
))
1915 else if (typeof(val
) == 'object')
1918 var s
= String(val
).trim();
1923 return s
.split(/\s+/);
1927 * Returns a promise resolving with either the given value or or with
1928 * the given default in case the input value is a rejecting promise.
1934 * The value to resolve the promise with.
1936 * @param {*} defvalue
1937 * The default value to resolve the promise with in case the given
1938 * input value is a rejecting promise.
1940 * @returns {Promise<*>}
1941 * Returns a new promise resolving either to the given input value or
1942 * to the given default value on error.
1944 resolveDefault: function(value
, defvalue
) {
1945 return Promise
.resolve(value
).catch(function() { return defvalue
});
1949 * The request callback function is invoked whenever an HTTP
1950 * reply to a request made using the `L.get()`, `L.post()` or
1951 * `L.poll()` function is timed out or received successfully.
1956 * @callback LuCI.requestCallbackFn
1957 * @param {XMLHTTPRequest} xhr
1958 * The XMLHTTPRequest instance used to make the request.
1961 * The response JSON if the response could be parsed as such,
1964 * @param {number} duration
1965 * The total duration of the request in milliseconds.
1969 * Issues a GET request to the given url and invokes the specified
1970 * callback function. The function is a wrapper around
1971 * {@link LuCI.Request#request Request.request()}.
1977 * @param {string} url
1978 * The URL to request.
1980 * @param {Object<string, string>} [args]
1981 * Additional query string arguments to append to the URL.
1983 * @param {LuCI.requestCallbackFn} cb
1984 * The callback function to invoke when the request finishes.
1986 * @return {Promise<null>}
1987 * Returns a promise resolving to `null` when concluded.
1989 get: function(url
, args
, cb
) {
1990 return this.poll(null, url
, args
, cb
, false);
1994 * Issues a POST request to the given url and invokes the specified
1995 * callback function. The function is a wrapper around
1996 * {@link LuCI.Request#request Request.request()}. The request is
1997 * sent using `application/x-www-form-urlencoded` encoding and will
1998 * contain a field `token` with the current value of `LuCI.env.token`
2005 * @param {string} url
2006 * The URL to request.
2008 * @param {Object<string, string>} [args]
2009 * Additional post arguments to append to the request body.
2011 * @param {LuCI.requestCallbackFn} cb
2012 * The callback function to invoke when the request finishes.
2014 * @return {Promise<null>}
2015 * Returns a promise resolving to `null` when concluded.
2017 post: function(url
, args
, cb
) {
2018 return this.poll(null, url
, args
, cb
, true);
2022 * Register a polling HTTP request that invokes the specified
2023 * callback function. The function is a wrapper around
2024 * {@link LuCI.Request.poll#add Request.poll.add()}.
2030 * @param {number} interval
2031 * The poll interval to use. If set to a value less than or equal
2032 * to `0`, it will default to the global poll interval configured
2033 * in `LuCI.env.pollinterval`.
2035 * @param {string} url
2036 * The URL to request.
2038 * @param {Object<string, string>} [args]
2039 * Specifies additional arguments for the request. For GET requests,
2040 * the arguments are appended to the URL as query string, for POST
2041 * requests, they'll be added to the request body.
2043 * @param {LuCI.requestCallbackFn} cb
2044 * The callback function to invoke whenever a request finishes.
2046 * @param {boolean} [post=false]
2047 * When set to `false` or not specified, poll requests will be made
2048 * using the GET method. When set to `true`, POST requests will be
2049 * issued. In case of POST requests, the request body will contain
2050 * an argument `token` with the current value of `LuCI.env.token` by
2051 * default, regardless of the parameters specified with `args`.
2053 * @return {function}
2054 * Returns the internally created function that has been passed to
2055 * {@link LuCI.Request.poll#add Request.poll.add()}. This value can
2056 * be passed to {@link LuCI.Poll.remove Poll.remove()} to remove the
2059 poll: function(interval
, url
, args
, cb
, post
) {
2060 if (interval
!== null && interval
<= 0)
2061 interval
= this.env
.pollinterval
;
2063 var data
= post
? { token
: this.env
.token
} : null,
2064 method
= post
? 'POST' : 'GET';
2066 if (!/^(?:\/|\S+:\/\/)/.test(url
))
2067 url
= this.url(url
);
2070 data
= Object
.assign(data
|| {}, args
);
2072 if (interval
!== null)
2073 return Request
.poll
.add(interval
, url
, { method
: method
, query
: data
}, cb
);
2075 return Request
.request(url
, { method
: method
, query
: data
})
2076 .then(function(res
) {
2078 if (/^application\/json\b/.test(res
.headers
.get('Content-Type')))
2079 try { json
= res
.json() } catch(e
) {}
2080 cb(res
.xhr
, json
, res
.duration
);
2085 * Deprecated wrapper around {@link LuCI.Poll.remove Poll.remove()}.
2091 * @param {function} entry
2092 * The polling function to remove.
2095 * Returns `true` when the function has been removed or `false` if
2096 * it could not be found.
2098 stop: function(entry
) { return Poll
.remove(entry
) },
2101 * Deprecated wrapper around {@link LuCI.Poll.stop Poll.stop()}.
2108 * Returns `true` when the polling loop has been stopped or `false`
2109 * when it didn't run to begin with.
2111 halt: function() { return Poll
.stop() },
2114 * Deprecated wrapper around {@link LuCI.Poll.start Poll.start()}.
2121 * Returns `true` when the polling loop has been started or `false`
2122 * when it was already running.
2124 run: function() { return Poll
.start() },
2133 * The `dom` class provides convenience method for creating and
2134 * manipulating DOM elements.
2136 dom
: Class
.singleton(/* @lends LuCI.dom.prototype */ {
2137 __name__
: 'LuCI.DOM',
2140 * Tests whether the given argument is a valid DOM `Node`.
2143 * @memberof LuCI.dom
2145 * The value to test.
2147 * @returns {boolean}
2148 * Returns `true` if the value is a DOM `Node`, else `false`.
2151 return (e
!= null && typeof(e
) == 'object' && 'nodeType' in e
);
2155 * Parses a given string as HTML and returns the first child node.
2158 * @memberof LuCI.dom
2160 * A string containing an HTML fragment to parse. Note that only
2161 * the first result of the resulting structure is returned, so an
2162 * input value of `<div>foo</div> <div>bar</div>` will only return
2163 * the first `div` element node.
2166 * Returns the first DOM `Node` extracted from the HTML fragment or
2167 * `null` on parsing failures or if no element could be found.
2169 parse: function(s
) {
2173 domParser
= domParser
|| new DOMParser();
2174 elem
= domParser
.parseFromString(s
, 'text/html').body
.firstChild
;
2180 dummyElem
= dummyElem
|| document
.createElement('div');
2181 dummyElem
.innerHTML
= s
;
2182 elem
= dummyElem
.firstChild
;
2187 return elem
|| null;
2191 * Tests whether a given `Node` matches the given query selector.
2193 * This function is a convenience wrapper around the standard
2194 * `Node.matches("selector")` function with the added benefit that
2195 * the `node` argument may be a non-`Node` value, in which case
2196 * this function simply returns `false`.
2199 * @memberof LuCI.dom
2201 * The `Node` argument to test the selector against.
2203 * @param {string} [selector]
2204 * The query selector expression to test against the given node.
2206 * @returns {boolean}
2207 * Returns `true` if the given node matches the specified selector
2208 * or `false` when the node argument is no valid DOM `Node` or the
2209 * selector didn't match.
2211 matches: function(node
, selector
) {
2212 var m
= this.elem(node
) ? node
.matches
|| node
.msMatchesSelector
: null;
2213 return m
? m
.call(node
, selector
) : false;
2217 * Returns the closest parent node that matches the given query
2218 * selector expression.
2220 * This function is a convenience wrapper around the standard
2221 * `Node.closest("selector")` function with the added benefit that
2222 * the `node` argument may be a non-`Node` value, in which case
2223 * this function simply returns `null`.
2226 * @memberof LuCI.dom
2228 * The `Node` argument to find the closest parent for.
2230 * @param {string} [selector]
2231 * The query selector expression to test against each parent.
2233 * @returns {Node|null}
2234 * Returns the closest parent node matching the selector or
2235 * `null` when the node argument is no valid DOM `Node` or the
2236 * selector didn't match any parent.
2238 parent: function(node
, selector
) {
2239 if (this.elem(node
) && node
.closest
)
2240 return node
.closest(selector
);
2242 while (this.elem(node
))
2243 if (this.matches(node
, selector
))
2246 node
= node
.parentNode
;
2252 * Appends the given children data to the given node.
2255 * @memberof LuCI.dom
2257 * The `Node` argument to append the children to.
2259 * @param {*} [children]
2260 * The childrens to append to the given node.
2262 * When `children` is an array, then each item of the array
2263 * will be either appended as child element or text node,
2264 * depending on whether the item is a DOM `Node` instance or
2265 * some other non-`null` value. Non-`Node`, non-`null` values
2266 * will be converted to strings first before being passed as
2267 * argument to `createTextNode()`.
2269 * When `children` is a function, it will be invoked with
2270 * the passed `node` argument as sole parameter and the `append`
2271 * function will be invoked again, with the given `node` argument
2272 * as first and the return value of the `children` function as
2275 * When `children` is is a DOM `Node` instance, it will be
2276 * appended to the given `node`.
2278 * When `children` is any other non-`null` value, it will be
2279 * converted to a string and appened to the `innerHTML` property
2280 * of the given `node`.
2282 * @returns {Node|null}
2283 * Returns the last children `Node` appended to the node or `null`
2284 * if either the `node` argument was no valid DOM `node` or if the
2285 * `children` was `null` or didn't result in further DOM nodes.
2287 append: function(node
, children
) {
2288 if (!this.elem(node
))
2291 if (Array
.isArray(children
)) {
2292 for (var i
= 0; i
< children
.length
; i
++)
2293 if (this.elem(children
[i
]))
2294 node
.appendChild(children
[i
]);
2295 else if (children
!== null && children
!== undefined)
2296 node
.appendChild(document
.createTextNode('' + children
[i
]));
2298 return node
.lastChild
;
2300 else if (typeof(children
) === 'function') {
2301 return this.append(node
, children(node
));
2303 else if (this.elem(children
)) {
2304 return node
.appendChild(children
);
2306 else if (children
!== null && children
!== undefined) {
2307 node
.innerHTML
= '' + children
;
2308 return node
.lastChild
;
2315 * Replaces the content of the given node with the given children.
2317 * This function first removes any children of the given DOM
2318 * `Node` and then adds the given given children following the
2319 * rules outlined below.
2322 * @memberof LuCI.dom
2324 * The `Node` argument to replace the children of.
2326 * @param {*} [children]
2327 * The childrens to replace into the given node.
2329 * When `children` is an array, then each item of the array
2330 * will be either appended as child element or text node,
2331 * depending on whether the item is a DOM `Node` instance or
2332 * some other non-`null` value. Non-`Node`, non-`null` values
2333 * will be converted to strings first before being passed as
2334 * argument to `createTextNode()`.
2336 * When `children` is a function, it will be invoked with
2337 * the passed `node` argument as sole parameter and the `append`
2338 * function will be invoked again, with the given `node` argument
2339 * as first and the return value of the `children` function as
2342 * When `children` is is a DOM `Node` instance, it will be
2343 * appended to the given `node`.
2345 * When `children` is any other non-`null` value, it will be
2346 * converted to a string and appened to the `innerHTML` property
2347 * of the given `node`.
2349 * @returns {Node|null}
2350 * Returns the last children `Node` appended to the node or `null`
2351 * if either the `node` argument was no valid DOM `node` or if the
2352 * `children` was `null` or didn't result in further DOM nodes.
2354 content: function(node
, children
) {
2355 if (!this.elem(node
))
2358 var dataNodes
= node
.querySelectorAll('[data-idref]');
2360 for (var i
= 0; i
< dataNodes
.length
; i
++)
2361 delete this.registry
[dataNodes
[i
].getAttribute('data-idref')];
2363 while (node
.firstChild
)
2364 node
.removeChild(node
.firstChild
);
2366 return this.append(node
, children
);
2370 * Sets attributes or registers event listeners on element nodes.
2373 * @memberof LuCI.dom
2375 * The `Node` argument to set the attributes or add the event
2376 * listeners for. When the given `node` value is not a valid
2377 * DOM `Node`, the function returns and does nothing.
2379 * @param {string|Object<string, *>} key
2380 * Specifies either the attribute or event handler name to use,
2381 * or an object containing multiple key, value pairs which are
2382 * each added to the node as either attribute or event handler,
2383 * depending on the respective value.
2386 * Specifies the attribute value or event handler function to add.
2387 * If the `key` parameter is an `Object`, this parameter will be
2390 * When `val` is of type function, it will be registered as event
2391 * handler on the given `node` with the `key` parameter being the
2394 * When `val` is of type object, it will be serialized as JSON and
2395 * added as attribute to the given `node`, using the given `key`
2396 * as attribute name.
2398 * When `val` is of any other type, it will be added as attribute
2399 * to the given `node` as-is, with the underlying `setAttribute()`
2400 * call implicitely turning it into a string.
2402 attr: function(node
, key
, val
) {
2403 if (!this.elem(node
))
2408 if (typeof(key
) === 'object' && key
!== null)
2410 else if (typeof(key
) === 'string')
2411 attr
= {}, attr
[key
] = val
;
2414 if (!attr
.hasOwnProperty(key
) || attr
[key
] == null)
2417 switch (typeof(attr
[key
])) {
2419 node
.addEventListener(key
, attr
[key
]);
2423 node
.setAttribute(key
, JSON
.stringify(attr
[key
]));
2427 node
.setAttribute(key
, attr
[key
]);
2433 * Creates a new DOM `Node` from the given `html`, `attr` and
2434 * `data` parameters.
2436 * This function has multiple signatures, it can be either invoked
2437 * in the form `create(html[, attr[, data]])` or in the form
2438 * `create(html[, data])`. The used variant is determined from the
2439 * type of the second argument.
2442 * @memberof LuCI.dom
2444 * Describes the node to create.
2446 * When the value of `html` is of type array, a `DocumentFragment`
2447 * node is created and each item of the array is first converted
2448 * to a DOM `Node` by passing it through `create()` and then added
2449 * as child to the fragment.
2451 * When the value of `html` is a DOM `Node` instance, no new
2452 * element will be created but the node will be used as-is.
2454 * When the value of `html` is a string starting with `<`, it will
2455 * be passed to `dom.parse()` and the resulting value is used.
2457 * When the value of `html` is any other string, it will be passed
2458 * to `document.createElement()` for creating a new DOM `Node` of
2461 * @param {Object<string, *>} [attr]
2462 * Specifies an Object of key, value pairs to set as attributes
2463 * or event handlers on the created node. Refer to
2464 * {@link LuCI.dom#attr dom.attr()} for details.
2467 * Specifies children to append to the newly created element.
2468 * Refer to {@link LuCI.dom#append dom.append()} for details.
2470 * @throws {InvalidCharacterError}
2471 * Throws an `InvalidCharacterError` when the given `html`
2472 * argument contained malformed markup (such as not escaped
2473 * `&` characters in XHTML mode) or when the given node name
2474 * in `html` contains characters which are not legal in DOM
2475 * element names, such as spaces.
2478 * Returns the newly created `Node`.
2480 create: function() {
2481 var html
= arguments
[0],
2482 attr
= arguments
[1],
2483 data
= arguments
[2],
2486 if (!(attr
instanceof Object
) || Array
.isArray(attr
))
2487 data
= attr
, attr
= null;
2489 if (Array
.isArray(html
)) {
2490 elem
= document
.createDocumentFragment();
2491 for (var i
= 0; i
< html
.length
; i
++)
2492 elem
.appendChild(this.create(html
[i
]));
2494 else if (this.elem(html
)) {
2497 else if (html
.charCodeAt(0) === 60) {
2498 elem
= this.parse(html
);
2501 elem
= document
.createElement(html
);
2507 this.attr(elem
, attr
);
2508 this.append(elem
, data
);
2516 * Attaches or detaches arbitrary data to and from a DOM `Node`.
2518 * This function is useful to attach non-string values or runtime
2519 * data that is not serializable to DOM nodes. To decouple data
2520 * from the DOM, values are not added directly to nodes, but
2521 * inserted into a registry instead which is then referenced by a
2522 * string key stored as `data-idref` attribute in the node.
2524 * This function has multiple signatures and is sensitive to the
2525 * number of arguments passed to it.
2527 * - `dom.data(node)` -
2528 * Fetches all data associated with the given node.
2529 * - `dom.data(node, key)` -
2530 * Fetches a specific key associated with the given node.
2531 * - `dom.data(node, key, val)` -
2532 * Sets a specific key to the given value associated with the
2534 * - `dom.data(node, null)` -
2535 * Clears any data associated with the node.
2536 * - `dom.data(node, key, null)` -
2537 * Clears the given key associated with the node.
2540 * @memberof LuCI.dom
2541 * @param {Node} node
2542 * The DOM `Node` instance to set or retrieve the data for.
2544 * @param {string|null} [key]
2545 * This is either a string specifying the key to retrieve, or
2546 * `null` to unset the entire node data.
2548 * @param {*|null} [val]
2549 * This is either a non-`null` value to set for a given key or
2550 * `null` to remove the given `key` from the specified node.
2553 * Returns the get or set value, or `null` when no value could
2556 data: function(node
, key
, val
) {
2557 if (!node
|| !node
.getAttribute
)
2560 var id
= node
.getAttribute('data-idref');
2562 /* clear all data */
2563 if (arguments
.length
> 1 && key
== null) {
2565 node
.removeAttribute('data-idref');
2566 val
= this.registry
[id
]
2567 delete this.registry
[id
];
2575 else if (arguments
.length
> 2 && key
!= null && val
== null) {
2577 val
= this.registry
[id
][key
];
2578 delete this.registry
[id
][key
];
2586 else if (arguments
.length
> 2 && key
!= null && val
!= null) {
2588 do { id
= Math
.floor(Math
.random() * 0xffffffff).toString(16) }
2589 while (this.registry
.hasOwnProperty(id
));
2591 node
.setAttribute('data-idref', id
);
2592 this.registry
[id
] = {};
2595 return (this.registry
[id
][key
] = val
);
2599 else if (arguments
.length
== 1) {
2601 return this.registry
[id
];
2607 else if (arguments
.length
== 2) {
2609 return this.registry
[id
][key
];
2616 * Binds the given class instance ot the specified DOM `Node`.
2618 * This function uses the `dom.data()` facility to attach the
2619 * passed instance of a Class to a node. This is needed for
2620 * complex widget elements or similar where the corresponding
2621 * class instance responsible for the element must be retrieved
2622 * from DOM nodes obtained by `querySelector()` or similar means.
2625 * @memberof LuCI.dom
2626 * @param {Node} node
2627 * The DOM `Node` instance to bind the class to.
2629 * @param {Class} inst
2630 * The Class instance to bind to the node.
2632 * @throws {TypeError}
2633 * Throws a `TypeError` when the given instance argument isn't
2634 * a valid Class instance.
2637 * Returns the bound class instance.
2639 bindClassInstance: function(node
, inst
) {
2640 if (!(inst
instanceof Class
))
2641 L
.error('TypeError', 'Argument must be a class instance');
2643 return this.data(node
, '_class', inst
);
2647 * Finds a bound class instance on the given node itself or the
2648 * first bound instance on its closest parent node.
2651 * @memberof LuCI.dom
2652 * @param {Node} node
2653 * The DOM `Node` instance to start from.
2655 * @returns {Class|null}
2656 * Returns the founds class instance if any or `null` if no bound
2657 * class could be found on the node itself or any of its parents.
2659 findClassInstance: function(node
) {
2663 inst
= this.data(node
, '_class');
2664 node
= node
.parentNode
;
2666 while (!(inst
instanceof Class
) && node
!= null);
2672 * Finds a bound class instance on the given node itself or the
2673 * first bound instance on its closest parent node and invokes
2674 * the specified method name on the found class instance.
2677 * @memberof LuCI.dom
2678 * @param {Node} node
2679 * The DOM `Node` instance to start from.
2681 * @param {string} method
2682 * The name of the method to invoke on the found class instance.
2684 * @param {...*} params
2685 * Additional arguments to pass to the invoked method as-is.
2688 * Returns the return value of the invoked method if a class
2689 * instance and method has been found. Returns `null` if either
2690 * no bound class instance could be found, or if the found
2691 * instance didn't have the requested `method`.
2693 callClassMethod: function(node
, method
/*, ... */) {
2694 var inst
= this.findClassInstance(node
);
2696 if (inst
== null || typeof(inst
[method
]) != 'function')
2699 return inst
[method
].apply(inst
, inst
.varargs(arguments
, 2));
2703 * The ignore callback function is invoked by `isEmpty()` for each
2704 * child node to decide whether to ignore a child node or not.
2706 * When this function returns `false`, the node passed to it is
2707 * ignored, else not.
2709 * @callback LuCI.dom~ignoreCallbackFn
2710 * @param {Node} node
2711 * The child node to test.
2713 * @returns {boolean}
2714 * Boolean indicating whether to ignore the node or not.
2718 * Tests whether a given DOM `Node` instance is empty or appears
2721 * Any element child nodes which have the CSS class `hidden` set
2722 * or for which the optionally passed `ignoreFn` callback function
2723 * returns `false` are ignored.
2726 * @memberof LuCI.dom
2727 * @param {Node} node
2728 * The DOM `Node` instance to test.
2730 * @param {LuCI.dom~ignoreCallbackFn} [ignoreFn]
2731 * Specifies an optional function which is invoked for each child
2732 * node to decide whether the child node should be ignored or not.
2734 * @returns {boolean}
2735 * Returns `true` if the node does not have any children or if
2736 * any children node either has a `hidden` CSS class or a `false`
2737 * result when testing it using the given `ignoreFn`.
2739 isEmpty: function(node
, ignoreFn
) {
2740 for (var child
= node
.firstElementChild
; child
!= null; child
= child
.nextElementSibling
)
2741 if (!child
.classList
.contains('hidden') && (!ignoreFn
|| !ignoreFn(child
)))
2758 * The `view` class forms the basis of views and provides a standard
2759 * set of methods to inherit from.
2761 view
: Class
.extend(/* @lends LuCI.view.prototype */ {
2762 __name__
: 'LuCI.View',
2764 __init__: function() {
2765 var vp
= document
.getElementById('view');
2767 L
.dom
.content(vp
, E('div', { 'class': 'spinning' }, _('Loading view…')));
2769 return Promise
.resolve(this.load())
2770 .then(L
.bind(this.render
, this))
2771 .then(L
.bind(function(nodes
) {
2772 var vp
= document
.getElementById('view');
2774 L
.dom
.content(vp
, nodes
);
2775 L
.dom
.append(vp
, this.addFooter());
2776 }, this)).catch(L
.error
);
2780 * The load function is invoked before the view is rendered.
2782 * The invocation of this function is wrapped by
2783 * `Promise.resolve()` so it may return Promises if needed.
2785 * The return value of the function (or the resolved values
2786 * of the promise returned by it) will be passed as first
2787 * argument to `render()`.
2789 * This function is supposed to be overwritten by subclasses,
2790 * the default implementation does nothing.
2794 * @memberof LuCI.view
2796 * @returns {*|Promise<*>}
2797 * May return any value or a Promise resolving to any value.
2799 load: function() {},
2802 * The render function is invoked after the
2803 * {@link LuCI.view#load load()} function and responsible
2804 * for setting up the view contents. It must return a DOM
2805 * `Node` or `DocumentFragment` holding the contents to
2806 * insert into the view area.
2808 * The invocation of this function is wrapped by
2809 * `Promise.resolve()` so it may return Promises if needed.
2811 * The return value of the function (or the resolved values
2812 * of the promise returned by it) will be inserted into the
2813 * main content area using
2814 * {@link LuCI.dom#append dom.append()}.
2816 * This function is supposed to be overwritten by subclasses,
2817 * the default implementation does nothing.
2821 * @memberof LuCI.view
2822 * @param {*|null} load_results
2823 * This function will receive the return value of the
2824 * {@link LuCI.view#load view.load()} function as first
2827 * @returns {Node|Promise<Node>}
2828 * Should return a DOM `Node` value or a `Promise` resolving
2829 * to a `Node` value.
2831 render: function() {},
2834 * The handleSave function is invoked when the user clicks
2835 * the `Save` button in the page action footer.
2837 * The default implementation should be sufficient for most
2838 * views using {@link form#Map form.Map()} based forms - it
2839 * will iterate all forms present in the view and invoke
2840 * the {@link form#Map#save Map.save()} method on each form.
2842 * Views not using `Map` instances or requiring other special
2843 * logic should overwrite `handleSave()` with a custom
2846 * To disable the `Save` page footer button, views extending
2847 * this base class should overwrite the `handleSave` function
2850 * The invocation of this function is wrapped by
2851 * `Promise.resolve()` so it may return Promises if needed.
2854 * @memberof LuCI.view
2856 * The DOM event that triggered the function.
2858 * @returns {*|Promise<*>}
2859 * Any return values of this function are discarded, but
2860 * passed through `Promise.resolve()` to ensure that any
2861 * returned promise runs to completion before the button
2864 handleSave: function(ev
) {
2867 document
.getElementById('maincontent')
2868 .querySelectorAll('.cbi-map').forEach(function(map
) {
2869 tasks
.push(L
.dom
.callClassMethod(map
, 'save'));
2872 return Promise
.all(tasks
);
2876 * The handleSaveApply function is invoked when the user clicks
2877 * the `Save & Apply` button in the page action footer.
2879 * The default implementation should be sufficient for most
2880 * views using {@link form#Map form.Map()} based forms - it
2882 * {@link LuCI.view.handleSave view.handleSave()} and then
2883 * call {@link ui#changes#apply ui.changes.apply()} to start the
2884 * modal config apply and page reload flow.
2886 * Views not using `Map` instances or requiring other special
2887 * logic should overwrite `handleSaveApply()` with a custom
2890 * To disable the `Save & Apply` page footer button, views
2891 * extending this base class should overwrite the
2892 * `handleSaveApply` function with `null`.
2894 * The invocation of this function is wrapped by
2895 * `Promise.resolve()` so it may return Promises if needed.
2898 * @memberof LuCI.view
2900 * The DOM event that triggered the function.
2902 * @returns {*|Promise<*>}
2903 * Any return values of this function are discarded, but
2904 * passed through `Promise.resolve()` to ensure that any
2905 * returned promise runs to completion before the button
2908 handleSaveApply: function(ev
, mode
) {
2909 return this.handleSave(ev
).then(function() {
2910 L
.ui
.changes
.apply(mode
== '0');
2915 * The handleReset function is invoked when the user clicks
2916 * the `Reset` button in the page action footer.
2918 * The default implementation should be sufficient for most
2919 * views using {@link form#Map form.Map()} based forms - it
2920 * will iterate all forms present in the view and invoke
2921 * the {@link form#Map#save Map.reset()} method on each form.
2923 * Views not using `Map` instances or requiring other special
2924 * logic should overwrite `handleReset()` with a custom
2927 * To disable the `Reset` page footer button, views extending
2928 * this base class should overwrite the `handleReset` function
2931 * The invocation of this function is wrapped by
2932 * `Promise.resolve()` so it may return Promises if needed.
2935 * @memberof LuCI.view
2937 * The DOM event that triggered the function.
2939 * @returns {*|Promise<*>}
2940 * Any return values of this function are discarded, but
2941 * passed through `Promise.resolve()` to ensure that any
2942 * returned promise runs to completion before the button
2945 handleReset: function(ev
) {
2948 document
.getElementById('maincontent')
2949 .querySelectorAll('.cbi-map').forEach(function(map
) {
2950 tasks
.push(L
.dom
.callClassMethod(map
, 'reset'));
2953 return Promise
.all(tasks
);
2957 * Renders a standard page action footer if any of the
2958 * `handleSave()`, `handleSaveApply()` or `handleReset()`
2959 * functions are defined.
2961 * The default implementation should be sufficient for most
2962 * views - it will render a standard page footer with action
2963 * buttons labeled `Save`, `Save & Apply` and `Reset`
2964 * triggering the `handleSave()`, `handleSaveApply()` and
2965 * `handleReset()` functions respectively.
2967 * When any of these `handle*()` functions is overwritten
2968 * with `null` by a view extending this class, the
2969 * corresponding button will not be rendered.
2972 * @memberof LuCI.view
2973 * @returns {DocumentFragment}
2974 * Returns a `DocumentFragment` containing the footer bar
2975 * with buttons for each corresponding `handle*()` action
2976 * or an empty `DocumentFragment` if all three `handle*()`
2977 * methods are overwritten with `null`.
2979 addFooter: function() {
2982 var saveApplyBtn
= this.handleSaveApply
? new L
.ui
.ComboButton('0', {
2983 0: [ _('Save & Apply') ],
2984 1: [ _('Apply unchecked') ]
2987 0: 'cbi-button cbi-button-apply important',
2988 1: 'cbi-button cbi-button-negative important'
2990 click
: L
.ui
.createHandlerFn(this, 'handleSaveApply')
2991 }).render() : E([]);
2993 if (this.handleSaveApply
|| this.handleSave
|| this.handleReset
) {
2994 footer
.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
2996 this.handleSave
? E('button', {
2997 'class': 'cbi-button cbi-button-save',
2998 'click': L
.ui
.createHandlerFn(this, 'handleSave')
2999 }, [ _('Save') ]) : '', ' ',
3000 this.handleReset
? E('button', {
3001 'class': 'cbi-button cbi-button-reset',
3002 'click': L
.ui
.createHandlerFn(this, 'handleReset')
3003 }, [ _('Reset') ]) : ''
3018 * The `LuCI.XHR` class is a legacy compatibility shim for the
3019 * functionality formerly provided by `xhr.js`. It is registered as global
3020 * `window.XHR` symbol for compatibility with legacy code.
3022 * New code should use {@link LuCI.Request} instead to implement HTTP
3025 var XHR
= Class
.extend(/** @lends LuCI.XHR.prototype */ {
3026 __name__
: 'LuCI.XHR',
3027 __init__: function() {
3028 if (window
.console
&& console
.debug
)
3029 console
.debug('Direct use XHR() is deprecated, please use L.Request instead');
3032 _response: function(cb
, res
, json
, duration
) {
3034 cb(res
, json
, duration
);
3039 * This function is a legacy wrapper around
3040 * {@link LuCI#get LuCI.get()}.
3044 * @memberof LuCI.XHR
3046 * @param {string} url
3047 * The URL to request
3049 * @param {Object} [data]
3050 * Additional query string data
3052 * @param {LuCI.requestCallbackFn} [callback]
3053 * Callback function to invoke on completion
3055 * @param {number} [timeout]
3056 * Request timeout to use
3058 * @return {Promise<null>}
3060 get: function(url
, data
, callback
, timeout
) {
3062 L
.get(url
, data
, this._response
.bind(this, callback
), timeout
);
3066 * This function is a legacy wrapper around
3067 * {@link LuCI#post LuCI.post()}.
3071 * @memberof LuCI.XHR
3073 * @param {string} url
3074 * The URL to request
3076 * @param {Object} [data]
3077 * Additional data to append to the request body.
3079 * @param {LuCI.requestCallbackFn} [callback]
3080 * Callback function to invoke on completion
3082 * @param {number} [timeout]
3083 * Request timeout to use
3085 * @return {Promise<null>}
3087 post: function(url
, data
, callback
, timeout
) {
3089 L
.post(url
, data
, this._response
.bind(this, callback
), timeout
);
3093 * Cancels a running request.
3095 * This function does not actually cancel the underlying
3096 * `XMLHTTPRequest` request but it sets a flag which prevents the
3097 * invocation of the callback function when the request eventually
3098 * finishes or timed out.
3102 * @memberof LuCI.XHR
3104 cancel: function() { delete this.active
},
3107 * Checks the running state of the request.
3111 * @memberof LuCI.XHR
3113 * @returns {boolean}
3114 * Returns `true` if the request is still running or `false` if it
3115 * already completed.
3117 busy: function() { return (this.active
=== true) },
3120 * Ignored for backwards compatibility.
3122 * This function does nothing.
3126 * @memberof LuCI.XHR
3128 abort: function() {},
3131 * Existing for backwards compatibility.
3133 * This function simply throws an `InternalError` when invoked.
3137 * @memberof LuCI.XHR
3139 * @throws {InternalError}
3140 * Throws an `InternalError` with the message `Not implemented`
3143 send_form: function() { L
.error('InternalError', 'Not implemented') },
3146 XHR
.get = function() { return window
.L
.get.apply(window
.L
, arguments
) };
3147 XHR
.post = function() { return window
.L
.post
.apply(window
.L
, arguments
) };
3148 XHR
.poll = function() { return window
.L
.poll
.apply(window
.L
, arguments
) };
3149 XHR
.stop
= Request
.poll
.remove
.bind(Request
.poll
);
3150 XHR
.halt
= Request
.poll
.stop
.bind(Request
.poll
);
3151 XHR
.run
= Request
.poll
.start
.bind(Request
.poll
);
3152 XHR
.running
= Request
.poll
.active
.bind(Request
.poll
);
3156 })(window
, document
);