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 content = JSON.stringify(opt.content);
364 contenttype = 'application/json';
368 content = String(opt.content);
372 if ('headers' in opt)
373 for (var header in opt.headers)
374 if (opt.headers.hasOwnProperty(header)) {
375 if (header.toLowerCase() != 'content-type')
376 opt.xhr.setRequestHeader(header, opt.headers[header]);
378 contenttype = opt.headers[header];
381 if (contenttype != null)
382 opt.xhr.setRequestHeader('Content-Type', contenttype);
385 opt.xhr.send(content);
388 rejectFn.call(opt, e);
393 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
396 if (xhr.readyState !== 4)
399 if (xhr.status === 0 && xhr.statusText === '') {
400 rejectFn.call(this, new Error('XHR request aborted by browser'));
403 var response = new Response(
404 xhr, xhr.responseURL || this.url, Date.now() - this.start);
406 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
407 .then(resolveFn.bind(this, response))
408 .catch(rejectFn.bind(this));
412 get: function(url, options) {
413 return this.request(url, Object.assign({ method: 'GET' }, options));
416 post: function(url, data, options) {
417 return this.request(url, Object.assign({ method: 'POST', content: data }, options));
420 addInterceptor: function(interceptorFn) {
421 if (typeof(interceptorFn) == 'function')
422 this.interceptors.push(interceptorFn);
423 return interceptorFn;
426 removeInterceptor: function(interceptorFn) {
427 var oldlen = this.interceptors.length, i = oldlen;
429 if (this.interceptors[i] === interceptorFn)
430 this.interceptors.splice(i, 1);
431 return (this.interceptors.length < oldlen);
435 add: function(interval, url, options, callback) {
436 if (isNaN(interval) || interval <= 0)
437 throw new TypeError('Invalid poll interval');
439 var ival = interval >>> 0,
440 opts = Object.assign({}, options, { timeout: ival * 1000 - 5 });
442 return Poll.add(function() {
443 return Request.request(url, options).then(function(res) {
448 callback(res, res.json(), res.duration);
451 callback(res, null, res.duration);
457 remove: function(entry) { return Poll.remove(entry) },
458 start: function() { return Poll.start() },
459 stop: function() { return Poll.stop() },
460 active: function() { return Poll.active() }
464 var Poll = Class.singleton({
465 __name__: 'LuCI.Poll',
469 add: function(fn, interval) {
470 if (interval == null || interval <= 0)
471 interval = window.L ? window.L.env.pollinterval : null;
473 if (isNaN(interval) || typeof(fn) != 'function')
474 throw new TypeError('Invalid argument to LuCI.Poll.add()');
476 for (var i = 0; i < this.queue.length; i++)
477 if (this.queue[i].fn === fn)
488 if (this.tick != null && !this.active())
494 remove: function(entry) {
495 if (typeof(fn) != 'function')
496 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
498 var len = this.queue.length;
500 for (var i = len; i > 0; i--)
501 if (this.queue[i-1].fn === fn)
502 this.queue.splice(i-1, 1);
504 if (!this.queue.length && this.stop())
507 return (this.queue.length != len);
516 if (this.queue.length) {
517 this.timer = window.setInterval(this.step, 1000);
519 document.dispatchEvent(new CustomEvent('poll-start'));
529 document.dispatchEvent(new CustomEvent('poll-stop'));
530 window.clearInterval(this.timer);
537 for (var i = 0, e = null; (e = Poll.queue[i]) != null; i++) {
538 if ((Poll.tick % e.i) != 0)
546 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
549 Poll.tick = (Poll.tick + 1) % Math.pow(2, 32);
553 return (this.timer != null);
558 var dummyElem = null,
560 originalCBIInit = null,
564 var LuCI = Class.extend({
566 __init__: function(env) {
568 document.querySelectorAll('script[src*="/luci.js"]').forEach(function(s) {
569 if (env.base_url == null || env.base_url == '')
570 env.base_url = s.getAttribute('src').replace(/\/luci\.js(?:\?v=[^?]+)?$/, '');
573 if (env.base_url == null)
574 this.error('InternalError', 'Cannot find url of luci.js');
576 Object.assign(this.env, env);
578 document.addEventListener('poll-start', function(ev) {
579 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
580 e.style.display = (e.id == 'xhr_poll_status_off') ? 'none' : '';
584 document.addEventListener('poll-stop', function(ev) {
585 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
586 e.style.display = (e.id == 'xhr_poll_status_on') ? 'none' : '';
590 var domReady = new Promise(function(resolveFn, rejectFn) {
591 document.addEventListener('DOMContentLoaded', resolveFn);
598 this.require('form'),
599 this.probeRPCBaseURL()
600 ]).then(this.setupDOM.bind(this)).catch(this.error);
602 originalCBIInit = window.cbi_init;
603 window.cbi_init = function() {};
606 raise: function(type, fmt /*, ...*/) {
608 msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
611 if (type instanceof Error) {
613 stack = (e.stack || '').split(/\n/);
616 e.message = msg + ': ' + e.message;
619 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
620 e.name = type || 'Error';
623 if (window.console && console.debug)
629 error: function(type, fmt /*, ...*/) {
631 L.raise.apply(L, Array.prototype.slice.call(arguments));
634 var stack = (e.stack || '').split(/\n/).map(function(frame) {
635 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
636 return frame ? ' ' + frame : '';
639 if (!/^ at /.test(stack[0]))
642 if (/\braise /.test(stack[0]))
645 if (/\berror /.test(stack[0]))
648 stack = stack.length ? '\n' + stack.join('\n') : '';
651 L.ui.showModal(e.name || _('Runtime error'),
652 E('pre', { 'class': 'alert-message error' }, e.message + stack));
654 L.dom.content(document.querySelector('#maincontent'),
655 E('pre', { 'class': 'alert-message error' }, e + stack));
661 bind: function(fn, self /*, ... */) {
662 return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
666 require: function(name, from) {
667 var L = this, url = null, from = from || [];
669 /* Class already loaded */
670 if (classes[name] != null) {
671 /* Circular dependency */
672 if (from.indexOf(name) != -1)
673 L.raise('DependencyError',
674 'Circular dependency: class "%s" depends on "%s"',
675 name, from.join('" which depends on "'));
677 return classes[name];
680 url = '%s/%s.js'.format(L.env.base_url, name.replace(/\./g, '/'));
681 from = [ name ].concat(from);
683 var compileClass = function(res) {
685 L.raise('NetworkError',
686 'HTTP error %d while loading class file "%s"', res.status, url);
688 var source = res.text(),
689 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
690 strictmatch = /^use[ \t]+strict$/,
694 /* find require statements in source */
695 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
696 var chr = source.charCodeAt(i);
701 else if (chr == 92) {
704 else if (chr == quote) {
705 var s = source.substring(off, i),
706 m = requirematch.exec(s);
709 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
710 depends.push(L.require(dep, from));
713 else if (!strictmatch.exec(s)) {
720 else if (quote == -1 && (chr == 34 || chr == 39)) {
726 /* load dependencies and instantiate class */
727 return Promise.all(depends).then(function(instances) {
728 var _factory, _class;
732 '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
733 .format(args, source, res.url));
736 L.raise('SyntaxError', '%s\n in %s:%s',
737 error.message, res.url, error.lineNumber || '?');
740 _factory.displayName = toCamelCase(name + 'ClassFactory');
741 _class = _factory.apply(_factory, [window, document, L].concat(instances));
743 if (!Class.isSubclass(_class))
744 L.error('TypeError', '"%s" factory yields invalid constructor', name);
746 if (_class.displayName == 'AnonymousClass')
747 _class.displayName = toCamelCase(name + 'Class');
749 var ptr = Object.getPrototypeOf(L),
750 parts = name.split(/\./),
751 instance = new _class();
753 for (var i = 0; ptr && i < parts.length - 1; i++)
757 ptr[parts[i]] = instance;
759 classes[name] = instance;
765 /* Request class file */
766 classes[name] = Request.get(url, { cache: true }).then(compileClass);
768 return classes[name];
772 probeRPCBaseURL: function() {
773 if (rpcBaseURL == null) {
775 rpcBaseURL = window.sessionStorage.getItem('rpcBaseURL');
780 if (rpcBaseURL == null) {
781 var rpcFallbackURL = this.url('admin/ubus');
783 rpcBaseURL = Request.get('/ubus/').then(function(res) {
784 return (rpcBaseURL = (res.status == 400) ? '/ubus/' : rpcFallbackURL);
786 return (rpcBaseURL = rpcFallbackURL);
787 }).then(function(url) {
789 window.sessionStorage.setItem('rpcBaseURL', url);
797 return Promise.resolve(rpcBaseURL);
800 setupDOM: function(res) {
807 rpcClass.setBaseURL(rpcBaseURL);
809 Request.addInterceptor(function(res) {
810 if (res.status != 403 || res.headers.get('X-LuCI-Login-Required') != 'yes')
815 L.ui.showModal(_('Session expired'), [
816 E('div', { class: 'alert-message warning' },
817 _('A new login is required since the authentication session expired.')),
818 E('div', { class: 'right' },
820 class: 'btn primary',
822 var loc = window.location;
823 window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
828 throw 'Session expired';
835 document.dispatchEvent(new CustomEvent('luci-loaded'));
840 /* URL construction helpers */
841 path: function(prefix, parts) {
842 var url = [ prefix || '' ];
844 for (var i = 0; i < parts.length; i++)
845 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
846 url.push('/', parts[i]);
848 if (url.length === 1)
855 return this.path(this.env.scriptname, arguments);
858 resource: function() {
859 return this.path(this.env.resource, arguments);
862 location: function() {
863 return this.path(this.env.scriptname, this.env.requestpath);
868 isObject: function(val) {
869 return (val != null && typeof(val) == 'object');
872 sortedKeys: function(obj, key, sortmode) {
873 if (obj == null || typeof(obj) != 'object')
876 return Object.keys(obj).map(function(e) {
877 var v = (key != null) ? obj[e][key] : e;
881 v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
882 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
886 v = (v != null) ? +v : null;
891 }).filter(function(e) {
892 return (e[1] != null);
893 }).sort(function(a, b) {
894 return (a[1] > b[1]);
900 toArray: function(val) {
903 else if (Array.isArray(val))
905 else if (typeof(val) == 'object')
908 var s = String(val).trim();
913 return s.split(/\s+/);
917 /* HTTP resource fetching */
918 get: function(url, args, cb) {
919 return this.poll(null, url, args, cb, false);
922 post: function(url, args, cb) {
923 return this.poll(null, url, args, cb, true);
926 poll: function(interval, url, args, cb, post) {
927 if (interval !== null && interval <= 0)
928 interval = this.env.pollinterval;
930 var data = post ? { token: this.env.token } : null,
931 method = post ? 'POST' : 'GET';
933 if (!/^(?:\/|\S+:\/\/)/.test(url))
937 data = Object.assign(data || {}, args);
939 if (interval !== null)
940 return Request.poll.add(interval, url, { method: method, query: data }, cb);
942 return Request.request(url, { method: method, query: data })
943 .then(function(res) {
945 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
946 try { json = res.json() } catch(e) {}
947 cb(res.xhr, json, res.duration);
951 stop: function(entry) { return Poll.remove(entry) },
952 halt: function() { return Poll.stop() },
953 run: function() { return Poll.start() },
955 /* DOM manipulation */
956 dom: Class.singleton({
957 __name__: 'LuCI.DOM',
960 return (e != null && typeof(e) == 'object' && 'nodeType' in e);
967 domParser = domParser || new DOMParser();
968 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
974 dummyElem = dummyElem || document.createElement('div');
975 dummyElem.innerHTML = s;
976 elem = dummyElem.firstChild;
984 matches: function(node, selector) {
985 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
986 return m ? m.call(node, selector) : false;
989 parent: function(node, selector) {
990 if (this.elem(node) && node.closest)
991 return node.closest(selector);
993 while (this.elem(node))
994 if (this.matches(node, selector))
997 node = node.parentNode;
1002 append: function(node, children) {
1003 if (!this.elem(node))
1006 if (Array.isArray(children)) {
1007 for (var i = 0; i < children.length; i++)
1008 if (this.elem(children[i]))
1009 node.appendChild(children[i]);
1010 else if (children !== null && children !== undefined)
1011 node.appendChild(document.createTextNode('' + children[i]));
1013 return node.lastChild;
1015 else if (typeof(children) === 'function') {
1016 return this.append(node, children(node));
1018 else if (this.elem(children)) {
1019 return node.appendChild(children);
1021 else if (children !== null && children !== undefined) {
1022 node.innerHTML = '' + children;
1023 return node.lastChild;
1029 content: function(node, children) {
1030 if (!this.elem(node))
1033 var dataNodes = node.querySelectorAll('[data-idref]');
1035 for (var i = 0; i < dataNodes.length; i++)
1036 delete this.registry[dataNodes[i].getAttribute('data-idref')];
1038 while (node.firstChild)
1039 node.removeChild(node.firstChild);
1041 return this.append(node, children);
1044 attr: function(node, key, val) {
1045 if (!this.elem(node))
1050 if (typeof(key) === 'object' && key !== null)
1052 else if (typeof(key) === 'string')
1053 attr = {}, attr[key] = val;
1056 if (!attr.hasOwnProperty(key) || attr[key] == null)
1059 switch (typeof(attr[key])) {
1061 node.addEventListener(key, attr[key]);
1065 node.setAttribute(key, JSON.stringify(attr[key]));
1069 node.setAttribute(key, attr[key]);
1074 create: function() {
1075 var html = arguments[0],
1076 attr = arguments[1],
1077 data = arguments[2],
1080 if (!(attr instanceof Object) || Array.isArray(attr))
1081 data = attr, attr = null;
1083 if (Array.isArray(html)) {
1084 elem = document.createDocumentFragment();
1085 for (var i = 0; i < html.length; i++)
1086 elem.appendChild(this.create(html[i]));
1088 else if (this.elem(html)) {
1091 else if (html.charCodeAt(0) === 60) {
1092 elem = this.parse(html);
1095 elem = document.createElement(html);
1101 this.attr(elem, attr);
1102 this.append(elem, data);
1109 data: function(node, key, val) {
1110 var id = node.getAttribute('data-idref');
1112 /* clear all data */
1113 if (arguments.length > 1 && key == null) {
1115 node.removeAttribute('data-idref');
1116 val = this.registry[id]
1117 delete this.registry[id];
1125 else if (arguments.length > 2 && key != null && val == null) {
1127 val = this.registry[id][key];
1128 delete this.registry[id][key];
1136 else if (arguments.length > 2 && key != null && val != null) {
1138 do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
1139 while (this.registry.hasOwnProperty(id));
1141 node.setAttribute('data-idref', id);
1142 this.registry[id] = {};
1145 return (this.registry[id][key] = val);
1149 else if (arguments.length == 1) {
1151 return this.registry[id];
1157 else if (arguments.length == 2) {
1159 return this.registry[id][key];
1165 bindClassInstance: function(node, inst) {
1166 if (!(inst instanceof Class))
1167 L.error('TypeError', 'Argument must be a class instance');
1169 return this.data(node, '_class', inst);
1172 findClassInstance: function(node) {
1176 inst = this.data(node, '_class');
1177 node = node.parentNode;
1179 while (!(inst instanceof Class) && node != null);
1184 callClassMethod: function(node, method /*, ... */) {
1185 var inst = this.findClassInstance(node);
1187 if (inst == null || typeof(inst[method]) != 'function')
1190 return inst[method].apply(inst, inst.varargs(arguments, 2));
1193 isEmpty: function(node) {
1194 for (var child = node.firstElementChild; child != null; child = child.nextElementSibling)
1195 if (!child.classList.contains('hidden'))
1206 view: Class.extend({
1207 __name__: 'LuCI.View',
1209 __init__: function() {
1210 var vp = document.getElementById('view');
1212 L.dom.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
1214 return Promise.resolve(this.load())
1215 .then(L.bind(this.render, this))
1216 .then(L.bind(function(nodes) {
1217 var vp = document.getElementById('view');
1219 L.dom.content(vp, nodes);
1220 L.dom.append(vp, this.addFooter());
1221 }, this)).catch(L.error);
1224 load: function() {},
1225 render: function() {},
1227 handleSave: function(ev) {
1230 document.getElementById('maincontent')
1231 .querySelectorAll('.cbi-map').forEach(function(map) {
1232 tasks.push(L.dom.callClassMethod(map, 'save'));
1235 return Promise.all(tasks);
1238 handleSaveApply: function(ev) {
1239 return this.handleSave(ev).then(function() {
1240 L.ui.changes.apply(true);
1244 handleReset: function(ev) {
1247 document.getElementById('maincontent')
1248 .querySelectorAll('.cbi-map').forEach(function(map) {
1249 tasks.push(L.dom.callClassMethod(map, 'reset'));
1252 return Promise.all(tasks);
1255 addFooter: function() {
1257 mc = document.getElementById('maincontent');
1259 if (mc.querySelector('.cbi-map')) {
1260 footer.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
1262 'class': 'cbi-button cbi-button-apply',
1264 'value': _('Save & Apply'),
1265 'click': L.bind(this.handleSaveApply, this)
1268 'class': 'cbi-button cbi-button-save',
1271 'click': L.bind(this.handleSave, this)
1274 'class': 'cbi-button cbi-button-reset',
1276 'value': _('Reset'),
1277 'click': L.bind(this.handleReset, this)
1287 var XHR = Class.extend({
1288 __name__: 'LuCI.XHR',
1289 __init__: function() {
1290 if (window.console && console.debug)
1291 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
1294 _response: function(cb, res, json, duration) {
1296 cb(res, json, duration);
1300 get: function(url, data, callback, timeout) {
1302 L.get(url, data, this._response.bind(this, callback), timeout);
1305 post: function(url, data, callback, timeout) {
1307 L.post(url, data, this._response.bind(this, callback), timeout);
1310 cancel: function() { delete this.active },
1311 busy: function() { return (this.active === true) },
1312 abort: function() {},
1313 send_form: function() { L.error('InternalError', 'Not implemented') },
1316 XHR.get = function() { return window.L.get.apply(window.L, arguments) };
1317 XHR.post = function() { return window.L.post.apply(window.L, arguments) };
1318 XHR.poll = function() { return window.L.poll.apply(window.L, arguments) };
1319 XHR.stop = Request.poll.remove.bind(Request.poll);
1320 XHR.halt = Request.poll.stop.bind(Request.poll);
1321 XHR.run = Request.poll.start.bind(Request.poll);
1322 XHR.running = Request.poll.active.bind(Request.poll);
1326 })(window, document);