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
= [],
216 function isQueueableRequest(opt
) {
220 if (opt
.method
!= 'POST' || typeof(opt
.content
) != 'object')
223 if (opt
.nobatch
=== true)
226 if (rpcBaseURL
== null)
227 rpcBaseURL
= Request
.expandURL(classes
.rpc
.getBaseURL());
229 return (rpcBaseURL
!= null && opt
.url
.indexOf(rpcBaseURL
) == 0);
232 function flushRequestQueue() {
233 if (!requestQueue
.length
)
236 var reqopt
= Object
.assign({}, requestQueue
[0][0], { content
: [], nobatch
: true }),
239 for (var i
= 0; i
< requestQueue
.length
; i
++) {
240 batch
[i
] = requestQueue
[i
];
241 reqopt
.content
[i
] = batch
[i
][0].content
;
244 requestQueue
.length
= 0;
246 Request
.request(rpcBaseURL
, reqopt
).then(function(reply
) {
247 var json
= null, req
= null;
249 try { json
= reply
.json() }
252 while ((req
= batch
.shift()) != null)
253 if (Array
.isArray(json
) && json
.length
)
254 req
[2].call(reqopt
, reply
.clone(json
.shift()));
256 req
[1].call(reqopt
, new Error('No related RPC reply'));
257 }).catch(function(error
) {
260 while ((req
= batch
.shift()) != null)
261 req
[1].call(reqopt
, error
);
265 var Request
= Class
.singleton({
266 __name__
: 'LuCI.Request',
270 expandURL: function(url
) {
271 if (!/^(?:[^/]+:)?\/\//.test(url
))
272 url
= location
.protocol
+ '//' + location
.host
+ url
;
277 request: function(target
, options
) {
278 var state
= { xhr
: new XMLHttpRequest(), url
: this.expandURL(target
), start
: Date
.now() },
279 opt
= Object
.assign({}, options
, state
),
282 callback
= this.handleReadyStateChange
;
284 return new Promise(function(resolveFn
, rejectFn
) {
285 opt
.xhr
.onreadystatechange
= callback
.bind(opt
, resolveFn
, rejectFn
);
286 opt
.method
= String(opt
.method
|| 'GET').toUpperCase();
288 if ('query' in opt
) {
289 var q
= (opt
.query
!= null) ? Object
.keys(opt
.query
).map(function(k
) {
290 if (opt
.query
[k
] != null) {
291 var v
= (typeof(opt
.query
[k
]) == 'object')
292 ? JSON
.stringify(opt
.query
[k
])
293 : String(opt
.query
[k
]);
295 return '%s=%s'.format(encodeURIComponent(k
), encodeURIComponent(v
));
298 return encodeURIComponent(k
);
303 switch (opt
.method
) {
307 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + q
;
311 if (content
== null) {
313 contenttype
= 'application/x-www-form-urlencoded';
320 opt
.url
+= ((/\?/).test(opt
.url
) ? '&' : '?') + (new Date()).getTime();
322 if (isQueueableRequest(opt
)) {
323 requestQueue
.push([opt
, rejectFn
, resolveFn
]);
324 requestAnimationFrame(flushRequestQueue
);
328 if ('username' in opt
&& 'password' in opt
)
329 opt
.xhr
.open(opt
.method
, opt
.url
, true, opt
.username
, opt
.password
);
331 opt
.xhr
.open(opt
.method
, opt
.url
, true);
333 opt
.xhr
.responseType
= 'text';
334 opt
.xhr
.overrideMimeType('application/octet-stream');
336 if ('timeout' in opt
)
337 opt
.xhr
.timeout
= +opt
.timeout
;
339 if ('credentials' in opt
)
340 opt
.xhr
.withCredentials
= !!opt
.credentials
;
342 if (opt
.content
!= null) {
343 switch (typeof(opt
.content
)) {
345 content
= opt
.content(xhr
);
349 content
= JSON
.stringify(opt
.content
);
350 contenttype
= 'application/json';
354 content
= String(opt
.content
);
358 if ('headers' in opt
)
359 for (var header
in opt
.headers
)
360 if (opt
.headers
.hasOwnProperty(header
)) {
361 if (header
.toLowerCase() != 'content-type')
362 opt
.xhr
.setRequestHeader(header
, opt
.headers
[header
]);
364 contenttype
= opt
.headers
[header
];
367 if (contenttype
!= null)
368 opt
.xhr
.setRequestHeader('Content-Type', contenttype
);
371 opt
.xhr
.send(content
);
374 rejectFn
.call(opt
, e
);
379 handleReadyStateChange: function(resolveFn
, rejectFn
, ev
) {
382 if (xhr
.readyState
!== 4)
385 if (xhr
.status
=== 0 && xhr
.statusText
=== '') {
386 rejectFn
.call(this, new Error('XHR request aborted by browser'));
389 var response
= new Response(
390 xhr
, xhr
.responseURL
|| this.url
, Date
.now() - this.start
);
392 Promise
.all(Request
.interceptors
.map(function(fn
) { return fn(response
) }))
393 .then(resolveFn
.bind(this, response
))
394 .catch(rejectFn
.bind(this));
403 get: function(url
, options
) {
404 return this.request(url
, Object
.assign({ method
: 'GET' }, options
));
407 post: function(url
, data
, options
) {
408 return this.request(url
, Object
.assign({ method
: 'POST', content
: data
}, options
));
411 addInterceptor: function(interceptorFn
) {
412 if (typeof(interceptorFn
) == 'function')
413 this.interceptors
.push(interceptorFn
);
414 return interceptorFn
;
417 removeInterceptor: function(interceptorFn
) {
418 var oldlen
= this.interceptors
.length
, i
= oldlen
;
420 if (this.interceptors
[i
] === interceptorFn
)
421 this.interceptors
.splice(i
, 1);
422 return (this.interceptors
.length
< oldlen
);
426 add: function(interval
, url
, options
, callback
) {
427 if (isNaN(interval
) || interval
<= 0)
428 throw new TypeError('Invalid poll interval');
430 var ival
= interval
>>> 0,
431 opts
= Object
.assign({}, options
, { timeout
: ival
* 1000 - 5 });
433 return Poll
.add(function() {
434 return Request
.request(url
, options
).then(function(res
) {
439 callback(res
, res
.json(), res
.duration
);
442 callback(res
, null, res
.duration
);
448 remove: function(entry
) { return Poll
.remove(entry
) },
449 start: function() { return Poll
.start() },
450 stop: function() { return Poll
.stop() },
451 active: function() { return Poll
.active() }
455 var Poll
= Class
.singleton({
456 __name__
: 'LuCI.Poll',
460 add: function(fn
, interval
) {
461 if (interval
== null || interval
<= 0)
462 interval
= window
.L
? window
.L
.env
.pollinterval
: null;
464 if (isNaN(interval
) || typeof(fn
) != 'function')
465 throw new TypeError('Invalid argument to LuCI.Poll.add()');
467 for (var i
= 0; i
< this.queue
.length
; i
++)
468 if (this.queue
[i
].fn
=== fn
)
479 if (this.tick
!= null && !this.active())
485 remove: function(entry
) {
486 if (typeof(fn
) != 'function')
487 throw new TypeError('Invalid argument to LuCI.Poll.remove()');
489 var len
= this.queue
.length
;
491 for (var i
= len
; i
> 0; i
--)
492 if (this.queue
[i
-1].fn
=== fn
)
493 this.queue
.splice(i
-1, 1);
495 if (!this.queue
.length
&& this.stop())
498 return (this.queue
.length
!= len
);
507 if (this.queue
.length
) {
508 this.timer
= window
.setInterval(this.step
, 1000);
510 document
.dispatchEvent(new CustomEvent('poll-start'));
520 document
.dispatchEvent(new CustomEvent('poll-stop'));
521 window
.clearInterval(this.timer
);
528 for (var i
= 0, e
= null; (e
= Poll
.queue
[i
]) != null; i
++) {
529 if ((Poll
.tick
% e
.i
) != 0)
537 Promise
.resolve(e
.fn()).finally((function() { this.r
= true }).bind(e
));
540 Poll
.tick
= (Poll
.tick
+ 1) % Math
.pow(2, 32);
544 return (this.timer
!= null);
549 var dummyElem
= null,
551 originalCBIInit
= null,
554 var LuCI
= Class
.extend({
556 __init__: function(env
) {
558 document
.querySelectorAll('script[src*="/luci.js"]').forEach(function(s
) {
559 if (env
.base_url
== null || env
.base_url
== '')
560 env
.base_url
= s
.getAttribute('src').replace(/\/luci\.js(?:\?v=[^?]+)?$/, '');
563 if (env
.base_url
== null)
564 this.error('InternalError', 'Cannot find url of luci.js');
566 Object
.assign(this.env
, env
);
568 document
.addEventListener('poll-start', function(ev
) {
569 document
.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e
) {
570 e
.style
.display
= (e
.id
== 'xhr_poll_status_off') ? 'none' : '';
574 document
.addEventListener('poll-stop', function(ev
) {
575 document
.querySelectorAll('[id^="xhr_poll_status"]').forEach(function(e
) {
576 e
.style
.display
= (e
.id
== 'xhr_poll_status_on') ? 'none' : '';
580 var domReady
= new Promise(function(resolveFn
, rejectFn
) {
581 document
.addEventListener('DOMContentLoaded', resolveFn
);
588 ]).then(this.setupDOM
.bind(this)).catch(this.error
);
590 originalCBIInit
= window
.cbi_init
;
591 window
.cbi_init = function() {};
594 raise: function(type
, fmt
/*, ...*/) {
596 msg
= fmt
? String
.prototype.format
.apply(fmt
, this.varargs(arguments
, 2)) : null,
599 if (type
instanceof Error
) {
601 stack
= (e
.stack
|| '').split(/\n/);
604 e
.message
= msg
+ ': ' + e
.message
;
607 e
= new (window
[type
|| 'Error'] || Error
)(msg
|| 'Unspecified error');
608 e
.name
= type
|| 'Error';
611 if (window
.console
&& console
.debug
)
617 error: function(type
, fmt
/*, ...*/) {
619 L
.raise
.apply(L
, Array
.prototype.slice
.call(arguments
));
622 var stack
= (e
.stack
|| '').split(/\n/).map(function(frame
) {
623 frame
= frame
.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
624 return frame
? ' ' + frame
: '';
627 if (!/^ at /.test(stack
[0]))
630 if (/\braise /.test(stack
[0]))
633 if (/\berror /.test(stack
[0]))
636 stack
= stack
.length
? '\n' + stack
.join('\n') : '';
639 L
.ui
.showModal(e
.name
|| _('Runtime error'),
640 E('pre', { 'class': 'alert-message error' }, e
.message
+ stack
));
642 L
.dom
.content(document
.querySelector('#maincontent'),
643 E('pre', { 'class': 'alert-message error' }, e
+ stack
));
649 bind: function(fn
, self
/*, ... */) {
650 return Function
.prototype.bind
.apply(fn
, this.varargs(arguments
, 2, self
));
654 require: function(name
, from) {
655 var L
= this, url
= null, from = from || [];
657 /* Class already loaded */
658 if (classes
[name
] != null) {
659 /* Circular dependency */
660 if (from.indexOf(name
) != -1)
661 L
.error('DependencyError',
662 'Circular dependency: class "%s" depends on "%s"',
663 name
, from.join('" which depends on "'));
665 return classes
[name
];
668 url
= '%s/%s.js'.format(L
.env
.base_url
, name
.replace(/\./g, '/'));
669 from = [ name ].concat(from);
671 var compileClass = function(res) {
673 L.error('NetworkError
',
674 'HTTP error
%d
while loading
class file
"%s"', res.status, url);
676 var source = res.text(),
677 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
678 strictmatch = /^use[ \t]+strict$/,
682 /* find require statements in source */
683 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
684 var chr = source.charCodeAt(i);
689 else if (chr == 92) {
692 else if (chr == quote) {
693 var s = source.substring(off, i),
694 m = requirematch.exec(s);
697 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_
');
698 depends.push(L.require(dep, from));
701 else if (!strictmatch.exec(s)) {
708 else if (quote == -1 && (chr == 34 || chr == 39)) {
714 /* load dependencies and instantiate class */
715 return Promise.all(depends).then(function(instances) {
716 var _factory, _class;
720 '(function(window
, document
, L
%s
) { %s
})\n\n//# sourceURL=%s\n'
721 .format(args
, source
, res
.url
));
724 L
.error('SyntaxError', '%s\n in %s:%s',
725 error
.message
, res
.url
, error
.lineNumber
|| '?');
728 _factory
.displayName
= toCamelCase(name
+ 'ClassFactory');
729 _class
= _factory
.apply(_factory
, [window
, document
, L
].concat(instances
));
731 if (!Class
.isSubclass(_class
))
732 L
.error('TypeError', '"%s" factory yields invalid constructor', name
);
734 if (_class
.displayName
== 'AnonymousClass')
735 _class
.displayName
= toCamelCase(name
+ 'Class');
737 var ptr
= Object
.getPrototypeOf(L
),
738 parts
= name
.split(/\./),
739 instance
= new _class();
741 for (var i
= 0; ptr
&& i
< parts
.length
- 1; i
++)
745 ptr
[parts
[i
]] = instance
;
747 classes
[name
] = instance
;
753 /* Request class file */
754 classes
[name
] = Request
.get(url
, { cache
: true })
758 return classes
[name
];
762 setupDOM: function(ev
) {
763 Request
.addInterceptor(function(res
) {
764 if (res
.status
!= 403 || res
.headers
.get('X-LuCI-Login-Required') != 'yes')
769 L
.ui
.showModal(_('Session expired'), [
770 E('div', { class: 'alert-message warning' },
771 _('A new login is required since the authentication session expired.')),
772 E('div', { class: 'right' },
774 class: 'btn primary',
776 var loc
= window
.location
;
777 window
.location
= loc
.protocol
+ '//' + loc
.host
+ loc
.pathname
+ loc
.search
;
782 throw 'Session expired';
789 document
.dispatchEvent(new CustomEvent('luci-loaded'));
794 /* URL construction helpers */
795 path: function(prefix
, parts
) {
796 var url
= [ prefix
|| '' ];
798 for (var i
= 0; i
< parts
.length
; i
++)
799 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts
[i
]))
800 url
.push('/', parts
[i
]);
802 if (url
.length
=== 1)
809 return this.path(this.env
.scriptname
, arguments
);
812 resource: function() {
813 return this.path(this.env
.resource
, arguments
);
816 location: function() {
817 return this.path(this.env
.scriptname
, this.env
.requestpath
);
821 /* HTTP resource fetching */
822 get: function(url
, args
, cb
) {
823 return this.poll(null, url
, args
, cb
, false);
826 post: function(url
, args
, cb
) {
827 return this.poll(null, url
, args
, cb
, true);
830 poll: function(interval
, url
, args
, cb
, post
) {
831 if (interval
!== null && interval
<= 0)
832 interval
= this.env
.pollinterval
;
834 var data
= post
? { token
: this.env
.token
} : null,
835 method
= post
? 'POST' : 'GET';
837 if (!/^(?:\/|\S+:\/\/)/.test(url
))
841 data
= Object
.assign(data
|| {}, args
);
843 if (interval
!== null)
844 return Request
.poll
.add(interval
, url
, { method
: method
, query
: data
}, cb
);
846 return Request
.request(url
, { method
: method
, query
: data
})
847 .then(function(res
) {
849 if (/^application\/json\b/.test(res
.headers
.get('Content-Type')))
850 try { json
= res
.json() } catch(e
) {}
851 cb(res
.xhr
, json
, res
.duration
);
855 stop: function(entry
) { return Poll
.remove(entry
) },
856 halt: function() { return Poll
.stop() },
857 run: function() { return Poll
.start() },
859 /* DOM manipulation */
860 dom
: Class
.singleton({
861 __name__
: 'LuCI.DOM',
864 return (e
!= null && typeof(e
) == 'object' && 'nodeType' in e
);
871 domParser
= domParser
|| new DOMParser();
872 elem
= domParser
.parseFromString(s
, 'text/html').body
.firstChild
;
878 dummyElem
= dummyElem
|| document
.createElement('div');
879 dummyElem
.innerHTML
= s
;
880 elem
= dummyElem
.firstChild
;
888 matches: function(node
, selector
) {
889 var m
= this.elem(node
) ? node
.matches
|| node
.msMatchesSelector
: null;
890 return m
? m
.call(node
, selector
) : false;
893 parent: function(node
, selector
) {
894 if (this.elem(node
) && node
.closest
)
895 return node
.closest(selector
);
897 while (this.elem(node
))
898 if (this.matches(node
, selector
))
901 node
= node
.parentNode
;
906 append: function(node
, children
) {
907 if (!this.elem(node
))
910 if (Array
.isArray(children
)) {
911 for (var i
= 0; i
< children
.length
; i
++)
912 if (this.elem(children
[i
]))
913 node
.appendChild(children
[i
]);
914 else if (children
!== null && children
!== undefined)
915 node
.appendChild(document
.createTextNode('' + children
[i
]));
917 return node
.lastChild
;
919 else if (typeof(children
) === 'function') {
920 return this.append(node
, children(node
));
922 else if (this.elem(children
)) {
923 return node
.appendChild(children
);
925 else if (children
!== null && children
!== undefined) {
926 node
.innerHTML
= '' + children
;
927 return node
.lastChild
;
933 content: function(node
, children
) {
934 if (!this.elem(node
))
937 var dataNodes
= node
.querySelectorAll('[data-idref]');
939 for (var i
= 0; i
< dataNodes
.length
; i
++)
940 delete this.registry
[dataNodes
[i
].getAttribute('data-idref')];
942 while (node
.firstChild
)
943 node
.removeChild(node
.firstChild
);
945 return this.append(node
, children
);
948 attr: function(node
, key
, val
) {
949 if (!this.elem(node
))
954 if (typeof(key
) === 'object' && key
!== null)
956 else if (typeof(key
) === 'string')
957 attr
= {}, attr
[key
] = val
;
960 if (!attr
.hasOwnProperty(key
) || attr
[key
] == null)
963 switch (typeof(attr
[key
])) {
965 node
.addEventListener(key
, attr
[key
]);
969 node
.setAttribute(key
, JSON
.stringify(attr
[key
]));
973 node
.setAttribute(key
, attr
[key
]);
979 var html
= arguments
[0],
984 if (!(attr
instanceof Object
) || Array
.isArray(attr
))
985 data
= attr
, attr
= null;
987 if (Array
.isArray(html
)) {
988 elem
= document
.createDocumentFragment();
989 for (var i
= 0; i
< html
.length
; i
++)
990 elem
.appendChild(this.create(html
[i
]));
992 else if (this.elem(html
)) {
995 else if (html
.charCodeAt(0) === 60) {
996 elem
= this.parse(html
);
999 elem
= document
.createElement(html
);
1005 this.attr(elem
, attr
);
1006 this.append(elem
, data
);
1013 data: function(node
, key
, val
) {
1014 var id
= node
.getAttribute('data-idref');
1016 /* clear all data */
1017 if (arguments
.length
> 1 && key
== null) {
1019 node
.removeAttribute('data-idref');
1020 val
= this.registry
[id
]
1021 delete this.registry
[id
];
1029 else if (arguments
.length
> 2 && key
!= null && val
== null) {
1031 val
= this.registry
[id
][key
];
1032 delete this.registry
[id
][key
];
1040 else if (arguments
.length
> 2 && key
!= null && val
!= null) {
1042 do { id
= Math
.floor(Math
.random() * 0xffffffff).toString(16) }
1043 while (this.registry
.hasOwnProperty(id
));
1045 node
.setAttribute('data-idref', id
);
1046 this.registry
[id
] = {};
1049 return (this.registry
[id
][key
] = val
);
1053 else if (arguments
.length
== 1) {
1055 return this.registry
[id
];
1061 else if (arguments
.length
== 2) {
1063 return this.registry
[id
][key
];
1069 bindClassInstance: function(node
, inst
) {
1070 if (!(inst
instanceof Class
))
1071 L
.error('TypeError', 'Argument must be a class instance');
1073 return this.data(node
, '_class', inst
);
1076 findClassInstance: function(node
) {
1080 inst
= this.data(node
, '_class');
1081 node
= node
.parentNode
;
1083 while (!(inst
instanceof Class
) && node
!= null);
1088 callClassMethod: function(node
, method
/*, ... */) {
1089 var inst
= this.findClassInstance(node
);
1091 if (inst
== null || typeof(inst
[method
]) != 'function')
1094 return inst
[method
].apply(inst
, inst
.varargs(arguments
, 2));
1102 view
: Class
.extend({
1103 __name__
: 'LuCI.View',
1105 __init__: function() {
1106 var vp
= document
.getElementById('view');
1108 L
.dom
.content(vp
, E('div', { 'class': 'spinning' }, _('Loading view…')));
1110 return Promise
.resolve(this.load())
1111 .then(L
.bind(this.render
, this))
1112 .then(L
.bind(function(nodes
) {
1113 var vp
= document
.getElementById('view');
1115 L
.dom
.content(vp
, nodes
);
1116 L
.dom
.append(vp
, this.addFooter());
1117 }, this)).catch(L
.error
);
1120 load: function() {},
1121 render: function() {},
1123 handleSave: function(ev
) {
1126 document
.getElementById('maincontent')
1127 .querySelectorAll('.cbi-map').forEach(function(map
) {
1128 tasks
.push(L
.dom
.callClassMethod(map
, 'save'));
1131 return Promise
.all(tasks
);
1134 handleSaveApply: function(ev
) {
1135 return this.handleSave(ev
).then(function() {
1136 L
.ui
.changes
.apply(true);
1140 handleReset: function(ev
) {
1143 document
.getElementById('maincontent')
1144 .querySelectorAll('.cbi-map').forEach(function(map
) {
1145 tasks
.push(L
.dom
.callClassMethod(map
, 'reset'));
1148 return Promise
.all(tasks
);
1151 addFooter: function() {
1153 mc
= document
.getElementById('maincontent');
1155 if (mc
.querySelector('.cbi-map')) {
1156 footer
.appendChild(E('div', { 'class': 'cbi-page-actions' }, [
1158 'class': 'cbi-button cbi-button-apply',
1160 'value': _('Save & Apply'),
1161 'click': L
.bind(this.handleSaveApply
, this)
1164 'class': 'cbi-button cbi-button-save',
1167 'click': L
.bind(this.handleSave
, this)
1170 'class': 'cbi-button cbi-button-reset',
1172 'value': _('Reset'),
1173 'click': L
.bind(this.handleReset
, this)
1183 var XHR
= Class
.extend({
1184 __name__
: 'LuCI.XHR',
1185 __init__: function() {
1186 if (window
.console
&& console
.debug
)
1187 console
.debug('Direct use XHR() is deprecated, please use L.Request instead');
1190 _response: function(cb
, res
, json
, duration
) {
1192 cb(res
, json
, duration
);
1196 get: function(url
, data
, callback
, timeout
) {
1198 L
.get(url
, data
, this._response
.bind(this, callback
), timeout
);
1201 post: function(url
, data
, callback
, timeout
) {
1203 L
.post(url
, data
, this._response
.bind(this, callback
), timeout
);
1206 cancel: function() { delete this.active
},
1207 busy: function() { return (this.active
=== true) },
1208 abort: function() {},
1209 send_form: function() { L
.error('InternalError', 'Not implemented') },
1212 XHR
.get = function() { return window
.L
.get.apply(window
.L
, arguments
) };
1213 XHR
.post = function() { return window
.L
.post
.apply(window
.L
, arguments
) };
1214 XHR
.poll = function() { return window
.L
.poll
.apply(window
.L
, arguments
) };
1215 XHR
.stop
= Request
.poll
.remove
.bind(Request
.poll
);
1216 XHR
.halt
= Request
.poll
.stop
.bind(Request
.poll
);
1217 XHR
.run
= Request
.poll
.start
.bind(Request
.poll
);
1218 XHR
.running
= Request
.poll
.active
.bind(Request
.poll
);
1222 })(window
, document
);