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];
27 * Class declaration and inheritance helper
30 var toCamelCase = function(s) {
31 return s.replace(/(?:^|[\. -])(.)/g, function(m0, m1) { return m1.toUpperCase() });
34 var superContext = null, Class = Object.assign(function() {}, {
35 extend: function(properties) {
37 __base__: { value: this.prototype },
38 __name__: { value: properties.__name__ || 'anonymous' }
41 var ClassConstructor = function() {
42 if (!(this instanceof ClassConstructor))
43 throw new TypeError('Constructor must not be called without "new"');
45 if (Object.getPrototypeOf(this).hasOwnProperty('__init__')) {
46 if (typeof(this.__init__) != 'function')
47 throw new TypeError('Class __init__ member is not a function');
49 this.__init__.apply(this, arguments)
52 this.super('__init__', arguments);
56 for (var key in properties)
57 if (!props[key] && properties.hasOwnProperty(key))
58 props[key] = { value: properties[key], writable: true };
60 ClassConstructor.prototype = Object.create(this.prototype, props);
61 ClassConstructor.prototype.constructor = ClassConstructor;
62 Object.assign(ClassConstructor, this);
63 ClassConstructor.displayName = toCamelCase(props.__name__.value + 'Class');
65 return ClassConstructor;
68 singleton: function(properties /*, ... */) {
69 return Class.extend(properties)
70 .instantiate(Class.prototype.varargs(arguments, 1));
73 instantiate: function(args) {
74 return new (Function.prototype.bind.apply(this,
75 Class.prototype.varargs(args, 0, null)))();
78 call: function(self, method) {
79 if (typeof(this.prototype[method]) != 'function')
80 throw new ReferenceError(method + ' is not defined in class');
82 return this.prototype[method].apply(self, self.varargs(arguments, 1));
85 isSubclass: function(_class) {
86 return (_class != null &&
87 typeof(_class) == 'function' &&
88 _class.prototype instanceof this);
92 varargs: function(args, offset /*, ... */) {
93 return Array.prototype.slice.call(arguments, 2)
94 .concat(Array.prototype.slice.call(args, offset));
97 super: function(key, callArgs) {
98 for (superContext = Object.getPrototypeOf(superContext ||
99 Object.getPrototypeOf(this));
100 superContext && !superContext.hasOwnProperty(key);
101 superContext = Object.getPrototypeOf(superContext)) { }
106 var res = superContext[key];
108 if (arguments.length > 1) {
109 if (typeof(res) != 'function')
110 throw new ReferenceError(key + ' is not a function in base class');
112 if (typeof(callArgs) != 'object')
113 callArgs = this.varargs(arguments, 1);
115 res = res.apply(this, callArgs);
123 toString: function() {
124 var s = '[' + this.constructor.displayName + ']', f = true;
125 for (var k in this) {
126 if (this.hasOwnProperty(k)) {
127 s += (f ? ' {\n' : '') + ' ' + k + ': ' + typeof(this[k]) + '\n';
131 return s + (f ? '' : '}');
138 * HTTP Request helper
141 var Headers = Class.extend({
142 __name__: 'LuCI.XHR.Headers',
143 __init__: function(xhr) {
144 var hdrs = this.headers = {};
145 xhr.getAllResponseHeaders().split(/\r\n/).forEach(function(line) {
146 var m = /^([^:]+):(.*)$/.exec(line);
148 hdrs[m[1].trim().toLowerCase()] = m[2].trim();
152 has: function(name) {
153 return this.headers.hasOwnProperty(String(name).toLowerCase());
156 get: function(name) {
157 var key = String(name).toLowerCase();
158 return this.headers.hasOwnProperty(key) ? this.headers[key] : null;
162 var Response = Class.extend({
163 __name__: 'LuCI.XHR.Response',
164 __init__: function(xhr, url, duration, headers, content) {
165 this.ok = (xhr.status >= 200 && xhr.status <= 299);
166 this.status = xhr.status;
167 this.statusText = xhr.statusText;
168 this.headers = (headers != null) ? headers : new Headers(xhr);
169 this.duration = duration;
173 if (content != null && typeof(content) == 'object') {
174 this.responseJSON = content;
175 this.responseText = null;
177 else if (content != null) {
178 this.responseJSON = null;
179 this.responseText = String(content);
182 this.responseJSON = null;
183 this.responseText = xhr.responseText;
187 clone: function(content) {
188 var copy = new Response(this.xhr, this.url, this.duration, this.headers, content);
191 copy.status = this.status;
192 copy.statusText = this.statusText;
198 if (this.responseJSON == null)
199 this.responseJSON = JSON.parse(this.responseText);
201 return this.responseJSON;
205 if (this.responseText == null && this.responseJSON != null)
206 this.responseText = JSON.stringify(this.responseJSON);
208 return this.responseText;
213 var requestQueue = [];
215 function isQueueableRequest(opt) {
219 if (opt.method != 'POST' || typeof(opt.content) != 'object')
222 if (opt.nobatch === true)
225 var rpcBaseURL = Request.expandURL(classes.rpc.getBaseURL());
227 return (rpcBaseURL != null && opt.url.indexOf(rpcBaseURL) == 0);
230 function flushRequestQueue() {
231 if (!requestQueue.length)
234 var reqopt = Object.assign({}, requestQueue[0][0], { content: [], nobatch: true }),
237 for (var i = 0; i < requestQueue.length; i++) {
238 batch[i] = requestQueue[i];
239 reqopt.content[i] = batch[i][0].content;
242 requestQueue.length = 0;
244 Request.request(rpcBaseURL, reqopt).then(function(reply) {
245 var json = null, req = null;
247 try { json = reply.json() }
250 while ((req = batch.shift()) != null)
251 if (Array.isArray(json) && json.length)
252 req[2].call(reqopt, reply.clone(json.shift()));
254 req[1].call(reqopt, new Error('No related RPC reply'));
255 }).catch(function(error) {
258 while ((req = batch.shift()) != null)
259 req[1].call(reqopt, error);
263 var Request = Class.singleton({
264 __name__: 'LuCI.Request',
268 expandURL: function(url) {
269 if (!/^(?:[^/]+:)?\/\//.test(url))
270 url = location.protocol + '//' + location.host + url;
275 request: function(target, options) {
276 var state = { xhr: new XMLHttpRequest(), url: this.expandURL(target), start: Date.now() },
277 opt = Object.assign({}, options, state),
280 callback = this.handleReadyStateChange;
282 return new Promise(function(resolveFn, rejectFn) {
283 opt.xhr.onreadystatechange = callback.bind(opt, resolveFn, rejectFn);
284 opt.method = String(opt.method || 'GET').toUpperCase();
286 if ('query' in opt) {
287 var q = (opt.query != null) ? Object.keys(opt.query).map(function(k) {
288 if (opt.query[k] != null) {
289 var v = (typeof(opt.query[k]) == 'object')
290 ? JSON.stringify(opt.query[k])
291 : String(opt.query[k]);
293 return '%s=%s'.format(encodeURIComponent(k), encodeURIComponent(v));
296 return encodeURIComponent(k);
301 switch (opt.method) {
305 opt.url += ((/\?/).test(opt.url) ? '&' : '?') + q;
309 if (content == null) {
311 contenttype = 'application/x-www-form-urlencoded';
318 opt.url += ((/\?/).test(opt.url) ? '&' : '?') + (new Date()).getTime();
320 if (isQueueableRequest(opt)) {
321 requestQueue.push([opt, rejectFn, resolveFn]);
322 requestAnimationFrame(flushRequestQueue);
326 if ('username' in opt && 'password' in opt)
327 opt.xhr.open(opt.method, opt.url, true, opt.username, opt.password);
329 opt.xhr.open(opt.method, opt.url, true);
331 opt.xhr.responseType = 'text';
332 opt.xhr.overrideMimeType('application/octet-stream');
334 if ('timeout' in opt)
335 opt.xhr.timeout = +opt.timeout;
337 if ('credentials' in opt)
338 opt.xhr.withCredentials = !!opt.credentials;
340 if (opt.content != null) {
341 switch (typeof(opt.content)) {
343 content = opt.content(xhr);
347 content = JSON.stringify(opt.content);
348 contenttype = 'application/json';
352 content = String(opt.content);
356 if ('headers' in opt)
357 for (var header in opt.headers)
358 if (opt.headers.hasOwnProperty(header)) {
359 if (header.toLowerCase() != 'content-type')
360 opt.xhr.setRequestHeader(header, opt.headers[header]);
362 contenttype = opt.headers[header];
365 if (contenttype != null)
366 opt.xhr.setRequestHeader('Content-Type', contenttype);
369 opt.xhr.send(content);
372 rejectFn.call(opt, e);
377 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
380 if (xhr.readyState !== 4)
383 if (xhr.status === 0 && xhr.statusText === '') {
384 rejectFn.call(this, new Error('XHR request aborted by browser'));
387 var response = new Response(
388 xhr, xhr.responseURL || this.url, Date.now() - this.start);
390 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
391 .then(resolveFn.bind(this, response))
392 .catch(rejectFn.bind(this));
396 get: function(url, options) {
397 return this.request(url, Object.assign({ method: 'GET' }, options));
400 post: function(url, data, options) {
401 return this.request(url, Object.assign({ method: 'POST', content: data }, options));
404 addInterceptor: function(interceptorFn) {
405 if (typeof(interceptorFn) == 'function')
406 this.interceptors.push(interceptorFn);
407 return interceptorFn;
410 removeInterceptor: function(interceptorFn) {
411 var oldlen = this.interceptors.length, i = oldlen;
413 if (this.interceptors[i] === interceptorFn)
414 this.interceptors.splice(i, 1);
415 return (this.interceptors.length < oldlen);
419 add: function(interval, url, options, callback) {
420 if (isNaN(interval) || interval <= 0)
421 throw new TypeError('Invalid poll interval');
423 var ival = interval >>> 0,
424 opts = Object.assign({}, options, { timeout: ival * 1000 - 5 });
426 return Poll.add(function() {
427 return Request.request(url, options).then(function(res) {
432 callback(res, res.json(), res.duration);
435 callback(res, null, res.duration);
441 remove: function(entry) { return Poll.remove(entry) },
442 start: function() { return Poll.start() },
443 stop: function() { return Poll.stop() },
444 active: function() { return Poll.active() }
448 var Poll = Class.singleton({
449 __name__: 'LuCI.Poll',
453 add: function(fn, interval) {
454 if (interval == null || interval <= 0)
455 interval = window.L ? window.L.env.pollinterval : null;
457 if (isNaN(interval) || typeof(fn) != 'function')
458 throw new TypeError('Invalid argument to LuCI.Poll.add()');
460 for (var i = 0; i < this.queue.length; i++)
461 if (this.queue[i].fn === fn)
472 if (this.tick != null && !this.active())
478 remove: function(entry) {
479 if (typeof(fn) != 'function')
480 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
482 var len = this.queue.length;
484 for (var i = len; i > 0; i--)
485 if (this.queue[i-1].fn === fn)
486 this.queue.splice(i-1, 1);
488 if (!this.queue.length && this.stop())
491 return (this.queue.length != len);
500 if (this.queue.length) {
501 this.timer = window.setInterval(this.step, 1000);
503 document.dispatchEvent(new CustomEvent('poll-start'));
513 document.dispatchEvent(new CustomEvent('poll-stop'));
514 window.clearInterval(this.timer);
521 for (var i = 0, e = null; (e = Poll.queue[i]) != null; i++) {
522 if ((Poll.tick % e.i) != 0)
530 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
533 Poll.tick = (Poll.tick + 1) % Math.pow(2, 32);
537 return (this.timer != null);
542 var dummyElem = null,
544 originalCBIInit = null,
548 var LuCI = Class.extend({
550 __init__: function(env) {
552 document.querySelectorAll('script[src*="/luci.js"]').forEach(function(s) {
553 if (env.base_url == null || env.base_url == '')
554 env.base_url = s.getAttribute('src').replace(/\/luci\.js(?:\?v=[^?]+)?$/, '');
557 if (env.base_url == null)
558 this.error('InternalError', 'Cannot find url of luci.js');
560 Object.assign(this.env, env);
562 document.addEventListener('poll-start', function(ev) {
563 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
564 e.style.display = (e.id == 'xhr_poll_status_off') ? 'none' : '';
568 document.addEventListener('poll-stop', function(ev) {
569 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
570 e.style.display = (e.id == 'xhr_poll_status_on') ? 'none' : '';
574 var domReady = new Promise(function(resolveFn, rejectFn) {
575 document.addEventListener('DOMContentLoaded', resolveFn);
582 this.require('form'),
583 this.probeRPCBaseURL()
584 ]).then(this.setupDOM.bind(this)).catch(this.error);
586 originalCBIInit = window.cbi_init;
587 window.cbi_init = function() {};
590 raise: function(type, fmt /*, ...*/) {
592 msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
595 if (type instanceof Error) {
597 stack = (e.stack || '').split(/\n/);
600 e.message = msg + ': ' + e.message;
603 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
604 e.name = type || 'Error';
607 if (window.console && console.debug)
613 error: function(type, fmt /*, ...*/) {
615 L.raise.apply(L, Array.prototype.slice.call(arguments));
618 var stack = (e.stack || '').split(/\n/).map(function(frame) {
619 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
620 return frame ? ' ' + frame : '';
623 if (!/^ at /.test(stack[0]))
626 if (/\braise /.test(stack[0]))
629 if (/\berror /.test(stack[0]))
632 stack = stack.length ? '\n' + stack.join('\n') : '';
635 L.ui.showModal(e.name || _('Runtime error'),
636 E('pre', { 'class': 'alert-message error' }, e.message + stack));
638 L.dom.content(document.querySelector('#maincontent'),
639 E('pre', { 'class': 'alert-message error' }, e + stack));
645 bind: function(fn, self /*, ... */) {
646 return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
650 require: function(name, from) {
651 var L = this, url = null, from = from || [];
653 /* Class already loaded */
654 if (classes[name] != null) {
655 /* Circular dependency */
656 if (from.indexOf(name) != -1)
657 L.raise('DependencyError',
658 'Circular dependency: class "%s" depends on "%s"',
659 name, from.join('" which depends on "'));
661 return classes[name];
664 url = '%s/%s.js'.format(L.env.base_url, name.replace(/\./g, '/'));
665 from = [ name ].concat(from);
667 var compileClass = function(res) {
669 L.raise('NetworkError',
670 'HTTP error %d while loading class file "%s"', res.status, url);
672 var source = res.text(),
673 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
674 strictmatch = /^use[ \t]+strict$/,
678 /* find require statements in source */
679 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
680 var chr = source.charCodeAt(i);
685 else if (chr == 92) {
688 else if (chr == quote) {
689 var s = source.substring(off, i),
690 m = requirematch.exec(s);
693 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
694 depends.push(L.require(dep, from));
697 else if (!strictmatch.exec(s)) {
704 else if (quote == -1 && (chr == 34 || chr == 39)) {
710 /* load dependencies and instantiate class */
711 return Promise.all(depends).then(function(instances) {
712 var _factory, _class;
716 '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
717 .format(args, source, res.url));
720 L.raise('SyntaxError', '%s\n in %s:%s',
721 error.message, res.url, error.lineNumber || '?');
724 _factory.displayName = toCamelCase(name + 'ClassFactory');
725 _class = _factory.apply(_factory, [window, document, L].concat(instances));
727 if (!Class.isSubclass(_class))
728 L.error('TypeError', '"%s" factory yields invalid constructor', name);
730 if (_class.displayName == 'AnonymousClass')
731 _class.displayName = toCamelCase(name + 'Class');
733 var ptr = Object.getPrototypeOf(L),
734 parts = name.split(/\./),
735 instance = new _class();
737 for (var i = 0; ptr && i < parts.length - 1; i++)
741 ptr[parts[i]] = instance;
743 classes[name] = instance;
749 /* Request class file */
750 classes[name] = Request.get(url, { cache: true }).then(compileClass);
752 return classes[name];
756 probeRPCBaseURL: function() {
757 if (rpcBaseURL == null) {
759 rpcBaseURL = window.sessionStorage.getItem('rpcBaseURL');
764 if (rpcBaseURL == null) {
765 var rpcFallbackURL = this.url('admin/ubus');
767 rpcBaseURL = Request.get('/ubus/').then(function(res) {
768 return (rpcBaseURL = (res.status == 400) ? '/ubus/' : rpcFallbackURL);
770 return (rpcBaseURL = rpcFallbackURL);
771 }).then(function(url) {
773 window.sessionStorage.setItem('rpcBaseURL', url);
781 return Promise.resolve(rpcBaseURL);
784 setupDOM: function(res) {
791 rpcClass.setBaseURL(rpcBaseURL);
793 Request.addInterceptor(function(res) {
794 if (res.status != 403 || res.headers.get('X-LuCI-Login-Required') != 'yes')
799 L.ui.showModal(_('Session expired'), [
800 E('div', { class: 'alert-message warning' },
801 _('A new login is required since the authentication session expired.')),
802 E('div', { class: 'right' },
804 class: 'btn primary',
806 var loc = window.location;
807 window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
812 throw 'Session expired';
819 document.dispatchEvent(new CustomEvent('luci-loaded'));
824 /* URL construction helpers */
825 path: function(prefix, parts) {
826 var url = [ prefix || '' ];
828 for (var i = 0; i < parts.length; i++)
829 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
830 url.push('/', parts[i]);
832 if (url.length === 1)
839 return this.path(this.env.scriptname, arguments);
842 resource: function() {
843 return this.path(this.env.resource, arguments);
846 location: function() {
847 return this.path(this.env.scriptname, this.env.requestpath);
852 isObject: function(val) {
853 return (val != null && typeof(val) == 'object');
856 sortedKeys: function(obj, key, sortmode) {
857 if (obj == null || typeof(obj) != 'object')
860 return Object.keys(obj).map(function(e) {
861 var v = (key != null) ? obj[e][key] : e;
865 v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
866 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
870 v = (v != null) ? +v : null;
875 }).filter(function(e) {
876 return (e[1] != null);
877 }).sort(function(a, b) {
878 return (a[1] > b[1]);
884 toArray: function(val) {
887 else if (Array.isArray(val))
889 else if (typeof(val) == 'object')
892 var s = String(val).trim();
897 return s.split(/\s+/);
901 /* HTTP resource fetching */
902 get: function(url, args, cb) {
903 return this.poll(null, url, args, cb, false);
906 post: function(url, args, cb) {
907 return this.poll(null, url, args, cb, true);
910 poll: function(interval, url, args, cb, post) {
911 if (interval !== null && interval <= 0)
912 interval = this.env.pollinterval;
914 var data = post ? { token: this.env.token } : null,
915 method = post ? 'POST' : 'GET';
917 if (!/^(?:\/|\S+:\/\/)/.test(url))
921 data = Object.assign(data || {}, args);
923 if (interval !== null)
924 return Request.poll.add(interval, url, { method: method, query: data }, cb);
926 return Request.request(url, { method: method, query: data })
927 .then(function(res) {
929 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
930 try { json = res.json() } catch(e) {}
931 cb(res.xhr, json, res.duration);
935 stop: function(entry) { return Poll.remove(entry) },
936 halt: function() { return Poll.stop() },
937 run: function() { return Poll.start() },
939 /* DOM manipulation */
940 dom: Class.singleton({
941 __name__: 'LuCI.DOM',
944 return (e != null && typeof(e) == 'object' && 'nodeType' in e);
951 domParser = domParser || new DOMParser();
952 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
958 dummyElem = dummyElem || document.createElement('div');
959 dummyElem.innerHTML = s;
960 elem = dummyElem.firstChild;
968 matches: function(node, selector) {
969 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
970 return m ? m.call(node, selector) : false;
973 parent: function(node, selector) {
974 if (this.elem(node) && node.closest)
975 return node.closest(selector);
977 while (this.elem(node))
978 if (this.matches(node, selector))
981 node = node.parentNode;
986 append: function(node, children) {
987 if (!this.elem(node))
990 if (Array.isArray(children)) {
991 for (var i = 0; i < children.length; i++)
992 if (this.elem(children[i]))
993 node.appendChild(children[i]);
994 else if (children !== null && children !== undefined)
995 node.appendChild(document.createTextNode('' + children[i]));
997 return node.lastChild;
999 else if (typeof(children) === 'function') {
1000 return this.append(node, children(node));
1002 else if (this.elem(children)) {
1003 return node.appendChild(children);
1005 else if (children !== null && children !== undefined) {
1006 node.innerHTML = '' + children;
1007 return node.lastChild;
1013 content: function(node, children) {
1014 if (!this.elem(node))
1017 var dataNodes = node.querySelectorAll('[data-idref]');
1019 for (var i = 0; i < dataNodes.length; i++)
1020 delete this.registry[dataNodes[i].getAttribute('data-idref')];
1022 while (node.firstChild)
1023 node.removeChild(node.firstChild);
1025 return this.append(node, children);
1028 attr: function(node, key, val) {
1029 if (!this.elem(node))
1034 if (typeof(key) === 'object' && key !== null)
1036 else if (typeof(key) === 'string')
1037 attr = {}, attr[key] = val;
1040 if (!attr.hasOwnProperty(key) || attr[key] == null)
1043 switch (typeof(attr[key])) {
1045 node.addEventListener(key, attr[key]);
1049 node.setAttribute(key, JSON.stringify(attr[key]));
1053 node.setAttribute(key, attr[key]);
1058 create: function() {
1059 var html = arguments[0],
1060 attr = arguments[1],
1061 data = arguments[2],
1064 if (!(attr instanceof Object) || Array.isArray(attr))
1065 data = attr, attr = null;
1067 if (Array.isArray(html)) {
1068 elem = document.createDocumentFragment();
1069 for (var i = 0; i < html.length; i++)
1070 elem.appendChild(this.create(html[i]));
1072 else if (this.elem(html)) {
1075 else if (html.charCodeAt(0) === 60) {
1076 elem = this.parse(html);
1079 elem = document.createElement(html);
1085 this.attr(elem, attr);
1086 this.append(elem, data);
1093 data: function(node, key, val) {
1094 var id = node.getAttribute('data-idref');
1096 /* clear all data */
1097 if (arguments.length > 1 && key == null) {
1099 node.removeAttribute('data-idref');
1100 val = this.registry[id]
1101 delete this.registry[id];
1109 else if (arguments.length > 2 && key != null && val == null) {
1111 val = this.registry[id][key];
1112 delete this.registry[id][key];
1120 else if (arguments.length > 2 && key != null && val != null) {
1122 do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
1123 while (this.registry.hasOwnProperty(id));
1125 node.setAttribute('data-idref', id);
1126 this.registry[id] = {};
1129 return (this.registry[id][key] = val);
1133 else if (arguments.length == 1) {
1135 return this.registry[id];
1141 else if (arguments.length == 2) {
1143 return this.registry[id][key];
1149 bindClassInstance: function(node, inst) {
1150 if (!(inst instanceof Class))
1151 L.error('TypeError', 'Argument must be a class instance');
1153 return this.data(node, '_class', inst);
1156 findClassInstance: function(node) {
1160 inst = this.data(node, '_class');
1161 node = node.parentNode;
1163 while (!(inst instanceof Class) && node != null);
1168 callClassMethod: function(node, method /*, ... */) {
1169 var inst = this.findClassInstance(node);
1171 if (inst == null || typeof(inst[method]) != 'function')
1174 return inst[method].apply(inst, inst.varargs(arguments, 2));
1182 view: Class.extend({
1183 __name__: 'LuCI.View',
1185 __init__: function() {
1186 var vp = document.getElementById('view');
1188 L.dom.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
1190 return Promise.resolve(this.load())
1191 .then(L.bind(this.render, this))
1192 .then(L.bind(function(nodes) {
1193 var vp = document.getElementById('view');
1195 L.dom.content(vp, nodes);
1196 L.dom.append(vp, this.addFooter());
1197 }, this)).catch(L.error);
1200 load: function() {},
1201 render: function() {},
1203 handleSave: function(ev) {
1206 document.getElementById('maincontent')
1207 .querySelectorAll('.cbi-map').forEach(function(map) {
1208 tasks.push(L.dom.callClassMethod(map, 'save'));
1211 return Promise.all(tasks);
1214 handleSaveApply: function(ev) {
1215 return this.handleSave(ev).then(function() {
1216 L.ui.changes.apply(true);
1220 handleReset: function(ev) {
1223 document.getElementById('maincontent')
1224 .querySelectorAll('.cbi-map').forEach(function(map) {
1225 tasks.push(L.dom.callClassMethod(map, 'reset'));
1228 return Promise.all(tasks);
1231 addFooter: function() {
1233 mc = document.getElementById('maincontent');
1235 if (mc.querySelector('.cbi-map')) {
1236 footer.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
1238 'class': 'cbi-button cbi-button-apply',
1240 'value': _('Save & Apply'),
1241 'click': L.bind(this.handleSaveApply, this)
1244 'class': 'cbi-button cbi-button-save',
1247 'click': L.bind(this.handleSave, this)
1250 'class': 'cbi-button cbi-button-reset',
1252 'value': _('Reset'),
1253 'click': L.bind(this.handleReset, this)
1263 var XHR = Class.extend({
1264 __name__: 'LuCI.XHR',
1265 __init__: function() {
1266 if (window.console && console.debug)
1267 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
1270 _response: function(cb, res, json, duration) {
1272 cb(res, json, duration);
1276 get: function(url, data, callback, timeout) {
1278 L.get(url, data, this._response.bind(this, callback), timeout);
1281 post: function(url, data, callback, timeout) {
1283 L.post(url, data, this._response.bind(this, callback), timeout);
1286 cancel: function() { delete this.active },
1287 busy: function() { return (this.active === true) },
1288 abort: function() {},
1289 send_form: function() { L.error('InternalError', 'Not implemented') },
1292 XHR.get = function() { return window.L.get.apply(window.L, arguments) };
1293 XHR.post = function() { return window.L.post.apply(window.L, arguments) };
1294 XHR.poll = function() { return window.L.poll.apply(window.L, arguments) };
1295 XHR.stop = Request.poll.remove.bind(Request.poll);
1296 XHR.halt = Request.poll.stop.bind(Request.poll);
1297 XHR.run = Request.poll.start.bind(Request.poll);
1298 XHR.running = Request.poll.active.bind(Request.poll);
1302 })(window, document);