1 (function(window
, document
, undefined) {
4 /* Object.assign polyfill for IE */
5 if (typeof Object
.assign
!== 'function') {
6 Object
.defineProperty(Object
, 'assign', {
7 value
: function assign(target
, varArgs
) {
9 throw new TypeError('Cannot convert undefined or null to object');
11 var to
= Object(target
);
13 for (var index
= 1; index
< arguments
.length
; index
++)
14 if (arguments
[index
] != null)
15 for (var nextKey
in arguments
[index
])
16 if (Object
.prototype.hasOwnProperty
.call(arguments
[index
], nextKey
))
17 to
[nextKey
] = arguments
[index
][nextKey
];
26 /* Promise.finally polyfill */
27 if (typeof Promise
.prototype.finally !== 'function') {
28 Promise
.prototype.finally = function(fn
) {
29 var onFinally = function(cb
) {
30 return Promise
.resolve(fn
.call(this)).then(cb
);
34 function(result
) { return onFinally
.call(this, function() { return result
}) },
35 function(reason
) { return onFinally
.call(this, function() { return Promise
.reject(reason
) }) }
41 * Class declaration and inheritance helper
44 var toCamelCase = function(s
) {
45 return s
.replace(/(?:^|[\. -])(.)/g, function(m0
, m1
) { return m1
.toUpperCase() });
48 var superContext
= null, Class
= Object
.assign(function() {}, {
49 extend: function(properties
) {
51 __base__
: { value
: this.prototype },
52 __name__
: { value
: properties
.__name__
|| 'anonymous' }
55 var ClassConstructor = function() {
56 if (!(this instanceof ClassConstructor
))
57 throw new TypeError('Constructor must not be called without "new"');
59 if (Object
.getPrototypeOf(this).hasOwnProperty('__init__')) {
60 if (typeof(this.__init__
) != 'function')
61 throw new TypeError('Class __init__ member is not a function');
63 this.__init__
.apply(this, arguments
)
66 this.super('__init__', arguments
);
70 for (var key
in properties
)
71 if (!props
[key
] && properties
.hasOwnProperty(key
))
72 props
[key
] = { value
: properties
[key
], writable
: true };
74 ClassConstructor
.prototype = Object
.create(this.prototype, props
);
75 ClassConstructor
.prototype.constructor = ClassConstructor
;
76 Object
.assign(ClassConstructor
, this);
77 ClassConstructor
.displayName
= toCamelCase(props
.__name__
.value
+ 'Class');
79 return ClassConstructor
;
82 singleton: function(properties
/*, ... */) {
83 return Class
.extend(properties
)
84 .instantiate(Class
.prototype.varargs(arguments
, 1));
87 instantiate: function(args
) {
88 return new (Function
.prototype.bind
.apply(this,
89 Class
.prototype.varargs(args
, 0, null)))();
92 call: function(self
, method
) {
93 if (typeof(this.prototype[method
]) != 'function')
94 throw new ReferenceError(method
+ ' is not defined in class');
96 return this.prototype[method
].apply(self
, self
.varargs(arguments
, 1));
99 isSubclass: function(_class
) {
100 return (_class
!= null &&
101 typeof(_class
) == 'function' &&
102 _class
.prototype instanceof this);
106 varargs: function(args
, offset
/*, ... */) {
107 return Array
.prototype.slice
.call(arguments
, 2)
108 .concat(Array
.prototype.slice
.call(args
, offset
));
111 super: function(key
, callArgs
) {
112 for (superContext
= Object
.getPrototypeOf(superContext
||
113 Object
.getPrototypeOf(this));
114 superContext
&& !superContext
.hasOwnProperty(key
);
115 superContext
= Object
.getPrototypeOf(superContext
)) { }
120 var res
= superContext
[key
];
122 if (arguments
.length
> 1) {
123 if (typeof(res
) != 'function')
124 throw new ReferenceError(key
+ ' is not a function in base class');
126 if (typeof(callArgs
) != 'object')
127 callArgs
= this.varargs(arguments
, 1);
129 res
= res
.apply(this, callArgs
);
137 toString: function() {
138 var s
= '[' + this.constructor.displayName
+ ']', f
= true;
139 for (var k
in this) {
140 if (this.hasOwnProperty(k
)) {
141 s
+= (f
? ' {\n' : '') + ' ' + k
+ ': ' + typeof(this[k
]) + '\n';
145 return s
+ (f
? '' : '}');
152 * HTTP Request helper
155 var Headers
= Class
.extend({
156 __name__
: 'LuCI.XHR.Headers',
157 __init__: function(xhr
) {
158 var hdrs
= this.headers
= {};
159 xhr
.getAllResponseHeaders().split(/\r\n/).forEach(function(line
) {
160 var m
= /^([^:]+):(.*)$/.exec(line
);
162 hdrs
[m
[1].trim().toLowerCase()] = m
[2].trim();
166 has: function(name
) {
167 return this.headers
.hasOwnProperty(String(name
).toLowerCase());
170 get: function(name
) {
171 var key
= String(name
).toLowerCase();
172 return this.headers
.hasOwnProperty(key
) ? this.headers
[key
] : null;
176 var Response
= Class
.extend({
177 __name__
: 'LuCI.XHR.Response',
178 __init__: function(xhr
, url
, duration
, headers
, content
) {
179 this.ok
= (xhr
.status
>= 200 && xhr
.status
<= 299);
180 this.status
= xhr
.status
;
181 this.statusText
= xhr
.statusText
;
182 this.headers
= (headers
!= null) ? headers
: new Headers(xhr
);
183 this.duration
= duration
;
187 if (content
!= null && typeof(content
) == 'object') {
188 this.responseJSON
= content
;
189 this.responseText
= null;
191 else if (content
!= null) {
192 this.responseJSON
= null;
193 this.responseText
= String(content
);
196 this.responseJSON
= null;
197 this.responseText
= xhr
.responseText
;
201 clone: function(content
) {
202 var copy
= new Response(this.xhr
, this.url
, this.duration
, this.headers
, content
);
205 copy
.status
= this.status
;
206 copy
.statusText
= this.statusText
;
212 if (this.responseJSON
== null)
213 this.responseJSON
= JSON
.parse(this.responseText
);
215 return this.responseJSON
;
219 if (this.responseText
== null && this.responseJSON
!= null)
220 this.responseText
= JSON
.stringify(this.responseJSON
);
222 return this.responseText
;
227 var requestQueue
= [];
229 function isQueueableRequest(opt
) {
233 if (opt
.method
!= 'POST' || typeof(opt
.content
) != 'object')
236 if (opt
.nobatch
=== true)
239 var rpcBaseURL
= Request
.expandURL(classes
.rpc
.getBaseURL());
241 return (rpcBaseURL
!= null && opt
.url
.indexOf(rpcBaseURL
) == 0);
244 function flushRequestQueue() {
245 if (!requestQueue
.length
)
248 var reqopt
= Object
.assign({}, requestQueue
[0][0], { content
: [], nobatch
: true }),
251 for (var i
= 0; i
< requestQueue
.length
; i
++) {
252 batch
[i
] = requestQueue
[i
];
253 reqopt
.content
[i
] = batch
[i
][0].content
;
256 requestQueue
.length
= 0;
258 Request
.request(rpcBaseURL
, reqopt
).then(function(reply
) {
259 var json
= null, req
= null;
261 try { json
= reply
.json() }
264 while ((req
= batch
.shift()) != null)
265 if (Array
.isArray(json
) && json
.length
)
266 req
[2].call(reqopt
, reply
.clone(json
.shift()));
268 req
[1].call(reqopt
, new Error('No related RPC reply'));
269 }).catch(function(error
) {
272 while ((req
= batch
.shift()) != null)
273 req
[1].call(reqopt
, error
);
277 var Request
= Class
.singleton({
278 __name__
: 'LuCI.Request',
282 expandURL: function(url
) {
283 if (!/^(?:[^/]+:)?\/\//.test(url
))
284 url
= location
.protocol
+ '//' + location
.host
+ url
;
289 request: function(target
, options
) {
290 var state
= { xhr
: new XMLHttpRequest(), url
: this.expandURL(target
), start
: Date
.now() },
291 opt
= Object
.assign({}, options
, state
),
294 callback
= this.handleReadyStateChange
;
296 return new Promise(function(resolveFn
, rejectFn
) {
297 opt
.xhr
.onreadystatechange
= callback
.bind(opt
, resolveFn
, rejectFn
);
298 opt
.method
= String(opt
.method
|| 'GET').toUpperCase();
300 if ('query' in opt
) {
301 var q
= (opt
.query
!= null) ? Object
.keys(opt
.query
).map(function(k
) {
302 if (opt
.query
[k
] != null) {
303 var v
= (typeof(opt
.query
[k
]) == 'object')
304 ? JSON
.stringify(opt
.query
[k
])
305 : String(opt
.query
[k
]);
307 return '%s=%s'.format(encodeURIComponent(k
), encodeURIComponent(v
));
310 return encodeURIComponent(k
);
315 switch (opt
.method
) {
319 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + q
;
323 if (content
== null) {
325 contenttype
= 'application/x-www-form-urlencoded';
332 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + (new Date()).getTime();
334 if (isQueueableRequest(opt
)) {
335 requestQueue
.push([opt
, rejectFn
, resolveFn
]);
336 requestAnimationFrame(flushRequestQueue
);
340 if ('username' in opt
&& 'password' in opt
)
341 opt
.xhr
.open(opt
.method
, opt
.url
, true, opt
.username
, opt
.password
);
343 opt
.xhr
.open(opt
.method
, opt
.url
, true);
345 opt
.xhr
.responseType
= 'text';
347 if ('overrideMimeType' in opt
.xhr
)
348 opt
.xhr
.overrideMimeType('application/octet-stream');
350 if ('timeout' in opt
)
351 opt
.xhr
.timeout
= +opt
.timeout
;
353 if ('credentials' in opt
)
354 opt
.xhr
.withCredentials
= !!opt
.credentials
;
356 if (opt
.content
!= null) {
357 switch (typeof(opt
.content
)) {
359 content
= opt
.content(xhr
);
363 if (!(opt
.content
instanceof FormData
)) {
364 content
= JSON
.stringify(opt
.content
);
365 contenttype
= 'application/json';
368 content
= opt
.content
;
373 content
= String(opt
.content
);
377 if ('headers' in opt
)
378 for (var header
in opt
.headers
)
379 if (opt
.headers
.hasOwnProperty(header
)) {
380 if (header
.toLowerCase() != 'content-type')
381 opt
.xhr
.setRequestHeader(header
, opt
.headers
[header
]);
383 contenttype
= opt
.headers
[header
];
386 if ('progress' in opt
&& 'upload' in opt
.xhr
)
387 opt
.xhr
.upload
.addEventListener('progress', opt
.progress
);
389 if (contenttype
!= null)
390 opt
.xhr
.setRequestHeader('Content-Type', contenttype
);
393 opt
.xhr
.send(content
);
396 rejectFn
.call(opt
, e
);
401 handleReadyStateChange: function(resolveFn
, rejectFn
, ev
) {
404 if (xhr
.readyState
!== 4)
407 if (xhr
.status
=== 0 && xhr
.statusText
=== '') {
408 rejectFn
.call(this, new Error('XHR request aborted by browser'));
411 var response
= new Response(
412 xhr
, xhr
.responseURL
|| this.url
, Date
.now() - this.start
);
414 Promise
.all(Request
.interceptors
.map(function(fn
) { return fn(response
) }))
415 .then(resolveFn
.bind(this, response
))
416 .catch(rejectFn
.bind(this));
420 get: function(url
, options
) {
421 return this.request(url
, Object
.assign({ method
: 'GET' }, options
));
424 post: function(url
, data
, options
) {
425 return this.request(url
, Object
.assign({ method
: 'POST', content
: data
}, options
));
428 addInterceptor: function(interceptorFn
) {
429 if (typeof(interceptorFn
) == 'function')
430 this.interceptors
.push(interceptorFn
);
431 return interceptorFn
;
434 removeInterceptor: function(interceptorFn
) {
435 var oldlen
= this.interceptors
.length
, i
= oldlen
;
437 if (this.interceptors
[i
] === interceptorFn
)
438 this.interceptors
.splice(i
, 1);
439 return (this.interceptors
.length
< oldlen
);
443 add: function(interval
, url
, options
, callback
) {
444 if (isNaN(interval
) || interval
<= 0)
445 throw new TypeError('Invalid poll interval');
447 var ival
= interval
>>> 0,
448 opts
= Object
.assign({}, options
, { timeout
: ival
* 1000 - 5 });
450 return Poll
.add(function() {
451 return Request
.request(url
, options
).then(function(res
) {
456 callback(res
, res
.json(), res
.duration
);
459 callback(res
, null, res
.duration
);
465 remove: function(entry
) { return Poll
.remove(entry
) },
466 start: function() { return Poll
.start() },
467 stop: function() { return Poll
.stop() },
468 active: function() { return Poll
.active() }
472 var Poll
= Class
.singleton({
473 __name__
: 'LuCI.Poll',
477 add: function(fn
, interval
) {
478 if (interval
== null || interval
<= 0)
479 interval
= window
.L
? window
.L
.env
.pollinterval
: null;
481 if (isNaN(interval
) || typeof(fn
) != 'function')
482 throw new TypeError('Invalid argument to LuCI.Poll.add()');
484 for (var i
= 0; i
< this.queue
.length
; i
++)
485 if (this.queue
[i
].fn
=== fn
)
496 if (this.tick
!= null && !this.active())
502 remove: function(fn
) {
503 if (typeof(fn
) != 'function')
504 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
506 var len
= this.queue
.length
;
508 for (var i
= len
; i
> 0; i
--)
509 if (this.queue
[i
-1].fn
=== fn
)
510 this.queue
.splice(i
-1, 1);
512 if (!this.queue
.length
&& this.stop())
515 return (this.queue
.length
!= len
);
524 if (this.queue
.length
) {
525 this.timer
= window
.setInterval(this.step
, 1000);
527 document
.dispatchEvent(new CustomEvent('poll-start'));
537 document
.dispatchEvent(new CustomEvent('poll-stop'));
538 window
.clearInterval(this.timer
);
545 for (var i
= 0, e
= null; (e
= Poll
.queue
[i
]) != null; i
++) {
546 if ((Poll
.tick
% e
.i
) != 0)
554 Promise
.resolve(e
.fn()).finally((function() { this.r
= true }).bind(e
));
557 Poll
.tick
= (Poll
.tick
+ 1) % Math
.pow(2, 32);
561 return (this.timer
!= null);
566 var dummyElem
= null,
568 originalCBIInit
= null,
573 var LuCI
= Class
.extend({
575 __init__: function(env
) {
577 document
.querySelectorAll('script[src*="/luci.js"]').forEach(function(s
) {
578 if (env
.base_url
== null || env
.base_url
== '') {
579 var m
= (s
.getAttribute('src') || '').match(/^(.*)\/luci\.js(?:\?v=([^?]+))?$/);
582 env
.resource_version
= m
[2];
587 if (env
.base_url
== null)
588 this.error('InternalError', 'Cannot find url of luci.js');
590 Object
.assign(this.env
, env
);
592 document
.addEventListener('poll-start', function(ev
) {
593 document
.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e
) {
594 e
.style
.display
= (e
.id
== 'xhr_poll_status_off') ? 'none' : '';
598 document
.addEventListener('poll-stop', function(ev
) {
599 document
.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e
) {
600 e
.style
.display
= (e
.id
== 'xhr_poll_status_on') ? 'none' : '';
604 var domReady
= new Promise(function(resolveFn
, rejectFn
) {
605 document
.addEventListener('DOMContentLoaded', resolveFn
);
612 this.require('form'),
613 this.probeRPCBaseURL()
614 ]).then(this.setupDOM
.bind(this)).catch(this.error
);
616 originalCBIInit
= window
.cbi_init
;
617 window
.cbi_init = function() {};
620 raise: function(type
, fmt
/*, ...*/) {
622 msg
= fmt
? String
.prototype.format
.apply(fmt
, this.varargs(arguments
, 2)) : null,
625 if (type
instanceof Error
) {
629 e
.message
= msg
+ ': ' + e
.message
;
632 try { throw new Error('stacktrace') }
633 catch (e2
) { stack
= (e2
.stack
|| '').split(/\n/) }
635 e
= new (window
[type
|| 'Error'] || Error
)(msg
|| 'Unspecified error');
636 e
.name
= type
|| 'Error';
639 stack
= (stack
|| []).map(function(frame
) {
640 frame
= frame
.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
641 return frame
? ' ' + frame
: '';
644 if (!/^ at /.test(stack
[0]))
647 if (/\braise /.test(stack
[0]))
650 if (/\berror /.test(stack
[0]))
654 e
.message
+= '\n' + stack
.join('\n');
656 if (window
.console
&& console
.debug
)
662 error: function(type
, fmt
/*, ...*/) {
664 L
.raise
.apply(L
, Array
.prototype.slice
.call(arguments
));
669 L
.ui
.addNotification(e
.name
|| _('Runtime error'),
670 E('pre', {}, e
.message
), 'danger');
672 L
.dom
.content(document
.querySelector('#maincontent'),
673 E('pre', { 'class': 'alert-message error' }, e
.message
));
682 bind: function(fn
, self
/*, ... */) {
683 return Function
.prototype.bind
.apply(fn
, this.varargs(arguments
, 2, self
));
687 require: function(name
, from) {
688 var L
= this, url
= null, from = from || [];
690 /* Class already loaded */
691 if (classes
[name
] != null) {
692 /* Circular dependency */
693 if (from.indexOf(name
) != -1)
694 L
.raise('DependencyError',
695 'Circular dependency: class "%s" depends on "%s"',
696 name
, from.join('" which depends on "'));
698 return classes
[name
];
701 url
= '%s/%s.js%s'.format(L
.env
.base_url
, name
.replace(/\./g, '/'), (L.env.resource_version ? '?v
=' + L.env.resource_version : ''));
702 from = [ name ].concat(from);
704 var compileClass = function(res) {
706 L.raise('NetworkError
',
707 'HTTP error
%d
while loading
class file
"%s"', res.status, url);
709 var source = res.text(),
710 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
711 strictmatch = /^use[ \t]+strict$/,
715 /* find require statements in source */
716 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
717 var chr = source.charCodeAt(i);
722 else if (chr == 92) {
725 else if (chr == quote) {
726 var s = source.substring(off, i),
727 m = requirematch.exec(s);
730 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_
');
731 depends.push(L.require(dep, from));
734 else if (!strictmatch.exec(s)) {
741 else if (quote == -1 && (chr == 34 || chr == 39)) {
747 /* load dependencies and instantiate class */
748 return Promise.all(depends).then(function(instances) {
749 var _factory, _class;
753 '(function(window
, document
, L
%s
) { %s
})\n\n//# sourceURL=%s\n'
754 .format(args
, source
, res
.url
));
757 L
.raise('SyntaxError', '%s\n in %s:%s',
758 error
.message
, res
.url
, error
.lineNumber
|| '?');
761 _factory
.displayName
= toCamelCase(name
+ 'ClassFactory');
762 _class
= _factory
.apply(_factory
, [window
, document
, L
].concat(instances
));
764 if (!Class
.isSubclass(_class
))
765 L
.error('TypeError', '"%s" factory yields invalid constructor', name
);
767 if (_class
.displayName
== 'AnonymousClass')
768 _class
.displayName
= toCamelCase(name
+ 'Class');
770 var ptr
= Object
.getPrototypeOf(L
),
771 parts
= name
.split(/\./),
772 instance
= new _class();
774 for (var i
= 0; ptr
&& i
< parts
.length
- 1; i
++)
778 ptr
[parts
[i
]] = instance
;
780 classes
[name
] = instance
;
786 /* Request class file */
787 classes
[name
] = Request
.get(url
, { cache
: true }).then(compileClass
);
789 return classes
[name
];
793 probeRPCBaseURL: function() {
794 if (rpcBaseURL
== null) {
796 rpcBaseURL
= window
.sessionStorage
.getItem('rpcBaseURL');
801 if (rpcBaseURL
== null) {
802 var rpcFallbackURL
= this.url('admin/ubus');
804 rpcBaseURL
= Request
.get('/ubus/').then(function(res
) {
805 return (rpcBaseURL
= (res
.status
== 400) ? '/ubus/' : rpcFallbackURL
);
807 return (rpcBaseURL
= rpcFallbackURL
);
808 }).then(function(url
) {
810 window
.sessionStorage
.setItem('rpcBaseURL', url
);
818 return Promise
.resolve(rpcBaseURL
);
821 probeSystemFeatures: function() {
822 if (sysFeatures
== null) {
824 sysFeatures
= JSON
.parse(window
.sessionStorage
.getItem('sysFeatures'));
829 if (!this.isObject(sysFeatures
)) {
830 sysFeatures
= classes
.rpc
.declare({
832 method
: 'getFeatures',
834 })().then(function(features
) {
836 window
.sessionStorage
.setItem('sysFeatures', JSON
.stringify(features
));
840 sysFeatures
= features
;
846 return Promise
.resolve(sysFeatures
);
849 hasSystemFeature: function() {
850 var ft
= sysFeatures
[arguments
[0]];
852 if (arguments
.length
== 2)
853 return this.isObject(ft
) ? ft
[arguments
[1]] : null;
855 return (ft
!= null && ft
!= false);
858 notifySessionExpiry: function() {
861 L
.ui
.showModal(_('Session expired'), [
862 E('div', { class: 'alert-message warning' },
863 _('A new login is required since the authentication session expired.')),
864 E('div', { class: 'right' },
866 class: 'btn primary',
868 var loc
= window
.location
;
869 window
.location
= loc
.protocol
+ '//' + loc
.host
+ loc
.pathname
+ loc
.search
;
874 L
.raise('SessionError', 'Login session is expired');
877 setupDOM: function(res
) {
884 rpcClass
.setBaseURL(rpcBaseURL
);
886 rpcClass
.addInterceptor(function(msg
, req
) {
887 if (!L
.isObject(msg
) || !L
.isObject(msg
.error
) || msg
.error
.code
!= -32002)
890 if (!L
.isObject(req
) || (req
.object
== 'session' && req
.method
== 'access'))
893 return rpcClass
.declare({
896 'params': [ 'scope', 'object', 'function' ],
897 'expect': { access
: true }
898 })('uci', 'luci', 'read').catch(L
.notifySessionExpiry
);
901 Request
.addInterceptor(function(res
) {
902 var isDenied
= false;
904 if (res
.status
== 403 && res
.headers
.get('X-LuCI-Login-Required') == 'yes')
910 L
.notifySessionExpiry();
913 return this.probeSystemFeatures().finally(this.initDOM
);
916 initDOM: function() {
919 document
.dispatchEvent(new CustomEvent('luci-loaded'));
924 /* URL construction helpers */
925 path: function(prefix
, parts
) {
926 var url
= [ prefix
|| '' ];
928 for (var i
= 0; i
< parts
.length
; i
++)
929 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts
[i
]))
930 url
.push('/', parts
[i
]);
932 if (url
.length
=== 1)
939 return this.path(this.env
.scriptname
, arguments
);
942 resource: function() {
943 return this.path(this.env
.resource
, arguments
);
946 location: function() {
947 return this.path(this.env
.scriptname
, this.env
.requestpath
);
952 isObject: function(val
) {
953 return (val
!= null && typeof(val
) == 'object');
956 sortedKeys: function(obj
, key
, sortmode
) {
957 if (obj
== null || typeof(obj
) != 'object')
960 return Object
.keys(obj
).map(function(e
) {
961 var v
= (key
!= null) ? obj
[e
][key
] : e
;
965 v
= (v
!= null) ? v
.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
966 function(m0
, m1
) { return ('000' + m1
.toLowerCase()).substr(-4) }) : null;
970 v
= (v
!= null) ? +v
: null;
975 }).filter(function(e
) {
976 return (e
[1] != null);
977 }).sort(function(a
, b
) {
978 return (a
[1] > b
[1]);
984 toArray: function(val
) {
987 else if (Array
.isArray(val
))
989 else if (typeof(val
) == 'object')
992 var s
= String(val
).trim();
997 return s
.split(/\s+/);
1001 /* HTTP resource fetching */
1002 get: function(url
, args
, cb
) {
1003 return this.poll(null, url
, args
, cb
, false);
1006 post: function(url
, args
, cb
) {
1007 return this.poll(null, url
, args
, cb
, true);
1010 poll: function(interval
, url
, args
, cb
, post
) {
1011 if (interval
!== null && interval
<= 0)
1012 interval
= this.env
.pollinterval
;
1014 var data
= post
? { token
: this.env
.token
} : null,
1015 method
= post
? 'POST' : 'GET';
1017 if (!/^(?:\/|\S+:\/\/)/.test(url
))
1018 url
= this.url(url
);
1021 data
= Object
.assign(data
|| {}, args
);
1023 if (interval
!== null)
1024 return Request
.poll
.add(interval
, url
, { method
: method
, query
: data
}, cb
);
1026 return Request
.request(url
, { method
: method
, query
: data
})
1027 .then(function(res
) {
1029 if (/^application\/json\b/.test(res
.headers
.get('Content-Type')))
1030 try { json
= res
.json() } catch(e
) {}
1031 cb(res
.xhr
, json
, res
.duration
);
1035 stop: function(entry
) { return Poll
.remove(entry
) },
1036 halt: function() { return Poll
.stop() },
1037 run: function() { return Poll
.start() },
1039 /* DOM manipulation */
1040 dom
: Class
.singleton({
1041 __name__
: 'LuCI.DOM',
1044 return (e
!= null && typeof(e
) == 'object' && 'nodeType' in e
);
1047 parse: function(s
) {
1051 domParser
= domParser
|| new DOMParser();
1052 elem
= domParser
.parseFromString(s
, 'text/html').body
.firstChild
;
1058 dummyElem
= dummyElem
|| document
.createElement('div');
1059 dummyElem
.innerHTML
= s
;
1060 elem
= dummyElem
.firstChild
;
1065 return elem
|| null;
1068 matches: function(node
, selector
) {
1069 var m
= this.elem(node
) ? node
.matches
|| node
.msMatchesSelector
: null;
1070 return m
? m
.call(node
, selector
) : false;
1073 parent: function(node
, selector
) {
1074 if (this.elem(node
) && node
.closest
)
1075 return node
.closest(selector
);
1077 while (this.elem(node
))
1078 if (this.matches(node
, selector
))
1081 node
= node
.parentNode
;
1086 append: function(node
, children
) {
1087 if (!this.elem(node
))
1090 if (Array
.isArray(children
)) {
1091 for (var i
= 0; i
< children
.length
; i
++)
1092 if (this.elem(children
[i
]))
1093 node
.appendChild(children
[i
]);
1094 else if (children
!== null && children
!== undefined)
1095 node
.appendChild(document
.createTextNode('' + children
[i
]));
1097 return node
.lastChild
;
1099 else if (typeof(children
) === 'function') {
1100 return this.append(node
, children(node
));
1102 else if (this.elem(children
)) {
1103 return node
.appendChild(children
);
1105 else if (children
!== null && children
!== undefined) {
1106 node
.innerHTML
= '' + children
;
1107 return node
.lastChild
;
1113 content: function(node
, children
) {
1114 if (!this.elem(node
))
1117 var dataNodes
= node
.querySelectorAll('[data-idref]');
1119 for (var i
= 0; i
< dataNodes
.length
; i
++)
1120 delete this.registry
[dataNodes
[i
].getAttribute('data-idref')];
1122 while (node
.firstChild
)
1123 node
.removeChild(node
.firstChild
);
1125 return this.append(node
, children
);
1128 attr: function(node
, key
, val
) {
1129 if (!this.elem(node
))
1134 if (typeof(key
) === 'object' && key
!== null)
1136 else if (typeof(key
) === 'string')
1137 attr
= {}, attr
[key
] = val
;
1140 if (!attr
.hasOwnProperty(key
) || attr
[key
] == null)
1143 switch (typeof(attr
[key
])) {
1145 node
.addEventListener(key
, attr
[key
]);
1149 node
.setAttribute(key
, JSON
.stringify(attr
[key
]));
1153 node
.setAttribute(key
, attr
[key
]);
1158 create: function() {
1159 var html
= arguments
[0],
1160 attr
= arguments
[1],
1161 data
= arguments
[2],
1164 if (!(attr
instanceof Object
) || Array
.isArray(attr
))
1165 data
= attr
, attr
= null;
1167 if (Array
.isArray(html
)) {
1168 elem
= document
.createDocumentFragment();
1169 for (var i
= 0; i
< html
.length
; i
++)
1170 elem
.appendChild(this.create(html
[i
]));
1172 else if (this.elem(html
)) {
1175 else if (html
.charCodeAt(0) === 60) {
1176 elem
= this.parse(html
);
1179 elem
= document
.createElement(html
);
1185 this.attr(elem
, attr
);
1186 this.append(elem
, data
);
1193 data: function(node
, key
, val
) {
1194 var id
= node
.getAttribute('data-idref');
1196 /* clear all data */
1197 if (arguments
.length
> 1 && key
== null) {
1199 node
.removeAttribute('data-idref');
1200 val
= this.registry
[id
]
1201 delete this.registry
[id
];
1209 else if (arguments
.length
> 2 && key
!= null && val
== null) {
1211 val
= this.registry
[id
][key
];
1212 delete this.registry
[id
][key
];
1220 else if (arguments
.length
> 2 && key
!= null && val
!= null) {
1222 do { id
= Math
.floor(Math
.random() * 0xffffffff).toString(16) }
1223 while (this.registry
.hasOwnProperty(id
));
1225 node
.setAttribute('data-idref', id
);
1226 this.registry
[id
] = {};
1229 return (this.registry
[id
][key
] = val
);
1233 else if (arguments
.length
== 1) {
1235 return this.registry
[id
];
1241 else if (arguments
.length
== 2) {
1243 return this.registry
[id
][key
];
1249 bindClassInstance: function(node
, inst
) {
1250 if (!(inst
instanceof Class
))
1251 L
.error('TypeError', 'Argument must be a class instance');
1253 return this.data(node
, '_class', inst
);
1256 findClassInstance: function(node
) {
1260 inst
= this.data(node
, '_class');
1261 node
= node
.parentNode
;
1263 while (!(inst
instanceof Class
) && node
!= null);
1268 callClassMethod: function(node
, method
/*, ... */) {
1269 var inst
= this.findClassInstance(node
);
1271 if (inst
== null || typeof(inst
[method
]) != 'function')
1274 return inst
[method
].apply(inst
, inst
.varargs(arguments
, 2));
1277 isEmpty: function(node
, ignoreFn
) {
1278 for (var child
= node
.firstElementChild
; child
!= null; child
= child
.nextElementSibling
)
1279 if (!child
.classList
.contains('hidden') && (!ignoreFn
|| !ignoreFn(child
)))
1290 view
: Class
.extend({
1291 __name__
: 'LuCI.View',
1293 __init__: function() {
1294 var vp
= document
.getElementById('view');
1296 L
.dom
.content(vp
, E('div', { 'class': 'spinning' }, _('Loading view…')));
1298 return Promise
.resolve(this.load())
1299 .then(L
.bind(this.render
, this))
1300 .then(L
.bind(function(nodes
) {
1301 var vp
= document
.getElementById('view');
1303 L
.dom
.content(vp
, nodes
);
1304 L
.dom
.append(vp
, this.addFooter());
1305 }, this)).catch(L
.error
);
1308 load: function() {},
1309 render: function() {},
1311 handleSave: function(ev
) {
1314 document
.getElementById('maincontent')
1315 .querySelectorAll('.cbi-map').forEach(function(map
) {
1316 tasks
.push(L
.dom
.callClassMethod(map
, 'save'));
1319 return Promise
.all(tasks
);
1322 handleSaveApply: function(ev
) {
1323 return this.handleSave(ev
).then(function() {
1324 L
.ui
.changes
.apply(true);
1328 handleReset: function(ev
) {
1331 document
.getElementById('maincontent')
1332 .querySelectorAll('.cbi-map').forEach(function(map
) {
1333 tasks
.push(L
.dom
.callClassMethod(map
, 'reset'));
1336 return Promise
.all(tasks
);
1339 addFooter: function() {
1342 if (this.handleSaveApply
|| this.handleSave
|| this.handleReset
) {
1343 footer
.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
1344 this.handleSaveApply
? E('button', {
1345 'class': 'cbi-button cbi-button-apply',
1346 'click': L
.ui
.createHandlerFn(this, 'handleSaveApply')
1347 }, [ _('Save & Apply') ]) : '', ' ',
1348 this.handleSave
? E('button', {
1349 'class': 'cbi-button cbi-button-save',
1350 'click': L
.ui
.createHandlerFn(this, 'handleSave')
1351 }, [ _('Save') ]) : '', ' ',
1352 this.handleReset
? E('button', {
1353 'class': 'cbi-button cbi-button-reset',
1354 'click': L
.ui
.createHandlerFn(this, 'handleReset')
1355 }, [ _('Reset') ]) : ''
1364 var XHR
= Class
.extend({
1365 __name__
: 'LuCI.XHR',
1366 __init__: function() {
1367 if (window
.console
&& console
.debug
)
1368 console
.debug('Direct use XHR() is deprecated, please use L.Request instead');
1371 _response: function(cb
, res
, json
, duration
) {
1373 cb(res
, json
, duration
);
1377 get: function(url
, data
, callback
, timeout
) {
1379 L
.get(url
, data
, this._response
.bind(this, callback
), timeout
);
1382 post: function(url
, data
, callback
, timeout
) {
1384 L
.post(url
, data
, this._response
.bind(this, callback
), timeout
);
1387 cancel: function() { delete this.active
},
1388 busy: function() { return (this.active
=== true) },
1389 abort: function() {},
1390 send_form: function() { L
.error('InternalError', 'Not implemented') },
1393 XHR
.get = function() { return window
.L
.get.apply(window
.L
, arguments
) };
1394 XHR
.post = function() { return window
.L
.post
.apply(window
.L
, arguments
) };
1395 XHR
.poll = function() { return window
.L
.poll
.apply(window
.L
, arguments
) };
1396 XHR
.stop
= Request
.poll
.remove
.bind(Request
.poll
);
1397 XHR
.halt
= Request
.poll
.stop
.bind(Request
.poll
);
1398 XHR
.run
= Request
.poll
.start
.bind(Request
.poll
);
1399 XHR
.running
= Request
.poll
.active
.bind(Request
.poll
);
1403 })(window
, document
);