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) {
17 /* Object.assign polyfill for IE */
18 if (typeof Object
.assign
!== 'function') {
19 Object
.defineProperty(Object
, 'assign', {
20 value
: function assign(target
, varArgs
) {
22 throw new TypeError('Cannot convert undefined or null to object');
24 var to
= Object(target
);
26 for (var index
= 1; index
< arguments
.length
; index
++)
27 if (arguments
[index
] != null)
28 for (var nextKey
in arguments
[index
])
29 if (Object
.prototype.hasOwnProperty
.call(arguments
[index
], nextKey
))
30 to
[nextKey
] = arguments
[index
][nextKey
];
39 /* Promise.finally polyfill */
40 if (typeof Promise
.prototype.finally !== 'function') {
41 Promise
.prototype.finally = function(fn
) {
42 var onFinally = function(cb
) {
43 return Promise
.resolve(fn
.call(this)).then(cb
);
47 function(result
) { return onFinally
.call(this, function() { return result
}) },
48 function(reason
) { return onFinally
.call(this, function() { return Promise
.reject(reason
) }) }
54 * Class declaration and inheritance helper
57 var toCamelCase = function(s
) {
58 return s
.replace(/(?:^|[\. -])(.)/g, function(m0
, m1
) { return m1
.toUpperCase() });
67 * `LuCI.baseclass` is the abstract base class all LuCI classes inherit from.
69 * It provides simple means to create subclasses of given classes and
70 * implements prototypal inheritance.
72 var superContext
= {}, classIndex
= 0, Class
= Object
.assign(function() {}, {
74 * Extends this base class with the properties described in
75 * `properties` and returns a new subclassed Class instance
77 * @memberof LuCI.baseclass
79 * @param {Object<string, *>} properties
80 * An object describing the properties to add to the new
83 * @returns {LuCI.baseclass}
84 * Returns a new LuCI.baseclass sublassed from this class, extended
85 * by the given properties and with its prototype set to this base
86 * class to enable inheritance. The resulting value represents a
87 * class constructor and can be instantiated with `new`.
89 extend: function(properties
) {
91 __id__
: { value
: classIndex
},
92 __base__
: { value
: this.prototype },
93 __name__
: { value
: properties
.__name__
|| 'anonymous' + classIndex
++ }
96 var ClassConstructor = function() {
97 if (!(this instanceof ClassConstructor
))
98 throw new TypeError('Constructor must not be called without "new"');
100 if (Object
.getPrototypeOf(this).hasOwnProperty('__init__')) {
101 if (typeof(this.__init__
) != 'function')
102 throw new TypeError('Class __init__ member is not a function');
104 this.__init__
.apply(this, arguments
)
107 this.super('__init__', arguments
);
111 for (var key
in properties
)
112 if (!props
[key
] && properties
.hasOwnProperty(key
))
113 props
[key
] = { value
: properties
[key
], writable
: true };
115 ClassConstructor
.prototype = Object
.create(this.prototype, props
);
116 ClassConstructor
.prototype.constructor = ClassConstructor
;
117 Object
.assign(ClassConstructor
, this);
118 ClassConstructor
.displayName
= toCamelCase(props
.__name__
.value
+ 'Class');
120 return ClassConstructor
;
124 * Extends this base class with the properties described in
125 * `properties`, instantiates the resulting subclass using
126 * the additional optional arguments passed to this function
127 * and returns the resulting subclassed Class instance.
129 * This function serves as a convenience shortcut for
130 * {@link LuCI.baseclass.extend Class.extend()} and subsequent
133 * @memberof LuCI.baseclass
135 * @param {Object<string, *>} properties
136 * An object describing the properties to add to the new
139 * @param {...*} [new_args]
140 * Specifies arguments to be passed to the subclass constructor
141 * as-is in order to instantiate the new subclass.
143 * @returns {LuCI.baseclass}
144 * Returns a new LuCI.baseclass instance extended by the given
145 * properties with its prototype set to this base class to
146 * enable inheritance.
148 singleton: function(properties
/*, ... */) {
149 return Class
.extend(properties
)
150 .instantiate(Class
.prototype.varargs(arguments
, 1));
154 * Calls the class constructor using `new` with the given argument
155 * array being passed as variadic parameters to the constructor.
157 * @memberof LuCI.baseclass
159 * @param {Array<*>} params
160 * An array of arbitrary values which will be passed as arguments
161 * to the constructor function.
163 * @param {...*} [new_args]
164 * Specifies arguments to be passed to the subclass constructor
165 * as-is in order to instantiate the new subclass.
167 * @returns {LuCI.baseclass}
168 * Returns a new LuCI.baseclass instance extended by the given
169 * properties with its prototype set to this base class to
170 * enable inheritance.
172 instantiate: function(args
) {
173 return new (Function
.prototype.bind
.apply(this,
174 Class
.prototype.varargs(args
, 0, null)))();
178 call: function(self
, method
) {
179 if (typeof(this.prototype[method
]) != 'function')
180 throw new ReferenceError(method
+ ' is not defined in class');
182 return this.prototype[method
].apply(self
, self
.varargs(arguments
, 1));
186 * Checks whether the given class value is a subclass of this class.
188 * @memberof LuCI.baseclass
190 * @param {LuCI.baseclass} classValue
191 * The class object to test.
194 * Returns `true` when the given `classValue` is a subclass of this
195 * class or `false` if the given value is not a valid class or not
196 * a subclass of this class'.
198 isSubclass: function(classValue
) {
199 return (classValue
!= null &&
200 typeof(classValue
) == 'function' &&
201 classValue
.prototype instanceof this);
206 * Extract all values from the given argument array beginning from
207 * `offset` and prepend any further given optional parameters to
208 * the beginning of the resulting array copy.
210 * @memberof LuCI.baseclass
213 * @param {Array<*>} args
214 * The array to extract the values from.
216 * @param {number} offset
217 * The offset from which to extract the values. An offset of `0`
218 * would copy all values till the end.
220 * @param {...*} [extra_args]
221 * Extra arguments to add to prepend to the resultung array.
223 * @returns {Array<*>}
224 * Returns a new array consisting of the optional extra arguments
225 * and the values extracted from the `args` array beginning with
228 varargs: function(args
, offset
/*, ... */) {
229 return Array
.prototype.slice
.call(arguments
, 2)
230 .concat(Array
.prototype.slice
.call(args
, offset
));
234 * Walks up the parent class chain and looks for a class member
235 * called `key` in any of the parent classes this class inherits
236 * from. Returns the member value of the superclass or calls the
237 * member as function and returns its return value when the
238 * optional `callArgs` array is given.
240 * This function has two signatures and is sensitive to the
241 * amount of arguments passed to it:
243 * Returns the value of `key` when found within one of the
245 * - `super('key', ['arg1', 'arg2'])` -
246 * Calls the `key()` method with parameters `arg1` and `arg2`
247 * when found within one of the parent classes.
249 * @memberof LuCI.baseclass
252 * @param {string} key
253 * The name of the superclass member to retrieve.
255 * @param {Array<*>} [callArgs]
256 * An optional array of function call parameters to use. When
257 * this parameter is specified, the found member value is called
258 * as function using the values of this array as arguments.
260 * @throws {ReferenceError}
261 * Throws a `ReferenceError` when `callArgs` are specified and
262 * the found member named by `key` is not a function value.
265 * Returns the value of the found member or the return value of
266 * the call to the found method. Returns `null` when no member
267 * was found in the parent class chain or when the call to the
268 * superclass method returned `null`.
270 super: function(key
, callArgs
) {
274 var slotIdx
= this.__id__
+ '.' + key
,
275 symStack
= superContext
[slotIdx
],
278 for (protoCtx
= Object
.getPrototypeOf(symStack
? symStack
[0] : Object
.getPrototypeOf(this));
279 protoCtx
!= null && !protoCtx
.hasOwnProperty(key
);
280 protoCtx
= Object
.getPrototypeOf(protoCtx
)) {}
282 if (protoCtx
== null)
285 var res
= protoCtx
[key
];
287 if (arguments
.length
> 1) {
288 if (typeof(res
) != 'function')
289 throw new ReferenceError(key
+ ' is not a function in base class');
291 if (typeof(callArgs
) != 'object')
292 callArgs
= this.varargs(arguments
, 1);
295 symStack
.unshift(protoCtx
);
297 superContext
[slotIdx
] = [ protoCtx
];
299 res
= res
.apply(this, callArgs
);
301 if (symStack
&& symStack
.length
> 1)
302 symStack
.shift(protoCtx
);
304 delete superContext
[slotIdx
];
311 * Returns a string representation of this class.
314 * Returns a string representation of this class containing the
315 * constructor functions `displayName` and describing the class
316 * members and their respective types.
318 toString: function() {
319 var s
= '[' + this.constructor.displayName
+ ']', f
= true;
320 for (var k
in this) {
321 if (this.hasOwnProperty(k
)) {
322 s
+= (f
? ' {\n' : '') + ' ' + k
+ ': ' + typeof(this[k
]) + '\n';
326 return s
+ (f
? '' : '}');
338 * The `Headers` class is an internal utility class exposed in HTTP
339 * response objects using the `response.headers` property.
341 var Headers
= Class
.extend(/** @lends LuCI.headers.prototype */ {
342 __name__
: 'LuCI.headers',
343 __init__: function(xhr
) {
344 var hdrs
= this.headers
= {};
345 xhr
.getAllResponseHeaders().split(/\r\n/).forEach(function(line
) {
346 var m
= /^([^:]+):(.*)$/.exec(line
);
348 hdrs
[m
[1].trim().toLowerCase()] = m
[2].trim();
353 * Checks whether the given header name is present.
354 * Note: Header-Names are case-insensitive.
357 * @memberof LuCI.headers
358 * @param {string} name
359 * The header name to check
362 * Returns `true` if the header name is present, `false` otherwise
364 has: function(name
) {
365 return this.headers
.hasOwnProperty(String(name
).toLowerCase());
369 * Returns the value of the given header name.
370 * Note: Header-Names are case-insensitive.
373 * @memberof LuCI.headers
374 * @param {string} name
375 * The header name to read
377 * @returns {string|null}
378 * The value of the given header name or `null` if the header isn't present.
380 get: function(name
) {
381 var key
= String(name
).toLowerCase();
382 return this.headers
.hasOwnProperty(key
) ? this.headers
[key
] : null;
392 * The `Response` class is an internal utility class representing HTTP responses.
394 var Response
= Class
.extend({
395 __name__
: 'LuCI.response',
396 __init__: function(xhr
, url
, duration
, headers
, content
) {
398 * Describes whether the response is successful (status codes `200..299`) or not
400 * @memberof LuCI.response
404 this.ok
= (xhr
.status
>= 200 && xhr
.status
<= 299);
407 * The numeric HTTP status code of the response
409 * @memberof LuCI.response
413 this.status
= xhr
.status
;
416 * The HTTP status description message of the response
418 * @memberof LuCI.response
422 this.statusText
= xhr
.statusText
;
425 * The HTTP headers of the response
427 * @memberof LuCI.response
429 * @type {LuCI.headers}
431 this.headers
= (headers
!= null) ? headers
: new Headers(xhr
);
434 * The total duration of the HTTP request in milliseconds
436 * @memberof LuCI.response
440 this.duration
= duration
;
443 * The final URL of the request, i.e. after following redirects.
445 * @memberof LuCI.response
454 if (content
instanceof Blob
) {
455 this.responseBlob
= content
;
456 this.responseJSON
= null;
457 this.responseText
= null;
459 else if (content
!= null && typeof(content
) == 'object') {
460 this.responseBlob
= null;
461 this.responseJSON
= content
;
462 this.responseText
= null;
464 else if (content
!= null) {
465 this.responseBlob
= null;
466 this.responseJSON
= null;
467 this.responseText
= String(content
);
470 this.responseJSON
= null;
472 if (xhr
.responseType
== 'blob') {
473 this.responseBlob
= xhr
.response
;
474 this.responseText
= null;
477 this.responseBlob
= null;
478 this.responseText
= xhr
.responseText
;
484 * Clones the given response object, optionally overriding the content
485 * of the cloned instance.
488 * @memberof LuCI.response
489 * @param {*} [content]
490 * Override the content of the cloned response. Object values will be
491 * treated as JSON response data, all other types will be converted
492 * using `String()` and treated as response text.
494 * @returns {LuCI.response}
495 * The cloned `Response` instance.
497 clone: function(content
) {
498 var copy
= new Response(this.xhr
, this.url
, this.duration
, this.headers
, content
);
501 copy
.status
= this.status
;
502 copy
.statusText
= this.statusText
;
508 * Access the response content as JSON data.
511 * @memberof LuCI.response
512 * @throws {SyntaxError}
513 * Throws `SyntaxError` if the content isn't valid JSON.
516 * The parsed JSON data.
519 if (this.responseJSON
== null)
520 this.responseJSON
= JSON
.parse(this.responseText
);
522 return this.responseJSON
;
526 * Access the response content as string.
529 * @memberof LuCI.response
531 * The response content.
534 if (this.responseText
== null && this.responseJSON
!= null)
535 this.responseText
= JSON
.stringify(this.responseJSON
);
537 return this.responseText
;
541 * Access the response content as blob.
544 * @memberof LuCI.response
546 * The response content as blob.
549 return this.responseBlob
;
554 var requestQueue
= [];
556 function isQueueableRequest(opt
) {
560 if (opt
.method
!= 'POST' || typeof(opt
.content
) != 'object')
563 if (opt
.nobatch
=== true)
566 var rpcBaseURL
= Request
.expandURL(classes
.rpc
.getBaseURL());
568 return (rpcBaseURL
!= null && opt
.url
.indexOf(rpcBaseURL
) == 0);
571 function flushRequestQueue() {
572 if (!requestQueue
.length
)
575 var reqopt
= Object
.assign({}, requestQueue
[0][0], { content
: [], nobatch
: true }),
578 for (var i
= 0; i
< requestQueue
.length
; i
++) {
579 batch
[i
] = requestQueue
[i
];
580 reqopt
.content
[i
] = batch
[i
][0].content
;
583 requestQueue
.length
= 0;
585 Request
.request(rpcBaseURL
, reqopt
).then(function(reply
) {
586 var json
= null, req
= null;
588 try { json
= reply
.json() }
591 while ((req
= batch
.shift()) != null)
592 if (Array
.isArray(json
) && json
.length
)
593 req
[2].call(reqopt
, reply
.clone(json
.shift()));
595 req
[1].call(reqopt
, new Error('No related RPC reply'));
596 }).catch(function(error
) {
599 while ((req
= batch
.shift()) != null)
600 req
[1].call(reqopt
, error
);
610 * The `Request` class allows initiating HTTP requests and provides utilities
611 * for dealing with responses.
613 var Request
= Class
.singleton(/** @lends LuCI.request.prototype */ {
614 __name__
: 'LuCI.request',
619 * Turn the given relative URL into an absolute URL if necessary.
622 * @memberof LuCI.request
623 * @param {string} url
624 * The URL to convert.
627 * The absolute URL derived from the given one, or the original URL
628 * if it already was absolute.
630 expandURL: function(url
) {
631 if (!/^(?:[^/]+:)?\/\//.test(url
))
632 url
= location
.protocol
+ '//' + location
.host
+ url
;
638 * @typedef {Object} RequestOptions
639 * @memberof LuCI.request
641 * @property {string} [method=GET]
642 * The HTTP method to use, e.g. `GET` or `POST`.
644 * @property {Object<string, Object|string>} [query]
645 * Query string data to append to the URL. Non-string values of the
646 * given object will be converted to JSON.
648 * @property {boolean} [cache=false]
649 * Specifies whether the HTTP response may be retrieved from cache.
651 * @property {string} [username]
652 * Provides a username for HTTP basic authentication.
654 * @property {string} [password]
655 * Provides a password for HTTP basic authentication.
657 * @property {number} [timeout]
658 * Specifies the request timeout in milliseconds.
660 * @property {boolean} [credentials=false]
661 * Whether to include credentials such as cookies in the request.
663 * @property {string} [responseType=text]
664 * Overrides the request response type. Valid values or `text` to
665 * interpret the response as UTF-8 string or `blob` to handle the
666 * response as binary `Blob` data.
668 * @property {*} [content]
669 * Specifies the HTTP message body to send along with the request.
670 * If the value is a function, it is invoked and the return value
671 * used as content, if it is a FormData instance, it is used as-is,
672 * if it is an object, it will be converted to JSON, in all other
673 * cases it is converted to a string.
675 * @property {Object<string, string>} [header]
676 * Specifies HTTP headers to set for the request.
678 * @property {function} [progress]
679 * An optional request callback function which receives ProgressEvent
680 * instances as sole argument during the HTTP request transfer.
684 * Initiate an HTTP request to the given target.
687 * @memberof LuCI.request
688 * @param {string} target
689 * The URL to request.
691 * @param {LuCI.request.RequestOptions} [options]
692 * Additional options to configure the request.
694 * @returns {Promise<LuCI.response>}
695 * The resulting HTTP response.
697 request: function(target
, options
) {
698 var state
= { xhr
: new XMLHttpRequest(), url
: this.expandURL(target
), start
: Date
.now() },
699 opt
= Object
.assign({}, options
, state
),
702 callback
= this.handleReadyStateChange
;
704 return new Promise(function(resolveFn
, rejectFn
) {
705 opt
.xhr
.onreadystatechange
= callback
.bind(opt
, resolveFn
, rejectFn
);
706 opt
.method
= String(opt
.method
|| 'GET').toUpperCase();
708 if ('query' in opt
) {
709 var q
= (opt
.query
!= null) ? Object
.keys(opt
.query
).map(function(k
) {
710 if (opt
.query
[k
] != null) {
711 var v
= (typeof(opt
.query
[k
]) == 'object')
712 ? JSON
.stringify(opt
.query
[k
])
713 : String(opt
.query
[k
]);
715 return '%s=%s'.format(encodeURIComponent(k
), encodeURIComponent(v
));
718 return encodeURIComponent(k
);
723 switch (opt
.method
) {
727 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + q
;
731 if (content
== null) {
733 contenttype
= 'application/x-www-form-urlencoded';
740 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + (new Date()).getTime();
742 if (isQueueableRequest(opt
)) {
743 requestQueue
.push([opt
, rejectFn
, resolveFn
]);
744 requestAnimationFrame(flushRequestQueue
);
748 if ('username' in opt
&& 'password' in opt
)
749 opt
.xhr
.open(opt
.method
, opt
.url
, true, opt
.username
, opt
.password
);
751 opt
.xhr
.open(opt
.method
, opt
.url
, true);
753 opt
.xhr
.responseType
= opt
.responseType
|| 'text';
755 if ('overrideMimeType' in opt
.xhr
)
756 opt
.xhr
.overrideMimeType('application/octet-stream');
758 if ('timeout' in opt
)
759 opt
.xhr
.timeout
= +opt
.timeout
;
761 if ('credentials' in opt
)
762 opt
.xhr
.withCredentials
= !!opt
.credentials
;
764 if (opt
.content
!= null) {
765 switch (typeof(opt
.content
)) {
767 content
= opt
.content(opt
.xhr
);
771 if (!(opt
.content
instanceof FormData
)) {
772 content
= JSON
.stringify(opt
.content
);
773 contenttype
= 'application/json';
776 content
= opt
.content
;
781 content
= String(opt
.content
);
785 if ('headers' in opt
)
786 for (var header
in opt
.headers
)
787 if (opt
.headers
.hasOwnProperty(header
)) {
788 if (header
.toLowerCase() != 'content-type')
789 opt
.xhr
.setRequestHeader(header
, opt
.headers
[header
]);
791 contenttype
= opt
.headers
[header
];
794 if ('progress' in opt
&& 'upload' in opt
.xhr
)
795 opt
.xhr
.upload
.addEventListener('progress', opt
.progress
);
797 if (contenttype
!= null)
798 opt
.xhr
.setRequestHeader('Content-Type', contenttype
);
801 opt
.xhr
.send(content
);
804 rejectFn
.call(opt
, e
);
809 handleReadyStateChange: function(resolveFn
, rejectFn
, ev
) {
811 duration
= Date
.now() - this.start
;
813 if (xhr
.readyState
!== 4)
816 if (xhr
.status
=== 0 && xhr
.statusText
=== '') {
817 if (duration
>= this.timeout
)
818 rejectFn
.call(this, new Error('XHR request timed out'));
820 rejectFn
.call(this, new Error('XHR request aborted by browser'));
823 var response
= new Response(
824 xhr
, xhr
.responseURL
|| this.url
, duration
);
826 Promise
.all(Request
.interceptors
.map(function(fn
) { return fn(response
) }))
827 .then(resolveFn
.bind(this, response
))
828 .catch(rejectFn
.bind(this));
833 * Initiate an HTTP GET request to the given target.
836 * @memberof LuCI.request
837 * @param {string} target
838 * The URL to request.
840 * @param {LuCI.request.RequestOptions} [options]
841 * Additional options to configure the request.
843 * @returns {Promise<LuCI.response>}
844 * The resulting HTTP response.
846 get: function(url
, options
) {
847 return this.request(url
, Object
.assign({ method
: 'GET' }, options
));
851 * Initiate an HTTP POST request to the given target.
854 * @memberof LuCI.request
855 * @param {string} target
856 * The URL to request.
859 * The request data to send, see {@link LuCI.request.RequestOptions} for details.
861 * @param {LuCI.request.RequestOptions} [options]
862 * Additional options to configure the request.
864 * @returns {Promise<LuCI.response>}
865 * The resulting HTTP response.
867 post: function(url
, data
, options
) {
868 return this.request(url
, Object
.assign({ method
: 'POST', content
: data
}, options
));
872 * Interceptor functions are invoked whenever an HTTP reply is received, in the order
873 * these functions have been registered.
874 * @callback LuCI.request.interceptorFn
875 * @param {LuCI.response} res
876 * The HTTP response object
880 * Register an HTTP response interceptor function. Interceptor
881 * functions are useful to perform default actions on incoming HTTP
882 * responses, such as checking for expired authentication or for
883 * implementing request retries before returning a failure.
886 * @memberof LuCI.request
887 * @param {LuCI.request.interceptorFn} interceptorFn
888 * The interceptor function to register.
890 * @returns {LuCI.request.interceptorFn}
891 * The registered function.
893 addInterceptor: function(interceptorFn
) {
894 if (typeof(interceptorFn
) == 'function')
895 this.interceptors
.push(interceptorFn
);
896 return interceptorFn
;
900 * Remove an HTTP response interceptor function. The passed function
901 * value must be the very same value that was used to register the
905 * @memberof LuCI.request
906 * @param {LuCI.request.interceptorFn} interceptorFn
907 * The interceptor function to remove.
910 * Returns `true` if any function has been removed, else `false`.
912 removeInterceptor: function(interceptorFn
) {
913 var oldlen
= this.interceptors
.length
, i
= oldlen
;
915 if (this.interceptors
[i
] === interceptorFn
)
916 this.interceptors
.splice(i
, 1);
917 return (this.interceptors
.length
< oldlen
);
922 * @memberof LuCI.request
926 * The `Request.poll` class provides some convience wrappers around
927 * {@link LuCI.poll} mainly to simplify registering repeating HTTP
928 * request calls as polling functions.
932 * The callback function is invoked whenever an HTTP reply to a
933 * polled request is received or when the polled request timed
936 * @callback LuCI.request.poll~callbackFn
937 * @param {LuCI.response} res
938 * The HTTP response object.
941 * The response JSON if the response could be parsed as such,
944 * @param {number} duration
945 * The total duration of the request in milliseconds.
949 * Register a repeating HTTP request with an optional callback
950 * to invoke whenever a response for the request is received.
953 * @memberof LuCI.request.poll
954 * @param {number} interval
955 * The poll interval in seconds.
957 * @param {string} url
958 * The URL to request on each poll.
960 * @param {LuCI.request.RequestOptions} [options]
961 * Additional options to configure the request.
963 * @param {LuCI.request.poll~callbackFn} [callback]
964 * {@link LuCI.request.poll~callbackFn Callback} function to
965 * invoke for each HTTP reply.
967 * @throws {TypeError}
968 * Throws `TypeError` when an invalid interval was passed.
970 * @returns {function}
971 * Returns the internally created poll function.
973 add: function(interval
, url
, options
, callback
) {
974 if (isNaN(interval
) || interval
<= 0)
975 throw new TypeError('Invalid poll interval');
977 var ival
= interval
>>> 0,
978 opts
= Object
.assign({}, options
, { timeout
: ival
* 1000 - 5 });
980 var fn = function() {
981 return Request
.request(url
, options
).then(function(res
) {
987 res_json
= res
.json();
991 callback(res
, res_json
, res
.duration
);
995 return (Poll
.add(fn
, ival
) ? fn
: null);
999 * Remove a polling request that has been previously added using `add()`.
1000 * This function is essentially a wrapper around
1001 * {@link LuCI.poll.remove LuCI.poll.remove()}.
1004 * @memberof LuCI.request.poll
1005 * @param {function} entry
1006 * The poll function returned by {@link LuCI.request.poll#add add()}.
1008 * @returns {boolean}
1009 * Returns `true` if any function has been removed, else `false`.
1011 remove: function(entry
) { return Poll
.remove(entry
) },
1014 * Alias for {@link LuCI.poll.start LuCI.poll.start()}.
1017 * @memberof LuCI.request.poll
1019 start: function() { return Poll
.start() },
1022 * Alias for {@link LuCI.poll.stop LuCI.poll.stop()}.
1025 * @memberof LuCI.request.poll
1027 stop: function() { return Poll
.stop() },
1030 * Alias for {@link LuCI.poll.active LuCI.poll.active()}.
1033 * @memberof LuCI.request.poll
1035 active: function() { return Poll
.active() }
1045 * The `Poll` class allows registering and unregistering poll actions,
1046 * as well as starting, stopping and querying the state of the polling
1049 var Poll
= Class
.singleton(/** @lends LuCI.poll.prototype */ {
1050 __name__
: 'LuCI.poll',
1055 * Add a new operation to the polling loop. If the polling loop is not
1056 * already started at this point, it will be implicitely started.
1059 * @memberof LuCI.poll
1060 * @param {function} fn
1061 * The function to invoke on each poll interval.
1063 * @param {number} interval
1064 * The poll interval in seconds.
1066 * @throws {TypeError}
1067 * Throws `TypeError` when an invalid interval was passed.
1069 * @returns {boolean}
1070 * Returns `true` if the function has been added or `false` if it
1071 * already is registered.
1073 add: function(fn
, interval
) {
1074 if (interval
== null || interval
<= 0)
1075 interval
= env
.pollinterval
|| null;
1077 if (isNaN(interval
) || typeof(fn
) != 'function')
1078 throw new TypeError('Invalid argument to LuCI.poll.add()');
1080 for (var i
= 0; i
< this.queue
.length
; i
++)
1081 if (this.queue
[i
].fn
=== fn
)
1092 if (this.tick
!= null && !this.active())
1099 * Remove an operation from the polling loop. If no further operatons
1100 * are registered, the polling loop is implicitely stopped.
1103 * @memberof LuCI.poll
1104 * @param {function} fn
1105 * The function to remove.
1107 * @throws {TypeError}
1108 * Throws `TypeError` when the given argument isn't a function.
1110 * @returns {boolean}
1111 * Returns `true` if the function has been removed or `false` if it
1114 remove: function(fn
) {
1115 if (typeof(fn
) != 'function')
1116 throw new TypeError('Invalid argument to LuCI.poll.remove()');
1118 var len
= this.queue
.length
;
1120 for (var i
= len
; i
> 0; i
--)
1121 if (this.queue
[i
-1].fn
=== fn
)
1122 this.queue
.splice(i
-1, 1);
1124 if (!this.queue
.length
&& this.stop())
1127 return (this.queue
.length
!= len
);
1131 * (Re)start the polling loop. Dispatches a custom `poll-start` event
1132 * to the `document` object upon successful start.
1135 * @memberof LuCI.poll
1136 * @returns {boolean}
1137 * Returns `true` if polling has been started (or if no functions
1138 * where registered) or `false` when the polling loop already runs.
1146 if (this.queue
.length
) {
1147 this.timer
= window
.setInterval(this.step
, 1000);
1149 document
.dispatchEvent(new CustomEvent('poll-start'));
1156 * Stop the polling loop. Dispatches a custom `poll-stop` event
1157 * to the `document` object upon successful stop.
1160 * @memberof LuCI.poll
1161 * @returns {boolean}
1162 * Returns `true` if polling has been stopped or `false` if it din't
1163 * run to begin with.
1169 document
.dispatchEvent(new CustomEvent('poll-stop'));
1170 window
.clearInterval(this.timer
);
1178 for (var i
= 0, e
= null; (e
= Poll
.queue
[i
]) != null; i
++) {
1179 if ((Poll
.tick
% e
.i
) != 0)
1187 Promise
.resolve(e
.fn()).finally((function() { this.r
= true }).bind(e
));
1190 Poll
.tick
= (Poll
.tick
+ 1) % Math
.pow(2, 32);
1194 * Test whether the polling loop is running.
1197 * @memberof LuCI.poll
1198 * @returns {boolean} - Returns `true` if polling is active, else `false`.
1200 active: function() {
1201 return (this.timer
!= null);
1211 * The `dom` class provides convenience method for creating and
1212 * manipulating DOM elements.
1214 * To import the class in views, use `'require dom'`, to import it in
1215 * external JavaScript, use `L.require("dom").then(...)`.
1217 var DOM
= Class
.singleton(/** @lends LuCI.dom.prototype */ {
1218 __name__
: 'LuCI.dom',
1221 * Tests whether the given argument is a valid DOM `Node`.
1224 * @memberof LuCI.dom
1226 * The value to test.
1228 * @returns {boolean}
1229 * Returns `true` if the value is a DOM `Node`, else `false`.
1232 return (e
!= null && typeof(e
) == 'object' && 'nodeType' in e
);
1236 * Parses a given string as HTML and returns the first child node.
1239 * @memberof LuCI.dom
1241 * A string containing an HTML fragment to parse. Note that only
1242 * the first result of the resulting structure is returned, so an
1243 * input value of `<div>foo</div> <div>bar</div>` will only return
1244 * the first `div` element node.
1247 * Returns the first DOM `Node` extracted from the HTML fragment or
1248 * `null` on parsing failures or if no element could be found.
1250 parse: function(s
) {
1254 domParser
= domParser
|| new DOMParser();
1255 elem
= domParser
.parseFromString(s
, 'text/html').body
.firstChild
;
1261 dummyElem
= dummyElem
|| document
.createElement('div');
1262 dummyElem
.innerHTML
= s
;
1263 elem
= dummyElem
.firstChild
;
1268 return elem
|| null;
1272 * Tests whether a given `Node` matches the given query selector.
1274 * This function is a convenience wrapper around the standard
1275 * `Node.matches("selector")` function with the added benefit that
1276 * the `node` argument may be a non-`Node` value, in which case
1277 * this function simply returns `false`.
1280 * @memberof LuCI.dom
1282 * The `Node` argument to test the selector against.
1284 * @param {string} [selector]
1285 * The query selector expression to test against the given node.
1287 * @returns {boolean}
1288 * Returns `true` if the given node matches the specified selector
1289 * or `false` when the node argument is no valid DOM `Node` or the
1290 * selector didn't match.
1292 matches: function(node
, selector
) {
1293 var m
= this.elem(node
) ? node
.matches
|| node
.msMatchesSelector
: null;
1294 return m
? m
.call(node
, selector
) : false;
1298 * Returns the closest parent node that matches the given query
1299 * selector expression.
1301 * This function is a convenience wrapper around the standard
1302 * `Node.closest("selector")` function with the added benefit that
1303 * the `node` argument may be a non-`Node` value, in which case
1304 * this function simply returns `null`.
1307 * @memberof LuCI.dom
1309 * The `Node` argument to find the closest parent for.
1311 * @param {string} [selector]
1312 * The query selector expression to test against each parent.
1314 * @returns {Node|null}
1315 * Returns the closest parent node matching the selector or
1316 * `null` when the node argument is no valid DOM `Node` or the
1317 * selector didn't match any parent.
1319 parent: function(node
, selector
) {
1320 if (this.elem(node
) && node
.closest
)
1321 return node
.closest(selector
);
1323 while (this.elem(node
))
1324 if (this.matches(node
, selector
))
1327 node
= node
.parentNode
;
1333 * Appends the given children data to the given node.
1336 * @memberof LuCI.dom
1338 * The `Node` argument to append the children to.
1340 * @param {*} [children]
1341 * The childrens to append to the given node.
1343 * When `children` is an array, then each item of the array
1344 * will be either appended as child element or text node,
1345 * depending on whether the item is a DOM `Node` instance or
1346 * some other non-`null` value. Non-`Node`, non-`null` values
1347 * will be converted to strings first before being passed as
1348 * argument to `createTextNode()`.
1350 * When `children` is a function, it will be invoked with
1351 * the passed `node` argument as sole parameter and the `append`
1352 * function will be invoked again, with the given `node` argument
1353 * as first and the return value of the `children` function as
1356 * When `children` is is a DOM `Node` instance, it will be
1357 * appended to the given `node`.
1359 * When `children` is any other non-`null` value, it will be
1360 * converted to a string and appened to the `innerHTML` property
1361 * of the given `node`.
1363 * @returns {Node|null}
1364 * Returns the last children `Node` appended to the node or `null`
1365 * if either the `node` argument was no valid DOM `node` or if the
1366 * `children` was `null` or didn't result in further DOM nodes.
1368 append: function(node
, children
) {
1369 if (!this.elem(node
))
1372 if (Array
.isArray(children
)) {
1373 for (var i
= 0; i
< children
.length
; i
++)
1374 if (this.elem(children
[i
]))
1375 node
.appendChild(children
[i
]);
1376 else if (children
!== null && children
!== undefined)
1377 node
.appendChild(document
.createTextNode('' + children
[i
]));
1379 return node
.lastChild
;
1381 else if (typeof(children
) === 'function') {
1382 return this.append(node
, children(node
));
1384 else if (this.elem(children
)) {
1385 return node
.appendChild(children
);
1387 else if (children
!== null && children
!== undefined) {
1388 node
.innerHTML
= '' + children
;
1389 return node
.lastChild
;
1396 * Replaces the content of the given node with the given children.
1398 * This function first removes any children of the given DOM
1399 * `Node` and then adds the given given children following the
1400 * rules outlined below.
1403 * @memberof LuCI.dom
1405 * The `Node` argument to replace the children of.
1407 * @param {*} [children]
1408 * The childrens to replace into the given node.
1410 * When `children` is an array, then each item of the array
1411 * will be either appended as child element or text node,
1412 * depending on whether the item is a DOM `Node` instance or
1413 * some other non-`null` value. Non-`Node`, non-`null` values
1414 * will be converted to strings first before being passed as
1415 * argument to `createTextNode()`.
1417 * When `children` is a function, it will be invoked with
1418 * the passed `node` argument as sole parameter and the `append`
1419 * function will be invoked again, with the given `node` argument
1420 * as first and the return value of the `children` function as
1423 * When `children` is is a DOM `Node` instance, it will be
1424 * appended to the given `node`.
1426 * When `children` is any other non-`null` value, it will be
1427 * converted to a string and appened to the `innerHTML` property
1428 * of the given `node`.
1430 * @returns {Node|null}
1431 * Returns the last children `Node` appended to the node or `null`
1432 * if either the `node` argument was no valid DOM `node` or if the
1433 * `children` was `null` or didn't result in further DOM nodes.
1435 content: function(node
, children
) {
1436 if (!this.elem(node
))
1439 var dataNodes
= node
.querySelectorAll('[data-idref]');
1441 for (var i
= 0; i
< dataNodes
.length
; i
++)
1442 delete this.registry
[dataNodes
[i
].getAttribute('data-idref')];
1444 while (node
.firstChild
)
1445 node
.removeChild(node
.firstChild
);
1447 return this.append(node
, children
);
1451 * Sets attributes or registers event listeners on element nodes.
1454 * @memberof LuCI.dom
1456 * The `Node` argument to set the attributes or add the event
1457 * listeners for. When the given `node` value is not a valid
1458 * DOM `Node`, the function returns and does nothing.
1460 * @param {string|Object<string, *>} key
1461 * Specifies either the attribute or event handler name to use,
1462 * or an object containing multiple key, value pairs which are
1463 * each added to the node as either attribute or event handler,
1464 * depending on the respective value.
1467 * Specifies the attribute value or event handler function to add.
1468 * If the `key` parameter is an `Object`, this parameter will be
1471 * When `val` is of type function, it will be registered as event
1472 * handler on the given `node` with the `key` parameter being the
1475 * When `val` is of type object, it will be serialized as JSON and
1476 * added as attribute to the given `node`, using the given `key`
1477 * as attribute name.
1479 * When `val` is of any other type, it will be added as attribute
1480 * to the given `node` as-is, with the underlying `setAttribute()`
1481 * call implicitely turning it into a string.
1483 attr: function(node
, key
, val
) {
1484 if (!this.elem(node
))
1489 if (typeof(key
) === 'object' && key
!== null)
1491 else if (typeof(key
) === 'string')
1492 attr
= {}, attr
[key
] = val
;
1495 if (!attr
.hasOwnProperty(key
) || attr
[key
] == null)
1498 switch (typeof(attr
[key
])) {
1500 node
.addEventListener(key
, attr
[key
]);
1504 node
.setAttribute(key
, JSON
.stringify(attr
[key
]));
1508 node
.setAttribute(key
, attr
[key
]);
1514 * Creates a new DOM `Node` from the given `html`, `attr` and
1515 * `data` parameters.
1517 * This function has multiple signatures, it can be either invoked
1518 * in the form `create(html[, attr[, data]])` or in the form
1519 * `create(html[, data])`. The used variant is determined from the
1520 * type of the second argument.
1523 * @memberof LuCI.dom
1525 * Describes the node to create.
1527 * When the value of `html` is of type array, a `DocumentFragment`
1528 * node is created and each item of the array is first converted
1529 * to a DOM `Node` by passing it through `create()` and then added
1530 * as child to the fragment.
1532 * When the value of `html` is a DOM `Node` instance, no new
1533 * element will be created but the node will be used as-is.
1535 * When the value of `html` is a string starting with `<`, it will
1536 * be passed to `dom.parse()` and the resulting value is used.
1538 * When the value of `html` is any other string, it will be passed
1539 * to `document.createElement()` for creating a new DOM `Node` of
1542 * @param {Object<string, *>} [attr]
1543 * Specifies an Object of key, value pairs to set as attributes
1544 * or event handlers on the created node. Refer to
1545 * {@link LuCI.dom#attr dom.attr()} for details.
1548 * Specifies children to append to the newly created element.
1549 * Refer to {@link LuCI.dom#append dom.append()} for details.
1551 * @throws {InvalidCharacterError}
1552 * Throws an `InvalidCharacterError` when the given `html`
1553 * argument contained malformed markup (such as not escaped
1554 * `&` characters in XHTML mode) or when the given node name
1555 * in `html` contains characters which are not legal in DOM
1556 * element names, such as spaces.
1559 * Returns the newly created `Node`.
1561 create: function() {
1562 var html
= arguments
[0],
1563 attr
= arguments
[1],
1564 data
= arguments
[2],
1567 if (!(attr
instanceof Object
) || Array
.isArray(attr
))
1568 data
= attr
, attr
= null;
1570 if (Array
.isArray(html
)) {
1571 elem
= document
.createDocumentFragment();
1572 for (var i
= 0; i
< html
.length
; i
++)
1573 elem
.appendChild(this.create(html
[i
]));
1575 else if (this.elem(html
)) {
1578 else if (html
.charCodeAt(0) === 60) {
1579 elem
= this.parse(html
);
1582 elem
= document
.createElement(html
);
1588 this.attr(elem
, attr
);
1589 this.append(elem
, data
);
1597 * Attaches or detaches arbitrary data to and from a DOM `Node`.
1599 * This function is useful to attach non-string values or runtime
1600 * data that is not serializable to DOM nodes. To decouple data
1601 * from the DOM, values are not added directly to nodes, but
1602 * inserted into a registry instead which is then referenced by a
1603 * string key stored as `data-idref` attribute in the node.
1605 * This function has multiple signatures and is sensitive to the
1606 * number of arguments passed to it.
1608 * - `dom.data(node)` -
1609 * Fetches all data associated with the given node.
1610 * - `dom.data(node, key)` -
1611 * Fetches a specific key associated with the given node.
1612 * - `dom.data(node, key, val)` -
1613 * Sets a specific key to the given value associated with the
1615 * - `dom.data(node, null)` -
1616 * Clears any data associated with the node.
1617 * - `dom.data(node, key, null)` -
1618 * Clears the given key associated with the node.
1621 * @memberof LuCI.dom
1622 * @param {Node} node
1623 * The DOM `Node` instance to set or retrieve the data for.
1625 * @param {string|null} [key]
1626 * This is either a string specifying the key to retrieve, or
1627 * `null` to unset the entire node data.
1629 * @param {*|null} [val]
1630 * This is either a non-`null` value to set for a given key or
1631 * `null` to remove the given `key` from the specified node.
1634 * Returns the get or set value, or `null` when no value could
1637 data: function(node
, key
, val
) {
1638 if (!node
|| !node
.getAttribute
)
1641 var id
= node
.getAttribute('data-idref');
1643 /* clear all data */
1644 if (arguments
.length
> 1 && key
== null) {
1646 node
.removeAttribute('data-idref');
1647 val
= this.registry
[id
]
1648 delete this.registry
[id
];
1656 else if (arguments
.length
> 2 && key
!= null && val
== null) {
1658 val
= this.registry
[id
][key
];
1659 delete this.registry
[id
][key
];
1667 else if (arguments
.length
> 2 && key
!= null && val
!= null) {
1669 do { id
= Math
.floor(Math
.random() * 0xffffffff).toString(16) }
1670 while (this.registry
.hasOwnProperty(id
));
1672 node
.setAttribute('data-idref', id
);
1673 this.registry
[id
] = {};
1676 return (this.registry
[id
][key
] = val
);
1680 else if (arguments
.length
== 1) {
1682 return this.registry
[id
];
1688 else if (arguments
.length
== 2) {
1690 return this.registry
[id
][key
];
1697 * Binds the given class instance ot the specified DOM `Node`.
1699 * This function uses the `dom.data()` facility to attach the
1700 * passed instance of a Class to a node. This is needed for
1701 * complex widget elements or similar where the corresponding
1702 * class instance responsible for the element must be retrieved
1703 * from DOM nodes obtained by `querySelector()` or similar means.
1706 * @memberof LuCI.dom
1707 * @param {Node} node
1708 * The DOM `Node` instance to bind the class to.
1710 * @param {Class} inst
1711 * The Class instance to bind to the node.
1713 * @throws {TypeError}
1714 * Throws a `TypeError` when the given instance argument isn't
1715 * a valid Class instance.
1718 * Returns the bound class instance.
1720 bindClassInstance: function(node
, inst
) {
1721 if (!(inst
instanceof Class
))
1722 LuCI
.prototype.error('TypeError', 'Argument must be a class instance');
1724 return this.data(node
, '_class', inst
);
1728 * Finds a bound class instance on the given node itself or the
1729 * first bound instance on its closest parent node.
1732 * @memberof LuCI.dom
1733 * @param {Node} node
1734 * The DOM `Node` instance to start from.
1736 * @returns {Class|null}
1737 * Returns the founds class instance if any or `null` if no bound
1738 * class could be found on the node itself or any of its parents.
1740 findClassInstance: function(node
) {
1744 inst
= this.data(node
, '_class');
1745 node
= node
.parentNode
;
1747 while (!(inst
instanceof Class
) && node
!= null);
1753 * Finds a bound class instance on the given node itself or the
1754 * first bound instance on its closest parent node and invokes
1755 * the specified method name on the found class instance.
1758 * @memberof LuCI.dom
1759 * @param {Node} node
1760 * The DOM `Node` instance to start from.
1762 * @param {string} method
1763 * The name of the method to invoke on the found class instance.
1765 * @param {...*} params
1766 * Additional arguments to pass to the invoked method as-is.
1769 * Returns the return value of the invoked method if a class
1770 * instance and method has been found. Returns `null` if either
1771 * no bound class instance could be found, or if the found
1772 * instance didn't have the requested `method`.
1774 callClassMethod: function(node
, method
/*, ... */) {
1775 var inst
= this.findClassInstance(node
);
1777 if (inst
== null || typeof(inst
[method
]) != 'function')
1780 return inst
[method
].apply(inst
, inst
.varargs(arguments
, 2));
1784 * The ignore callback function is invoked by `isEmpty()` for each
1785 * child node to decide whether to ignore a child node or not.
1787 * When this function returns `false`, the node passed to it is
1788 * ignored, else not.
1790 * @callback LuCI.dom~ignoreCallbackFn
1791 * @param {Node} node
1792 * The child node to test.
1794 * @returns {boolean}
1795 * Boolean indicating whether to ignore the node or not.
1799 * Tests whether a given DOM `Node` instance is empty or appears
1802 * Any element child nodes which have the CSS class `hidden` set
1803 * or for which the optionally passed `ignoreFn` callback function
1804 * returns `false` are ignored.
1807 * @memberof LuCI.dom
1808 * @param {Node} node
1809 * The DOM `Node` instance to test.
1811 * @param {LuCI.dom~ignoreCallbackFn} [ignoreFn]
1812 * Specifies an optional function which is invoked for each child
1813 * node to decide whether the child node should be ignored or not.
1815 * @returns {boolean}
1816 * Returns `true` if the node does not have any children or if
1817 * any children node either has a `hidden` CSS class or a `false`
1818 * result when testing it using the given `ignoreFn`.
1820 isEmpty: function(node
, ignoreFn
) {
1821 for (var child
= node
.firstElementChild
; child
!= null; child
= child
.nextElementSibling
)
1822 if (!child
.classList
.contains('hidden') && (!ignoreFn
|| !ignoreFn(child
)))
1835 * The `session` class provides various session related functionality.
1837 var Session
= Class
.singleton(/** @lends LuCI.session.prototype */ {
1838 __name__
: 'LuCI.session',
1841 * Retrieve the current session ID.
1844 * Returns the current session ID.
1847 return env
.sessionid
|| '00000000000000000000000000000000';
1851 * Retrieve the current session token.
1853 * @returns {string|null}
1854 * Returns the current session token or `null` if not logged in.
1856 getToken: function() {
1857 return env
.token
|| null;
1861 * Retrieve data from the local session storage.
1863 * @param {string} [key]
1864 * The key to retrieve from the session data store. If omitted, all
1865 * session data will be returned.
1868 * Returns the stored session data or `null` if the given key wasn't
1871 getLocalData: function(key
) {
1873 var sid
= this.getID(),
1874 item
= 'luci-session-store',
1875 data
= JSON
.parse(window
.sessionStorage
.getItem(item
));
1877 if (!LuCI
.prototype.isObject(data
) || !data
.hasOwnProperty(sid
)) {
1883 return data
[sid
].hasOwnProperty(key
) ? data
[sid
][key
] : null;
1888 return (key
!= null) ? null : {};
1893 * Set data in the local session storage.
1895 * @param {string} key
1896 * The key to set in the session data store.
1899 * The value to store. It will be internally converted to JSON before
1900 * being put in the session store.
1902 * @returns {boolean}
1903 * Returns `true` if the data could be stored or `false` on error.
1905 setLocalData: function(key
, value
) {
1910 var sid
= this.getID(),
1911 item
= 'luci-session-store',
1912 data
= JSON
.parse(window
.sessionStorage
.getItem(item
));
1914 if (!LuCI
.prototype.isObject(data
) || !data
.hasOwnProperty(sid
)) {
1920 data
[sid
][key
] = value
;
1922 delete data
[sid
][key
];
1924 window
.sessionStorage
.setItem(item
, JSON
.stringify(data
));
1940 * The `view` class forms the basis of views and provides a standard
1941 * set of methods to inherit from.
1943 var View
= Class
.extend(/** @lends LuCI.view.prototype */ {
1944 __name__
: 'LuCI.view',
1946 __init__: function() {
1947 var vp
= document
.getElementById('view');
1949 DOM
.content(vp
, E('div', { 'class': 'spinning' }, _('Loading view…')));
1951 return Promise
.resolve(this.load())
1952 .then(LuCI
.prototype.bind(this.render
, this))
1953 .then(LuCI
.prototype.bind(function(nodes
) {
1954 var vp
= document
.getElementById('view');
1956 DOM
.content(vp
, nodes
);
1957 DOM
.append(vp
, this.addFooter());
1958 }, this)).catch(LuCI
.prototype.error
);
1962 * The load function is invoked before the view is rendered.
1964 * The invocation of this function is wrapped by
1965 * `Promise.resolve()` so it may return Promises if needed.
1967 * The return value of the function (or the resolved values
1968 * of the promise returned by it) will be passed as first
1969 * argument to `render()`.
1971 * This function is supposed to be overwritten by subclasses,
1972 * the default implementation does nothing.
1976 * @memberof LuCI.view
1978 * @returns {*|Promise<*>}
1979 * May return any value or a Promise resolving to any value.
1981 load: function() {},
1984 * The render function is invoked after the
1985 * {@link LuCI.view#load load()} function and responsible
1986 * for setting up the view contents. It must return a DOM
1987 * `Node` or `DocumentFragment` holding the contents to
1988 * insert into the view area.
1990 * The invocation of this function is wrapped by
1991 * `Promise.resolve()` so it may return Promises if needed.
1993 * The return value of the function (or the resolved values
1994 * of the promise returned by it) will be inserted into the
1995 * main content area using
1996 * {@link LuCI.dom#append dom.append()}.
1998 * This function is supposed to be overwritten by subclasses,
1999 * the default implementation does nothing.
2003 * @memberof LuCI.view
2004 * @param {*|null} load_results
2005 * This function will receive the return value of the
2006 * {@link LuCI.view#load view.load()} function as first
2009 * @returns {Node|Promise<Node>}
2010 * Should return a DOM `Node` value or a `Promise` resolving
2011 * to a `Node` value.
2013 render: function() {},
2016 * The handleSave function is invoked when the user clicks
2017 * the `Save` button in the page action footer.
2019 * The default implementation should be sufficient for most
2020 * views using {@link form#Map form.Map()} based forms - it
2021 * will iterate all forms present in the view and invoke
2022 * the {@link form#Map#save Map.save()} method on each form.
2024 * Views not using `Map` instances or requiring other special
2025 * logic should overwrite `handleSave()` with a custom
2028 * To disable the `Save` page footer button, views extending
2029 * this base class should overwrite the `handleSave` function
2032 * The invocation of this function is wrapped by
2033 * `Promise.resolve()` so it may return Promises if needed.
2036 * @memberof LuCI.view
2038 * The DOM event that triggered the function.
2040 * @returns {*|Promise<*>}
2041 * Any return values of this function are discarded, but
2042 * passed through `Promise.resolve()` to ensure that any
2043 * returned promise runs to completion before the button
2046 handleSave: function(ev
) {
2049 document
.getElementById('maincontent')
2050 .querySelectorAll('.cbi-map').forEach(function(map
) {
2051 tasks
.push(DOM
.callClassMethod(map
, 'save'));
2054 return Promise
.all(tasks
);
2058 * The handleSaveApply function is invoked when the user clicks
2059 * the `Save & Apply` button in the page action footer.
2061 * The default implementation should be sufficient for most
2062 * views using {@link form#Map form.Map()} based forms - it
2064 * {@link LuCI.view.handleSave view.handleSave()} and then
2065 * call {@link ui#changes#apply ui.changes.apply()} to start the
2066 * modal config apply and page reload flow.
2068 * Views not using `Map` instances or requiring other special
2069 * logic should overwrite `handleSaveApply()` with a custom
2072 * To disable the `Save & Apply` page footer button, views
2073 * extending this base class should overwrite the
2074 * `handleSaveApply` function with `null`.
2076 * The invocation of this function is wrapped by
2077 * `Promise.resolve()` so it may return Promises if needed.
2080 * @memberof LuCI.view
2082 * The DOM event that triggered the function.
2084 * @returns {*|Promise<*>}
2085 * Any return values of this function are discarded, but
2086 * passed through `Promise.resolve()` to ensure that any
2087 * returned promise runs to completion before the button
2090 handleSaveApply: function(ev
, mode
) {
2091 return this.handleSave(ev
).then(function() {
2092 classes
.ui
.changes
.apply(mode
== '0');
2097 * The handleReset function is invoked when the user clicks
2098 * the `Reset` button in the page action footer.
2100 * The default implementation should be sufficient for most
2101 * views using {@link form#Map form.Map()} based forms - it
2102 * will iterate all forms present in the view and invoke
2103 * the {@link form#Map#save Map.reset()} method on each form.
2105 * Views not using `Map` instances or requiring other special
2106 * logic should overwrite `handleReset()` with a custom
2109 * To disable the `Reset` page footer button, views extending
2110 * this base class should overwrite the `handleReset` function
2113 * The invocation of this function is wrapped by
2114 * `Promise.resolve()` so it may return Promises if needed.
2117 * @memberof LuCI.view
2119 * The DOM event that triggered the function.
2121 * @returns {*|Promise<*>}
2122 * Any return values of this function are discarded, but
2123 * passed through `Promise.resolve()` to ensure that any
2124 * returned promise runs to completion before the button
2127 handleReset: function(ev
) {
2130 document
.getElementById('maincontent')
2131 .querySelectorAll('.cbi-map').forEach(function(map
) {
2132 tasks
.push(DOM
.callClassMethod(map
, 'reset'));
2135 return Promise
.all(tasks
);
2139 * Renders a standard page action footer if any of the
2140 * `handleSave()`, `handleSaveApply()` or `handleReset()`
2141 * functions are defined.
2143 * The default implementation should be sufficient for most
2144 * views - it will render a standard page footer with action
2145 * buttons labeled `Save`, `Save & Apply` and `Reset`
2146 * triggering the `handleSave()`, `handleSaveApply()` and
2147 * `handleReset()` functions respectively.
2149 * When any of these `handle*()` functions is overwritten
2150 * with `null` by a view extending this class, the
2151 * corresponding button will not be rendered.
2154 * @memberof LuCI.view
2155 * @returns {DocumentFragment}
2156 * Returns a `DocumentFragment` containing the footer bar
2157 * with buttons for each corresponding `handle*()` action
2158 * or an empty `DocumentFragment` if all three `handle*()`
2159 * methods are overwritten with `null`.
2161 addFooter: function() {
2163 vp
= document
.getElementById('view'),
2167 vp
.querySelectorAll('.cbi-map').forEach(function(map
) {
2168 var m
= DOM
.findClassInstance(map
);
2178 readonly
= !LuCI
.prototype.hasViewPermission();
2180 var saveApplyBtn
= this.handleSaveApply
? new classes
.ui
.ComboButton('0', {
2181 0: [ _('Save & Apply') ],
2182 1: [ _('Apply unchecked') ]
2185 0: 'btn cbi-button cbi-button-apply important',
2186 1: 'btn cbi-button cbi-button-negative important'
2188 click
: classes
.ui
.createHandlerFn(this, 'handleSaveApply'),
2189 disabled
: readonly
|| null
2190 }).render() : E([]);
2192 if (this.handleSaveApply
|| this.handleSave
|| this.handleReset
) {
2193 footer
.appendChild(E('div', { 'class': 'cbi-page-actions control-group' }, [
2195 this.handleSave
? E('button', {
2196 'class': 'cbi-button cbi-button-save',
2197 'click': classes
.ui
.createHandlerFn(this, 'handleSave'),
2198 'disabled': readonly
|| null
2199 }, [ _('Save') ]) : '', ' ',
2200 this.handleReset
? E('button', {
2201 'class': 'cbi-button cbi-button-reset',
2202 'click': classes
.ui
.createHandlerFn(this, 'handleReset'),
2203 'disabled': readonly
|| null
2204 }, [ _('Reset') ]) : ''
2213 var dummyElem
= null,
2215 originalCBIInit
= null,
2218 preloadClasses
= null;
2220 /* "preload" builtin classes to make the available via require */
2230 var LuCI
= Class
.extend(/** @lends LuCI.prototype */ {
2232 __init__: function(setenv
) {
2234 document
.querySelectorAll('script[src*="/luci.js"]').forEach(function(s
) {
2235 if (setenv
.base_url
== null || setenv
.base_url
== '') {
2236 var m
= (s
.getAttribute('src') || '').match(/^(.*)\/luci\.js(?:\?v=([^?]+))?$/);
2238 setenv
.base_url
= m
[1];
2239 setenv
.resource_version
= m
[2];
2244 if (setenv
.base_url
== null)
2245 this.error('InternalError', 'Cannot find url of luci.js');
2247 setenv
.cgi_base
= setenv
.scriptname
.replace(/\/[^\/]+$/, '');
2249 Object
.assign(env
, setenv
);
2251 var domReady
= new Promise(function(resolveFn
, rejectFn
) {
2252 document
.addEventListener('DOMContentLoaded', resolveFn
);
2258 this.require('rpc'),
2259 this.require('form'),
2260 this.probeRPCBaseURL()
2261 ]).then(this.setupDOM
.bind(this)).catch(this.error
);
2263 originalCBIInit
= window
.cbi_init
;
2264 window
.cbi_init = function() {};
2268 * Captures the current stack trace and throws an error of the
2269 * specified type as a new exception. Also logs the exception as
2270 * error to the debug console if it is available.
2275 * @param {Error|string} [type=Error]
2276 * Either a string specifying the type of the error to throw or an
2277 * existing `Error` instance to copy.
2279 * @param {string} [fmt=Unspecified error]
2280 * A format string which is used to form the error message, together
2281 * with all subsequent optional arguments.
2283 * @param {...*} [args]
2284 * Zero or more variable arguments to the supplied format string.
2287 * Throws the created error object with the captured stack trace
2288 * appended to the message and the type set to the given type
2289 * argument or copied from the given error instance.
2291 raise: function(type
, fmt
/*, ...*/) {
2293 msg
= fmt
? String
.prototype.format
.apply(fmt
, this.varargs(arguments
, 2)) : null,
2296 if (type
instanceof Error
) {
2300 e
.message
= msg
+ ': ' + e
.message
;
2303 try { throw new Error('stacktrace') }
2304 catch (e2
) { stack
= (e2
.stack
|| '').split(/\n/) }
2306 e
= new (window
[type
|| 'Error'] || Error
)(msg
|| 'Unspecified error');
2307 e
.name
= type
|| 'Error';
2310 stack
= (stack
|| []).map(function(frame
) {
2311 frame
= frame
.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
2312 return frame
? ' ' + frame
: '';
2315 if (!/^ at /.test(stack
[0]))
2318 if (/\braise /.test(stack
[0]))
2321 if (/\berror /.test(stack
[0]))
2325 e
.message
+= '\n' + stack
.join('\n');
2327 if (window
.console
&& console
.debug
)
2334 * A wrapper around {@link LuCI#raise raise()} which also renders
2335 * the error either as modal overlay when `ui.js` is already loaed
2336 * or directly into the view body.
2341 * @param {Error|string} [type=Error]
2342 * Either a string specifying the type of the error to throw or an
2343 * existing `Error` instance to copy.
2345 * @param {string} [fmt=Unspecified error]
2346 * A format string which is used to form the error message, together
2347 * with all subsequent optional arguments.
2349 * @param {...*} [args]
2350 * Zero or more variable arguments to the supplied format string.
2353 * Throws the created error object with the captured stack trace
2354 * appended to the message and the type set to the given type
2355 * argument or copied from the given error instance.
2357 error: function(type
, fmt
/*, ...*/) {
2359 LuCI
.prototype.raise
.apply(LuCI
.prototype,
2360 Array
.prototype.slice
.call(arguments
));
2365 classes
.ui
.addNotification(e
.name
|| _('Runtime error'),
2366 E('pre', {}, e
.message
), 'danger');
2368 DOM
.content(document
.querySelector('#maincontent'),
2369 E('pre', { 'class': 'alert-message error' }, e
.message
));
2379 * Return a bound function using the given `self` as `this` context
2380 * and any further arguments as parameters to the bound function.
2385 * @param {function} fn
2386 * The function to bind.
2389 * The value to bind as `this` context to the specified function.
2391 * @param {...*} [args]
2392 * Zero or more variable arguments which are bound to the function
2395 * @returns {function}
2396 * Returns the bound function.
2398 bind: function(fn
, self
/*, ... */) {
2399 return Function
.prototype.bind
.apply(fn
, this.varargs(arguments
, 2, self
));
2403 * Load an additional LuCI JavaScript class and its dependencies,
2404 * instantiate it and return the resulting class instance. Each
2405 * class is only loaded once. Subsequent attempts to load the same
2406 * class will return the already instantiated class.
2411 * @param {string} name
2412 * The name of the class to load in dotted notation. Dots will
2413 * be replaced by spaces and joined with the runtime-determined
2414 * base URL of LuCI.js to form an absolute URL to load the class
2417 * @throws {DependencyError}
2418 * Throws a `DependencyError` when the class to load includes
2419 * circular dependencies.
2421 * @throws {NetworkError}
2422 * Throws `NetworkError` when the underlying {@link LuCI.request}
2425 * @throws {SyntaxError}
2426 * Throws `SyntaxError` when the loaded class file code cannot
2427 * be interpreted by `eval`.
2429 * @throws {TypeError}
2430 * Throws `TypeError` when the class file could be loaded and
2431 * interpreted, but when invoking its code did not yield a valid
2434 * @returns {Promise<LuCI.baseclass>}
2435 * Returns the instantiated class.
2437 require: function(name
, from) {
2438 var L
= this, url
= null, from = from || [];
2440 /* Class already loaded */
2441 if (classes
[name
] != null) {
2442 /* Circular dependency */
2443 if (from.indexOf(name
) != -1)
2444 LuCI
.prototype.raise('DependencyError',
2445 'Circular dependency: class "%s" depends on "%s"',
2446 name
, from.join('" which depends on "'));
2448 return Promise
.resolve(classes
[name
]);
2451 url
= '%s/%s.js%s'.format(env
.base_url
, name
.replace(/\./g, '/'), (env.resource_version ? '?v
=' + env.resource_version : ''));
2452 from = [ name ].concat(from);
2454 var compileClass = function(res) {
2456 LuCI.prototype.raise('NetworkError
',
2457 'HTTP error
%d
while loading
class file
"%s"', res.status, url);
2459 var source = res.text(),
2460 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
2461 strictmatch = /^use[ \t]+strict$/,
2465 /* find require statements in source */
2466 for (var i = 0, off = -1, prev = -1, quote = -1, comment = -1, esc = false; i < source.length; i++) {
2467 var chr = source.charCodeAt(i);
2472 else if (comment != -1) {
2473 if ((comment == 47 && chr == 10) || (comment == 42 && prev == 42 && chr == 47))
2476 else if ((chr == 42 || chr == 47) && prev == 47) {
2479 else if (chr == 92) {
2482 else if (chr == quote) {
2483 var s = source.substring(off, i),
2484 m = requirematch.exec(s);
2487 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_
');
2488 depends.push(LuCI.prototype.require(dep, from));
2491 else if (!strictmatch.exec(s)) {
2498 else if (quote == -1 && (chr == 34 || chr == 39)) {
2506 /* load dependencies and instantiate class */
2507 return Promise.all(depends).then(function(instances) {
2508 var _factory, _class;
2512 '(function(window
, document
, L
%s
) { %s
})\n\n//# sourceURL=%s\n'
2513 .format(args
, source
, res
.url
));
2516 LuCI
.prototype.raise('SyntaxError', '%s\n in %s:%s',
2517 error
.message
, res
.url
, error
.lineNumber
|| '?');
2520 _factory
.displayName
= toCamelCase(name
+ 'ClassFactory');
2521 _class
= _factory
.apply(_factory
, [window
, document
, L
].concat(instances
));
2523 if (!Class
.isSubclass(_class
))
2524 LuCI
.prototype.error('TypeError', '"%s" factory yields invalid constructor', name
);
2526 if (_class
.displayName
== 'AnonymousClass')
2527 _class
.displayName
= toCamelCase(name
+ 'Class');
2529 var ptr
= Object
.getPrototypeOf(L
),
2530 parts
= name
.split(/\./),
2531 instance
= new _class();
2533 for (var i
= 0; ptr
&& i
< parts
.length
- 1; i
++)
2534 ptr
= ptr
[parts
[i
]];
2537 ptr
[parts
[i
]] = instance
;
2539 classes
[name
] = instance
;
2545 /* Request class file */
2546 classes
[name
] = Request
.get(url
, { cache
: true }).then(compileClass
);
2548 return classes
[name
];
2552 probeRPCBaseURL: function() {
2553 if (rpcBaseURL
== null)
2554 rpcBaseURL
= Session
.getLocalData('rpcBaseURL');
2556 if (rpcBaseURL
== null) {
2563 var rpcFallbackURL
= this.url('admin/ubus');
2565 rpcBaseURL
= Request
.post(env
.ubuspath
, msg
, { nobatch
: true }).then(function(res
) {
2566 return (rpcBaseURL
= res
.status
== 200 ? env
.ubuspath
: rpcFallbackURL
);
2568 return (rpcBaseURL
= rpcFallbackURL
);
2569 }).then(function(url
) {
2570 Session
.setLocalData('rpcBaseURL', url
);
2575 return Promise
.resolve(rpcBaseURL
);
2578 probeSystemFeatures: function() {
2579 if (sysFeatures
== null)
2580 sysFeatures
= Session
.getLocalData('features');
2582 if (!this.isObject(sysFeatures
)) {
2583 sysFeatures
= classes
.rpc
.declare({
2585 method
: 'getFeatures',
2587 })().then(function(features
) {
2588 Session
.setLocalData('features', features
);
2589 sysFeatures
= features
;
2595 return Promise
.resolve(sysFeatures
);
2598 probePreloadClasses: function() {
2599 if (preloadClasses
== null)
2600 preloadClasses
= Session
.getLocalData('preload');
2602 if (!Array
.isArray(preloadClasses
)) {
2603 preloadClasses
= this.resolveDefault(classes
.rpc
.declare({
2607 expect
: { 'entries': [] }
2608 })(this.fspath(this.resource('preload'))), []).then(function(entries
) {
2611 for (var i
= 0; i
< entries
.length
; i
++) {
2612 if (entries
[i
].type
!= 'file')
2615 var m
= entries
[i
].name
.match(/(.+)\.js$/);
2618 classes
.push('preload.%s'.format(m
[1]));
2621 Session
.setLocalData('preload', classes
);
2622 preloadClasses
= classes
;
2628 return Promise
.resolve(preloadClasses
);
2632 * Test whether a particular system feature is available, such as
2633 * hostapd SAE support or an installed firewall. The features are
2634 * queried once at the beginning of the LuCI session and cached in
2635 * `SessionStorage` throughout the lifetime of the associated tab or
2641 * @param {string} feature
2642 * The feature to test. For detailed list of known feature flags,
2643 * see `/modules/luci-base/root/usr/libexec/rpcd/luci`.
2645 * @param {string} [subfeature]
2646 * Some feature classes like `hostapd` provide sub-feature flags,
2647 * such as `sae` or `11w` support. The `subfeature` argument can
2648 * be used to query these.
2650 * @return {boolean|null}
2651 * Return `true` if the queried feature (and sub-feature) is available
2652 * or `false` if the requested feature isn't present or known.
2653 * Return `null` when a sub-feature was queried for a feature which
2654 * has no sub-features.
2656 hasSystemFeature: function() {
2657 var ft
= sysFeatures
[arguments
[0]];
2659 if (arguments
.length
== 2)
2660 return this.isObject(ft
) ? ft
[arguments
[1]] : null;
2662 return (ft
!= null && ft
!= false);
2666 notifySessionExpiry: function() {
2669 classes
.ui
.showModal(_('Session expired'), [
2670 E('div', { class: 'alert-message warning' },
2671 _('A new login is required since the authentication session expired.')),
2672 E('div', { class: 'right' },
2674 class: 'btn primary',
2676 var loc
= window
.location
;
2677 window
.location
= loc
.protocol
+ '//' + loc
.host
+ loc
.pathname
+ loc
.search
;
2679 }, _('To login…')))
2682 LuCI
.prototype.raise('SessionError', 'Login session is expired');
2686 setupDOM: function(res
) {
2691 rpcBaseURL
= res
[4];
2693 rpcClass
.setBaseURL(rpcBaseURL
);
2695 rpcClass
.addInterceptor(function(msg
, req
) {
2696 if (!LuCI
.prototype.isObject(msg
) ||
2697 !LuCI
.prototype.isObject(msg
.error
) ||
2698 msg
.error
.code
!= -32002)
2701 if (!LuCI
.prototype.isObject(req
) ||
2702 (req
.object
== 'session' && req
.method
== 'access'))
2705 return rpcClass
.declare({
2706 'object': 'session',
2708 'params': [ 'scope', 'object', 'function' ],
2709 'expect': { access
: true }
2710 })('uci', 'luci', 'read').catch(LuCI
.prototype.notifySessionExpiry
);
2713 Request
.addInterceptor(function(res
) {
2714 var isDenied
= false;
2716 if (res
.status
== 403 && res
.headers
.get('X-LuCI-Login-Required') == 'yes')
2722 LuCI
.prototype.notifySessionExpiry();
2725 document
.addEventListener('poll-start', function(ev
) {
2726 uiClass
.showIndicator('poll-status', _('Refreshing'), function(ev
) {
2727 Request
.poll
.active() ? Request
.poll
.stop() : Request
.poll
.start();
2731 document
.addEventListener('poll-stop', function(ev
) {
2732 uiClass
.showIndicator('poll-status', _('Paused'), null, 'inactive');
2735 return Promise
.all([
2736 this.probeSystemFeatures(),
2737 this.probePreloadClasses()
2738 ]).finally(LuCI
.prototype.bind(function() {
2741 if (Array
.isArray(preloadClasses
))
2742 for (var i
= 0; i
< preloadClasses
.length
; i
++)
2743 tasks
.push(this.require(preloadClasses
[i
]));
2745 return Promise
.all(tasks
);
2746 }, this)).finally(this.initDOM
);
2750 initDOM: function() {
2753 document
.dispatchEvent(new CustomEvent('luci-loaded'));
2757 * The `env` object holds environment settings used by LuCI, such
2758 * as request timeouts, base URLs etc.
2766 * Construct an absolute filesystem path relative to the server
2772 * @param {...string} [parts]
2773 * An array of parts to join into a path.
2776 * Return the joined path.
2778 fspath: function(/* ... */) {
2779 var path
= env
.documentroot
;
2781 for (var i
= 0; i
< arguments
.length
; i
++)
2782 path
+= '/' + arguments
[i
];
2784 var p
= path
.replace(/\/+$/, '').replace(/\/+/g, '/').split(/\//),
2787 for (var i
= 0; i
< p
.length
; i
++)
2790 else if (p
[i
] != '.')
2793 return res
.join('/');
2797 * Construct a relative URL path from the given prefix and parts.
2798 * The resulting URL is guaranteed to only contain the characters
2799 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2800 * as `/` for the path separator.
2805 * @param {string} [prefix]
2806 * The prefix to join the given parts with. If the `prefix` is
2807 * omitted, it defaults to an empty string.
2809 * @param {string[]} [parts]
2810 * An array of parts to join into an URL path. Parts may contain
2811 * slashes and any of the other characters mentioned above.
2814 * Return the joined URL path.
2816 path: function(prefix
, parts
) {
2817 var url
= [ prefix
|| '' ];
2819 for (var i
= 0; i
< parts
.length
; i
++)
2820 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts
[i
]))
2821 url
.push('/', parts
[i
]);
2823 if (url
.length
=== 1)
2826 return url
.join('');
2830 * Construct an URL pathrelative to the script path of the server
2831 * side LuCI application (usually `/cgi-bin/luci`).
2833 * The resulting URL is guaranteed to only contain the characters
2834 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2835 * as `/` for the path separator.
2840 * @param {string[]} [parts]
2841 * An array of parts to join into an URL path. Parts may contain
2842 * slashes and any of the other characters mentioned above.
2845 * Returns the resulting URL path.
2848 return this.path(env
.scriptname
, arguments
);
2852 * Construct an URL path relative to the global static resource path
2853 * of the LuCI ui (usually `/luci-static/resources`).
2855 * The resulting URL is guaranteed to only contain the characters
2856 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2857 * as `/` for the path separator.
2862 * @param {string[]} [parts]
2863 * An array of parts to join into an URL path. Parts may contain
2864 * slashes and any of the other characters mentioned above.
2867 * Returns the resulting URL path.
2869 resource: function() {
2870 return this.path(env
.resource
, arguments
);
2874 * Construct an URL path relative to the media resource path of the
2875 * LuCI ui (usually `/luci-static/$theme_name`).
2877 * The resulting URL is guaranteed to only contain the characters
2878 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2879 * as `/` for the path separator.
2884 * @param {string[]} [parts]
2885 * An array of parts to join into an URL path. Parts may contain
2886 * slashes and any of the other characters mentioned above.
2889 * Returns the resulting URL path.
2892 return this.path(env
.media
, arguments
);
2896 * Return the complete URL path to the current view.
2902 * Returns the URL path to the current view.
2904 location: function() {
2905 return this.path(env
.scriptname
, env
.requestpath
);
2910 * Tests whether the passed argument is a JavaScript object.
2911 * This function is meant to be an object counterpart to the
2912 * standard `Array.isArray()` function.
2921 * Returns `true` if the given value is of type object and
2922 * not `null`, else returns `false`.
2924 isObject: function(val
) {
2925 return (val
!= null && typeof(val
) == 'object');
2929 * Return an array of sorted object keys, optionally sorted by
2930 * a different key or a different sorting mode.
2935 * @param {object} obj
2936 * The object to extract the keys from. If the given value is
2937 * not an object, the function will return an empty array.
2939 * @param {string} [key]
2940 * Specifies the key to order by. This is mainly useful for
2941 * nested objects of objects or objects of arrays when sorting
2942 * shall not be performed by the primary object keys but by
2943 * some other key pointing to a value within the nested values.
2945 * @param {string} [sortmode]
2946 * May be either `addr` or `num` to override the natural
2947 * lexicographic sorting with a sorting suitable for IP/MAC style
2948 * addresses or numeric values respectively.
2950 * @return {string[]}
2951 * Returns an array containing the sorted keys of the given object.
2953 sortedKeys: function(obj
, key
, sortmode
) {
2954 if (obj
== null || typeof(obj
) != 'object')
2957 return Object
.keys(obj
).map(function(e
) {
2958 var v
= (key
!= null) ? obj
[e
][key
] : e
;
2962 v
= (v
!= null) ? v
.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
2963 function(m0
, m1
) { return ('000' + m1
.toLowerCase()).substr(-4) }) : null;
2967 v
= (v
!= null) ? +v
: null;
2972 }).filter(function(e
) {
2973 return (e
[1] != null);
2974 }).sort(function(a
, b
) {
2977 else if (a
[1] > b
[1])
2981 }).map(function(e
) {
2987 * Converts the given value to an array. If the given value is of
2988 * type array, it is returned as-is, values of type object are
2989 * returned as one-element array containing the object, empty
2990 * strings and `null` values are returned as empty array, all other
2991 * values are converted using `String()`, trimmed, split on white
2992 * space and returned as array.
2998 * The value to convert into an array.
3000 * @return {Array<*>}
3001 * Returns the resulting array.
3003 toArray: function(val
) {
3006 else if (Array
.isArray(val
))
3008 else if (typeof(val
) == 'object')
3011 var s
= String(val
).trim();
3016 return s
.split(/\s+/);
3020 * Returns a promise resolving with either the given value or or with
3021 * the given default in case the input value is a rejecting promise.
3027 * The value to resolve the promise with.
3029 * @param {*} defvalue
3030 * The default value to resolve the promise with in case the given
3031 * input value is a rejecting promise.
3033 * @returns {Promise<*>}
3034 * Returns a new promise resolving either to the given input value or
3035 * to the given default value on error.
3037 resolveDefault: function(value
, defvalue
) {
3038 return Promise
.resolve(value
).catch(function() { return defvalue
});
3042 * The request callback function is invoked whenever an HTTP
3043 * reply to a request made using the `L.get()`, `L.post()` or
3044 * `L.poll()` function is timed out or received successfully.
3049 * @callback LuCI.requestCallbackFn
3050 * @param {XMLHTTPRequest} xhr
3051 * The XMLHTTPRequest instance used to make the request.
3054 * The response JSON if the response could be parsed as such,
3057 * @param {number} duration
3058 * The total duration of the request in milliseconds.
3062 * Issues a GET request to the given url and invokes the specified
3063 * callback function. The function is a wrapper around
3064 * {@link LuCI.request#request Request.request()}.
3070 * @param {string} url
3071 * The URL to request.
3073 * @param {Object<string, string>} [args]
3074 * Additional query string arguments to append to the URL.
3076 * @param {LuCI.requestCallbackFn} cb
3077 * The callback function to invoke when the request finishes.
3079 * @return {Promise<null>}
3080 * Returns a promise resolving to `null` when concluded.
3082 get: function(url
, args
, cb
) {
3083 return this.poll(null, url
, args
, cb
, false);
3087 * Issues a POST request to the given url and invokes the specified
3088 * callback function. The function is a wrapper around
3089 * {@link LuCI.request#request Request.request()}. The request is
3090 * sent using `application/x-www-form-urlencoded` encoding and will
3091 * contain a field `token` with the current value of `LuCI.env.token`
3098 * @param {string} url
3099 * The URL to request.
3101 * @param {Object<string, string>} [args]
3102 * Additional post arguments to append to the request body.
3104 * @param {LuCI.requestCallbackFn} cb
3105 * The callback function to invoke when the request finishes.
3107 * @return {Promise<null>}
3108 * Returns a promise resolving to `null` when concluded.
3110 post: function(url
, args
, cb
) {
3111 return this.poll(null, url
, args
, cb
, true);
3115 * Register a polling HTTP request that invokes the specified
3116 * callback function. The function is a wrapper around
3117 * {@link LuCI.request.poll#add Request.poll.add()}.
3123 * @param {number} interval
3124 * The poll interval to use. If set to a value less than or equal
3125 * to `0`, it will default to the global poll interval configured
3126 * in `LuCI.env.pollinterval`.
3128 * @param {string} url
3129 * The URL to request.
3131 * @param {Object<string, string>} [args]
3132 * Specifies additional arguments for the request. For GET requests,
3133 * the arguments are appended to the URL as query string, for POST
3134 * requests, they'll be added to the request body.
3136 * @param {LuCI.requestCallbackFn} cb
3137 * The callback function to invoke whenever a request finishes.
3139 * @param {boolean} [post=false]
3140 * When set to `false` or not specified, poll requests will be made
3141 * using the GET method. When set to `true`, POST requests will be
3142 * issued. In case of POST requests, the request body will contain
3143 * an argument `token` with the current value of `LuCI.env.token` by
3144 * default, regardless of the parameters specified with `args`.
3146 * @return {function}
3147 * Returns the internally created function that has been passed to
3148 * {@link LuCI.request.poll#add Request.poll.add()}. This value can
3149 * be passed to {@link LuCI.poll.remove Poll.remove()} to remove the
3152 poll: function(interval
, url
, args
, cb
, post
) {
3153 if (interval
!== null && interval
<= 0)
3154 interval
= env
.pollinterval
;
3156 var data
= post
? { token
: env
.token
} : null,
3157 method
= post
? 'POST' : 'GET';
3159 if (!/^(?:\/|\S+:\/\/)/.test(url
))
3160 url
= this.url(url
);
3163 data
= Object
.assign(data
|| {}, args
);
3165 if (interval
!== null)
3166 return Request
.poll
.add(interval
, url
, { method
: method
, query
: data
}, cb
);
3168 return Request
.request(url
, { method
: method
, query
: data
})
3169 .then(function(res
) {
3171 if (/^application\/json\b/.test(res
.headers
.get('Content-Type')))
3172 try { json
= res
.json() } catch(e
) {}
3173 cb(res
.xhr
, json
, res
.duration
);
3178 * Check whether a view has sufficient permissions.
3180 * @return {boolean|null}
3181 * Returns `null` if the current session has no permission at all to
3182 * load resources required by the view. Returns `false` if readonly
3183 * permissions are granted or `true` if at least one required ACL
3184 * group is granted with write permissions.
3186 hasViewPermission: function() {
3187 if (!this.isObject(env
.nodespec
) || !env
.nodespec
.satisfied
)
3190 return !env
.nodespec
.readonly
;
3194 * Deprecated wrapper around {@link LuCI.poll.remove Poll.remove()}.
3200 * @param {function} entry
3201 * The polling function to remove.
3204 * Returns `true` when the function has been removed or `false` if
3205 * it could not be found.
3207 stop: function(entry
) { return Poll
.remove(entry
) },
3210 * Deprecated wrapper around {@link LuCI.poll.stop Poll.stop()}.
3217 * Returns `true` when the polling loop has been stopped or `false`
3218 * when it didn't run to begin with.
3220 halt: function() { return Poll
.stop() },
3223 * Deprecated wrapper around {@link LuCI.poll.start Poll.start()}.
3230 * Returns `true` when the polling loop has been started or `false`
3231 * when it was already running.
3233 run: function() { return Poll
.start() },
3236 * Legacy `L.dom` class alias. New view code should use `'require dom';`
3237 * to request the `LuCI.dom` class.
3246 * Legacy `L.view` class alias. New view code should use `'require view';`
3247 * to request the `LuCI.view` class.
3256 * Legacy `L.Poll` class alias. New view code should use `'require poll';`
3257 * to request the `LuCI.poll` class.
3266 * Legacy `L.Request` class alias. New view code should use `'require request';`
3267 * to request the `LuCI.request` class.
3276 * Legacy `L.Class` class alias. New view code should use `'require baseclass';`
3277 * to request the `LuCI.baseclass` class.
3292 * The `LuCI.xhr` class is a legacy compatibility shim for the
3293 * functionality formerly provided by `xhr.js`. It is registered as global
3294 * `window.XHR` symbol for compatibility with legacy code.
3296 * New code should use {@link LuCI.request} instead to implement HTTP
3299 var XHR
= Class
.extend(/** @lends LuCI.xhr.prototype */ {
3300 __name__
: 'LuCI.xhr',
3301 __init__: function() {
3302 if (window
.console
&& console
.debug
)
3303 console
.debug('Direct use XHR() is deprecated, please use L.Request instead');
3306 _response: function(cb
, res
, json
, duration
) {
3308 cb(res
, json
, duration
);
3313 * This function is a legacy wrapper around
3314 * {@link LuCI#get LuCI.get()}.
3318 * @memberof LuCI.xhr
3320 * @param {string} url
3321 * The URL to request
3323 * @param {Object} [data]
3324 * Additional query string data
3326 * @param {LuCI.requestCallbackFn} [callback]
3327 * Callback function to invoke on completion
3329 * @param {number} [timeout]
3330 * Request timeout to use
3332 * @return {Promise<null>}
3334 get: function(url
, data
, callback
, timeout
) {
3336 LuCI
.prototype.get(url
, data
, this._response
.bind(this, callback
), timeout
);
3340 * This function is a legacy wrapper around
3341 * {@link LuCI#post LuCI.post()}.
3345 * @memberof LuCI.xhr
3347 * @param {string} url
3348 * The URL to request
3350 * @param {Object} [data]
3351 * Additional data to append to the request body.
3353 * @param {LuCI.requestCallbackFn} [callback]
3354 * Callback function to invoke on completion
3356 * @param {number} [timeout]
3357 * Request timeout to use
3359 * @return {Promise<null>}
3361 post: function(url
, data
, callback
, timeout
) {
3363 LuCI
.prototype.post(url
, data
, this._response
.bind(this, callback
), timeout
);
3367 * Cancels a running request.
3369 * This function does not actually cancel the underlying
3370 * `XMLHTTPRequest` request but it sets a flag which prevents the
3371 * invocation of the callback function when the request eventually
3372 * finishes or timed out.
3376 * @memberof LuCI.xhr
3378 cancel: function() { delete this.active
},
3381 * Checks the running state of the request.
3385 * @memberof LuCI.xhr
3387 * @returns {boolean}
3388 * Returns `true` if the request is still running or `false` if it
3389 * already completed.
3391 busy: function() { return (this.active
=== true) },
3394 * Ignored for backwards compatibility.
3396 * This function does nothing.
3400 * @memberof LuCI.xhr
3402 abort: function() {},
3405 * Existing for backwards compatibility.
3407 * This function simply throws an `InternalError` when invoked.
3411 * @memberof LuCI.xhr
3413 * @throws {InternalError}
3414 * Throws an `InternalError` with the message `Not implemented`
3417 send_form: function() { LuCI
.prototype.error('InternalError', 'Not implemented') },
3420 XHR
.get = function() { return LuCI
.prototype.get.apply(LuCI
.prototype, arguments
) };
3421 XHR
.post = function() { return LuCI
.prototype.post
.apply(LuCI
.prototype, arguments
) };
3422 XHR
.poll = function() { return LuCI
.prototype.poll
.apply(LuCI
.prototype, arguments
) };
3423 XHR
.stop
= Request
.poll
.remove
.bind(Request
.poll
);
3424 XHR
.halt
= Request
.poll
.stop
.bind(Request
.poll
);
3425 XHR
.run
= Request
.poll
.start
.bind(Request
.poll
);
3426 XHR
.running
= Request
.poll
.active
.bind(Request
.poll
);
3430 })(window
, document
);