luci-base: luci.js: tweak CSS classes
[oweals/luci.git] / modules / luci-base / htdocs / luci-static / resources / luci.js
1 /**
2  * @class LuCI
3  * @classdesc
4  *
5  * This is the LuCI base class. It is automatically instantiated and
6  * accessible using the global `L` variable.
7  *
8  * @param {Object} env
9  * The environment settings to use for the LuCI runtime.
10  */
11
12 (function(window, document, undefined) {
13         'use strict';
14
15         /* Object.assign polyfill for IE */
16         if (typeof Object.assign !== 'function') {
17                 Object.defineProperty(Object, 'assign', {
18                         value: function assign(target, varArgs) {
19                                 if (target == null)
20                                         throw new TypeError('Cannot convert undefined or null to object');
21
22                                 var to = Object(target);
23
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];
29
30                                 return to;
31                         },
32                         writable: true,
33                         configurable: true
34                 });
35         }
36
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);
42                         };
43
44                         return this.then(
45                                 function(result) { return onFinally.call(this, function() { return result }) },
46                                 function(reason) { return onFinally.call(this, function() { return Promise.reject(reason) }) }
47                         );
48                 };
49         }
50
51         /*
52          * Class declaration and inheritance helper
53          */
54
55         var toCamelCase = function(s) {
56                 return s.replace(/(?:^|[\. -])(.)/g, function(m0, m1) { return m1.toUpperCase() });
57         };
58
59         /**
60          * @class Class
61          * @hideconstructor
62          * @memberof LuCI
63          * @classdesc
64          *
65          * `LuCI.Class` is the abstract base class all LuCI classes inherit from.
66          *
67          * It provides simple means to create subclasses of given classes and
68          * implements prototypal inheritance.
69          */
70         var superContext = {}, classIndex = 0, Class = Object.assign(function() {}, {
71                 /**
72                  * Extends this base class with the properties described in
73                  * `properties` and returns a new subclassed Class instance
74                  *
75                  * @memberof LuCI.Class
76                  *
77                  * @param {Object<string, *>} properties
78                  * An object describing the properties to add to the new
79                  * subclass.
80                  *
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`.
86                  */
87                 extend: function(properties) {
88                         var props = {
89                                 __id__: { value: classIndex },
90                                 __base__: { value: this.prototype },
91                                 __name__: { value: properties.__name__ || 'anonymous' + classIndex++ }
92                         };
93
94                         var ClassConstructor = function() {
95                                 if (!(this instanceof ClassConstructor))
96                                         throw new TypeError('Constructor must not be called without "new"');
97
98                                 if (Object.getPrototypeOf(this).hasOwnProperty('__init__')) {
99                                         if (typeof(this.__init__) != 'function')
100                                                 throw new TypeError('Class __init__ member is not a function');
101
102                                         this.__init__.apply(this, arguments)
103                                 }
104                                 else {
105                                         this.super('__init__', arguments);
106                                 }
107                         };
108
109                         for (var key in properties)
110                                 if (!props[key] && properties.hasOwnProperty(key))
111                                         props[key] = { value: properties[key], writable: true };
112
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');
117
118                         return ClassConstructor;
119                 },
120
121                 /**
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.
126                  *
127                  * This function serves as a convenience shortcut for
128                  * {@link LuCI.Class.extend Class.extend()} and subsequent
129                  * `new`.
130                  *
131                  * @memberof LuCI.Class
132                  *
133                  * @param {Object<string, *>} properties
134                  * An object describing the properties to add to the new
135                  * subclass.
136                  *
137                  * @param {...*} [new_args]
138                  * Specifies arguments to be passed to the subclass constructor
139                  * as-is in order to instantiate the new subclass.
140                  *
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.
145                  */
146                 singleton: function(properties /*, ... */) {
147                         return Class.extend(properties)
148                                 .instantiate(Class.prototype.varargs(arguments, 1));
149                 },
150
151                 /**
152                  * Calls the class constructor using `new` with the given argument
153                  * array being passed as variadic parameters to the constructor.
154                  *
155                  * @memberof LuCI.Class
156                  *
157                  * @param {Array<*>} params
158                  * An array of arbitrary values which will be passed as arguments
159                  * to the constructor function.
160                  *
161                  * @param {...*} [new_args]
162                  * Specifies arguments to be passed to the subclass constructor
163                  * as-is in order to instantiate the new subclass.
164                  *
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.
169                  */
170                 instantiate: function(args) {
171                         return new (Function.prototype.bind.apply(this,
172                                 Class.prototype.varargs(args, 0, null)))();
173                 },
174
175                 /* unused */
176                 call: function(self, method) {
177                         if (typeof(this.prototype[method]) != 'function')
178                                 throw new ReferenceError(method + ' is not defined in class');
179
180                         return this.prototype[method].apply(self, self.varargs(arguments, 1));
181                 },
182
183                 /**
184                  * Checks whether the given class value is a subclass of this class.
185                  *
186                  * @memberof LuCI.Class
187                  *
188                  * @param {LuCI.Class} classValue
189                  * The class object to test.
190                  *
191                  * @returns {boolean}
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'.
195                  */
196                 isSubclass: function(classValue) {
197                         return (classValue != null &&
198                                 typeof(classValue) == 'function' &&
199                                 classValue.prototype instanceof this);
200                 },
201
202                 prototype: {
203                         /**
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.
207                          *
208                          * @memberof LuCI.Class
209                          * @instance
210                          *
211                          * @param {Array<*>} args
212                          * The array to extract the values from.
213                          *
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.
217                          *
218                          * @param {...*} [extra_args]
219                          * Extra arguments to add to prepend to the resultung array.
220                          *
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
224                          * `offset`.
225                          */
226                         varargs: function(args, offset /*, ... */) {
227                                 return Array.prototype.slice.call(arguments, 2)
228                                         .concat(Array.prototype.slice.call(args, offset));
229                         },
230
231                         /**
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.
237                          *
238                          * This function has two signatures and is sensitive to the
239                          * amount of arguments passed to it:
240                          *  - `super('key')` -
241                          *    Returns the value of `key` when found within one of the
242                          *    parent classes.
243                          *  - `super('key', ['arg1', 'arg2'])` -
244                          *    Calls the `key()` method with parameters `arg1` and `arg2`
245                          *    when found within one of the parent classes.
246                          *
247                          * @memberof LuCI.Class
248                          * @instance
249                          *
250                          * @param {string} key
251                          * The name of the superclass member to retrieve.
252                          *
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.
257                          *
258                          * @throws {ReferenceError}
259                          * Throws a `ReferenceError` when `callArgs` are specified and
260                          * the found member named by `key` is not a function value.
261                          *
262                          * @returns {*|null}
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`.
267                          */
268                         super: function(key, callArgs) {
269                                 if (key == null)
270                                         return null;
271
272                                 var slotIdx = this.__id__ + '.' + key,
273                                     symStack = superContext[slotIdx],
274                                     protoCtx = null;
275
276                                 for (protoCtx = Object.getPrototypeOf(symStack ? symStack[0] : Object.getPrototypeOf(this));
277                                      protoCtx != null && !protoCtx.hasOwnProperty(key);
278                                      protoCtx = Object.getPrototypeOf(protoCtx)) {}
279
280                                 if (protoCtx == null)
281                                         return null;
282
283                                 var res = protoCtx[key];
284
285                                 if (arguments.length > 1) {
286                                         if (typeof(res) != 'function')
287                                                 throw new ReferenceError(key + ' is not a function in base class');
288
289                                         if (typeof(callArgs) != 'object')
290                                                 callArgs = this.varargs(arguments, 1);
291
292                                         if (symStack)
293                                                 symStack.unshift(protoCtx);
294                                         else
295                                                 superContext[slotIdx] = [ protoCtx ];
296
297                                         res = res.apply(this, callArgs);
298
299                                         if (symStack && symStack.length > 1)
300                                                 symStack.shift(protoCtx);
301                                         else
302                                                 delete superContext[slotIdx];
303                                 }
304
305                                 return res;
306                         },
307
308                         /**
309                          * Returns a string representation of this class.
310                          *
311                          * @returns {string}
312                          * Returns a string representation of this class containing the
313                          * constructor functions `displayName` and describing the class
314                          * members and their respective types.
315                          */
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';
321                                                 f = false;
322                                         }
323                                 }
324                                 return s + (f ? '' : '}');
325                         }
326                 }
327         });
328
329
330         /**
331          * @class
332          * @memberof LuCI
333          * @hideconstructor
334          * @classdesc
335          *
336          * The `Headers` class is an internal utility class exposed in HTTP
337          * response objects using the `response.headers` property.
338          */
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);
345                                 if (m != null)
346                                         hdrs[m[1].trim().toLowerCase()] = m[2].trim();
347                         });
348                 },
349
350                 /**
351                  * Checks whether the given header name is present.
352                  * Note: Header-Names are case-insensitive.
353                  *
354                  * @instance
355                  * @memberof LuCI.Headers
356                  * @param {string} name
357                  * The header name to check
358                  *
359                  * @returns {boolean}
360                  * Returns `true` if the header name is present, `false` otherwise
361                  */
362                 has: function(name) {
363                         return this.headers.hasOwnProperty(String(name).toLowerCase());
364                 },
365
366                 /**
367                  * Returns the value of the given header name.
368                  * Note: Header-Names are case-insensitive.
369                  *
370                  * @instance
371                  * @memberof LuCI.Headers
372                  * @param {string} name
373                  * The header name to read
374                  *
375                  * @returns {string|null}
376                  * The value of the given header name or `null` if the header isn't present.
377                  */
378                 get: function(name) {
379                         var key = String(name).toLowerCase();
380                         return this.headers.hasOwnProperty(key) ? this.headers[key] : null;
381                 }
382         });
383
384         /**
385          * @class
386          * @memberof LuCI
387          * @hideconstructor
388          * @classdesc
389          *
390          * The `Response` class is an internal utility class representing HTTP responses.
391          */
392         var Response = Class.extend({
393                 __name__: 'LuCI.XHR.Response',
394                 __init__: function(xhr, url, duration, headers, content) {
395                         /**
396                          * Describes whether the response is successful (status codes `200..299`) or not
397                          * @instance
398                          * @memberof LuCI.Response
399                          * @name ok
400                          * @type {boolean}
401                          */
402                         this.ok = (xhr.status >= 200 && xhr.status <= 299);
403
404                         /**
405                          * The numeric HTTP status code of the response
406                          * @instance
407                          * @memberof LuCI.Response
408                          * @name status
409                          * @type {number}
410                          */
411                         this.status = xhr.status;
412
413                         /**
414                          * The HTTP status description message of the response
415                          * @instance
416                          * @memberof LuCI.Response
417                          * @name statusText
418                          * @type {string}
419                          */
420                         this.statusText = xhr.statusText;
421
422                         /**
423                          * The HTTP headers of the response
424                          * @instance
425                          * @memberof LuCI.Response
426                          * @name headers
427                          * @type {LuCI.Headers}
428                          */
429                         this.headers = (headers != null) ? headers : new Headers(xhr);
430
431                         /**
432                          * The total duration of the HTTP request in milliseconds
433                          * @instance
434                          * @memberof LuCI.Response
435                          * @name duration
436                          * @type {number}
437                          */
438                         this.duration = duration;
439
440                         /**
441                          * The final URL of the request, i.e. after following redirects.
442                          * @instance
443                          * @memberof LuCI.Response
444                          * @name url
445                          * @type {string}
446                          */
447                         this.url = url;
448
449                         /* privates */
450                         this.xhr = xhr;
451
452                         if (content instanceof Blob) {
453                                 this.responseBlob = content;
454                                 this.responseJSON = null;
455                                 this.responseText = null;
456                         }
457                         else if (content != null && typeof(content) == 'object') {
458                                 this.responseBlob = null;
459                                 this.responseJSON = content;
460                                 this.responseText = null;
461                         }
462                         else if (content != null) {
463                                 this.responseBlob = null;
464                                 this.responseJSON = null;
465                                 this.responseText = String(content);
466                         }
467                         else {
468                                 this.responseJSON = null;
469
470                                 if (xhr.responseType == 'blob') {
471                                         this.responseBlob = xhr.response;
472                                         this.responseText = null;
473                                 }
474                                 else {
475                                         this.responseBlob = null;
476                                         this.responseText = xhr.responseText;
477                                 }
478                         }
479                 },
480
481                 /**
482                  * Clones the given response object, optionally overriding the content
483                  * of the cloned instance.
484                  *
485                  * @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.
491                  *
492                  * @returns {LuCI.Response}
493                  * The cloned `Response` instance.
494                  */
495                 clone: function(content) {
496                         var copy = new Response(this.xhr, this.url, this.duration, this.headers, content);
497
498                         copy.ok = this.ok;
499                         copy.status = this.status;
500                         copy.statusText = this.statusText;
501
502                         return copy;
503                 },
504
505                 /**
506                  * Access the response content as JSON data.
507                  *
508                  * @instance
509                  * @memberof LuCI.Response
510                  * @throws {SyntaxError}
511                  * Throws `SyntaxError` if the content isn't valid JSON.
512                  *
513                  * @returns {*}
514                  * The parsed JSON data.
515                  */
516                 json: function() {
517                         if (this.responseJSON == null)
518                                 this.responseJSON = JSON.parse(this.responseText);
519
520                         return this.responseJSON;
521                 },
522
523                 /**
524                  * Access the response content as string.
525                  *
526                  * @instance
527                  * @memberof LuCI.Response
528                  * @returns {string}
529                  * The response content.
530                  */
531                 text: function() {
532                         if (this.responseText == null && this.responseJSON != null)
533                                 this.responseText = JSON.stringify(this.responseJSON);
534
535                         return this.responseText;
536                 },
537
538                 /**
539                  * Access the response content as blob.
540                  *
541                  * @instance
542                  * @memberof LuCI.Response
543                  * @returns {Blob}
544                  * The response content as blob.
545                  */
546                 blob: function() {
547                         return this.responseBlob;
548                 }
549         });
550
551
552         var requestQueue = [];
553
554         function isQueueableRequest(opt) {
555                 if (!classes.rpc)
556                         return false;
557
558                 if (opt.method != 'POST' || typeof(opt.content) != 'object')
559                         return false;
560
561                 if (opt.nobatch === true)
562                         return false;
563
564                 var rpcBaseURL = Request.expandURL(classes.rpc.getBaseURL());
565
566                 return (rpcBaseURL != null && opt.url.indexOf(rpcBaseURL) == 0);
567         }
568
569         function flushRequestQueue() {
570                 if (!requestQueue.length)
571                         return;
572
573                 var reqopt = Object.assign({}, requestQueue[0][0], { content: [], nobatch: true }),
574                     batch = [];
575
576                 for (var i = 0; i < requestQueue.length; i++) {
577                         batch[i] = requestQueue[i];
578                         reqopt.content[i] = batch[i][0].content;
579                 }
580
581                 requestQueue.length = 0;
582
583                 Request.request(rpcBaseURL, reqopt).then(function(reply) {
584                         var json = null, req = null;
585
586                         try { json = reply.json() }
587                         catch(e) { }
588
589                         while ((req = batch.shift()) != null)
590                                 if (Array.isArray(json) && json.length)
591                                         req[2].call(reqopt, reply.clone(json.shift()));
592                                 else
593                                         req[1].call(reqopt, new Error('No related RPC reply'));
594                 }).catch(function(error) {
595                         var req = null;
596
597                         while ((req = batch.shift()) != null)
598                                 req[1].call(reqopt, error);
599                 });
600         }
601
602         /**
603          * @class
604          * @memberof LuCI
605          * @hideconstructor
606          * @classdesc
607          *
608          * The `Request` class allows initiating HTTP requests and provides utilities
609          * for dealing with responses.
610          */
611         var Request = Class.singleton(/** @lends LuCI.Request.prototype */ {
612                 __name__: 'LuCI.Request',
613
614                 interceptors: [],
615
616                 /**
617                  * Turn the given relative URL into an absolute URL if necessary.
618                  *
619                  * @instance
620                  * @memberof LuCI.Request
621                  * @param {string} url
622                  * The URL to convert.
623                  *
624                  * @returns {string}
625                  * The absolute URL derived from the given one, or the original URL
626                  * if it already was absolute.
627                  */
628                 expandURL: function(url) {
629                         if (!/^(?:[^/]+:)?\/\//.test(url))
630                                 url = location.protocol + '//' + location.host + url;
631
632                         return url;
633                 },
634
635                 /**
636                  * @typedef {Object} RequestOptions
637                  * @memberof LuCI.Request
638                  *
639                  * @property {string} [method=GET]
640                  * The HTTP method to use, e.g. `GET` or `POST`.
641                  *
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.
645                  *
646                  * @property {boolean} [cache=false]
647                  * Specifies whether the HTTP response may be retrieved from cache.
648                  *
649                  * @property {string} [username]
650                  * Provides a username for HTTP basic authentication.
651                  *
652                  * @property {string} [password]
653                  * Provides a password for HTTP basic authentication.
654                  *
655                  * @property {number} [timeout]
656                  * Specifies the request timeout in seconds.
657                  *
658                  * @property {boolean} [credentials=false]
659                  * Whether to include credentials such as cookies in the request.
660                  *
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.
665                  *
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.
672                  *
673              * @property {Object<string, string>} [header]
674              * Specifies HTTP headers to set for the request.
675              *
676              * @property {function} [progress]
677              * An optional request callback function which receives ProgressEvent
678              * instances as sole argument during the HTTP request transfer.
679                  */
680
681                 /**
682                  * Initiate an HTTP request to the given target.
683                  *
684                  * @instance
685                  * @memberof LuCI.Request
686                  * @param {string} target
687                  * The URL to request.
688                  *
689                  * @param {LuCI.Request.RequestOptions} [options]
690                  * Additional options to configure the request.
691                  *
692                  * @returns {Promise<LuCI.Response>}
693                  * The resulting HTTP response.
694                  */
695                 request: function(target, options) {
696                         var state = { xhr: new XMLHttpRequest(), url: this.expandURL(target), start: Date.now() },
697                             opt = Object.assign({}, options, state),
698                             content = null,
699                             contenttype = null,
700                             callback = this.handleReadyStateChange;
701
702                         return new Promise(function(resolveFn, rejectFn) {
703                                 opt.xhr.onreadystatechange = callback.bind(opt, resolveFn, rejectFn);
704                                 opt.method = String(opt.method || 'GET').toUpperCase();
705
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]);
712
713                                                         return '%s=%s'.format(encodeURIComponent(k), encodeURIComponent(v));
714                                                 }
715                                                 else {
716                                                         return encodeURIComponent(k);
717                                                 }
718                                         }).join('&') : '';
719
720                                         if (q !== '') {
721                                                 switch (opt.method) {
722                                                 case 'GET':
723                                                 case 'HEAD':
724                                                 case 'OPTIONS':
725                                                         opt.url += ((/\?/).test(opt.url) ? '&' : '?') + q;
726                                                         break;
727
728                                                 default:
729                                                         if (content == null) {
730                                                                 content = q;
731                                                                 contenttype = 'application/x-www-form-urlencoded';
732                                                         }
733                                                 }
734                                         }
735                                 }
736
737                                 if (!opt.cache)
738                                         opt.url += ((/\?/).test(opt.url) ? '&' : '?') + (new Date()).getTime();
739
740                                 if (isQueueableRequest(opt)) {
741                                         requestQueue.push([opt, rejectFn, resolveFn]);
742                                         requestAnimationFrame(flushRequestQueue);
743                                         return;
744                                 }
745
746                                 if ('username' in opt && 'password' in opt)
747                                         opt.xhr.open(opt.method, opt.url, true, opt.username, opt.password);
748                                 else
749                                         opt.xhr.open(opt.method, opt.url, true);
750
751                                 opt.xhr.responseType = opt.responseType || 'text';
752
753                                 if ('overrideMimeType' in opt.xhr)
754                                         opt.xhr.overrideMimeType('application/octet-stream');
755
756                                 if ('timeout' in opt)
757                                         opt.xhr.timeout = +opt.timeout;
758
759                                 if ('credentials' in opt)
760                                         opt.xhr.withCredentials = !!opt.credentials;
761
762                                 if (opt.content != null) {
763                                         switch (typeof(opt.content)) {
764                                         case 'function':
765                                                 content = opt.content(xhr);
766                                                 break;
767
768                                         case 'object':
769                                                 if (!(opt.content instanceof FormData)) {
770                                                         content = JSON.stringify(opt.content);
771                                                         contenttype = 'application/json';
772                                                 }
773                                                 else {
774                                                         content = opt.content;
775                                                 }
776                                                 break;
777
778                                         default:
779                                                 content = String(opt.content);
780                                         }
781                                 }
782
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]);
788                                                         else
789                                                                 contenttype = opt.headers[header];
790                                                 }
791
792                                 if ('progress' in opt && 'upload' in opt.xhr)
793                                         opt.xhr.upload.addEventListener('progress', opt.progress);
794
795                                 if (contenttype != null)
796                                         opt.xhr.setRequestHeader('Content-Type', contenttype);
797
798                                 try {
799                                         opt.xhr.send(content);
800                                 }
801                                 catch (e) {
802                                         rejectFn.call(opt, e);
803                                 }
804                         });
805                 },
806
807                 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
808                         var xhr = this.xhr,
809                             duration = Date.now() - this.start;
810
811                         if (xhr.readyState !== 4)
812                                 return;
813
814                         if (xhr.status === 0 && xhr.statusText === '') {
815                                 if (duration >= this.timeout)
816                                         rejectFn.call(this, new Error('XHR request timed out'));
817                                 else
818                                         rejectFn.call(this, new Error('XHR request aborted by browser'));
819                         }
820                         else {
821                                 var response = new Response(
822                                         xhr, xhr.responseURL || this.url, duration);
823
824                                 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
825                                         .then(resolveFn.bind(this, response))
826                                         .catch(rejectFn.bind(this));
827                         }
828                 },
829
830                 /**
831                  * Initiate an HTTP GET request to the given target.
832                  *
833                  * @instance
834                  * @memberof LuCI.Request
835                  * @param {string} target
836                  * The URL to request.
837                  *
838                  * @param {LuCI.Request.RequestOptions} [options]
839                  * Additional options to configure the request.
840                  *
841                  * @returns {Promise<LuCI.Response>}
842                  * The resulting HTTP response.
843                  */
844                 get: function(url, options) {
845                         return this.request(url, Object.assign({ method: 'GET' }, options));
846                 },
847
848                 /**
849                  * Initiate an HTTP POST request to the given target.
850                  *
851                  * @instance
852                  * @memberof LuCI.Request
853                  * @param {string} target
854                  * The URL to request.
855                  *
856                  * @param {*} [data]
857                  * The request data to send, see {@link LuCI.Request.RequestOptions} for details.
858                  *
859                  * @param {LuCI.Request.RequestOptions} [options]
860                  * Additional options to configure the request.
861                  *
862                  * @returns {Promise<LuCI.Response>}
863                  * The resulting HTTP response.
864                  */
865                 post: function(url, data, options) {
866                         return this.request(url, Object.assign({ method: 'POST', content: data }, options));
867                 },
868
869                 /**
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
875                  */
876
877                 /**
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.
882                  *
883                  * @instance
884                  * @memberof LuCI.Request
885                  * @param {LuCI.Request.interceptorFn} interceptorFn
886                  * The interceptor function to register.
887                  *
888                  * @returns {LuCI.Request.interceptorFn}
889                  * The registered function.
890                  */
891                 addInterceptor: function(interceptorFn) {
892                         if (typeof(interceptorFn) == 'function')
893                                 this.interceptors.push(interceptorFn);
894                         return interceptorFn;
895                 },
896
897                 /**
898                  * Remove an HTTP response interceptor function. The passed function
899                  * value must be the very same value that was used to register the
900                  * function.
901                  *
902                  * @instance
903                  * @memberof LuCI.Request
904                  * @param {LuCI.Request.interceptorFn} interceptorFn
905                  * The interceptor function to remove.
906                  *
907                  * @returns {boolean}
908                  * Returns `true` if any function has been removed, else `false`.
909                  */
910                 removeInterceptor: function(interceptorFn) {
911                         var oldlen = this.interceptors.length, i = oldlen;
912                         while (i--)
913                                 if (this.interceptors[i] === interceptorFn)
914                                         this.interceptors.splice(i, 1);
915                         return (this.interceptors.length < oldlen);
916                 },
917
918                 /**
919                  * @class
920                  * @memberof LuCI.Request
921                  * @hideconstructor
922                  * @classdesc
923                  *
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.
927                  */
928                 poll: {
929                         /**
930                          * The callback function is invoked whenever an HTTP reply to a
931                          * polled request is received or when the polled request timed
932                          * out.
933                          *
934                          * @callback LuCI.Request.poll~callbackFn
935                          * @param {LuCI.Response} res
936                          * The HTTP response object.
937                          *
938                          * @param {*} data
939                          * The response JSON if the response could be parsed as such,
940                          * else `null`.
941                          *
942                          * @param {number} duration
943                          * The total duration of the request in milliseconds.
944                          */
945
946                         /**
947                          * Register a repeating HTTP request with an optional callback
948                          * to invoke whenever a response for the request is received.
949                          *
950                          * @instance
951                          * @memberof LuCI.Request.poll
952                          * @param {number} interval
953                          * The poll interval in seconds.
954                          *
955                          * @param {string} url
956                          * The URL to request on each poll.
957                          *
958                          * @param {LuCI.Request.RequestOptions} [options]
959                          * Additional options to configure the request.
960                          *
961                          * @param {LuCI.Request.poll~callbackFn} [callback]
962                          * {@link LuCI.Request.poll~callbackFn Callback} function to
963                          * invoke for each HTTP reply.
964                          *
965                          * @throws {TypeError}
966                          * Throws `TypeError` when an invalid interval was passed.
967                          *
968                          * @returns {function}
969                          * Returns the internally created poll function.
970                          */
971                         add: function(interval, url, options, callback) {
972                                 if (isNaN(interval) || interval <= 0)
973                                         throw new TypeError('Invalid poll interval');
974
975                                 var ival = interval >>> 0,
976                                     opts = Object.assign({}, options, { timeout: ival * 1000 - 5 });
977
978                                 var fn = function() {
979                                         return Request.request(url, options).then(function(res) {
980                                                 if (!Poll.active())
981                                                         return;
982
983                                                 try {
984                                                         callback(res, res.json(), res.duration);
985                                                 }
986                                                 catch (err) {
987                                                         callback(res, null, res.duration);
988                                                 }
989                                         });
990                                 };
991
992                                 return (Poll.add(fn, ival) ? fn : null);
993                         },
994
995                         /**
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()}.
999                          *
1000                          * @instance
1001                          * @memberof LuCI.Request.poll
1002                          * @param {function} entry
1003                          * The poll function returned by {@link LuCI.Request.poll#add add()}.
1004                          *
1005                          * @returns {boolean}
1006                          * Returns `true` if any function has been removed, else `false`.
1007                          */
1008                         remove: function(entry) { return Poll.remove(entry) },
1009
1010                         /**
1011                           * Alias for {@link LuCI.Poll.start LuCI.Poll.start()}.
1012                           *
1013                           * @instance
1014                           * @memberof LuCI.Request.poll
1015                           */
1016                         start: function() { return Poll.start() },
1017
1018                         /**
1019                           * Alias for {@link LuCI.Poll.stop LuCI.Poll.stop()}.
1020                           *
1021                           * @instance
1022                           * @memberof LuCI.Request.poll
1023                           */
1024                         stop: function() { return Poll.stop() },
1025
1026                         /**
1027                           * Alias for {@link LuCI.Poll.active LuCI.Poll.active()}.
1028                           *
1029                           * @instance
1030                           * @memberof LuCI.Request.poll
1031                           */
1032                         active: function() { return Poll.active() }
1033                 }
1034         });
1035
1036         /**
1037          * @class
1038          * @memberof LuCI
1039          * @hideconstructor
1040          * @classdesc
1041          *
1042          * The `Poll` class allows registering and unregistering poll actions,
1043          * as well as starting, stopping and querying the state of the polling
1044          * loop.
1045          */
1046         var Poll = Class.singleton(/** @lends LuCI.Poll.prototype */ {
1047                 __name__: 'LuCI.Poll',
1048
1049                 queue: [],
1050
1051                 /**
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.
1054                  *
1055                  * @instance
1056                  * @memberof LuCI.Poll
1057                  * @param {function} fn
1058                  * The function to invoke on each poll interval.
1059                  *
1060                  * @param {number} interval
1061                  * The poll interval in seconds.
1062                  *
1063                  * @throws {TypeError}
1064                  * Throws `TypeError` when an invalid interval was passed.
1065                  *
1066                  * @returns {boolean}
1067                  * Returns `true` if the function has been added or `false` if it
1068                  * already is registered.
1069                  */
1070                 add: function(fn, interval) {
1071                         if (interval == null || interval <= 0)
1072                                 interval = window.L ? window.L.env.pollinterval : null;
1073
1074                         if (isNaN(interval) || typeof(fn) != 'function')
1075                                 throw new TypeError('Invalid argument to LuCI.Poll.add()');
1076
1077                         for (var i = 0; i < this.queue.length; i++)
1078                                 if (this.queue[i].fn === fn)
1079                                         return false;
1080
1081                         var e = {
1082                                 r: true,
1083                                 i: interval >>> 0,
1084                                 fn: fn
1085                         };
1086
1087                         this.queue.push(e);
1088
1089                         if (this.tick != null && !this.active())
1090                                 this.start();
1091
1092                         return true;
1093                 },
1094
1095                 /**
1096                  * Remove an operation from the polling loop. If no further operatons
1097                  * are registered, the polling loop is implicitely stopped.
1098                  *
1099                  * @instance
1100                  * @memberof LuCI.Poll
1101                  * @param {function} fn
1102                  * The function to remove.
1103                  *
1104                  * @throws {TypeError}
1105                  * Throws `TypeError` when the given argument isn't a function.
1106                  *
1107                  * @returns {boolean}
1108                  * Returns `true` if the function has been removed or `false` if it
1109                  * wasn't found.
1110                  */
1111                 remove: function(fn) {
1112                         if (typeof(fn) != 'function')
1113                                 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
1114
1115                         var len = this.queue.length;
1116
1117                         for (var i = len; i > 0; i--)
1118                                 if (this.queue[i-1].fn === fn)
1119                                         this.queue.splice(i-1, 1);
1120
1121                         if (!this.queue.length && this.stop())
1122                                 this.tick = 0;
1123
1124                         return (this.queue.length != len);
1125                 },
1126
1127                 /**
1128                  * (Re)start the polling loop. Dispatches a custom `poll-start` event
1129                  * to the `document` object upon successful start.
1130                  *
1131                  * @instance
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.
1136                  */
1137                 start: function() {
1138                         if (this.active())
1139                                 return false;
1140
1141                         this.tick = 0;
1142
1143                         if (this.queue.length) {
1144                                 this.timer = window.setInterval(this.step, 1000);
1145                                 this.step();
1146                                 document.dispatchEvent(new CustomEvent('poll-start'));
1147                         }
1148
1149                         return true;
1150                 },
1151
1152                 /**
1153                  * Stop the polling loop. Dispatches a custom `poll-stop` event
1154                  * to the `document` object upon successful stop.
1155                  *
1156                  * @instance
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.
1161                  */
1162                 stop: function() {
1163                         if (!this.active())
1164                                 return false;
1165
1166                         document.dispatchEvent(new CustomEvent('poll-stop'));
1167                         window.clearInterval(this.timer);
1168                         delete this.timer;
1169                         delete this.tick;
1170                         return true;
1171                 },
1172
1173                 /* private */
1174                 step: function() {
1175                         for (var i = 0, e = null; (e = Poll.queue[i]) != null; i++) {
1176                                 if ((Poll.tick % e.i) != 0)
1177                                         continue;
1178
1179                                 if (!e.r)
1180                                         continue;
1181
1182                                 e.r = false;
1183
1184                                 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
1185                         }
1186
1187                         Poll.tick = (Poll.tick + 1) % Math.pow(2, 32);
1188                 },
1189
1190                 /**
1191                  * Test whether the polling loop is running.
1192                  *
1193                  * @instance
1194                  * @memberof LuCI.Poll
1195                  * @returns {boolean} - Returns `true` if polling is active, else `false`.
1196                  */
1197                 active: function() {
1198                         return (this.timer != null);
1199                 }
1200         });
1201
1202
1203         var dummyElem = null,
1204             domParser = null,
1205             originalCBIInit = null,
1206             rpcBaseURL = null,
1207             sysFeatures = null,
1208             classes = {};
1209
1210         var LuCI = Class.extend(/** @lends LuCI.prototype */ {
1211                 __name__: 'LuCI',
1212                 __init__: function(env) {
1213
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=([^?]+))?$/);
1217                                         if (m) {
1218                                                 env.base_url = m[1];
1219                                                 env.resource_version = m[2];
1220                                         }
1221                                 }
1222                         });
1223
1224                         if (env.base_url == null)
1225                                 this.error('InternalError', 'Cannot find url of luci.js');
1226
1227                         env.cgi_base = env.scriptname.replace(/\/[^\/]+$/, '');
1228
1229                         Object.assign(this.env, env);
1230
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' : '';
1234                                 });
1235                         });
1236
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' : '';
1240                                 });
1241                         });
1242
1243                         var domReady = new Promise(function(resolveFn, rejectFn) {
1244                                 document.addEventListener('DOMContentLoaded', resolveFn);
1245                         });
1246
1247                         Promise.all([
1248                                 domReady,
1249                                 this.require('ui'),
1250                                 this.require('rpc'),
1251                                 this.require('form'),
1252                                 this.probeRPCBaseURL()
1253                         ]).then(this.setupDOM.bind(this)).catch(this.error);
1254
1255                         originalCBIInit = window.cbi_init;
1256                         window.cbi_init = function() {};
1257                 },
1258
1259                 /**
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.
1263                  *
1264                  * @instance
1265                  * @memberof LuCI
1266                  *
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.
1270                  *
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.
1274                  *
1275                  * @param {...*} [args]
1276                  * Zero or more variable arguments to the supplied format string.
1277                  *
1278                  * @throws {Error}
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.
1282                  */
1283                 raise: function(type, fmt /*, ...*/) {
1284                         var e = null,
1285                             msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
1286                             stack = null;
1287
1288                         if (type instanceof Error) {
1289                                 e = type;
1290
1291                                 if (msg)
1292                                         e.message = msg + ': ' + e.message;
1293                         }
1294                         else {
1295                                 try { throw new Error('stacktrace') }
1296                                 catch (e2) { stack = (e2.stack || '').split(/\n/) }
1297
1298                                 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
1299                                 e.name = type || 'Error';
1300                         }
1301
1302                         stack = (stack || []).map(function(frame) {
1303                                 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
1304                                 return frame ? '  ' + frame : '';
1305                         });
1306
1307                         if (!/^  at /.test(stack[0]))
1308                                 stack.shift();
1309
1310                         if (/\braise /.test(stack[0]))
1311                                 stack.shift();
1312
1313                         if (/\berror /.test(stack[0]))
1314                                 stack.shift();
1315
1316                         if (stack.length)
1317                                 e.message += '\n' + stack.join('\n');
1318
1319                         if (window.console && console.debug)
1320                                 console.debug(e);
1321
1322                         throw e;
1323                 },
1324
1325                 /**
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.
1329                  *
1330                  * @instance
1331                  * @memberof LuCI
1332                  *
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.
1336                  *
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.
1340                  *
1341                  * @param {...*} [args]
1342                  * Zero or more variable arguments to the supplied format string.
1343                  *
1344                  * @throws {Error}
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.
1348                  */
1349                 error: function(type, fmt /*, ...*/) {
1350                         try {
1351                                 L.raise.apply(L, Array.prototype.slice.call(arguments));
1352                         }
1353                         catch (e) {
1354                                 if (!e.reported) {
1355                                         if (L.ui)
1356                                                 L.ui.addNotification(e.name || _('Runtime error'),
1357                                                         E('pre', {}, e.message), 'danger');
1358                                         else
1359                                                 L.dom.content(document.querySelector('#maincontent'),
1360                                                         E('pre', { 'class': 'alert-message error' }, e.message));
1361
1362                                         e.reported = true;
1363                                 }
1364
1365                                 throw e;
1366                         }
1367                 },
1368
1369                 /**
1370                  * Return a bound function using the given `self` as `this` context
1371                  * and any further arguments as parameters to the bound function.
1372                  *
1373                  * @instance
1374                  * @memberof LuCI
1375                  *
1376                  * @param {function} fn
1377                  * The function to bind.
1378                  *
1379                  * @param {*} self
1380                  * The value to bind as `this` context to the specified function.
1381                  *
1382                  * @param {...*} [args]
1383                  * Zero or more variable arguments which are bound to the function
1384                  * as parameters.
1385                  *
1386                  * @returns {function}
1387                  * Returns the bound function.
1388                  */
1389                 bind: function(fn, self /*, ... */) {
1390                         return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
1391                 },
1392
1393                 /**
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.
1398                  *
1399                  * @instance
1400                  * @memberof LuCI
1401                  *
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
1406                  * file from.
1407                  *
1408                  * @throws {DependencyError}
1409                  * Throws a `DependencyError` when the class to load includes
1410                  * circular dependencies.
1411                  *
1412                  * @throws {NetworkError}
1413                  * Throws `NetworkError` when the underlying {@link LuCI.Request}
1414                  * call failed.
1415                  *
1416                  * @throws {SyntaxError}
1417                  * Throws `SyntaxError` when the loaded class file code cannot
1418                  * be interpreted by `eval`.
1419                  *
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
1423                  * class instance.
1424                  *
1425                  * @returns {Promise<LuCI#Class>}
1426                  * Returns the instantiated class.
1427                  */
1428                 require: function(name, from) {
1429                         var L = this, url = null, from = from || [];
1430
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 "'));
1438
1439                                 return Promise.resolve(classes[name]);
1440                         }
1441
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);
1444
1445                         var compileClass = function(res) {
1446                                 if (!res.ok)
1447                                         L.raise('NetworkError',
1448                                                 'HTTP error %d while loading class file "%s"', res.status, url);
1449
1450                                 var source = res.text(),
1451                                     requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
1452                                     strictmatch = /^use[ \t]+strict$/,
1453                                     depends = [],
1454                                     args = '';
1455
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);
1459
1460                                         if (esc) {
1461                                                 esc = false;
1462                                         }
1463                                         else if (chr == 92) {
1464                                                 esc = true;
1465                                         }
1466                                         else if (chr == quote) {
1467                                                 var s = source.substring(off, i),
1468                                                     m = requirematch.exec(s);
1469
1470                                                 if (m) {
1471                                                         var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
1472                                                         depends.push(L.require(dep, from));
1473                                                         args += ', ' + as;
1474                                                 }
1475                                                 else if (!strictmatch.exec(s)) {
1476                                                         break;
1477                                                 }
1478
1479                                                 off = -1;
1480                                                 quote = -1;
1481                                         }
1482                                         else if (quote == -1 && (chr == 34 || chr == 39)) {
1483                                                 off = i + 1;
1484                                                 quote = chr;
1485                                         }
1486                                 }
1487
1488                                 /* load dependencies and instantiate class */
1489                                 return Promise.all(depends).then(function(instances) {
1490                                         var _factory, _class;
1491
1492                                         try {
1493                                                 _factory = eval(
1494                                                         '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
1495                                                                 .format(args, source, res.url));
1496                                         }
1497                                         catch (error) {
1498                                                 L.raise('SyntaxError', '%s\n  in %s:%s',
1499                                                         error.message, res.url, error.lineNumber || '?');
1500                                         }
1501
1502                                         _factory.displayName = toCamelCase(name + 'ClassFactory');
1503                                         _class = _factory.apply(_factory, [window, document, L].concat(instances));
1504
1505                                         if (!Class.isSubclass(_class))
1506                                             L.error('TypeError', '"%s" factory yields invalid constructor', name);
1507
1508                                         if (_class.displayName == 'AnonymousClass')
1509                                                 _class.displayName = toCamelCase(name + 'Class');
1510
1511                                         var ptr = Object.getPrototypeOf(L),
1512                                             parts = name.split(/\./),
1513                                             instance = new _class();
1514
1515                                         for (var i = 0; ptr && i < parts.length - 1; i++)
1516                                                 ptr = ptr[parts[i]];
1517
1518                                         if (ptr)
1519                                                 ptr[parts[i]] = instance;
1520
1521                                         classes[name] = instance;
1522
1523                                         return instance;
1524                                 });
1525                         };
1526
1527                         /* Request class file */
1528                         classes[name] = Request.get(url, { cache: true }).then(compileClass);
1529
1530                         return classes[name];
1531                 },
1532
1533                 /* DOM setup */
1534                 probeRPCBaseURL: function() {
1535                         if (rpcBaseURL == null) {
1536                                 try {
1537                                         rpcBaseURL = window.sessionStorage.getItem('rpcBaseURL');
1538                                 }
1539                                 catch (e) { }
1540                         }
1541
1542                         if (rpcBaseURL == null) {
1543                                 var rpcFallbackURL = this.url('admin/ubus');
1544
1545                                 rpcBaseURL = Request.get(this.env.ubuspath).then(function(res) {
1546                                         return (rpcBaseURL = (res.status == 400) ? L.env.ubuspath : rpcFallbackURL);
1547                                 }, function() {
1548                                         return (rpcBaseURL = rpcFallbackURL);
1549                                 }).then(function(url) {
1550                                         try {
1551                                                 window.sessionStorage.setItem('rpcBaseURL', url);
1552                                         }
1553                                         catch (e) { }
1554
1555                                         return url;
1556                                 });
1557                         }
1558
1559                         return Promise.resolve(rpcBaseURL);
1560                 },
1561
1562                 probeSystemFeatures: function() {
1563                         var sessionid = classes.rpc.getSessionID();
1564
1565                         if (sysFeatures == null) {
1566                                 try {
1567                                         var data = JSON.parse(window.sessionStorage.getItem('sysFeatures'));
1568
1569                                         if (this.isObject(data) && this.isObject(data[sessionid]))
1570                                                 sysFeatures = data[sessionid];
1571                                 }
1572                                 catch (e) {}
1573                         }
1574
1575                         if (!this.isObject(sysFeatures)) {
1576                                 sysFeatures = classes.rpc.declare({
1577                                         object: 'luci',
1578                                         method: 'getFeatures',
1579                                         expect: { '': {} }
1580                                 })().then(function(features) {
1581                                         try {
1582                                                 var data = {};
1583                                                     data[sessionid] = features;
1584
1585                                                 window.sessionStorage.setItem('sysFeatures', JSON.stringify(data));
1586                                         }
1587                                         catch (e) {}
1588
1589                                         sysFeatures = features;
1590
1591                                         return features;
1592                                 });
1593                         }
1594
1595                         return Promise.resolve(sysFeatures);
1596                 },
1597
1598                 /**
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
1603                  * browser window.
1604                  *
1605                  * @instance
1606                  * @memberof LuCI
1607                  *
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`.
1611                  *
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.
1616                  *
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.
1622                  */
1623                 hasSystemFeature: function() {
1624                         var ft = sysFeatures[arguments[0]];
1625
1626                         if (arguments.length == 2)
1627                                 return this.isObject(ft) ? ft[arguments[1]] : null;
1628
1629                         return (ft != null && ft != false);
1630                 },
1631
1632                 /* private */
1633                 notifySessionExpiry: function() {
1634                         Poll.stop();
1635
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' },
1640                                         E('div', {
1641                                                 class: 'btn primary',
1642                                                 click: function() {
1643                                                         var loc = window.location;
1644                                                         window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
1645                                                 }
1646                                         }, _('To login…')))
1647                         ]);
1648
1649                         L.raise('SessionError', 'Login session is expired');
1650                 },
1651
1652                 /* private */
1653                 setupDOM: function(res) {
1654                         var domEv = res[0],
1655                             uiClass = res[1],
1656                             rpcClass = res[2],
1657                             formClass = res[3],
1658                             rpcBaseURL = res[4];
1659
1660                         rpcClass.setBaseURL(rpcBaseURL);
1661
1662                         rpcClass.addInterceptor(function(msg, req) {
1663                                 if (!L.isObject(msg) || !L.isObject(msg.error) || msg.error.code != -32002)
1664                                         return;
1665
1666                                 if (!L.isObject(req) || (req.object == 'session' && req.method == 'access'))
1667                                         return;
1668
1669                                 return rpcClass.declare({
1670                                         'object': 'session',
1671                                         'method': 'access',
1672                                         'params': [ 'scope', 'object', 'function' ],
1673                                         'expect': { access: true }
1674                                 })('uci', 'luci', 'read').catch(L.notifySessionExpiry);
1675                         });
1676
1677                         Request.addInterceptor(function(res) {
1678                                 var isDenied = false;
1679
1680                                 if (res.status == 403 && res.headers.get('X-LuCI-Login-Required') == 'yes')
1681                                         isDenied = true;
1682
1683                                 if (!isDenied)
1684                                         return;
1685
1686                                 L.notifySessionExpiry();
1687                         });
1688
1689                         return this.probeSystemFeatures().finally(this.initDOM);
1690                 },
1691
1692                 /* private */
1693                 initDOM: function() {
1694                         originalCBIInit();
1695                         Poll.start();
1696                         document.dispatchEvent(new CustomEvent('luci-loaded'));
1697                 },
1698
1699                 /**
1700                  * The `env` object holds environment settings used by LuCI, such
1701                  * as request timeouts, base URLs etc.
1702                  *
1703                  * @instance
1704                  * @memberof LuCI
1705                  */
1706                 env: {},
1707
1708                 /**
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.
1713                  *
1714                  * @instance
1715                  * @memberof LuCI
1716                  *
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.
1720                  *
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.
1724                  *
1725                  * @return {string}
1726                  * Return the joined URL path.
1727                  */
1728                 path: function(prefix, parts) {
1729                         var url = [ prefix || '' ];
1730
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]);
1734
1735                         if (url.length === 1)
1736                                 url.push('/');
1737
1738                         return url.join('');
1739                 },
1740
1741                 /**
1742                  * Construct an URL  pathrelative to the script path of the server
1743                  * side LuCI application (usually `/cgi-bin/luci`).
1744                  *
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.
1748                  *
1749                  * @instance
1750                  * @memberof LuCI
1751                  *
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.
1755                  *
1756                  * @return {string}
1757                  * Returns the resulting URL path.
1758                  */
1759                 url: function() {
1760                         return this.path(this.env.scriptname, arguments);
1761                 },
1762
1763                 /**
1764                  * Construct an URL path relative to the global static resource path
1765                  * of the LuCI ui (usually `/luci-static/resources`).
1766                  *
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.
1770                  *
1771                  * @instance
1772                  * @memberof LuCI
1773                  *
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.
1777                  *
1778                  * @return {string}
1779                  * Returns the resulting URL path.
1780                  */
1781                 resource: function() {
1782                         return this.path(this.env.resource, arguments);
1783                 },
1784
1785                 /**
1786                  * Construct an URL path relative to the media resource path of the
1787                  * LuCI ui (usually `/luci-static/$theme_name`).
1788                  *
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.
1792                  *
1793                  * @instance
1794                  * @memberof LuCI
1795                  *
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.
1799                  *
1800                  * @return {string}
1801                  * Returns the resulting URL path.
1802                  */
1803                 media: function() {
1804                         return this.path(this.env.media, arguments);
1805                 },
1806
1807                 /**
1808                  * Return the complete URL path to the current view.
1809                  *
1810                  * @instance
1811                  * @memberof LuCI
1812                  *
1813                  * @return {string}
1814                  * Returns the URL path to the current view.
1815                  */
1816                 location: function() {
1817                         return this.path(this.env.scriptname, this.env.requestpath);
1818                 },
1819
1820
1821                 /**
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.
1825                  *
1826                  * @instance
1827                  * @memberof LuCI
1828                  *
1829                  * @param {*} [val]
1830                  * The value to test
1831                  *
1832                  * @return {boolean}
1833                  * Returns `true` if the given value is of type object and
1834                  * not `null`, else returns `false`.
1835                  */
1836                 isObject: function(val) {
1837                         return (val != null && typeof(val) == 'object');
1838                 },
1839
1840                 /**
1841                  * Return an array of sorted object keys, optionally sorted by
1842                  * a different key or a different sorting mode.
1843                  *
1844                  * @instance
1845                  * @memberof LuCI
1846                  *
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.
1850                  *
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.
1856                  *
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.
1861                  *
1862                  * @return {string[]}
1863                  * Returns an array containing the sorted keys of the given object.
1864                  */
1865                 sortedKeys: function(obj, key, sortmode) {
1866                         if (obj == null || typeof(obj) != 'object')
1867                                 return [];
1868
1869                         return Object.keys(obj).map(function(e) {
1870                                 var v = (key != null) ? obj[e][key] : e;
1871
1872                                 switch (sortmode) {
1873                                 case 'addr':
1874                                         v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
1875                                                 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
1876                                         break;
1877
1878                                 case 'num':
1879                                         v = (v != null) ? +v : null;
1880                                         break;
1881                                 }
1882
1883                                 return [ e, v ];
1884                         }).filter(function(e) {
1885                                 return (e[1] != null);
1886                         }).sort(function(a, b) {
1887                                 return (a[1] > b[1]);
1888                         }).map(function(e) {
1889                                 return e[0];
1890                         });
1891                 },
1892
1893                 /**
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.
1900                  *
1901                  * @instance
1902                  * @memberof LuCI
1903                  *
1904                  * @param {*} val
1905                  * The value to convert into an array.
1906                  *
1907                  * @return {Array<*>}
1908                  * Returns the resulting array.
1909                  */
1910                 toArray: function(val) {
1911                         if (val == null)
1912                                 return [];
1913                         else if (Array.isArray(val))
1914                                 return val;
1915                         else if (typeof(val) == 'object')
1916                                 return [ val ];
1917
1918                         var s = String(val).trim();
1919
1920                         if (s == '')
1921                                 return [];
1922
1923                         return s.split(/\s+/);
1924                 },
1925
1926                 /**
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.
1929                  *
1930                  * @instance
1931                  * @memberof LuCI
1932                  *
1933                  * @param {*} value
1934                  * The value to resolve the promise with.
1935                  *
1936                  * @param {*} defvalue
1937                  * The default value to resolve the promise with in case the given
1938                  * input value is a rejecting promise.
1939                  *
1940                  * @returns {Promise<*>}
1941                  * Returns a new promise resolving either to the given input value or
1942                  * to the given default value on error.
1943                  */
1944                 resolveDefault: function(value, defvalue) {
1945                         return Promise.resolve(value).catch(function() { return defvalue });
1946                 },
1947
1948                 /**
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.
1952                  *
1953                  * @instance
1954                  * @memberof LuCI
1955                  *
1956                  * @callback LuCI.requestCallbackFn
1957                  * @param {XMLHTTPRequest} xhr
1958                  * The XMLHTTPRequest instance used to make the request.
1959                  *
1960                  * @param {*} data
1961                  * The response JSON if the response could be parsed as such,
1962                  * else `null`.
1963                  *
1964                  * @param {number} duration
1965                  * The total duration of the request in milliseconds.
1966                  */
1967
1968                 /**
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()}.
1972                  *
1973                  * @deprecated
1974                  * @instance
1975                  * @memberof LuCI
1976                  *
1977                  * @param {string} url
1978                  * The URL to request.
1979                  *
1980                  * @param {Object<string, string>} [args]
1981                  * Additional query string arguments to append to the URL.
1982                  *
1983                  * @param {LuCI.requestCallbackFn} cb
1984                  * The callback function to invoke when the request finishes.
1985                  *
1986                  * @return {Promise<null>}
1987                  * Returns a promise resolving to `null` when concluded.
1988                  */
1989                 get: function(url, args, cb) {
1990                         return this.poll(null, url, args, cb, false);
1991                 },
1992
1993                 /**
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`
1999                  * by default.
2000                  *
2001                  * @deprecated
2002                  * @instance
2003                  * @memberof LuCI
2004                  *
2005                  * @param {string} url
2006                  * The URL to request.
2007                  *
2008                  * @param {Object<string, string>} [args]
2009                  * Additional post arguments to append to the request body.
2010                  *
2011                  * @param {LuCI.requestCallbackFn} cb
2012                  * The callback function to invoke when the request finishes.
2013                  *
2014                  * @return {Promise<null>}
2015                  * Returns a promise resolving to `null` when concluded.
2016                  */
2017                 post: function(url, args, cb) {
2018                         return this.poll(null, url, args, cb, true);
2019                 },
2020
2021                 /**
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()}.
2025                  *
2026                  * @deprecated
2027                  * @instance
2028                  * @memberof LuCI
2029                  *
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`.
2034                  *
2035                  * @param {string} url
2036                  * The URL to request.
2037                  *
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.
2042                  *
2043                  * @param {LuCI.requestCallbackFn} cb
2044                  * The callback function to invoke whenever a request finishes.
2045                  *
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`.
2052                  *
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
2057                  * polling request.
2058                  */
2059                 poll: function(interval, url, args, cb, post) {
2060                         if (interval !== null && interval <= 0)
2061                                 interval = this.env.pollinterval;
2062
2063                         var data = post ? { token: this.env.token } : null,
2064                             method = post ? 'POST' : 'GET';
2065
2066                         if (!/^(?:\/|\S+:\/\/)/.test(url))
2067                                 url = this.url(url);
2068
2069                         if (args != null)
2070                                 data = Object.assign(data || {}, args);
2071
2072                         if (interval !== null)
2073                                 return Request.poll.add(interval, url, { method: method, query: data }, cb);
2074                         else
2075                                 return Request.request(url, { method: method, query: data })
2076                                         .then(function(res) {
2077                                                 var json = null;
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);
2081                                         });
2082                 },
2083
2084                 /**
2085                  * Deprecated wrapper around {@link LuCI.Poll.remove Poll.remove()}.
2086                  *
2087                  * @deprecated
2088                  * @instance
2089                  * @memberof LuCI
2090                  *
2091                  * @param {function} entry
2092                  * The polling function to remove.
2093                  *
2094                  * @return {boolean}
2095                  * Returns `true` when the function has been removed or `false` if
2096                  * it could not be found.
2097                  */
2098                 stop: function(entry) { return Poll.remove(entry) },
2099
2100                 /**
2101                  * Deprecated wrapper around {@link LuCI.Poll.stop Poll.stop()}.
2102                  *
2103                  * @deprecated
2104                  * @instance
2105                  * @memberof LuCI
2106                  *
2107                  * @return {boolean}
2108                  * Returns `true` when the polling loop has been stopped or `false`
2109                  * when it didn't run to begin with.
2110                  */
2111                 halt: function() { return Poll.stop() },
2112
2113                 /**
2114                  * Deprecated wrapper around {@link LuCI.Poll.start Poll.start()}.
2115                  *
2116                  * @deprecated
2117                  * @instance
2118                  * @memberof LuCI
2119                  *
2120                  * @return {boolean}
2121                  * Returns `true` when the polling loop has been started or `false`
2122                  * when it was already running.
2123                  */
2124                 run: function() { return Poll.start() },
2125
2126
2127                 /**
2128                  * @class
2129                  * @memberof LuCI
2130                  * @hideconstructor
2131                  * @classdesc
2132                  *
2133                  * The `dom` class provides convenience method for creating and
2134                  * manipulating DOM elements.
2135                  */
2136                 dom: Class.singleton(/* @lends LuCI.dom.prototype */ {
2137                         __name__: 'LuCI.DOM',
2138
2139                         /**
2140                          * Tests whether the given argument is a valid DOM `Node`.
2141                          *
2142                          * @instance
2143                          * @memberof LuCI.dom
2144                          * @param {*} e
2145                          * The value to test.
2146                          *
2147                          * @returns {boolean}
2148                          * Returns `true` if the value is a DOM `Node`, else `false`.
2149                          */
2150                         elem: function(e) {
2151                                 return (e != null && typeof(e) == 'object' && 'nodeType' in e);
2152                         },
2153
2154                         /**
2155                          * Parses a given string as HTML and returns the first child node.
2156                          *
2157                          * @instance
2158                          * @memberof LuCI.dom
2159                          * @param {string} s
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.
2164                          *
2165                          * @returns {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.
2168                          */
2169                         parse: function(s) {
2170                                 var elem;
2171
2172                                 try {
2173                                         domParser = domParser || new DOMParser();
2174                                         elem = domParser.parseFromString(s, 'text/html').body.firstChild;
2175                                 }
2176                                 catch(e) {}
2177
2178                                 if (!elem) {
2179                                         try {
2180                                                 dummyElem = dummyElem || document.createElement('div');
2181                                                 dummyElem.innerHTML = s;
2182                                                 elem = dummyElem.firstChild;
2183                                         }
2184                                         catch (e) {}
2185                                 }
2186
2187                                 return elem || null;
2188                         },
2189
2190                         /**
2191                          * Tests whether a given `Node` matches the given query selector.
2192                          *
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`.
2197                          *
2198                          * @instance
2199                          * @memberof LuCI.dom
2200                          * @param {*} node
2201                          * The `Node` argument to test the selector against.
2202                          *
2203                          * @param {string} [selector]
2204                          * The query selector expression to test against the given node.
2205                          *
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.
2210                          */
2211                         matches: function(node, selector) {
2212                                 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
2213                                 return m ? m.call(node, selector) : false;
2214                         },
2215
2216                         /**
2217                          * Returns the closest parent node that matches the given query
2218                          * selector expression.
2219                          *
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`.
2224                          *
2225                          * @instance
2226                          * @memberof LuCI.dom
2227                          * @param {*} node
2228                          * The `Node` argument to find the closest parent for.
2229                          *
2230                          * @param {string} [selector]
2231                          * The query selector expression to test against each parent.
2232                          *
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.
2237                          */
2238                         parent: function(node, selector) {
2239                                 if (this.elem(node) && node.closest)
2240                                         return node.closest(selector);
2241
2242                                 while (this.elem(node))
2243                                         if (this.matches(node, selector))
2244                                                 return node;
2245                                         else
2246                                                 node = node.parentNode;
2247
2248                                 return null;
2249                         },
2250
2251                         /**
2252                          * Appends the given children data to the given node.
2253                          *
2254                          * @instance
2255                          * @memberof LuCI.dom
2256                          * @param {*} node
2257                          * The `Node` argument to append the children to.
2258                          *
2259                          * @param {*} [children]
2260                          * The childrens to append to the given node.
2261                          *
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()`.
2268                          *
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
2273                          * second parameter.
2274                          *
2275                          * When `children` is is a DOM `Node` instance, it will be
2276                          * appended to the given `node`.
2277                          *
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`.
2281                          *
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.
2286                          */
2287                         append: function(node, children) {
2288                                 if (!this.elem(node))
2289                                         return null;
2290
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]));
2297
2298                                         return node.lastChild;
2299                                 }
2300                                 else if (typeof(children) === 'function') {
2301                                         return this.append(node, children(node));
2302                                 }
2303                                 else if (this.elem(children)) {
2304                                         return node.appendChild(children);
2305                                 }
2306                                 else if (children !== null && children !== undefined) {
2307                                         node.innerHTML = '' + children;
2308                                         return node.lastChild;
2309                                 }
2310
2311                                 return null;
2312                         },
2313
2314                         /**
2315                          * Replaces the content of the given node with the given children.
2316                          *
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.
2320                          *
2321                          * @instance
2322                          * @memberof LuCI.dom
2323                          * @param {*} node
2324                          * The `Node` argument to replace the children of.
2325                          *
2326                          * @param {*} [children]
2327                          * The childrens to replace into the given node.
2328                          *
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()`.
2335                          *
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
2340                          * second parameter.
2341                          *
2342                          * When `children` is is a DOM `Node` instance, it will be
2343                          * appended to the given `node`.
2344                          *
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`.
2348                          *
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.
2353                          */
2354                         content: function(node, children) {
2355                                 if (!this.elem(node))
2356                                         return null;
2357
2358                                 var dataNodes = node.querySelectorAll('[data-idref]');
2359
2360                                 for (var i = 0; i < dataNodes.length; i++)
2361                                         delete this.registry[dataNodes[i].getAttribute('data-idref')];
2362
2363                                 while (node.firstChild)
2364                                         node.removeChild(node.firstChild);
2365
2366                                 return this.append(node, children);
2367                         },
2368
2369                         /**
2370                          * Sets attributes or registers event listeners on element nodes.
2371                          *
2372                          * @instance
2373                          * @memberof LuCI.dom
2374                          * @param {*} node
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.
2378                          *
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.
2384                          *
2385                          * @param {*} [val]
2386                          * Specifies the attribute value or event handler function to add.
2387                          * If the `key` parameter is an `Object`, this parameter will be
2388                          * ignored.
2389                          *
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
2392                          * event name.
2393                          *
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.
2397                          *
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.
2401                          */
2402                         attr: function(node, key, val) {
2403                                 if (!this.elem(node))
2404                                         return null;
2405
2406                                 var attr = null;
2407
2408                                 if (typeof(key) === 'object' && key !== null)
2409                                         attr = key;
2410                                 else if (typeof(key) === 'string')
2411                                         attr = {}, attr[key] = val;
2412
2413                                 for (key in attr) {
2414                                         if (!attr.hasOwnProperty(key) || attr[key] == null)
2415                                                 continue;
2416
2417                                         switch (typeof(attr[key])) {
2418                                         case 'function':
2419                                                 node.addEventListener(key, attr[key]);
2420                                                 break;
2421
2422                                         case 'object':
2423                                                 node.setAttribute(key, JSON.stringify(attr[key]));
2424                                                 break;
2425
2426                                         default:
2427                                                 node.setAttribute(key, attr[key]);
2428                                         }
2429                                 }
2430                         },
2431
2432                         /**
2433                          * Creates a new DOM `Node` from the given `html`, `attr` and
2434                          * `data` parameters.
2435                          *
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.
2440                          *
2441                          * @instance
2442                          * @memberof LuCI.dom
2443                          * @param {*} html
2444                          * Describes the node to create.
2445                          *
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.
2450                          *
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.
2453                          *
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.
2456                          *
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
2459                          * the given name.
2460                          *
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.
2465                          *
2466                          * @param {*} [data]
2467                          * Specifies children to append to the newly created element.
2468                          * Refer to {@link LuCI.dom#append dom.append()} for details.
2469                          *
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.
2476                          *
2477                          * @returns {Node}
2478                          * Returns the newly created `Node`.
2479                          */
2480                         create: function() {
2481                                 var html = arguments[0],
2482                                     attr = arguments[1],
2483                                     data = arguments[2],
2484                                     elem;
2485
2486                                 if (!(attr instanceof Object) || Array.isArray(attr))
2487                                         data = attr, attr = null;
2488
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]));
2493                                 }
2494                                 else if (this.elem(html)) {
2495                                         elem = html;
2496                                 }
2497                                 else if (html.charCodeAt(0) === 60) {
2498                                         elem = this.parse(html);
2499                                 }
2500                                 else {
2501                                         elem = document.createElement(html);
2502                                 }
2503
2504                                 if (!elem)
2505                                         return null;
2506
2507                                 this.attr(elem, attr);
2508                                 this.append(elem, data);
2509
2510                                 return elem;
2511                         },
2512
2513                         registry: {},
2514
2515                         /**
2516                          * Attaches or detaches arbitrary data to and from a DOM `Node`.
2517                          *
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.
2523                          *
2524                          * This function has multiple signatures and is sensitive to the
2525                          * number of arguments passed to it.
2526                          *
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
2533                          *     given node.
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.
2538                          *
2539                          * @instance
2540                          * @memberof LuCI.dom
2541                          * @param {Node} node
2542                          * The DOM `Node` instance to set or retrieve the data for.
2543                          *
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.
2547                          *
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.
2551                          *
2552                          * @returns {*}
2553                          * Returns the get or set value, or `null` when no value could
2554                          * be found.
2555                          */
2556                         data: function(node, key, val) {
2557                                 if (!node || !node.getAttribute)
2558                                         return null;
2559
2560                                 var id = node.getAttribute('data-idref');
2561
2562                                 /* clear all data */
2563                                 if (arguments.length > 1 && key == null) {
2564                                         if (id != null) {
2565                                                 node.removeAttribute('data-idref');
2566                                                 val = this.registry[id]
2567                                                 delete this.registry[id];
2568                                                 return val;
2569                                         }
2570
2571                                         return null;
2572                                 }
2573
2574                                 /* clear a key */
2575                                 else if (arguments.length > 2 && key != null && val == null) {
2576                                         if (id != null) {
2577                                                 val = this.registry[id][key];
2578                                                 delete this.registry[id][key];
2579                                                 return val;
2580                                         }
2581
2582                                         return null;
2583                                 }
2584
2585                                 /* set a key */
2586                                 else if (arguments.length > 2 && key != null && val != null) {
2587                                         if (id == null) {
2588                                                 do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
2589                                                 while (this.registry.hasOwnProperty(id));
2590
2591                                                 node.setAttribute('data-idref', id);
2592                                                 this.registry[id] = {};
2593                                         }
2594
2595                                         return (this.registry[id][key] = val);
2596                                 }
2597
2598                                 /* get all data */
2599                                 else if (arguments.length == 1) {
2600                                         if (id != null)
2601                                                 return this.registry[id];
2602
2603                                         return null;
2604                                 }
2605
2606                                 /* get a key */
2607                                 else if (arguments.length == 2) {
2608                                         if (id != null)
2609                                                 return this.registry[id][key];
2610                                 }
2611
2612                                 return null;
2613                         },
2614
2615                         /**
2616                          * Binds the given class instance ot the specified DOM `Node`.
2617                          *
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.
2623                          *
2624                          * @instance
2625                          * @memberof LuCI.dom
2626                          * @param {Node} node
2627                          * The DOM `Node` instance to bind the class to.
2628                          *
2629                          * @param {Class} inst
2630                          * The Class instance to bind to the node.
2631                          *
2632                          * @throws {TypeError}
2633                          * Throws a `TypeError` when the given instance argument isn't
2634                          * a valid Class instance.
2635                          *
2636                          * @returns {Class}
2637                          * Returns the bound class instance.
2638                          */
2639                         bindClassInstance: function(node, inst) {
2640                                 if (!(inst instanceof Class))
2641                                         L.error('TypeError', 'Argument must be a class instance');
2642
2643                                 return this.data(node, '_class', inst);
2644                         },
2645
2646                         /**
2647                          * Finds a bound class instance on the given node itself or the
2648                          * first bound instance on its closest parent node.
2649                          *
2650                          * @instance
2651                          * @memberof LuCI.dom
2652                          * @param {Node} node
2653                          * The DOM `Node` instance to start from.
2654                          *
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.
2658                          */
2659                         findClassInstance: function(node) {
2660                                 var inst = null;
2661
2662                                 do {
2663                                         inst = this.data(node, '_class');
2664                                         node = node.parentNode;
2665                                 }
2666                                 while (!(inst instanceof Class) && node != null);
2667
2668                                 return inst;
2669                         },
2670
2671                         /**
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.
2675                          *
2676                          * @instance
2677                          * @memberof LuCI.dom
2678                          * @param {Node} node
2679                          * The DOM `Node` instance to start from.
2680                          *
2681                          * @param {string} method
2682                          * The name of the method to invoke on the found class instance.
2683                          *
2684                          * @param {...*} params
2685                          * Additional arguments to pass to the invoked method as-is.
2686                          *
2687                          * @returns {*|null}
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`.
2692                          */
2693                         callClassMethod: function(node, method /*, ... */) {
2694                                 var inst = this.findClassInstance(node);
2695
2696                                 if (inst == null || typeof(inst[method]) != 'function')
2697                                         return null;
2698
2699                                 return inst[method].apply(inst, inst.varargs(arguments, 2));
2700                         },
2701
2702                         /**
2703                          * The ignore callback function is invoked by `isEmpty()` for each
2704                          * child node to decide whether to ignore a child node or not.
2705                          *
2706                          * When this function returns `false`, the node passed to it is
2707                          * ignored, else not.
2708                          *
2709                          * @callback LuCI.dom~ignoreCallbackFn
2710                          * @param {Node} node
2711                          * The child node to test.
2712                          *
2713                          * @returns {boolean}
2714                          * Boolean indicating whether to ignore the node or not.
2715                          */
2716
2717                         /**
2718                          * Tests whether a given DOM `Node` instance is empty or appears
2719                          * empty.
2720                          *
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.
2724                          *
2725                          * @instance
2726                          * @memberof LuCI.dom
2727                          * @param {Node} node
2728                          * The DOM `Node` instance to test.
2729                          *
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.
2733                          *
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`.
2738                          */
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)))
2742                                                 return false;
2743
2744                                 return true;
2745                         }
2746                 }),
2747
2748                 Poll: Poll,
2749                 Class: Class,
2750                 Request: Request,
2751
2752                 /**
2753                  * @class
2754                  * @memberof LuCI
2755                  * @hideconstructor
2756                  * @classdesc
2757                  *
2758                  * The `view` class forms the basis of views and provides a standard
2759                  * set of methods to inherit from.
2760                  */
2761                 view: Class.extend(/* @lends LuCI.view.prototype */ {
2762                         __name__: 'LuCI.View',
2763
2764                         __init__: function() {
2765                                 var vp = document.getElementById('view');
2766
2767                                 L.dom.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
2768
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');
2773
2774                                                 L.dom.content(vp, nodes);
2775                                                 L.dom.append(vp, this.addFooter());
2776                                         }, this)).catch(L.error);
2777                         },
2778
2779                         /**
2780                          * The load function is invoked before the view is rendered.
2781                          *
2782                          * The invocation of this function is wrapped by
2783                          * `Promise.resolve()` so it may return Promises if needed.
2784                          *
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()`.
2788                          *
2789                          * This function is supposed to be overwritten by subclasses,
2790                          * the default implementation does nothing.
2791                          *
2792                          * @instance
2793                          * @abstract
2794                          * @memberof LuCI.view
2795                          *
2796                          * @returns {*|Promise<*>}
2797                          * May return any value or a Promise resolving to any value.
2798                          */
2799                         load: function() {},
2800
2801                         /**
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.
2807                          *
2808                          * The invocation of this function is wrapped by
2809                          * `Promise.resolve()` so it may return Promises if needed.
2810                          *
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()}.
2815                          *
2816                          * This function is supposed to be overwritten by subclasses,
2817                          * the default implementation does nothing.
2818                          *
2819                          * @instance
2820                          * @abstract
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
2825                          * argument.
2826                          *
2827                          * @returns {Node|Promise<Node>}
2828                          * Should return a DOM `Node` value or a `Promise` resolving
2829                          * to a `Node` value.
2830                          */
2831                         render: function() {},
2832
2833                         /**
2834                          * The handleSave function is invoked when the user clicks
2835                          * the `Save` button in the page action footer.
2836                          *
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.
2841                          *
2842                          * Views not using `Map` instances or requiring other special
2843                          * logic should overwrite `handleSave()` with a custom
2844                          * implementation.
2845                          *
2846                          * To disable the `Save` page footer button, views extending
2847                          * this base class should overwrite the `handleSave` function
2848                          * with `null`.
2849                          *
2850                          * The invocation of this function is wrapped by
2851                          * `Promise.resolve()` so it may return Promises if needed.
2852                          *
2853                          * @instance
2854                          * @memberof LuCI.view
2855                          * @param {Event} ev
2856                          * The DOM event that triggered the function.
2857                          *
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
2862                          * is reenabled.
2863                          */
2864                         handleSave: function(ev) {
2865                                 var tasks = [];
2866
2867                                 document.getElementById('maincontent')
2868                                         .querySelectorAll('.cbi-map').forEach(function(map) {
2869                                                 tasks.push(L.dom.callClassMethod(map, 'save'));
2870                                         });
2871
2872                                 return Promise.all(tasks);
2873                         },
2874
2875                         /**
2876                          * The handleSaveApply function is invoked when the user clicks
2877                          * the `Save & Apply` button in the page action footer.
2878                          *
2879                          * The default implementation should be sufficient for most
2880                          * views using {@link form#Map form.Map()} based forms - it
2881                          * will first invoke
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.
2885                          *
2886                          * Views not using `Map` instances or requiring other special
2887                          * logic should overwrite `handleSaveApply()` with a custom
2888                          * implementation.
2889                          *
2890                          * To disable the `Save & Apply` page footer button, views
2891                          * extending this base class should overwrite the
2892                          * `handleSaveApply` function with `null`.
2893                          *
2894                          * The invocation of this function is wrapped by
2895                          * `Promise.resolve()` so it may return Promises if needed.
2896                          *
2897                          * @instance
2898                          * @memberof LuCI.view
2899                          * @param {Event} ev
2900                          * The DOM event that triggered the function.
2901                          *
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
2906                          * is reenabled.
2907                          */
2908                         handleSaveApply: function(ev, mode) {
2909                                 return this.handleSave(ev).then(function() {
2910                                         L.ui.changes.apply(mode == '0');
2911                                 });
2912                         },
2913
2914                         /**
2915                          * The handleReset function is invoked when the user clicks
2916                          * the `Reset` button in the page action footer.
2917                          *
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.
2922                          *
2923                          * Views not using `Map` instances or requiring other special
2924                          * logic should overwrite `handleReset()` with a custom
2925                          * implementation.
2926                          *
2927                          * To disable the `Reset` page footer button, views extending
2928                          * this base class should overwrite the `handleReset` function
2929                          * with `null`.
2930                          *
2931                          * The invocation of this function is wrapped by
2932                          * `Promise.resolve()` so it may return Promises if needed.
2933                          *
2934                          * @instance
2935                          * @memberof LuCI.view
2936                          * @param {Event} ev
2937                          * The DOM event that triggered the function.
2938                          *
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
2943                          * is reenabled.
2944                          */
2945                         handleReset: function(ev) {
2946                                 var tasks = [];
2947
2948                                 document.getElementById('maincontent')
2949                                         .querySelectorAll('.cbi-map').forEach(function(map) {
2950                                                 tasks.push(L.dom.callClassMethod(map, 'reset'));
2951                                         });
2952
2953                                 return Promise.all(tasks);
2954                         },
2955
2956                         /**
2957                          * Renders a standard page action footer if any of the
2958                          * `handleSave()`, `handleSaveApply()` or `handleReset()`
2959                          * functions are defined.
2960                          *
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.
2966                          *
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.
2970                          *
2971                          * @instance
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`.
2978                          */
2979                         addFooter: function() {
2980                                 var footer = E([]);
2981
2982                                 var saveApplyBtn = this.handleSaveApply ? new L.ui.ComboButton('0', {
2983                                         0: [ _('Save & Apply') ],
2984                                         1: [ _('Apply unchecked') ]
2985                                 }, {
2986                                         classes: {
2987                                                 0: 'btn cbi-button cbi-button-apply important',
2988                                                 1: 'btn cbi-button cbi-button-negative important'
2989                                         },
2990                                         click: L.ui.createHandlerFn(this, 'handleSaveApply')
2991                                 }).render() : E([]);
2992
2993                                 if (this.handleSaveApply || this.handleSave || this.handleReset) {
2994                                         footer.appendChild(E('div', { 'class': 'cbi-page-actions control-group' }, [
2995                                                 saveApplyBtn, ' ',
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') ]) : ''
3004                                         ]));
3005                                 }
3006
3007                                 return footer;
3008                         }
3009                 })
3010         });
3011
3012         /**
3013          * @class
3014          * @memberof LuCI
3015          * @deprecated
3016          * @classdesc
3017          *
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.
3021          *
3022          * New code should use {@link LuCI.Request} instead to implement HTTP
3023          * request handling.
3024          */
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');
3030                 },
3031
3032                 _response: function(cb, res, json, duration) {
3033                         if (this.active)
3034                                 cb(res, json, duration);
3035                         delete this.active;
3036                 },
3037
3038                 /**
3039                  * This function is a legacy wrapper around
3040                  * {@link LuCI#get LuCI.get()}.
3041                  *
3042                  * @instance
3043                  * @deprecated
3044                  * @memberof LuCI.XHR
3045                  *
3046                  * @param {string} url
3047                  * The URL to request
3048                  *
3049                  * @param {Object} [data]
3050                  * Additional query string data
3051                  *
3052                  * @param {LuCI.requestCallbackFn} [callback]
3053                  * Callback function to invoke on completion
3054                  *
3055                  * @param {number} [timeout]
3056                  * Request timeout to use
3057                  *
3058                  * @return {Promise<null>}
3059                  */
3060                 get: function(url, data, callback, timeout) {
3061                         this.active = true;
3062                         L.get(url, data, this._response.bind(this, callback), timeout);
3063                 },
3064
3065                 /**
3066                  * This function is a legacy wrapper around
3067                  * {@link LuCI#post LuCI.post()}.
3068                  *
3069                  * @instance
3070                  * @deprecated
3071                  * @memberof LuCI.XHR
3072                  *
3073                  * @param {string} url
3074                  * The URL to request
3075                  *
3076                  * @param {Object} [data]
3077                  * Additional data to append to the request body.
3078                  *
3079                  * @param {LuCI.requestCallbackFn} [callback]
3080                  * Callback function to invoke on completion
3081                  *
3082                  * @param {number} [timeout]
3083                  * Request timeout to use
3084                  *
3085                  * @return {Promise<null>}
3086                  */
3087                 post: function(url, data, callback, timeout) {
3088                         this.active = true;
3089                         L.post(url, data, this._response.bind(this, callback), timeout);
3090                 },
3091
3092                 /**
3093                  * Cancels a running request.
3094                  *
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.
3099                  *
3100                  * @instance
3101                  * @deprecated
3102                  * @memberof LuCI.XHR
3103                  */
3104                 cancel: function() { delete this.active },
3105
3106                 /**
3107                  * Checks the running state of the request.
3108                  *
3109                  * @instance
3110                  * @deprecated
3111                  * @memberof LuCI.XHR
3112                  *
3113                  * @returns {boolean}
3114                  * Returns `true` if the request is still running or `false` if it
3115                  * already completed.
3116                  */
3117                 busy: function() { return (this.active === true) },
3118
3119                 /**
3120                  * Ignored for backwards compatibility.
3121                  *
3122                  * This function does nothing.
3123                  *
3124                  * @instance
3125                  * @deprecated
3126                  * @memberof LuCI.XHR
3127                  */
3128                 abort: function() {},
3129
3130                 /**
3131                  * Existing for backwards compatibility.
3132                  *
3133                  * This function simply throws an `InternalError` when invoked.
3134                  *
3135                  * @instance
3136                  * @deprecated
3137                  * @memberof LuCI.XHR
3138                  *
3139                  * @throws {InternalError}
3140                  * Throws an `InternalError` with the message `Not implemented`
3141                  * when invoked.
3142                  */
3143                 send_form: function() { L.error('InternalError', 'Not implemented') },
3144         });
3145
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);
3153
3154         window.XHR = XHR;
3155         window.LuCI = LuCI;
3156 })(window, document);