1 (function(window, document, undefined) {
2 /* Object.assign polyfill for IE */
3 if (typeof Object.assign !== 'function') {
4 Object.defineProperty(Object, 'assign', {
5 value: function assign(target, varArgs) {
7 throw new TypeError('Cannot convert undefined or null to object');
9 var to = Object(target);
11 for (var index = 1; index < arguments.length; index++)
12 if (arguments[index] != null)
13 for (var nextKey in arguments[index])
14 if (Object.prototype.hasOwnProperty.call(arguments[index], nextKey))
15 to[nextKey] = arguments[index][nextKey];
25 * Class declaration and inheritance helper
28 var toCamelCase = function(s) {
29 return s.replace(/(?:^|[\. -])(.)/g, function(m0, m1) { return m1.toUpperCase() });
32 var superContext = null, Class = Object.assign(function() {}, {
33 extend: function(properties) {
35 __base__: { value: this.prototype },
36 __name__: { value: properties.__name__ || 'anonymous' }
39 var ClassConstructor = function() {
40 if (!(this instanceof ClassConstructor))
41 throw new TypeError('Constructor must not be called without "new"');
43 if (Object.getPrototypeOf(this).hasOwnProperty('__init__')) {
44 if (typeof(this.__init__) != 'function')
45 throw new TypeError('Class __init__ member is not a function');
47 this.__init__.apply(this, arguments)
50 this.super('__init__', arguments);
54 for (var key in properties)
55 if (!props[key] && properties.hasOwnProperty(key))
56 props[key] = { value: properties[key], writable: true };
58 ClassConstructor.prototype = Object.create(this.prototype, props);
59 ClassConstructor.prototype.constructor = ClassConstructor;
60 Object.assign(ClassConstructor, this);
61 ClassConstructor.displayName = toCamelCase(props.__name__.value + 'Class');
63 return ClassConstructor;
66 singleton: function(properties /*, ... */) {
67 return Class.extend(properties)
68 .instantiate(Class.prototype.varargs(arguments, 1));
71 instantiate: function(args) {
72 return new (Function.prototype.bind.apply(this,
73 Class.prototype.varargs(args, 0, null)))();
76 call: function(self, method) {
77 if (typeof(this.prototype[method]) != 'function')
78 throw new ReferenceError(method + ' is not defined in class');
80 return this.prototype[method].apply(self, self.varargs(arguments, 1));
83 isSubclass: function(_class) {
84 return (_class != null &&
85 typeof(_class) == 'function' &&
86 _class.prototype instanceof this);
90 varargs: function(args, offset /*, ... */) {
91 return Array.prototype.slice.call(arguments, 2)
92 .concat(Array.prototype.slice.call(args, offset));
95 super: function(key, callArgs) {
96 for (superContext = Object.getPrototypeOf(superContext ||
97 Object.getPrototypeOf(this));
98 superContext && !superContext.hasOwnProperty(key);
99 superContext = Object.getPrototypeOf(superContext)) { }
104 var res = superContext[key];
106 if (arguments.length > 1) {
107 if (typeof(res) != 'function')
108 throw new ReferenceError(key + ' is not a function in base class');
110 if (typeof(callArgs) != 'object')
111 callArgs = this.varargs(arguments, 1);
113 res = res.apply(this, callArgs);
121 toString: function() {
122 var s = '[' + this.constructor.displayName + ']', f = true;
123 for (var k in this) {
124 if (this.hasOwnProperty(k)) {
125 s += (f ? ' {\n' : '') + ' ' + k + ': ' + typeof(this[k]) + '\n';
129 return s + (f ? '' : '}');
136 * HTTP Request helper
139 Headers = Class.extend({
140 __name__: 'LuCI.XHR.Headers',
141 __init__: function(xhr) {
142 var hdrs = this.headers = {};
143 xhr.getAllResponseHeaders().split(/\r\n/).forEach(function(line) {
144 var m = /^([^:]+):(.*)$/.exec(line);
146 hdrs[m[1].trim().toLowerCase()] = m[2].trim();
150 has: function(name) {
151 return this.headers.hasOwnProperty(String(name).toLowerCase());
154 get: function(name) {
155 var key = String(name).toLowerCase();
156 return this.headers.hasOwnProperty(key) ? this.headers[key] : null;
160 Response = Class.extend({
161 __name__: 'LuCI.XHR.Response',
162 __init__: function(xhr, url, duration) {
163 this.ok = (xhr.status >= 200 && xhr.status <= 299);
164 this.status = xhr.status;
165 this.statusText = xhr.statusText;
166 this.responseText = xhr.responseText;
167 this.headers = new Headers(xhr);
168 this.duration = duration;
174 return JSON.parse(this.responseText);
178 return this.responseText;
182 Request = Class.singleton({
183 __name__: 'LuCI.Request',
187 request: function(target, options) {
188 var state = { xhr: new XMLHttpRequest(), url: target, start: Date.now() },
189 opt = Object.assign({}, options, state),
192 callback = this.handleReadyStateChange;
194 return new Promise(function(resolveFn, rejectFn) {
195 opt.xhr.onreadystatechange = callback.bind(opt, resolveFn, rejectFn);
196 opt.method = String(opt.method || 'GET').toUpperCase();
198 if ('query' in opt) {
199 var q = (opt.query != null) ? Object.keys(opt.query).map(function(k) {
200 if (opt.query[k] != null) {
201 var v = (typeof(opt.query[k]) == 'object')
202 ? JSON.stringify(opt.query[k])
203 : String(opt.query[k]);
205 return '%s=%s'.format(encodeURIComponent(k), encodeURIComponent(v));
208 return encodeURIComponent(k);
213 switch (opt.method) {
217 opt.url += ((/\?/).test(opt.url) ? '&' : '?') + q;
221 if (content == null) {
223 contenttype = 'application/x-www-form-urlencoded';
230 opt.url += ((/\?/).test(opt.url) ? '&' : '?') + (new Date()).getTime();
232 if (!/^(?:[^/]+:)?\/\//.test(opt.url))
233 opt.url = location.protocol + '//' + location.host + opt.url;
235 if ('username' in opt && 'password' in opt)
236 opt.xhr.open(opt.method, opt.url, true, opt.username, opt.password);
238 opt.xhr.open(opt.method, opt.url, true);
240 opt.xhr.responseType = 'text';
241 opt.xhr.overrideMimeType('application/octet-stream');
243 if ('timeout' in opt)
244 opt.xhr.timeout = +opt.timeout;
246 if ('credentials' in opt)
247 opt.xhr.withCredentials = !!opt.credentials;
249 if (opt.content != null) {
250 switch (typeof(opt.content)) {
252 content = opt.content(xhr);
256 content = JSON.stringify(opt.content);
257 contenttype = 'application/json';
261 content = String(opt.content);
265 if ('headers' in opt)
266 for (var header in opt.headers)
267 if (opt.headers.hasOwnProperty(header)) {
268 if (header.toLowerCase() != 'content-type')
269 opt.xhr.setRequestHeader(header, opt.headers[header]);
271 contenttype = opt.headers[header];
274 if (contenttype != null)
275 opt.xhr.setRequestHeader('Content-Type', contenttype);
278 opt.xhr.send(content);
281 rejectFn.call(opt, e);
286 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
289 if (xhr.readyState !== 4)
292 if (xhr.status === 0 && xhr.statusText === '') {
293 rejectFn.call(this, new Error('XHR request aborted by browser'));
296 var response = new Response(
297 xhr, xhr.responseURL || this.url, Date.now() - this.start);
299 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
300 .then(resolveFn.bind(this, response))
301 .catch(rejectFn.bind(this));
310 get: function(url, options) {
311 return this.request(url, Object.assign({ method: 'GET' }, options));
314 post: function(url, data, options) {
315 return this.request(url, Object.assign({ method: 'POST', content: data }, options));
318 addInterceptor: function(interceptorFn) {
319 if (typeof(interceptorFn) == 'function')
320 this.interceptors.push(interceptorFn);
321 return interceptorFn;
324 removeInterceptor: function(interceptorFn) {
325 var oldlen = this.interceptors.length, i = oldlen;
327 if (this.interceptors[i] === interceptorFn)
328 this.interceptors.splice(i, 1);
329 return (this.interceptors.length < oldlen);
332 poll: Class.singleton({
333 __name__: 'LuCI.Request.Poll',
337 add: function(interval, url, options, callback) {
338 if (isNaN(interval) || interval <= 0)
339 throw new TypeError('Invalid poll interval');
352 remove: function(entry) {
353 var oldlen = this.queue.length, i = oldlen;
356 if (this.queue[i] === entry) {
357 delete this.queue[i].running;
358 this.queue.splice(i, 1);
361 if (!this.queue.length)
364 return (this.queue.length < oldlen);
368 if (!this.queue.length || this.active())
372 this.timer = window.setInterval(this.step, 1000);
374 document.dispatchEvent(new CustomEvent('poll-start'));
382 document.dispatchEvent(new CustomEvent('poll-stop'));
383 window.clearInterval(this.timer);
390 Request.poll.queue.forEach(function(e) {
391 if ((Request.poll.tick % e.interval) != 0)
397 var opts = Object.assign({}, e.options,
398 { timeout: e.interval * 1000 - 5 });
401 Request.request(e.url, opts)
402 .then(function(res) {
403 if (!e.running || !Request.poll.active())
407 e.callback(res, res.json(), res.duration);
410 e.callback(res, null, res.duration);
413 .finally(function() { delete e.running });
416 Request.poll.tick = (Request.poll.tick + 1) % Math.pow(2, 32);
420 return (this.timer != null);
426 var dummyElem = null,
428 originalCBIInit = null,
431 LuCI = Class.extend({
433 __init__: function(env) {
434 Object.assign(this.env, env);
436 document.addEventListener('poll-start', function(ev) {
437 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
438 e.style.display = (e.id == 'xhr_poll_status_off') ? 'none' : '';
442 document.addEventListener('poll-stop', function(ev) {
443 document.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e) {
444 e.style.display = (e.id == 'xhr_poll_status_on') ? 'none' : '';
448 var domReady = new Promise(function(resolveFn, rejectFn) {
449 document.addEventListener('DOMContentLoaded', resolveFn);
456 ]).then(this.setupDOM.bind(this)).catch(function(error) {
457 alert('LuCI class loading error:\n' + error);
460 originalCBIInit = window.cbi_init;
461 window.cbi_init = function() {};
464 error: function(type, fmt /*, ...*/) {
466 msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
469 if (type instanceof Error) {
471 stack = (e.stack || '').split(/\n/);
474 e.message = msg + ': ' + e.message;
477 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
478 e.name = type || 'Error';
480 try { throw new Error('stacktrace') }
481 catch (e2) { stack = (e2.stack || '').split(/\n/) }
483 /* IE puts the exception message into the first line */
484 if (stack[0] == 'Error: stacktrace')
487 /* Pop L.error() invocation from stack */
491 /* Append shortened & beautified stacktrace to message */
492 var trace = stack.join('\n')
493 .replace(/(.*?)@(.+):(\d+):(\d+)/g, ' at $1 ($2:$3:$4)');
495 if (e.message.indexOf(trace) == -1)
496 e.message += '\n' + trace;
498 if (window.console && console.debug)
502 this.ui.showModal(_('Runtime error'),
503 E('pre', { 'class': 'alert-message error' }, e));
505 L.dom.content(document.querySelector('#maincontent'),
506 E('pre', { 'class': 'alert-message error' }, e));
511 bind: function(fn, self /*, ... */) {
512 return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
516 require: function(name, from) {
517 var L = this, url = null, from = from || [];
519 /* Class already loaded */
520 if (classes[name] != null) {
521 /* Circular dependency */
522 if (from.indexOf(name) != -1)
523 L.error('DependencyError',
524 'Circular dependency: class "%s" depends on "%s"',
525 name, from.join('" which depends on "'));
527 return classes[name];
530 document.querySelectorAll('script[src$="/luci.js"]').forEach(function(s) {
531 url = '%s/%s.js'.format(
532 s.getAttribute('src').replace(/\/luci\.js$/, ''),
533 name.replace(/\./g, '/'));
537 L.error('InternalError', 'Cannot find url of luci.js');
539 from = [ name ].concat(from);
541 var compileClass = function(res) {
543 L.error('NetworkError',
544 'HTTP error %d while loading class file "%s"', res.status, url);
546 var source = res.text(),
547 reqmatch = /(?:^|\n)[ \t]*(?:["']require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?["']);/g,
551 /* find require statements in source */
552 for (var m = reqmatch.exec(source); m; m = reqmatch.exec(source)) {
553 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
554 depends.push(L.require(dep, from));
558 /* load dependencies and instantiate class */
559 return Promise.all(depends).then(function(instances) {
562 '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
563 .format(args, source, res.url));
566 L.error('SyntaxError', '%s\n in %s:%s',
567 error.message, res.url, error.lineNumber || '?');
570 _factory.displayName = toCamelCase(name + 'ClassFactory');
571 _class = _factory.apply(_factory, [window, document, L].concat(instances));
573 if (!Class.isSubclass(_class))
574 L.error('TypeError', '"%s" factory yields invalid constructor', name);
576 if (_class.displayName == 'AnonymousClass')
577 _class.displayName = toCamelCase(name + 'Class');
579 var ptr = Object.getPrototypeOf(L),
580 parts = name.split(/\./),
581 instance = new _class();
583 for (var i = 0; ptr && i < parts.length - 1; i++)
587 ptr[parts[i]] = instance;
589 classes[name] = instance;
595 /* Request class file */
596 classes[name] = Request.get(url, { cache: true })
600 return classes[name];
604 setupDOM: function(ev) {
605 Request.addInterceptor(function(res) {
606 if (res.status != 403 || res.headers.get('X-LuCI-Login-Required') != 'yes')
611 L.ui.showModal(_('Session expired'), [
612 E('div', { class: 'alert-message warning' },
613 _('A new login is required since the authentication session expired.')),
614 E('div', { class: 'right' },
616 class: 'btn primary',
618 var loc = window.location;
619 window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
624 throw 'Session expired';
628 Request.poll.start();
630 document.dispatchEvent(new CustomEvent('luci-loaded'));
635 /* URL construction helpers */
636 path: function(prefix, parts) {
637 var url = [ prefix || '' ];
639 for (var i = 0; i < parts.length; i++)
640 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
641 url.push('/', parts[i]);
643 if (url.length === 1)
650 return this.path(this.env.scriptname, arguments);
653 resource: function() {
654 return this.path(this.env.resource, arguments);
657 location: function() {
658 return this.path(this.env.scriptname, this.env.requestpath);
662 /* HTTP resource fetching */
663 get: function(url, args, cb) {
664 return this.poll(null, url, args, cb, false);
667 post: function(url, args, cb) {
668 return this.poll(null, url, args, cb, true);
671 poll: function(interval, url, args, cb, post) {
672 if (interval !== null && interval <= 0)
673 interval = this.env.pollinterval;
675 var data = post ? { token: this.env.token } : null,
676 method = post ? 'POST' : 'GET';
678 if (!/^(?:\/|\S+:\/\/)/.test(url))
682 data = Object.assign(data || {}, args);
684 if (interval !== null)
685 return Request.poll.add(interval, url, { method: method, query: data }, cb);
687 return Request.request(url, { method: method, query: data })
688 .then(function(res) {
690 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
691 try { json = res.json() } catch(e) {}
692 cb(res.xhr, json, res.duration);
696 stop: function(entry) { return Request.poll.remove(entry) },
697 halt: function() { return Request.poll.stop() },
698 run: function() { return Request.poll.start() },
700 /* DOM manipulation */
701 dom: Class.singleton({
702 __name__: 'LuCI.DOM',
705 return (e != null && typeof(e) == 'object' && 'nodeType' in e);
712 domParser = domParser || new DOMParser();
713 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
719 dummyElem = dummyElem || document.createElement('div');
720 dummyElem.innerHTML = s;
721 elem = dummyElem.firstChild;
729 matches: function(node, selector) {
730 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
731 return m ? m.call(node, selector) : false;
734 parent: function(node, selector) {
735 if (this.elem(node) && node.closest)
736 return node.closest(selector);
738 while (this.elem(node))
739 if (this.matches(node, selector))
742 node = node.parentNode;
747 append: function(node, children) {
748 if (!this.elem(node))
751 if (Array.isArray(children)) {
752 for (var i = 0; i < children.length; i++)
753 if (this.elem(children[i]))
754 node.appendChild(children[i]);
755 else if (children !== null && children !== undefined)
756 node.appendChild(document.createTextNode('' + children[i]));
758 return node.lastChild;
760 else if (typeof(children) === 'function') {
761 return this.append(node, children(node));
763 else if (this.elem(children)) {
764 return node.appendChild(children);
766 else if (children !== null && children !== undefined) {
767 node.innerHTML = '' + children;
768 return node.lastChild;
774 content: function(node, children) {
775 if (!this.elem(node))
778 var dataNodes = node.querySelectorAll('[data-idref]');
780 for (var i = 0; i < dataNodes.length; i++)
781 delete this.registry[dataNodes[i].getAttribute('data-idref')];
783 while (node.firstChild)
784 node.removeChild(node.firstChild);
786 return this.append(node, children);
789 attr: function(node, key, val) {
790 if (!this.elem(node))
795 if (typeof(key) === 'object' && key !== null)
797 else if (typeof(key) === 'string')
798 attr = {}, attr[key] = val;
801 if (!attr.hasOwnProperty(key) || attr[key] == null)
804 switch (typeof(attr[key])) {
806 node.addEventListener(key, attr[key]);
810 node.setAttribute(key, JSON.stringify(attr[key]));
814 node.setAttribute(key, attr[key]);
820 var html = arguments[0],
825 if (!(attr instanceof Object) || Array.isArray(attr))
826 data = attr, attr = null;
828 if (Array.isArray(html)) {
829 elem = document.createDocumentFragment();
830 for (var i = 0; i < html.length; i++)
831 elem.appendChild(this.create(html[i]));
833 else if (this.elem(html)) {
836 else if (html.charCodeAt(0) === 60) {
837 elem = this.parse(html);
840 elem = document.createElement(html);
846 this.attr(elem, attr);
847 this.append(elem, data);
854 data: function(node, key, val) {
855 var id = node.getAttribute('data-idref');
858 if (arguments.length > 1 && key == null) {
860 node.removeAttribute('data-idref');
861 val = this.registry[id]
862 delete this.registry[id];
870 else if (arguments.length > 2 && key != null && val == null) {
872 val = this.registry[id][key];
873 delete this.registry[id][key];
881 else if (arguments.length > 2 && key != null && val != null) {
883 do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
884 while (this.registry.hasOwnProperty(id));
886 node.setAttribute('data-idref', id);
887 this.registry[id] = {};
890 return (this.registry[id][key] = val);
894 else if (arguments.length == 1) {
896 return this.registry[id];
902 else if (arguments.length == 2) {
904 return this.registry[id][key];
910 bindClassInstance: function(node, inst) {
911 if (!(inst instanceof Class))
912 L.error('TypeError', 'Argument must be a class instance');
914 return this.data(node, '_class', inst);
917 findClassInstance: function(node) {
921 inst = this.data(node, '_class');
922 node = node.parentNode;
924 while (!(inst instanceof Class) && node != null);
929 callClassMethod: function(node, method /*, ... */) {
930 var inst = this.findClassInstance(node);
932 if (inst == null || typeof(inst[method]) != 'function')
935 return inst[method].apply(inst, inst.varargs(arguments, 2));
943 __name__: 'LuCI.View',
945 __init__: function() {
946 var vp = document.getElementById('view');
948 L.dom.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
950 return Promise.resolve(this.load())
951 .then(L.bind(this.render, this))
952 .then(L.bind(function(nodes) {
953 var vp = document.getElementById('view');
955 L.dom.content(vp, nodes);
956 L.dom.append(vp, this.addFooter());
957 }, this)).catch(L.error);
961 render: function() {},
963 handleSave: function(ev) {
966 document.getElementById('maincontent')
967 .querySelectorAll('.cbi-map').forEach(function(map) {
968 tasks.push(L.dom.callClassMethod(map, 'save'));
971 return Promise.all(tasks);
974 handleSaveApply: function(ev) {
975 return this.handleSave(ev).then(function() {
976 L.ui.changes.apply(true);
980 handleReset: function(ev) {
983 document.getElementById('maincontent')
984 .querySelectorAll('.cbi-map').forEach(function(map) {
985 tasks.push(L.dom.callClassMethod(map, 'reset'));
988 return Promise.all(tasks);
991 addFooter: function() {
993 mc = document.getElementById('maincontent');
995 if (mc.querySelector('.cbi-map')) {
996 footer.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
998 'class': 'cbi-button cbi-button-apply',
1000 'value': _('Save & Apply'),
1001 'click': L.bind(this.handleSaveApply, this)
1004 'class': 'cbi-button cbi-button-save',
1007 'click': L.bind(this.handleSave, this)
1010 'class': 'cbi-button cbi-button-reset',
1012 'value': _('Reset'),
1013 'click': L.bind(this.handleReset, this)
1023 XHR = Class.extend({
1024 __name__: 'LuCI.XHR',
1025 __init__: function() {
1026 if (window.console && console.debug)
1027 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
1030 _response: function(cb, res, json, duration) {
1032 cb(res, json, duration);
1036 get: function(url, data, callback, timeout) {
1038 L.get(url, data, this._response.bind(this, callback), timeout);
1041 post: function(url, data, callback, timeout) {
1043 L.post(url, data, this._response.bind(this, callback), timeout);
1046 cancel: function() { delete this.active },
1047 busy: function() { return (this.active === true) },
1048 abort: function() {},
1049 send_form: function() { L.error('InternalError', 'Not implemented') },
1052 XHR.get = function() { return window.L.get.apply(window.L, arguments) };
1053 XHR.post = function() { return window.L.post.apply(window.L, arguments) };
1054 XHR.poll = function() { return window.L.poll.apply(window.L, arguments) };
1055 XHR.stop = Request.poll.remove.bind(Request.poll);
1056 XHR.halt = Request.poll.stop.bind(Request.poll);
1057 XHR.run = Request.poll.start.bind(Request.poll);
1058 XHR.running = Request.poll.active.bind(Request.poll);
1062 })(window, document);