58d38df249aad5efcb159b8249d36739ae45079f
2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String
.prototype.format = function()
15 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g
, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
27 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
29 while ((a
= re
.exec(str
)) != null)
32 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
33 var pPrecision
= a
[6], pType
= a
[7];
43 if (numSubstitutions
< arguments
.length
)
45 var param
= arguments
[numSubstitutions
++];
48 if (pPad
&& pPad
.substr(0,1) == "'")
49 pad
= leftpart
.substr(1,1);
53 var justifyRight
= true;
54 if (pJustify
&& pJustify
=== "-")
59 minLength
= parseInt(pMinLength
);
62 if (pPrecision
&& pType
== 'f')
63 precision
= parseInt(pPrecision
.substring(1));
70 subst
= (parseInt(param
) || 0).toString(2);
74 subst
= String
.fromCharCode(parseInt(param
) || 0);
78 subst
= (parseInt(param
) || 0);
82 subst
= Math
.abs(parseInt(param
) || 0);
86 subst
= (precision
> -1)
87 ? ((parseFloat(param
) || 0.0)).toFixed(precision
)
88 : (parseFloat(param
) || 0.0);
92 subst
= (parseInt(param
) || 0).toString(8);
100 subst
= ('' + (parseInt(param
) || 0).toString(16)).toLowerCase();
104 subst
= ('' + (parseInt(param
) || 0).toString(16)).toUpperCase();
108 subst
= esc(param
, html_esc
);
112 subst
= esc(param
, quot_esc
);
116 subst
= String
.serialize(param
);
123 var ts
= (param
|| 0);
126 tm
= Math
.floor(ts
/ 60);
131 th
= Math
.floor(tm
/ 60);
136 td
= Math
.floor(th
/ 24);
141 ? '%dd %dh %dm %ds'.format(td
, th
, tm
, ts
)
142 : '%dh %dm %ds'.format(th
, tm
, ts
);
147 var mf
= pMinLength
? parseInt(pMinLength
) : 1000;
148 var pr
= pPrecision
? Math
.floor(10*parseFloat('0'+pPrecision
)) : 2;
151 var val
= parseFloat(param
|| 0);
152 var units
= [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
157 subst
= val
.toFixed(pr
) + ' ' + units
[i
];
161 subst
= (typeof(subst
) == 'undefined') ? '' : subst
.toString();
163 if (minLength
> 0 && pad
.length
> 0)
164 for (var i
= 0; i
< (minLength
- subst
.length
); i
++)
165 subst
= justifyRight
? (pad
+ subst
) : (subst
+ pad
);
169 out
+= leftpart
+ subst
;
170 str
= str
.substr(m
.length
);
180 var Class = function() { };
182 Class
.extend = function(properties
)
184 Class
.initializing
= true;
186 var prototype = new this();
187 var superprot
= this.prototype;
189 Class
.initializing
= false;
191 $.extend(prototype, properties
, {
192 callSuper: function() {
194 var meth
= arguments
[0];
196 if (typeof(superprot
[meth
]) != 'function')
199 for (var i
= 1; i
< arguments
.length
; i
++)
200 args
.push(arguments
[i
]);
202 return superprot
[meth
].apply(this, args
);
208 this.options
= arguments
[0] || { };
210 if (!Class
.initializing
&& typeof(this.init
) == 'function')
211 this.init
.apply(this, arguments
);
214 _class
.prototype = prototype;
215 _class
.prototype.constructor = _class
;
217 _class
.extend
= Class
.extend
;
222 this.defaults = function(obj
, def
)
225 if (typeof(obj
[key
]) == 'undefined')
231 this.isDeferred = function(x
)
233 return (typeof(x
) == 'object' &&
234 typeof(x
.then
) == 'function' &&
235 typeof(x
.promise
) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments
[0]))
243 var d
= $.Deferred();
244 d
.resolve
.apply(d
, arguments
);
253 plural: function(n
) { return 0 + (n
!= 1) },
256 if (_luci2
.i18n
.loaded
)
259 var lang
= (navigator
.userLanguage
|| navigator
.language
|| 'en').toLowerCase();
260 var langs
= (lang
.indexOf('-') > -1) ? [ lang
, lang
.split(/-/)[0] ] : [ lang
];
262 for (var i
= 0; i
< langs
.length
; i
++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2
.globals
.resource
, langs
[i
]), {
267 success: function(data
) {
268 $.extend(_luci2
.i18n
.catalog
, data
);
270 var pe
= _luci2
.i18n
.catalog
[''];
273 delete _luci2
.i18n
.catalog
[''];
275 var pf
= new Function('n', 'return 0 + (' + pe
+ ')');
276 _luci2
.i18n
.plural
= pf
;
282 _luci2
.i18n
.loaded
= true;
287 this.tr = function(msgid
)
291 var msgstr
= _luci2
.i18n
.catalog
[msgid
];
293 if (typeof(msgstr
) == 'undefined')
295 else if (typeof(msgstr
) == 'string')
301 this.trp = function(msgid
, msgid_plural
, count
)
305 var msgstr
= _luci2
.i18n
.catalog
[msgid
];
307 if (typeof(msgstr
) == 'undefined')
308 return (count
== 1) ? msgid
: msgid_plural
;
309 else if (typeof(msgstr
) == 'string')
312 return msgstr
[_luci2
.i18n
.plural(count
)];
315 this.trc = function(msgctx
, msgid
)
319 var msgstr
= _luci2
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
321 if (typeof(msgstr
) == 'undefined')
323 else if (typeof(msgstr
) == 'string')
329 this.trcp = function(msgctx
, msgid
, msgid_plural
, count
)
333 var msgstr
= _luci2
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
335 if (typeof(msgstr
) == 'undefined')
336 return (count
== 1) ? msgid
: msgid_plural
;
337 else if (typeof(msgstr
) == 'string')
340 return msgstr
[_luci2
.i18n
.plural(count
)];
343 this.setHash = function(key
, value
)
346 var data
= this.getHash(undefined);
348 if (typeof(value
) == 'undefined')
359 for (var i
= 0; i
< keys
.length
; i
++)
364 h
+= keys
[i
] + ':' + data
[keys
[i
]];
368 location
.hash
= '#' + h
;
373 this.getHash = function(key
)
376 var tuples
= (location
.hash
|| '#').substring(1).split(/,/);
378 for (var i
= 0; i
< tuples
.length
; i
++)
380 var tuple
= tuples
[i
].split(/:/);
381 if (tuple
.length
== 2)
382 data
[tuple
[0]] = tuple
[1];
385 if (typeof(key
) != 'undefined')
391 this.toArray = function(x
)
401 var l
= x
.split(/\s+/);
402 for (var i
= 0; i
< l
.length
; i
++)
411 for (var i
= 0; i
< x
.length
; i
++)
415 else if ($.isPlainObject(x
))
419 if (x
.hasOwnProperty(k
))
428 this.toObject = function(x
)
438 var l
= x
.split(/\x+/);
439 for (var i
= 0; i
< l
.length
; i
++)
448 for (var i
= 0; i
< x
.length
; i
++)
452 else if ($.isPlainObject(x
))
461 this.filterArray = function(array
, item
)
463 if (!$.isArray(array
))
466 for (var i
= 0; i
< array
.length
; i
++)
467 if (array
[i
] === item
)
468 array
.splice(i
--, 1);
473 this.toClassName = function(str
, suffix
)
476 var l
= str
.split(/[\/.]/);
478 for (var i
= 0; i
< l
.length
; i
++)
480 n
+= l
[i
].charAt(0).toUpperCase() + l
[i
].substr(1).toLowerCase();
482 if (typeof(suffix
) == 'string')
491 sid
: '00000000000000000000000000000000'
500 _call: function(req
, cb
)
502 return $.ajax('/ubus', {
504 contentType
: 'application/json',
505 data
: JSON
.stringify(req
),
508 timeout
: _luci2
.globals
.timeout
,
513 _list_cb: function(msg
)
515 var list
= msg
.result
;
517 /* verify message frame */
518 if (typeof(msg
) != 'object' || msg
.jsonrpc
!= '2.0' || !msg
.id
|| !$.isArray(list
))
521 return $.Deferred().resolveWith(this, [ list
]);
524 _call_cb: function(msg
)
527 var type
= Object
.prototype.toString
;
528 var reqs
= this._rpc_req
;
530 if (!$.isArray(reqs
))
536 for (var i
= 0; i
< msg
.length
; i
++)
538 /* fetch related request info */
539 var req
= _luci2
.rpc
._requests
[reqs
[i
].id
];
540 if (typeof(req
) != 'object')
541 throw 'No related request for JSON response';
543 /* fetch response attribute and verify returned type */
546 /* verify message frame */
547 if (typeof(msg
[i
]) == 'object' && msg
[i
].jsonrpc
== '2.0')
548 if ($.isArray(msg
[i
].result
) && msg
[i
].result
[0] == 0)
549 ret
= (msg
[i
].result
.length
> 1) ? msg
[i
].result
[1] : msg
[i
].result
[0];
553 for (var key
in req
.expect
)
555 if (typeof(ret
) != 'undefined' && key
!= '')
558 if (typeof(ret
) == 'undefined' || type
.call(ret
) != type
.call(req
.expect
[key
]))
559 ret
= req
.expect
[key
];
566 if (typeof(req
.filter
) == 'function')
569 req
.priv
[1] = req
.params
;
570 ret
= req
.filter
.apply(_luci2
.rpc
, req
.priv
);
573 /* store response data */
574 if (typeof(req
.index
) == 'number')
575 data
[req
.index
] = ret
;
579 /* delete request object */
580 delete _luci2
.rpc
._requests
[reqs
[i
].id
];
583 return $.Deferred().resolveWith(this, [ data
]);
589 for (var i
= 0; i
< arguments
.length
; i
++)
590 params
[i
] = arguments
[i
];
596 params
: (params
.length
> 0) ? params
: undefined
599 return this._call(msg
, this._list_cb
);
604 if (!$.isArray(this._batch
))
610 if (!$.isArray(this._batch
))
611 return _luci2
.deferrable([ ]);
613 var req
= this._batch
;
617 return this._call(req
, this._call_cb
);
620 declare: function(options
)
625 /* build parameter object */
628 if ($.isArray(options
.params
))
629 for (p_off
= 0; p_off
< options
.params
.length
; p_off
++)
630 params
[options
.params
[p_off
]] = arguments
[p_off
];
632 /* all remaining arguments are private args */
633 var priv
= [ undefined, undefined ];
634 for (; p_off
< arguments
.length
; p_off
++)
635 priv
.push(arguments
[p_off
]);
637 /* store request info */
638 var req
= _rpc
._requests
[_rpc
._id
] = {
639 expect
: options
.expect
,
640 filter
: options
.filter
,
645 /* build message object */
658 /* when a batch is in progress then store index in request data
659 * and push message object onto the stack */
660 if ($.isArray(_rpc
._batch
))
662 req
.index
= _rpc
._batch
.push(msg
) - 1;
663 return _luci2
.deferrable(msg
);
667 return _rpc
._call(msg
, _rpc
._call_cb
);
672 this.UCIContext
= Class
.extend({
686 _load
: _luci2
.rpc
.declare({
689 params
: [ 'config' ],
690 expect
: { values
: { } }
693 _order
: _luci2
.rpc
.declare({
696 params
: [ 'config', 'sections' ]
699 _add
: _luci2
.rpc
.declare({
702 params
: [ 'config', 'type', 'name', 'values' ],
703 expect
: { section
: '' }
706 _set
: _luci2
.rpc
.declare({
709 params
: [ 'config', 'section', 'values' ]
712 _delete
: _luci2
.rpc
.declare({
715 params
: [ 'config', 'section', 'options' ]
718 load: function(packages
)
724 if (!$.isArray(packages
))
725 packages
= [ packages
];
729 for (var i
= 0; i
< packages
.length
; i
++)
730 if (!seen
[packages
[i
]])
732 pkgs
.push(packages
[i
]);
733 seen
[packages
[i
]] = true;
734 self
._load(packages
[i
]);
737 return _luci2
.rpc
.flush().then(function(responses
) {
738 for (var i
= 0; i
< responses
.length
; i
++)
739 self
.state
.values
[pkgs
[i
]] = responses
[i
];
745 unload: function(packages
)
747 if (!$.isArray(packages
))
748 packages
= [ packages
];
750 for (var i
= 0; i
< packages
.length
; i
++)
752 delete this.state
.values
[packages
[i
]];
753 delete this.state
.creates
[packages
[i
]];
754 delete this.state
.changes
[packages
[i
]];
755 delete this.state
.deletes
[packages
[i
]];
759 add: function(conf
, type
, name
)
761 var c
= this.state
.creates
;
762 var s
= '.new.%d'.format(this.state
.newid
++);
772 '.index': 1000 + this.state
.newid
778 remove: function(conf
, sid
)
780 var n
= this.state
.creates
;
781 var c
= this.state
.changes
;
782 var d
= this.state
.deletes
;
784 /* requested deletion of a just created section */
785 if (sid
.indexOf('.new.') == 0)
802 sections: function(conf
, type
, cb
)
805 var v
= this.state
.values
[conf
];
806 var n
= this.state
.creates
[conf
];
807 var c
= this.state
.changes
[conf
];
808 var d
= this.state
.deletes
[conf
];
814 if (!d
|| d
[s
] !== true)
815 if (!type
|| v
[s
]['.type'] == type
)
816 sa
.push($.extend({ }, v
[s
], c
? c
[s
] : undefined));
820 if (!type
|| n
[s
]['.type'] == type
)
823 sa
.sort(function(a
, b
) {
824 return a
['.index'] - b
['.index'];
827 for (var i
= 0; i
< sa
.length
; i
++)
830 if (typeof(cb
) == 'function')
831 for (var i
= 0; i
< sa
.length
; i
++)
832 cb
.call(this, sa
[i
], sa
[i
]['.name']);
837 get: function(conf
, sid
, opt
)
839 var v
= this.state
.values
;
840 var n
= this.state
.creates
;
841 var c
= this.state
.changes
;
842 var d
= this.state
.deletes
;
844 if (typeof(sid
) == 'undefined')
847 /* requested option in a just created section */
848 if (sid
.indexOf('.new.') == 0)
853 if (typeof(opt
) == 'undefined')
856 return n
[conf
][sid
][opt
];
859 /* requested an option value */
860 if (typeof(opt
) != 'undefined')
862 /* check whether option was deleted */
863 if (d
[conf
] && d
[conf
][sid
])
865 if (d
[conf
][sid
] === true)
868 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
869 if (d
[conf
][sid
][i
] == opt
)
873 /* check whether option was changed */
874 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
875 return c
[conf
][sid
][opt
];
877 /* return base value */
878 if (v
[conf
] && v
[conf
][sid
])
879 return v
[conf
][sid
][opt
];
884 /* requested an entire section */
891 set: function(conf
, sid
, opt
, val
)
893 var n
= this.state
.creates
;
894 var c
= this.state
.changes
;
895 var d
= this.state
.deletes
;
897 if (typeof(sid
) == 'undefined' ||
898 typeof(opt
) == 'undefined' ||
899 opt
.charAt(0) == '.')
902 if (sid
.indexOf('.new.') == 0)
904 if (n
[conf
] && n
[conf
][sid
])
906 if (typeof(val
) != 'undefined')
907 n
[conf
][sid
][opt
] = val
;
909 delete n
[conf
][sid
][opt
];
912 else if (typeof(val
) != 'undefined')
914 /* do not set within deleted section */
915 if (d
[conf
] && d
[conf
][sid
] === true)
924 /* undelete option */
925 if (d
[conf
] && d
[conf
][sid
])
926 d
[conf
][sid
] = _luci2
.filterArray(d
[conf
][sid
], opt
);
928 c
[conf
][sid
][opt
] = val
;
938 if (d
[conf
][sid
] !== true)
939 d
[conf
][sid
].push(opt
);
943 unset: function(conf
, sid
, opt
)
945 return this.set(conf
, sid
, opt
, undefined);
952 for (var pkg
in this.state
.values
)
957 return this.load(pkgs
);
962 var v
= this.state
.values
;
963 var n
= this.state
.creates
;
964 var r
= this.state
.reorder
;
966 if ($.isEmptyObject(r
))
967 return _luci2
.deferrable();
972 gather all created and existing sections, sort them according
973 to their index value and issue an uci order call
988 o
.sort(function(a
, b
) {
989 return (a
['.index'] - b
['.index']);
994 for (var i
= 0; i
< o
.length
; i
++)
995 sids
.push(o
[i
]['.name']);
997 this._order(c
, sids
);
1001 this.state
.reorder
= { };
1002 return _luci2
.rpc
.flush();
1005 swap: function(conf
, sid1
, sid2
)
1007 var s1
= this.get(conf
, sid1
);
1008 var s2
= this.get(conf
, sid2
);
1009 var n1
= s1
? s1
['.index'] : NaN
;
1010 var n2
= s2
? s2
['.index'] : NaN
;
1012 if (isNaN(n1
) || isNaN(n2
))
1018 this.state
.reorder
[conf
] = true;
1030 if (self
.state
.creates
)
1031 for (var c
in self
.state
.creates
)
1032 for (var s
in self
.state
.creates
[c
])
1039 for (var k
in self
.state
.creates
[c
][s
])
1042 r
.type
= self
.state
.creates
[c
][s
][k
];
1043 else if (k
== '.create')
1044 r
.name
= self
.state
.creates
[c
][s
][k
];
1045 else if (k
.charAt(0) != '.')
1046 r
.values
[k
] = self
.state
.creates
[c
][s
][k
];
1049 snew
.push(self
.state
.creates
[c
][s
]);
1051 self
._add(r
.config
, r
.type
, r
.name
, r
.values
);
1054 if (self
.state
.changes
)
1055 for (var c
in self
.state
.changes
)
1056 for (var s
in self
.state
.changes
[c
])
1057 self
._set(c
, s
, self
.state
.changes
[c
][s
]);
1059 if (self
.state
.deletes
)
1060 for (var c
in self
.state
.deletes
)
1061 for (var s
in self
.state
.deletes
[c
])
1063 var o
= self
.state
.deletes
[c
][s
];
1064 self
._delete(c
, s
, (o
=== true) ? undefined : o
);
1067 return _luci2
.rpc
.flush().then(function(responses
) {
1069 array "snew" holds references to the created uci sections,
1070 use it to assign the returned names of the new sections
1072 for (var i
= 0; i
< snew
.length
; i
++)
1073 snew
[i
]['.name'] = responses
[i
];
1075 return self
._reorder();
1079 _apply
: _luci2
.rpc
.declare({
1082 params
: [ 'timeout', 'rollback' ]
1085 _confirm
: _luci2
.rpc
.declare({
1090 apply: function(timeout
)
1093 var date
= new Date();
1094 var deferred
= $.Deferred();
1096 if (typeof(timeout
) != 'number' || timeout
< 1)
1099 self
._apply(timeout
, true).then(function(rv
) {
1102 deferred
.rejectWith(self
, [ rv
]);
1106 var try_deadline
= date
.getTime() + 1000 * timeout
;
1107 var try_confirm = function()
1109 return self
._confirm().then(function(rv
) {
1112 if (date
.getTime() < try_deadline
)
1113 window
.setTimeout(try_confirm
, 250);
1115 deferred
.rejectWith(self
, [ rv
]);
1120 deferred
.resolveWith(self
, [ rv
]);
1124 window
.setTimeout(try_confirm
, 1000);
1130 changes
: _luci2
.rpc
.declare({
1133 expect
: { changes
: { } }
1136 readable: function(conf
)
1138 return _luci2
.session
.hasACL('uci', conf
, 'read');
1141 writable: function(conf
)
1143 return _luci2
.session
.hasACL('uci', conf
, 'write');
1149 writable: function()
1151 return _luci2
.session
.access('ubus', 'uci', 'commit');
1154 add
: _luci2
.rpc
.declare({
1157 params
: [ 'config', 'type', 'name', 'values' ],
1158 expect
: { section
: '' }
1166 configs
: _luci2
.rpc
.declare({
1169 expect
: { configs
: [ ] }
1172 _changes
: _luci2
.rpc
.declare({
1175 params
: [ 'config' ],
1176 expect
: { changes
: [ ] }
1179 changes: function(config
)
1181 if (typeof(config
) == 'string')
1182 return this._changes(config
);
1185 return this.configs().then(function(configs
) {
1187 configlist
= configs
;
1189 for (var i
= 0; i
< configs
.length
; i
++)
1190 _luci2
.uci
._changes(configs
[i
]);
1192 return _luci2
.rpc
.flush();
1193 }).then(function(changes
) {
1196 for (var i
= 0; i
< configlist
.length
; i
++)
1197 if (changes
[i
].length
)
1198 rv
[configlist
[i
]] = changes
[i
];
1204 commit
: _luci2
.rpc
.declare({
1207 params
: [ 'config' ]
1210 _delete_one
: _luci2
.rpc
.declare({
1213 params
: [ 'config', 'section', 'option' ]
1216 _delete_multiple
: _luci2
.rpc
.declare({
1219 params
: [ 'config', 'section', 'options' ]
1222 'delete': function(config
, section
, option
)
1224 if ($.isArray(option
))
1225 return this._delete_multiple(config
, section
, option
);
1227 return this._delete_one(config
, section
, option
);
1230 delete_all
: _luci2
.rpc
.declare({
1233 params
: [ 'config', 'type', 'match' ]
1236 _foreach
: _luci2
.rpc
.declare({
1239 params
: [ 'config', 'type' ],
1240 expect
: { values
: { } }
1243 foreach: function(config
, type
, cb
)
1245 return this._foreach(config
, type
).then(function(sections
) {
1246 for (var s
in sections
)
1251 get: _luci2
.rpc
.declare({
1254 params
: [ 'config', 'section', 'option' ],
1255 expect
: { '': { } },
1256 filter: function(data
, params
) {
1257 if (typeof(params
.option
) == 'undefined')
1258 return data
.values
? data
.values
['.type'] : undefined;
1264 get_all
: _luci2
.rpc
.declare({
1267 params
: [ 'config', 'section' ],
1268 expect
: { values
: { } },
1269 filter: function(data
, params
) {
1270 if (typeof(params
.section
) == 'string')
1271 data
['.section'] = params
.section
;
1272 else if (typeof(params
.config
) == 'string')
1273 data
['.package'] = params
.config
;
1278 get_first: function(config
, type
, option
)
1280 return this._foreach(config
, type
).then(function(sections
) {
1281 for (var s
in sections
)
1283 var val
= (typeof(option
) == 'string') ? sections
[s
][option
] : sections
[s
]['.name'];
1285 if (typeof(val
) != 'undefined')
1293 section
: _luci2
.rpc
.declare({
1296 params
: [ 'config', 'type', 'name', 'values' ],
1297 expect
: { section
: '' }
1300 _set
: _luci2
.rpc
.declare({
1303 params
: [ 'config', 'section', 'values' ]
1306 set: function(config
, section
, option
, value
)
1308 if (typeof(value
) == 'undefined' && typeof(option
) == 'string')
1309 return this.section(config
, section
, option
); /* option -> type */
1310 else if ($.isPlainObject(option
))
1311 return this._set(config
, section
, option
); /* option -> values */
1314 values
[option
] = value
;
1316 return this._set(config
, section
, values
);
1319 order
: _luci2
.rpc
.declare({
1322 params
: [ 'config', 'sections' ]
1327 listNetworkNames: function() {
1328 return _luci2
.rpc
.list('network.interface.*').then(function(list
) {
1330 for (var name
in list
)
1331 if (name
!= 'network.interface.loopback')
1332 names
.push(name
.substring(18));
1338 listDeviceNames
: _luci2
.rpc
.declare({
1339 object
: 'network.device',
1341 expect
: { '': { } },
1342 filter: function(data
) {
1344 for (var name
in data
)
1352 getNetworkStatus: function()
1357 return this.listNetworkNames().then(function(names
) {
1360 for (var i
= 0; i
< names
.length
; i
++)
1361 _luci2
.network
.getInterfaceStatus(names
[i
]);
1363 return _luci2
.rpc
.flush();
1364 }).then(function(networks
) {
1365 for (var i
= 0; i
< networks
.length
; i
++)
1367 var net
= nets
[i
] = networks
[i
];
1368 var dev
= net
.l3_device
|| net
.l2_device
;
1370 net
.device
= devs
[dev
] || (devs
[dev
] = { });
1375 for (var dev
in devs
)
1376 _luci2
.network
.getDeviceStatus(dev
);
1378 return _luci2
.rpc
.flush();
1379 }).then(function(devices
) {
1382 for (var i
= 0; i
< devices
.length
; i
++)
1384 var brm
= devices
[i
]['bridge-members'];
1385 delete devices
[i
]['bridge-members'];
1387 $.extend(devs
[devices
[i
]['device']], devices
[i
]);
1392 devs
[devices
[i
]['device']].subdevices
= [ ];
1394 for (var j
= 0; j
< brm
.length
; j
++)
1399 _luci2
.network
.getDeviceStatus(brm
[j
]);
1402 devs
[devices
[i
]['device']].subdevices
[j
] = devs
[brm
[j
]];
1406 return _luci2
.rpc
.flush();
1407 }).then(function(subdevices
) {
1408 for (var i
= 0; i
< subdevices
.length
; i
++)
1409 $.extend(devs
[subdevices
[i
]['device']], subdevices
[i
]);
1413 for (var dev
in devs
)
1414 _luci2
.wireless
.getDeviceStatus(dev
);
1416 return _luci2
.rpc
.flush();
1417 }).then(function(wifidevices
) {
1418 for (var i
= 0; i
< wifidevices
.length
; i
++)
1420 devs
[wifidevices
[i
]['device']].wireless
= wifidevices
[i
];
1422 nets
.sort(function(a
, b
) {
1423 if (a
['interface'] < b
['interface'])
1425 else if (a
['interface'] > b
['interface'])
1435 findWanInterfaces: function(cb
)
1437 return this.listNetworkNames().then(function(names
) {
1440 for (var i
= 0; i
< names
.length
; i
++)
1441 _luci2
.network
.getInterfaceStatus(names
[i
]);
1443 return _luci2
.rpc
.flush();
1444 }).then(function(interfaces
) {
1445 var rv
= [ undefined, undefined ];
1447 for (var i
= 0; i
< interfaces
.length
; i
++)
1449 if (!interfaces
[i
].route
)
1452 for (var j
= 0; j
< interfaces
[i
].route
.length
; j
++)
1454 var rt
= interfaces
[i
].route
[j
];
1456 if (typeof(rt
.table
) != 'undefined')
1459 if (rt
.target
== '0.0.0.0' && rt
.mask
== 0)
1460 rv
[0] = interfaces
[i
];
1461 else if (rt
.target
== '::' && rt
.mask
== 0)
1462 rv
[1] = interfaces
[i
];
1470 getDHCPLeases
: _luci2
.rpc
.declare({
1471 object
: 'luci2.network',
1472 method
: 'dhcp_leases',
1473 expect
: { leases
: [ ] }
1476 getDHCPv6Leases
: _luci2
.rpc
.declare({
1477 object
: 'luci2.network',
1478 method
: 'dhcp6_leases',
1479 expect
: { leases
: [ ] }
1482 getRoutes
: _luci2
.rpc
.declare({
1483 object
: 'luci2.network',
1485 expect
: { routes
: [ ] }
1488 getIPv6Routes
: _luci2
.rpc
.declare({
1489 object
: 'luci2.network',
1491 expect
: { routes
: [ ] }
1494 getARPTable
: _luci2
.rpc
.declare({
1495 object
: 'luci2.network',
1496 method
: 'arp_table',
1497 expect
: { entries
: [ ] }
1500 getInterfaceStatus
: _luci2
.rpc
.declare({
1501 object
: 'network.interface',
1503 params
: [ 'interface' ],
1504 expect
: { '': { } },
1505 filter: function(data
, params
) {
1506 data
['interface'] = params
['interface'];
1507 data
['l2_device'] = data
['device'];
1508 delete data
['device'];
1513 getDeviceStatus
: _luci2
.rpc
.declare({
1514 object
: 'network.device',
1517 expect
: { '': { } },
1518 filter: function(data
, params
) {
1519 data
['device'] = params
['name'];
1524 getConntrackCount
: _luci2
.rpc
.declare({
1525 object
: 'luci2.network',
1526 method
: 'conntrack_count',
1527 expect
: { '': { count
: 0, limit
: 0 } }
1530 listSwitchNames
: _luci2
.rpc
.declare({
1531 object
: 'luci2.network',
1532 method
: 'switch_list',
1533 expect
: { switches
: [ ] }
1536 getSwitchInfo
: _luci2
.rpc
.declare({
1537 object
: 'luci2.network',
1538 method
: 'switch_info',
1539 params
: [ 'switch' ],
1540 expect
: { info
: { } },
1541 filter: function(data
, params
) {
1542 data
['attrs'] = data
['switch'];
1543 data
['vlan_attrs'] = data
['vlan'];
1544 data
['port_attrs'] = data
['port'];
1545 data
['switch'] = params
['switch'];
1554 getSwitchStatus
: _luci2
.rpc
.declare({
1555 object
: 'luci2.network',
1556 method
: 'switch_status',
1557 params
: [ 'switch' ],
1558 expect
: { ports
: [ ] }
1562 runPing
: _luci2
.rpc
.declare({
1563 object
: 'luci2.network',
1566 expect
: { '': { code
: -1 } }
1569 runPing6
: _luci2
.rpc
.declare({
1570 object
: 'luci2.network',
1573 expect
: { '': { code
: -1 } }
1576 runTraceroute
: _luci2
.rpc
.declare({
1577 object
: 'luci2.network',
1578 method
: 'traceroute',
1580 expect
: { '': { code
: -1 } }
1583 runTraceroute6
: _luci2
.rpc
.declare({
1584 object
: 'luci2.network',
1585 method
: 'traceroute6',
1587 expect
: { '': { code
: -1 } }
1590 runNslookup
: _luci2
.rpc
.declare({
1591 object
: 'luci2.network',
1594 expect
: { '': { code
: -1 } }
1598 setUp
: _luci2
.rpc
.declare({
1599 object
: 'luci2.network',
1602 expect
: { '': { code
: -1 } }
1605 setDown
: _luci2
.rpc
.declare({
1606 object
: 'luci2.network',
1609 expect
: { '': { code
: -1 } }
1614 listDeviceNames
: _luci2
.rpc
.declare({
1617 expect
: { 'devices': [ ] },
1618 filter: function(data
) {
1624 getDeviceStatus
: _luci2
.rpc
.declare({
1627 params
: [ 'device' ],
1628 expect
: { '': { } },
1629 filter: function(data
, params
) {
1630 if (!$.isEmptyObject(data
))
1632 data
['device'] = params
['device'];
1639 getAssocList
: _luci2
.rpc
.declare({
1641 method
: 'assoclist',
1642 params
: [ 'device' ],
1643 expect
: { results
: [ ] },
1644 filter: function(data
, params
) {
1645 for (var i
= 0; i
< data
.length
; i
++)
1646 data
[i
]['device'] = params
['device'];
1648 data
.sort(function(a
, b
) {
1649 if (a
.bssid
< b
.bssid
)
1651 else if (a
.bssid
> b
.bssid
)
1661 getWirelessStatus: function() {
1662 return this.listDeviceNames().then(function(names
) {
1665 for (var i
= 0; i
< names
.length
; i
++)
1666 _luci2
.wireless
.getDeviceStatus(names
[i
]);
1668 return _luci2
.rpc
.flush();
1669 }).then(function(networks
) {
1673 'country', 'channel', 'frequency', 'frequency_offset',
1674 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1678 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1679 'signal', 'noise', 'bitrate', 'encryption'
1682 for (var i
= 0; i
< networks
.length
; i
++)
1684 var phy
= rv
[networks
[i
].phy
] || (
1685 rv
[networks
[i
].phy
] = { networks
: [ ] }
1689 device
: networks
[i
].device
1692 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1693 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1695 for (var j
= 0; j
< net_attrs
.length
; j
++)
1696 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1698 phy
.networks
.push(net
);
1705 getAssocLists: function()
1707 return this.listDeviceNames().then(function(names
) {
1710 for (var i
= 0; i
< names
.length
; i
++)
1711 _luci2
.wireless
.getAssocList(names
[i
]);
1713 return _luci2
.rpc
.flush();
1714 }).then(function(assoclists
) {
1717 for (var i
= 0; i
< assoclists
.length
; i
++)
1718 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1719 rv
.push(assoclists
[i
][j
]);
1725 formatEncryption: function(enc
)
1727 var format_list = function(l
, s
)
1730 for (var i
= 0; i
< l
.length
; i
++)
1731 rv
.push(l
[i
].toUpperCase());
1732 return rv
.join(s
? s
: ', ');
1735 if (!enc
|| !enc
.enabled
)
1736 return _luci2
.tr('None');
1740 if (enc
.wep
.length
== 2)
1741 return _luci2
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1742 else if (enc
.wep
[0] == 'shared')
1743 return _luci2
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1745 return _luci2
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1749 if (enc
.wpa
.length
== 2)
1750 return _luci2
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1751 format_list(enc
.authentication
, '/'),
1752 format_list(enc
.ciphers
, ', ')
1754 else if (enc
.wpa
[0] == 2)
1755 return 'WPA2 %s (%s)'.format(
1756 format_list(enc
.authentication
, '/'),
1757 format_list(enc
.ciphers
, ', ')
1760 return 'WPA %s (%s)'.format(
1761 format_list(enc
.authentication
, '/'),
1762 format_list(enc
.ciphers
, ', ')
1766 return _luci2
.tr('Unknown');
1771 getZoneColor: function(zone
)
1773 if ($.isPlainObject(zone
))
1778 else if (zone
== 'wan')
1781 for (var i
= 0, hash
= 0;
1783 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1785 for (var i
= 0, color
= '#';
1787 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1792 findZoneByNetwork: function(network
)
1795 var zone
= undefined;
1797 return _luci2
.uci
.foreach('firewall', 'zone', function(z
) {
1798 if (!z
.name
|| !z
.network
)
1801 if (!$.isArray(z
.network
))
1802 z
.network
= z
.network
.split(/\s+/);
1804 for (var i
= 0; i
< z
.network
.length
; i
++)
1806 if (z
.network
[i
] == network
)
1812 }).then(function() {
1814 zone
.color
= self
.getZoneColor(zone
);
1822 getSystemInfo
: _luci2
.rpc
.declare({
1828 getBoardInfo
: _luci2
.rpc
.declare({
1834 getDiskInfo
: _luci2
.rpc
.declare({
1835 object
: 'luci2.system',
1840 getInfo: function(cb
)
1844 this.getSystemInfo();
1845 this.getBoardInfo();
1848 return _luci2
.rpc
.flush().then(function(info
) {
1851 $.extend(rv
, info
[0]);
1852 $.extend(rv
, info
[1]);
1853 $.extend(rv
, info
[2]);
1859 getProcessList
: _luci2
.rpc
.declare({
1860 object
: 'luci2.system',
1861 method
: 'process_list',
1862 expect
: { processes
: [ ] },
1863 filter: function(data
) {
1864 data
.sort(function(a
, b
) { return a
.pid
- b
.pid
});
1869 getSystemLog
: _luci2
.rpc
.declare({
1870 object
: 'luci2.system',
1875 getKernelLog
: _luci2
.rpc
.declare({
1876 object
: 'luci2.system',
1881 getZoneInfo: function(cb
)
1883 return $.getJSON(_luci2
.globals
.resource
+ '/zoneinfo.json', cb
);
1886 sendSignal
: _luci2
.rpc
.declare({
1887 object
: 'luci2.system',
1888 method
: 'process_signal',
1889 params
: [ 'pid', 'signal' ],
1890 filter: function(data
) {
1895 initList
: _luci2
.rpc
.declare({
1896 object
: 'luci2.system',
1897 method
: 'init_list',
1898 expect
: { initscripts
: [ ] },
1899 filter: function(data
) {
1900 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
1905 initEnabled: function(init
, cb
)
1907 return this.initList().then(function(list
) {
1908 for (var i
= 0; i
< list
.length
; i
++)
1909 if (list
[i
].name
== init
)
1910 return !!list
[i
].enabled
;
1916 initRun
: _luci2
.rpc
.declare({
1917 object
: 'luci2.system',
1918 method
: 'init_action',
1919 params
: [ 'name', 'action' ],
1920 filter: function(data
) {
1925 initStart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'start', cb
) },
1926 initStop: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'stop', cb
) },
1927 initRestart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'restart', cb
) },
1928 initReload: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'reload', cb
) },
1929 initEnable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'enable', cb
) },
1930 initDisable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'disable', cb
) },
1933 getRcLocal
: _luci2
.rpc
.declare({
1934 object
: 'luci2.system',
1935 method
: 'rclocal_get',
1936 expect
: { data
: '' }
1939 setRcLocal
: _luci2
.rpc
.declare({
1940 object
: 'luci2.system',
1941 method
: 'rclocal_set',
1946 getCrontab
: _luci2
.rpc
.declare({
1947 object
: 'luci2.system',
1948 method
: 'crontab_get',
1949 expect
: { data
: '' }
1952 setCrontab
: _luci2
.rpc
.declare({
1953 object
: 'luci2.system',
1954 method
: 'crontab_set',
1959 getSSHKeys
: _luci2
.rpc
.declare({
1960 object
: 'luci2.system',
1961 method
: 'sshkeys_get',
1962 expect
: { keys
: [ ] }
1965 setSSHKeys
: _luci2
.rpc
.declare({
1966 object
: 'luci2.system',
1967 method
: 'sshkeys_set',
1972 setPassword
: _luci2
.rpc
.declare({
1973 object
: 'luci2.system',
1974 method
: 'password_set',
1975 params
: [ 'user', 'password' ]
1979 listLEDs
: _luci2
.rpc
.declare({
1980 object
: 'luci2.system',
1982 expect
: { leds
: [ ] }
1985 listUSBDevices
: _luci2
.rpc
.declare({
1986 object
: 'luci2.system',
1988 expect
: { devices
: [ ] }
1992 testUpgrade
: _luci2
.rpc
.declare({
1993 object
: 'luci2.system',
1994 method
: 'upgrade_test',
1998 startUpgrade
: _luci2
.rpc
.declare({
1999 object
: 'luci2.system',
2000 method
: 'upgrade_start',
2004 cleanUpgrade
: _luci2
.rpc
.declare({
2005 object
: 'luci2.system',
2006 method
: 'upgrade_clean'
2010 restoreBackup
: _luci2
.rpc
.declare({
2011 object
: 'luci2.system',
2012 method
: 'backup_restore'
2015 cleanBackup
: _luci2
.rpc
.declare({
2016 object
: 'luci2.system',
2017 method
: 'backup_clean'
2021 getBackupConfig
: _luci2
.rpc
.declare({
2022 object
: 'luci2.system',
2023 method
: 'backup_config_get',
2024 expect
: { config
: '' }
2027 setBackupConfig
: _luci2
.rpc
.declare({
2028 object
: 'luci2.system',
2029 method
: 'backup_config_set',
2034 listBackup
: _luci2
.rpc
.declare({
2035 object
: 'luci2.system',
2036 method
: 'backup_list',
2037 expect
: { files
: [ ] }
2041 testReset
: _luci2
.rpc
.declare({
2042 object
: 'luci2.system',
2043 method
: 'reset_test',
2044 expect
: { supported
: false }
2047 startReset
: _luci2
.rpc
.declare({
2048 object
: 'luci2.system',
2049 method
: 'reset_start'
2053 performReboot
: _luci2
.rpc
.declare({
2054 object
: 'luci2.system',
2060 updateLists
: _luci2
.rpc
.declare({
2061 object
: 'luci2.opkg',
2066 _allPackages
: _luci2
.rpc
.declare({
2067 object
: 'luci2.opkg',
2069 params
: [ 'offset', 'limit', 'pattern' ],
2073 _installedPackages
: _luci2
.rpc
.declare({
2074 object
: 'luci2.opkg',
2075 method
: 'list_installed',
2076 params
: [ 'offset', 'limit', 'pattern' ],
2080 _findPackages
: _luci2
.rpc
.declare({
2081 object
: 'luci2.opkg',
2083 params
: [ 'offset', 'limit', 'pattern' ],
2087 _fetchPackages: function(action
, offset
, limit
, pattern
)
2091 return action(offset
, limit
, pattern
).then(function(list
) {
2092 if (!list
.total
|| !list
.packages
)
2093 return { length
: 0, total
: 0 };
2095 packages
.push
.apply(packages
, list
.packages
);
2096 packages
.total
= list
.total
;
2101 if (packages
.length
>= limit
)
2106 for (var i
= offset
+ packages
.length
; i
< limit
; i
+= 100)
2107 action(i
, (Math
.min(i
+ 100, limit
) % 100) || 100, pattern
);
2109 return _luci2
.rpc
.flush();
2110 }).then(function(lists
) {
2111 for (var i
= 0; i
< lists
.length
; i
++)
2113 if (!lists
[i
].total
|| !lists
[i
].packages
)
2116 packages
.push
.apply(packages
, lists
[i
].packages
);
2117 packages
.total
= lists
[i
].total
;
2124 listPackages: function(offset
, limit
, pattern
)
2126 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._allPackages
, offset
, limit
, pattern
);
2129 installedPackages: function(offset
, limit
, pattern
)
2131 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._installedPackages
, offset
, limit
, pattern
);
2134 findPackages: function(offset
, limit
, pattern
)
2136 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._findPackages
, offset
, limit
, pattern
);
2139 installPackage
: _luci2
.rpc
.declare({
2140 object
: 'luci2.opkg',
2142 params
: [ 'package' ],
2146 removePackage
: _luci2
.rpc
.declare({
2147 object
: 'luci2.opkg',
2149 params
: [ 'package' ],
2153 getConfig
: _luci2
.rpc
.declare({
2154 object
: 'luci2.opkg',
2155 method
: 'config_get',
2156 expect
: { config
: '' }
2159 setConfig
: _luci2
.rpc
.declare({
2160 object
: 'luci2.opkg',
2161 method
: 'config_set',
2168 login
: _luci2
.rpc
.declare({
2171 params
: [ 'username', 'password' ],
2175 access
: _luci2
.rpc
.declare({
2178 params
: [ 'scope', 'object', 'function' ],
2179 expect
: { access
: false }
2184 return _luci2
.session
.access('ubus', 'session', 'access');
2187 startHeartbeat: function()
2189 this._hearbeatInterval
= window
.setInterval(function() {
2190 _luci2
.session
.isAlive().then(function(alive
) {
2193 _luci2
.session
.stopHeartbeat();
2194 _luci2
.ui
.login(true);
2198 }, _luci2
.globals
.timeout
* 2);
2201 stopHeartbeat: function()
2203 if (typeof(this._hearbeatInterval
) != 'undefined')
2205 window
.clearInterval(this._hearbeatInterval
);
2206 delete this._hearbeatInterval
;
2213 _fetch_acls
: _luci2
.rpc
.declare({
2219 _fetch_acls_cb: function(acls
)
2221 _luci2
.session
._acls
= acls
;
2224 updateACLs: function()
2226 return _luci2
.session
._fetch_acls()
2227 .then(_luci2
.session
._fetch_acls_cb
);
2230 hasACL: function(scope
, object
, func
)
2232 var acls
= _luci2
.session
._acls
;
2234 if (typeof(func
) == 'undefined')
2235 return (acls
&& acls
[scope
] && acls
[scope
][object
]);
2237 if (acls
&& acls
[scope
] && acls
[scope
][object
])
2238 for (var i
= 0; i
< acls
[scope
][object
].length
; i
++)
2239 if (acls
[scope
][object
][i
] == func
)
2248 saveScrollTop: function()
2250 this._scroll_top
= $(document
).scrollTop();
2253 restoreScrollTop: function()
2255 if (typeof(this._scroll_top
) == 'undefined')
2258 $(document
).scrollTop(this._scroll_top
);
2260 delete this._scroll_top
;
2263 loading: function(enable
)
2265 var win
= $(window
);
2266 var body
= $('body');
2268 var state
= _luci2
.ui
._loading
|| (_luci2
.ui
._loading
= {
2270 .addClass('modal fade')
2271 .append($('<div />')
2272 .addClass('modal-dialog')
2273 .append($('<div />')
2274 .addClass('modal-content luci2-modal-loader')
2275 .append($('<div />')
2276 .addClass('modal-body')
2277 .text(_luci2
.tr('Loading data…')))))
2285 state
.modal
.modal(enable
? 'show' : 'hide');
2288 dialog: function(title
, content
, options
)
2290 var win
= $(window
);
2291 var body
= $('body');
2293 var state
= _luci2
.ui
._dialog
|| (_luci2
.ui
._dialog
= {
2294 dialog
: $('<div />')
2295 .addClass('modal fade')
2296 .append($('<div />')
2297 .addClass('modal-dialog')
2298 .append($('<div />')
2299 .addClass('modal-content')
2300 .append($('<div />')
2301 .addClass('modal-header')
2303 .addClass('modal-title'))
2304 .append($('<div />')
2305 .addClass('modal-body'))
2306 .append($('<div />')
2307 .addClass('modal-footer')
2308 .append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
2310 $(this).parents('div.modal').modal('hide');
2315 if (typeof(options
) != 'object')
2318 if (title
=== false)
2320 state
.dialog
.modal('hide');
2325 var cnt
= state
.dialog
.children().children().children('div.modal-body');
2326 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
2330 if (options
.style
== 'confirm')
2332 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Ok'), 'primary')
2333 .click(options
.confirm
|| function() { _luci2
.ui
.dialog(false) }));
2335 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Cancel'), 'default')
2336 .click(options
.cancel
|| function() { _luci2
.ui
.dialog(false) }));
2338 else if (options
.style
== 'close')
2340 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
2341 .click(options
.close
|| function() { _luci2
.ui
.dialog(false) }));
2343 else if (options
.style
== 'wait')
2345 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
2346 .attr('disabled', true));
2349 state
.dialog
.find('h4:first').text(title
);
2350 state
.dialog
.modal('show');
2352 cnt
.empty().append(content
);
2355 upload: function(title
, content
, options
)
2357 var state
= _luci2
.ui
._upload
|| (_luci2
.ui
._upload
= {
2359 .attr('method', 'post')
2360 .attr('action', '/cgi-bin/luci-upload')
2361 .attr('enctype', 'multipart/form-data')
2362 .attr('target', 'cbi-fileupload-frame')
2364 .append($('<input />')
2365 .attr('type', 'hidden')
2366 .attr('name', 'sessionid'))
2367 .append($('<input />')
2368 .attr('type', 'hidden')
2369 .attr('name', 'filename'))
2370 .append($('<input />')
2371 .attr('type', 'file')
2372 .attr('name', 'filedata')
2373 .addClass('cbi-input-file'))
2374 .append($('<div />')
2375 .css('width', '100%')
2376 .addClass('progress progress-striped active')
2377 .append($('<div />')
2378 .addClass('progress-bar')
2379 .css('width', '100%')))
2380 .append($('<iframe />')
2381 .addClass('pull-right')
2382 .attr('name', 'cbi-fileupload-frame')
2383 .css('width', '1px')
2384 .css('height', '1px')
2385 .css('visibility', 'hidden')),
2387 finish_cb: function(ev
) {
2388 $(this).off('load');
2390 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
2391 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
2392 body
= body
.firstChild
;
2396 json
= $.parseJSON(body
.innerHTML
);
2399 message
: _luci2
.tr('Invalid server response received'),
2400 error
: [ -1, _luci2
.tr('Invalid data') ]
2406 L
.ui
.dialog(L
.tr('File upload'), [
2407 $('<p />').text(_luci2
.tr('The file upload failed with the server response below:')),
2408 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
2409 $('<p />').text(_luci2
.tr('In case of network problems try uploading the file again.'))
2410 ], { style
: 'close' });
2412 else if (typeof(state
.success_cb
) == 'function')
2414 state
.success_cb(json
);
2418 confirm_cb: function() {
2419 var f
= state
.form
.find('.cbi-input-file');
2420 var b
= state
.form
.find('.progress');
2421 var p
= state
.form
.find('p');
2426 state
.form
.find('iframe').on('load', state
.finish_cb
);
2427 state
.form
.submit();
2431 p
.text(_luci2
.tr('File upload in progress …'));
2433 state
.form
.parent().parent().find('button').prop('disabled', true);
2437 state
.form
.find('.progress').hide();
2438 state
.form
.find('.cbi-input-file').val('').show();
2439 state
.form
.find('p').text(content
|| _luci2
.tr('Select the file to upload and press "%s" to proceed.').format(_luci2
.tr('Ok')));
2441 state
.form
.find('[name=sessionid]').val(_luci2
.globals
.sid
);
2442 state
.form
.find('[name=filename]').val(options
.filename
);
2444 state
.success_cb
= options
.success
;
2446 _luci2
.ui
.dialog(title
|| _luci2
.tr('File upload'), state
.form
, {
2448 confirm
: state
.confirm_cb
2452 reconnect: function()
2454 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
2455 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
2456 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
2458 var interval
, timeout
;
2461 _luci2
.tr('Waiting for device'), [
2462 $('<p />').text(_luci2
.tr('Please stand by while the device is reconfiguring …')),
2464 .css('width', '100%')
2465 .addClass('progressbar')
2466 .addClass('intermediate')
2467 .append($('<div />')
2468 .css('width', '100%'))
2469 ], { style
: 'wait' }
2472 for (var i
= 0; i
< protocols
.length
; i
++)
2473 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
2475 //_luci2.network.getNetworkStatus(function(s) {
2476 // for (var i = 0; i < protocols.length; i++)
2478 // for (var j = 0; j < s.length; j++)
2480 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
2481 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
2483 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
2484 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
2487 //}).then(function() {
2488 images
.on('load', function() {
2489 var url
= this.getAttribute('url');
2490 _luci2
.session
.isAlive().then(function(access
) {
2493 window
.clearTimeout(timeout
);
2494 window
.clearInterval(interval
);
2495 _luci2
.ui
.dialog(false);
2500 location
.href
= url
;
2505 interval
= window
.setInterval(function() {
2506 images
.each(function() {
2507 this.setAttribute('src', this.getAttribute('url') + _luci2
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
2511 timeout
= window
.setTimeout(function() {
2512 window
.clearInterval(interval
);
2516 _luci2
.tr('Device not responding'),
2517 _luci2
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2524 login: function(invalid
)
2526 var state
= _luci2
.ui
._login
|| (_luci2
.ui
._login
= {
2529 .attr('method', 'post')
2531 .addClass('alert-message')
2532 .text(_luci2
.tr('Wrong username or password given!')))
2534 .append($('<label />')
2535 .text(_luci2
.tr('Username'))
2536 .append($('<br />'))
2537 .append($('<input />')
2538 .attr('type', 'text')
2539 .attr('name', 'username')
2540 .attr('value', 'root')
2541 .addClass('form-control')
2542 .keypress(function(ev
) {
2543 if (ev
.which
== 10 || ev
.which
== 13)
2547 .append($('<label />')
2548 .text(_luci2
.tr('Password'))
2549 .append($('<br />'))
2550 .append($('<input />')
2551 .attr('type', 'password')
2552 .attr('name', 'password')
2553 .addClass('form-control')
2554 .keypress(function(ev
) {
2555 if (ev
.which
== 10 || ev
.which
== 13)
2559 .text(_luci2
.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2
.tr('Ok')))),
2561 response_cb: function(response
) {
2562 if (!response
.ubus_rpc_session
)
2564 _luci2
.ui
.login(true);
2568 _luci2
.globals
.sid
= response
.ubus_rpc_session
;
2569 _luci2
.setHash('id', _luci2
.globals
.sid
);
2570 _luci2
.session
.startHeartbeat();
2571 _luci2
.ui
.dialog(false);
2572 state
.deferred
.resolve();
2576 confirm_cb: function() {
2577 var u
= state
.form
.find('[name=username]').val();
2578 var p
= state
.form
.find('[name=password]').val();
2584 _luci2
.tr('Logging in'), [
2585 $('<p />').text(_luci2
.tr('Log in in progress …')),
2587 .css('width', '100%')
2588 .addClass('progressbar')
2589 .addClass('intermediate')
2590 .append($('<div />')
2591 .css('width', '100%'))
2592 ], { style
: 'wait' }
2595 _luci2
.globals
.sid
= '00000000000000000000000000000000';
2596 _luci2
.session
.login(u
, p
).then(state
.response_cb
);
2600 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
2601 state
.deferred
= $.Deferred();
2603 /* try to find sid from hash */
2604 var sid
= _luci2
.getHash('id');
2605 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
2607 _luci2
.globals
.sid
= sid
;
2608 _luci2
.session
.isAlive().then(function(access
) {
2611 _luci2
.session
.startHeartbeat();
2612 state
.deferred
.resolve();
2616 _luci2
.setHash('id', undefined);
2621 return state
.deferred
;
2625 state
.form
.find('.alert-message').show();
2627 state
.form
.find('.alert-message').hide();
2629 _luci2
.ui
.dialog(_luci2
.tr('Authorization Required'), state
.form
, {
2631 confirm
: state
.confirm_cb
2634 state
.form
.find('[name=password]').focus();
2636 return state
.deferred
;
2639 cryptPassword
: _luci2
.rpc
.declare({
2643 expect
: { crypt
: '' }
2647 _acl_merge_scope: function(acl_scope
, scope
)
2649 if ($.isArray(scope
))
2651 for (var i
= 0; i
< scope
.length
; i
++)
2652 acl_scope
[scope
[i
]] = true;
2654 else if ($.isPlainObject(scope
))
2656 for (var object_name
in scope
)
2658 if (!$.isArray(scope
[object_name
]))
2661 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
2663 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
2664 acl_object
[scope
[object_name
][i
]] = true;
2669 _acl_merge_permission: function(acl_perm
, perm
)
2671 if ($.isPlainObject(perm
))
2673 for (var scope_name
in perm
)
2675 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
2676 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
2681 _acl_merge_group: function(acl_group
, group
)
2683 if ($.isPlainObject(group
))
2685 if (!acl_group
.description
)
2686 acl_group
.description
= group
.description
;
2690 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
2691 this._acl_merge_permission(acl_perm
, group
.read
);
2696 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
2697 this._acl_merge_permission(acl_perm
, group
.write
);
2702 _acl_merge_tree: function(acl_tree
, tree
)
2704 if ($.isPlainObject(tree
))
2706 for (var group_name
in tree
)
2708 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
2709 this._acl_merge_group(acl_group
, tree
[group_name
]);
2714 listAvailableACLs
: _luci2
.rpc
.declare({
2717 expect
: { acls
: [ ] },
2718 filter: function(trees
) {
2720 for (var i
= 0; i
< trees
.length
; i
++)
2721 _luci2
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
2726 renderMainMenu
: _luci2
.rpc
.declare({
2729 expect
: { menu
: { } },
2730 filter: function(entries
) {
2731 _luci2
.globals
.mainMenu
= new _luci2
.ui
.menu();
2732 _luci2
.globals
.mainMenu
.entries(entries
);
2736 .append(_luci2
.globals
.mainMenu
.render(0, 1));
2740 renderViewMenu: function()
2744 .append(_luci2
.globals
.mainMenu
.render(2, 900));
2747 renderView: function()
2749 var node
= arguments
[0];
2750 var name
= node
.view
.split(/\//).join('.');
2753 for (var i
= 1; i
< arguments
.length
; i
++)
2754 args
.push(arguments
[i
]);
2756 if (_luci2
.globals
.currentView
)
2757 _luci2
.globals
.currentView
.finish();
2759 _luci2
.ui
.renderViewMenu();
2762 _luci2
._views
= { };
2764 _luci2
.setHash('view', node
.view
);
2766 if (_luci2
._views
[name
] instanceof _luci2
.ui
.view
)
2768 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2769 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2772 var url
= _luci2
.globals
.resource
+ '/view/' + name
+ '.js';
2774 return $.ajax(url
, {
2778 }).then(function(data
) {
2780 var viewConstructorSource
= (
2781 '(function(L, $) { ' +
2783 '})(_luci2, $);\n\n' +
2785 ).format(data
, url
);
2787 var viewConstructor
= eval(viewConstructorSource
);
2789 _luci2
._views
[name
] = new viewConstructor({
2791 acls
: node
.write
|| { }
2794 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2795 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2798 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
2801 return $.Deferred().resolve();
2805 updateHostname: function()
2807 return _luci2
.system
.getBoardInfo().then(function(info
) {
2809 $('#hostname').text(info
.hostname
);
2813 updateChanges: function()
2815 return _luci2
.uci
.changes().then(function(changes
) {
2819 for (var config
in changes
)
2823 for (var i
= 0; i
< changes
[config
].length
; i
++)
2825 var c
= changes
[config
][i
];
2834 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
2836 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
2841 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
2843 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2847 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
2851 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2855 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2860 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
2862 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2867 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
2868 n
+= changes
[config
].length
;
2879 .text(_luci2
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
))
2880 .click(function(ev
) {
2881 _luci2
.ui
.dialog(_luci2
.tr('Staged configuration changes'), html
, { style
: 'close' });
2882 ev
.preventDefault();
2892 _luci2
.ui
.loading(true);
2895 _luci2
.ui
.updateHostname(),
2896 _luci2
.ui
.updateChanges(),
2897 _luci2
.ui
.renderMainMenu()
2899 _luci2
.ui
.renderView(_luci2
.globals
.defaultNode
).then(function() {
2900 _luci2
.ui
.loading(false);
2905 button: function(label
, style
, title
)
2907 style
= style
|| 'default';
2909 return $('<button />')
2910 .attr('type', 'button')
2911 .attr('title', title
? title
: '')
2912 .addClass('btn btn-' + style
)
2917 this.ui
.AbstractWidget
= Class
.extend({
2918 i18n: function(text
) {
2923 var key
= arguments
[0];
2926 for (var i
= 1; i
< arguments
.length
; i
++)
2927 args
.push(arguments
[i
]);
2929 switch (typeof(this.options
[key
]))
2935 return this.options
[key
].apply(this, args
);
2938 return ''.format
.apply('' + this.options
[key
], args
);
2942 toString: function() {
2943 return $('<div />').append(this.render()).html();
2946 insertInto: function(id
) {
2947 return $(id
).empty().append(this.render());
2950 appendTo: function(id
) {
2951 return $(id
).append(this.render());
2955 this.ui
.view
= this.ui
.AbstractWidget
.extend({
2956 _fetch_template: function()
2958 return $.ajax(_luci2
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
2962 success: function(data
) {
2963 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
2964 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
2971 return _luci2
.tr(p2
);
2974 return _luci2
.globals
[p2
] || '';
2977 return '(?' + match
+ ')';
2981 $('#maincontent').append(data
);
2988 throw "Not implemented";
2993 var container
= $('#maincontent');
2998 container
.append($('<h2 />').append(this.title
));
3000 if (this.description
)
3001 container
.append($('<p />').append(this.description
));
3006 for (var i
= 0; i
< arguments
.length
; i
++)
3007 args
.push(arguments
[i
]);
3009 return this._fetch_template().then(function() {
3010 return _luci2
.deferrable(self
.execute
.apply(self
, args
));
3014 repeat: function(func
, interval
)
3018 if (!self
._timeouts
)
3019 self
._timeouts
= [ ];
3021 var index
= self
._timeouts
.length
;
3023 if (typeof(interval
) != 'number')
3026 var setTimer
, runTimer
;
3028 setTimer = function() {
3030 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
3033 runTimer = function() {
3034 _luci2
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
3042 if ($.isArray(this._timeouts
))
3044 for (var i
= 0; i
< this._timeouts
.length
; i
++)
3045 window
.clearTimeout(this._timeouts
[i
]);
3047 delete this._timeouts
;
3052 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
3057 entries: function(entries
)
3059 for (var entry
in entries
)
3061 var path
= entry
.split(/\//);
3062 var node
= this._nodes
;
3064 for (i
= 0; i
< path
.length
; i
++)
3069 if (!node
.childs
[path
[i
]])
3070 node
.childs
[path
[i
]] = { };
3072 node
= node
.childs
[path
[i
]];
3075 $.extend(node
, entries
[entry
]);
3079 _indexcmp: function(a
, b
)
3081 var x
= a
.index
|| 0;
3082 var y
= b
.index
|| 0;
3086 firstChildView: function(node
)
3092 for (var child
in (node
.childs
|| { }))
3093 nodes
.push(node
.childs
[child
]);
3095 nodes
.sort(this._indexcmp
);
3097 for (var i
= 0; i
< nodes
.length
; i
++)
3099 var child
= this.firstChildView(nodes
[i
]);
3102 for (var key
in child
)
3103 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
3104 node
[key
] = child
[key
];
3113 _onclick: function(ev
)
3115 _luci2
.ui
.loading(true);
3116 _luci2
.ui
.renderView(ev
.data
).then(function() {
3117 _luci2
.ui
.loading(false);
3120 ev
.preventDefault();
3124 _render: function(childs
, level
, min
, max
)
3127 for (var node
in childs
)
3129 var child
= this.firstChildView(childs
[node
]);
3131 nodes
.push(childs
[node
]);
3134 nodes
.sort(this._indexcmp
);
3136 var list
= $('<ul />');
3139 list
.addClass('nav').addClass('navbar-nav');
3140 else if (level
== 1)
3141 list
.addClass('dropdown-menu').addClass('navbar-inverse');
3143 for (var i
= 0; i
< nodes
.length
; i
++)
3145 if (!_luci2
.globals
.defaultNode
)
3147 var v
= _luci2
.getHash('view');
3148 if (!v
|| v
== nodes
[i
].view
)
3149 _luci2
.globals
.defaultNode
= nodes
[i
];
3152 var item
= $('<li />')
3155 .text(_luci2
.tr(nodes
[i
].title
)))
3158 if (nodes
[i
].childs
&& level
< max
)
3160 item
.addClass('dropdown');
3163 .addClass('dropdown-toggle')
3164 .attr('data-toggle', 'dropdown')
3165 .append('<b class="caret"></b>');
3167 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
3171 item
.find('a').click(nodes
[i
], this._onclick
);
3178 render: function(min
, max
)
3180 var top
= min
? this.getNode(_luci2
.globals
.defaultNode
.view
, min
) : this._nodes
;
3181 return this._render(top
.childs
, 0, min
, max
);
3184 getNode: function(path
, max
)
3186 var p
= path
.split(/\//);
3187 var n
= this._nodes
;
3189 if (typeof(max
) == 'undefined')
3192 for (var i
= 0; i
< max
; i
++)
3194 if (!n
.childs
[p
[i
]])
3204 this.ui
.table
= this.ui
.AbstractWidget
.extend({
3210 row: function(values
)
3212 if ($.isArray(values
))
3214 this._rows
.push(values
);
3216 else if ($.isPlainObject(values
))
3219 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
3221 var col
= this.options
.columns
[i
];
3223 if (typeof col
.key
== 'string')
3224 v
.push(values
[col
.key
]);
3232 rows: function(rows
)
3234 for (var i
= 0; i
< rows
.length
; i
++)
3238 render: function(id
)
3240 var fieldset
= document
.createElement('fieldset');
3241 fieldset
.className
= 'cbi-section';
3243 if (this.options
.caption
)
3245 var legend
= document
.createElement('legend');
3246 $(legend
).append(this.options
.caption
);
3247 fieldset
.appendChild(legend
);
3250 var table
= document
.createElement('table');
3251 table
.className
= 'table table-condensed table-hover';
3253 var has_caption
= false;
3254 var has_description
= false;
3256 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
3257 if (this.options
.columns
[i
].caption
)
3262 else if (this.options
.columns
[i
].description
)
3264 has_description
= true;
3270 var tr
= table
.insertRow(-1);
3271 tr
.className
= 'cbi-section-table-titles';
3273 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
3275 var col
= this.options
.columns
[i
];
3276 var th
= document
.createElement('th');
3277 th
.className
= 'cbi-section-table-cell';
3282 th
.style
.width
= col
.width
;
3285 th
.style
.textAlign
= col
.align
;
3288 $(th
).append(col
.caption
);
3292 if (has_description
)
3294 var tr
= table
.insertRow(-1);
3295 tr
.className
= 'cbi-section-table-descr';
3297 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
3299 var col
= this.options
.columns
[i
];
3300 var th
= document
.createElement('th');
3301 th
.className
= 'cbi-section-table-cell';
3306 th
.style
.width
= col
.width
;
3309 th
.style
.textAlign
= col
.align
;
3311 if (col
.description
)
3312 $(th
).append(col
.description
);
3316 if (this._rows
.length
== 0)
3318 if (this.options
.placeholder
)
3320 var tr
= table
.insertRow(-1);
3321 var td
= tr
.insertCell(-1);
3322 td
.className
= 'cbi-section-table-cell';
3324 td
.colSpan
= this.options
.columns
.length
;
3325 $(td
).append(this.options
.placeholder
);
3330 for (var i
= 0; i
< this._rows
.length
; i
++)
3332 var tr
= table
.insertRow(-1);
3334 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
3336 var col
= this.options
.columns
[j
];
3337 var td
= tr
.insertCell(-1);
3339 var val
= this._rows
[i
][j
];
3341 if (typeof(val
) == 'undefined')
3342 val
= col
.placeholder
;
3344 if (typeof(val
) == 'undefined')
3348 td
.style
.width
= col
.width
;
3351 td
.style
.textAlign
= col
.align
;
3353 if (typeof col
.format
== 'string')
3354 $(td
).append(col
.format
.format(val
));
3355 else if (typeof col
.format
== 'function')
3356 $(td
).append(col
.format(val
, i
));
3364 fieldset
.appendChild(table
);
3370 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
3373 var vn
= parseInt(this.options
.value
) || 0;
3374 var mn
= parseInt(this.options
.max
) || 100;
3375 var pc
= Math
.floor((100 / mn
) * vn
);
3379 if (typeof(this.options
.format
) == 'string')
3380 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
3381 else if (typeof(this.options
.format
) == 'function')
3382 text
= this.options
.format(pc
);
3384 text
= '%.2f%%'.format(pc
);
3387 .addClass('progress')
3388 .append($('<div />')
3389 .addClass('progress-bar')
3390 .addClass('progress-bar-info')
3391 .css('width', pc
+ '%'))
3392 .append($('<small />')
3397 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
3400 var l2dev
= this.options
.l2_device
|| this.options
.device
;
3401 var l3dev
= this.options
.l3_device
;
3402 var dev
= l3dev
|| l2dev
|| '?';
3404 var span
= document
.createElement('span');
3405 span
.className
= 'badge';
3407 if (typeof(this.options
.signal
) == 'number' ||
3408 typeof(this.options
.noise
) == 'number')
3411 if (typeof(this.options
.signal
) != 'undefined' &&
3412 typeof(this.options
.noise
) != 'undefined')
3414 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
3427 span
.appendChild(document
.createElement('img'));
3428 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
3431 span
.title
= _luci2
.tr('No signal');
3433 span
.title
= '%s: %d %s / %s: %d %s'.format(
3434 _luci2
.tr('Signal'), this.options
.signal
, _luci2
.tr('dBm'),
3435 _luci2
.tr('Noise'), this.options
.noise
, _luci2
.tr('dBm')
3440 var type
= 'ethernet';
3441 var desc
= _luci2
.tr('Ethernet device');
3446 desc
= _luci2
.tr('Tunnel interface');
3448 else if (dev
.indexOf('br-') == 0)
3451 desc
= _luci2
.tr('Bridge');
3453 else if (dev
.indexOf('.') > 0)
3456 desc
= _luci2
.tr('VLAN interface');
3458 else if (dev
.indexOf('wlan') == 0 ||
3459 dev
.indexOf('ath') == 0 ||
3460 dev
.indexOf('wl') == 0)
3463 desc
= _luci2
.tr('Wireless Network');
3466 span
.appendChild(document
.createElement('img'));
3467 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
3471 $(span
).append(' ');
3472 $(span
).append(dev
);
3478 var type = function(f
, l
)
3488 _luci2
.cbi
.validation
.message
= _luci2
.tr(msg
);
3491 compile: function(code
)
3496 var types
= _luci2
.cbi
.validation
.types
;
3501 for (var i
= 0; i
< code
.length
; i
++)
3509 switch (code
.charCodeAt(i
))
3521 var label
= code
.substring(pos
, i
);
3522 label
= label
.replace(/\\(.)/g, '$1');
3523 label
= label
.replace(/^[ \t]+/g, '');
3524 label
= label
.replace(/[ \t]+$/g, '');
3526 if (label
&& !isNaN(label
))
3528 stack
.push(parseFloat(label
));
3530 else if (label
.match(/^(['"]).*\1$/))
3532 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
3534 else if (typeof types
[label
] == 'function')
3536 stack
.push(types
[label
]);
3541 throw "Syntax error, unhandled token '"+label
+"'";
3546 depth
+= (code
.charCodeAt(i
) == 40);
3552 if (typeof stack
[stack
.length
-2] != 'function')
3553 throw "Syntax error, argument list follows non-function";
3555 stack
[stack
.length
-1] =
3556 _luci2
.cbi
.validation
.compile(code
.substring(pos
, i
));
3569 var validation
= this.cbi
.validation
;
3571 validation
.types
= {
3572 'integer': function()
3574 if (this.match(/^-?[0-9]+$/) != null)
3577 validation
.i18n('Must be a valid integer');
3581 'uinteger': function()
3583 if (validation
.types
['integer'].apply(this) && (this >= 0))
3586 validation
.i18n('Must be a positive integer');
3592 if (!isNaN(parseFloat(this)))
3595 validation
.i18n('Must be a valid number');
3599 'ufloat': function()
3601 if (validation
.types
['float'].apply(this) && (this >= 0))
3604 validation
.i18n('Must be a positive number');
3608 'ipaddr': function()
3610 if (validation
.types
['ip4addr'].apply(this) ||
3611 validation
.types
['ip6addr'].apply(this))
3614 validation
.i18n('Must be a valid IP address');
3618 'ip4addr': function()
3620 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
3622 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
3623 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
3624 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
3625 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
3626 ((RegExp
.$6.indexOf('.') < 0)
3627 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
3628 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
3632 validation
.i18n('Must be a valid IPv4 address');
3636 'ip6addr': function()
3638 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
3640 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
3642 var addr
= RegExp
.$1;
3649 if (addr
.indexOf('.') > 0)
3651 var off
= addr
.lastIndexOf(':');
3653 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
3655 validation
.i18n('Must be a valid IPv6 address');
3659 addr
= addr
.substr(0, off
) + ':0:0';
3662 if (addr
.indexOf('::') >= 0)
3667 for (var i
= 1; i
< (addr
.length
-1); i
++)
3668 if (addr
.charAt(i
) == ':')
3673 validation
.i18n('Must be a valid IPv6 address');
3677 for (var i
= 0; i
< (7 - colons
); i
++)
3680 if (addr
.match(/^(.*?)::(.*?)$/))
3681 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
3682 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
3685 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3688 validation
.i18n('Must be a valid IPv6 address');
3693 validation
.i18n('Must be a valid IPv6 address');
3699 if (validation
.types
['integer'].apply(this) &&
3700 (this >= 0) && (this <= 65535))
3703 validation
.i18n('Must be a valid port number');
3707 'portrange': function()
3709 if (this.match(/^(\d+)-(\d+)$/))
3714 if (validation
.types
['port'].apply(p1
) &&
3715 validation
.types
['port'].apply(p2
) &&
3716 (parseInt(p1
) <= parseInt(p2
)))
3719 else if (validation
.types
['port'].apply(this))
3724 validation
.i18n('Must be a valid port range');
3728 'macaddr': function()
3730 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3733 validation
.i18n('Must be a valid MAC address');
3739 if (validation
.types
['hostname'].apply(this) ||
3740 validation
.types
['ipaddr'].apply(this))
3743 validation
.i18n('Must be a valid hostname or IP address');
3747 'hostname': function()
3749 if ((this.length
<= 253) &&
3750 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3751 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3752 this.match(/[^0-9.]/)))))
3755 validation
.i18n('Must be a valid host name');
3759 'network': function()
3761 if (validation
.types
['uciname'].apply(this) ||
3762 validation
.types
['host'].apply(this))
3765 validation
.i18n('Must be a valid network name');
3769 'wpakey': function()
3773 if ((v
.length
== 64)
3774 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
3775 : ((v
.length
>= 8) && (v
.length
<= 63)))
3778 validation
.i18n('Must be a valid WPA key');
3782 'wepkey': function()
3786 if (v
.substr(0,2) == 's:')
3789 if (((v
.length
== 10) || (v
.length
== 26))
3790 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
3791 : ((v
.length
== 5) || (v
.length
== 13)))
3794 validation
.i18n('Must be a valid WEP key');
3798 'uciname': function()
3800 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3803 validation
.i18n('Must be a valid UCI identifier');
3807 'range': function(min
, max
)
3809 var val
= parseFloat(this);
3811 if (validation
.types
['integer'].apply(this) &&
3812 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
3815 validation
.i18n('Must be a number between %d and %d');
3819 'min': function(min
)
3821 var val
= parseFloat(this);
3823 if (validation
.types
['integer'].apply(this) &&
3824 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
3827 validation
.i18n('Must be a number greater or equal to %d');
3831 'max': function(max
)
3833 var val
= parseFloat(this);
3835 if (validation
.types
['integer'].apply(this) &&
3836 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
3839 validation
.i18n('Must be a number lower or equal to %d');
3843 'rangelength': function(min
, max
)
3845 var val
= '' + this;
3847 if (!isNaN(min
) && !isNaN(max
) &&
3848 (val
.length
>= min
) && (val
.length
<= max
))
3851 validation
.i18n('Must be between %d and %d characters');
3855 'minlength': function(min
)
3857 var val
= '' + this;
3859 if (!isNaN(min
) && (val
.length
>= min
))
3862 validation
.i18n('Must be at least %d characters');
3866 'maxlength': function(max
)
3868 var val
= '' + this;
3870 if (!isNaN(max
) && (val
.length
<= max
))
3873 validation
.i18n('Must be at most %d characters');
3881 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3883 delete validation
.message
;
3885 if (typeof(arguments
[i
]) != 'function')
3887 if (arguments
[i
] == this)
3891 else if (arguments
[i
].apply(this, arguments
[i
+1]))
3896 if (validation
.message
)
3897 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3900 validation
.message
= msgs
.join( _luci2
.tr(' - or - '));
3908 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3910 delete validation
.message
;
3912 if (typeof arguments
[i
] != 'function')
3914 if (arguments
[i
] != this)
3918 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
3923 if (validation
.message
)
3924 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3927 validation
.message
= msgs
.join(', ');
3933 return validation
.types
['or'].apply(
3934 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
3937 'list': function(subvalidator
, subargs
)
3939 if (typeof subvalidator
!= 'function')
3942 var tokens
= this.match(/[^ \t]+/g);
3943 for (var i
= 0; i
< tokens
.length
; i
++)
3944 if (!subvalidator
.apply(tokens
[i
], subargs
))
3950 'phonedigit': function()
3952 if (this.match(/^[0-9\*#!\.]+$/) != null)
3955 validation
.i18n('Must be a valid phone number digit');
3959 'string': function()
3966 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
3967 init: function(name
, options
)
3970 this.instance
= { };
3971 this.dependencies
= [ ];
3972 this.rdependency
= { };
3974 this.options
= _luci2
.defaults(options
, {
3984 return this.section
.id('field', sid
|| '__unknown__', this.name
);
3987 render: function(sid
, condensed
)
3989 var i
= this.instance
[sid
] = { };
3991 i
.top
= $('<div />');
3995 i
.top
.addClass('form-group');
3997 if (typeof(this.options
.caption
) == 'string')
3999 .addClass('col-lg-2 control-label')
4000 .attr('for', this.id(sid
))
4001 .text(this.options
.caption
)
4005 i
.error
= $('<div />')
4007 .addClass('label label-danger');
4009 i
.widget
= $('<div />')
4011 .append(this.widget(sid
))
4017 i
.widget
.addClass('col-lg-5');
4020 .addClass('col-lg-5')
4021 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
4028 ucipath: function(sid
)
4031 config
: (this.options
.uci_package
|| this.map
.uci_package
),
4032 section
: (this.options
.uci_section
|| sid
),
4033 option
: (this.options
.uci_option
|| this.name
)
4037 ucivalue: function(sid
)
4039 var uci
= this.ucipath(sid
);
4040 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
4042 if (typeof(val
) == 'undefined')
4043 return this.options
.initial
;
4048 formvalue: function(sid
)
4050 var v
= $('#' + this.id(sid
)).val();
4051 return (v
=== '') ? undefined : v
;
4054 textvalue: function(sid
)
4056 var v
= this.formvalue(sid
);
4058 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
4059 v
= this.ucivalue(sid
);
4061 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
4062 v
= this.options
.placeholder
;
4064 if (typeof(v
) == 'undefined' || v
=== '')
4067 if (typeof(v
) == 'string' && $.isArray(this.choices
))
4069 for (var i
= 0; i
< this.choices
.length
; i
++)
4070 if (v
=== this.choices
[i
][0])
4071 return this.choices
[i
][1];
4073 else if (v
=== true)
4074 return _luci2
.tr('yes');
4075 else if (v
=== false)
4076 return _luci2
.tr('no');
4077 else if ($.isArray(v
))
4078 return v
.join(', ');
4083 changed: function(sid
)
4085 var a
= this.ucivalue(sid
);
4086 var b
= this.formvalue(sid
);
4088 if (typeof(a
) != typeof(b
))
4091 if (typeof(a
) == 'object')
4093 if (a
.length
!= b
.length
)
4096 for (var i
= 0; i
< a
.length
; i
++)
4108 var uci
= this.ucipath(sid
);
4110 if (this.instance
[sid
].disabled
)
4112 if (!this.options
.keep
)
4113 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
4118 var chg
= this.changed(sid
);
4119 var val
= this.formvalue(sid
);
4122 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
4127 _ev_validate: function(ev
)
4131 var val
= d
.elem
.val();
4132 var vstack
= d
.vstack
;
4134 if (vstack
&& typeof(vstack
[0]) == 'function')
4136 delete validation
.message
;
4138 if ((val
.length
== 0 && !d
.opt
))
4140 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
4141 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
4143 d
.inst
.error
.text(_luci2
.tr('Field must not be empty')).show();
4146 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
4148 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
4149 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
4151 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1])).show();
4156 d
.elem
.parents('div.form-group, td').first().removeClass('luci2-form-error');
4157 d
.elem
.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
4159 if (d
.multi
&& d
.inst
.widget
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
4162 d
.inst
.error
.text('').hide();
4167 for (var field
in d
.self
.rdependency
)
4168 d
.self
.rdependency
[field
].toggle(d
.sid
);
4173 validator: function(sid
, elem
, multi
)
4175 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
4179 if (typeof(this.options
.datatype
) == 'string')
4182 vstack
= _luci2
.cbi
.validation
.compile(this.options
.datatype
);
4185 else if (typeof(this.options
.datatype
) == 'function')
4187 var vfunc
= this.options
.datatype
;
4188 vstack
= [ function(elem
) {
4189 var rv
= vfunc(this, elem
);
4191 validation
.message
= rv
;
4192 return (rv
=== true);
4202 inst
: this.instance
[sid
],
4203 opt
: this.options
.optional
4206 if (elem
.prop('tagName') == 'SELECT')
4208 elem
.change(evdata
, this._ev_validate
);
4210 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
4212 elem
.click(evdata
, this._ev_validate
);
4213 elem
.blur(evdata
, this._ev_validate
);
4217 elem
.keyup(evdata
, this._ev_validate
);
4218 elem
.blur(evdata
, this._ev_validate
);
4221 elem
.attr('cbi-validate', true).on('validate', evdata
, this._ev_validate
);
4226 validate: function(sid
)
4228 var i
= this.instance
[sid
];
4230 i
.widget
.find('[cbi-validate]').trigger('validate');
4232 return (i
.disabled
|| i
.error
.text() == '');
4235 depends: function(d
, v
)
4242 for (var i
= 0; i
< d
.length
; i
++)
4244 if (typeof(d
[i
]) == 'string')
4246 else if (d
[i
] instanceof _luci2
.cbi
.AbstractValue
)
4247 dep
[d
[i
].name
] = true;
4250 else if (d
instanceof _luci2
.cbi
.AbstractValue
)
4253 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
4255 else if (typeof(d
) == 'object')
4259 else if (typeof(d
) == 'string')
4262 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
4265 if (!dep
|| $.isEmptyObject(dep
))
4268 for (var field
in dep
)
4270 var f
= this.section
.fields
[field
];
4272 f
.rdependency
[this.name
] = this;
4277 if ($.isEmptyObject(dep
))
4280 this.dependencies
.push(dep
);
4285 toggle: function(sid
)
4287 var d
= this.dependencies
;
4288 var i
= this.instance
[sid
];
4293 for (var n
= 0; n
< d
.length
; n
++)
4297 for (var field
in d
[n
])
4299 var val
= this.section
.fields
[field
].formvalue(sid
);
4300 var cmp
= d
[n
][field
];
4302 if (typeof(cmp
) == 'boolean')
4304 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
4310 else if (typeof(cmp
) == 'string')
4318 else if (typeof(cmp
) == 'function')
4326 else if (cmp
instanceof RegExp
)
4351 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
4358 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
4359 widget: function(sid
)
4361 var o
= this.options
;
4363 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
4364 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
4366 var i
= $('<input />')
4367 .attr('id', this.id(sid
))
4368 .attr('type', 'checkbox')
4369 .prop('checked', this.ucivalue(sid
));
4372 .addClass('checkbox')
4373 .append(this.validator(sid
, i
));
4376 ucivalue: function(sid
)
4378 var v
= this.callSuper('ucivalue', sid
);
4380 if (typeof(v
) == 'boolean')
4383 return (v
== this.options
.enabled
);
4386 formvalue: function(sid
)
4388 var v
= $('#' + this.id(sid
)).prop('checked');
4390 if (typeof(v
) == 'undefined')
4391 return !!this.options
.initial
;
4398 var uci
= this.ucipath(sid
);
4400 if (this.instance
[sid
].disabled
)
4402 if (!this.options
.keep
)
4403 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
4408 var chg
= this.changed(sid
);
4409 var val
= this.formvalue(sid
);
4413 if (this.options
.optional
&& val
== this.options
.initial
)
4414 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
4416 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
4423 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
4424 widget: function(sid
)
4426 var i
= $('<input />')
4427 .addClass('form-control')
4428 .attr('id', this.id(sid
))
4429 .attr('type', 'text')
4430 .attr('placeholder', this.options
.placeholder
)
4431 .val(this.ucivalue(sid
));
4433 return this.validator(sid
, i
);
4437 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
4438 widget: function(sid
)
4440 var i
= $('<input />')
4441 .addClass('form-control')
4442 .attr('id', this.id(sid
))
4443 .attr('type', 'password')
4444 .attr('placeholder', this.options
.placeholder
)
4445 .val(this.ucivalue(sid
));
4447 var t
= $('<span />')
4448 .addClass('input-group-btn')
4449 .append(_luci2
.ui
.button(_luci2
.tr('Reveal'), 'default')
4450 .click(function(ev
) {
4452 var i
= b
.parent().prev();
4453 var t
= i
.attr('type');
4454 b
.text(t
== 'password' ? _luci2
.tr('Hide') : _luci2
.tr('Reveal'));
4455 i
.attr('type', (t
== 'password') ? 'text' : 'password');
4459 this.validator(sid
, i
);
4462 .addClass('input-group')
4468 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
4469 widget: function(sid
)
4471 var s
= $('<select />')
4472 .addClass('form-control');
4474 if (this.options
.optional
)
4477 .text(_luci2
.tr('-- Please choose --'))
4481 for (var i
= 0; i
< this.choices
.length
; i
++)
4483 .attr('value', this.choices
[i
][0])
4484 .text(this.choices
[i
][1])
4487 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
4489 return this.validator(sid
, s
);
4492 value: function(k
, v
)
4497 this.choices
.push([k
, v
|| k
]);
4502 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
4503 widget: function(sid
)
4505 var v
= this.ucivalue(sid
);
4506 var t
= $('<div />').attr('id', this.id(sid
));
4509 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4512 for (var i
= 0; i
< v
.length
; i
++)
4516 for (var i
= 0; i
< this.choices
.length
; i
++)
4519 .addClass('checkbox')
4520 .append($('<input />')
4521 .attr('type', 'checkbox')
4522 .attr('value', this.choices
[i
][0])
4523 .prop('checked', s
[this.choices
[i
][0]]))
4524 .append(this.choices
[i
][1])
4531 formvalue: function(sid
)
4534 var fields
= $('#' + this.id(sid
) + ' > label > input');
4536 for (var i
= 0; i
< fields
.length
; i
++)
4537 if (fields
[i
].checked
)
4538 rv
.push(fields
[i
].getAttribute('value'));
4543 textvalue: function(sid
)
4545 var v
= this.formvalue(sid
);
4549 for (var i
= 0; i
< this.choices
.length
; i
++)
4550 c
[this.choices
[i
][0]] = this.choices
[i
][1];
4554 for (var i
= 0; i
< v
.length
; i
++)
4555 t
.push(c
[v
[i
]] || v
[i
]);
4557 return t
.join(', ');
4561 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
4562 _change: function(ev
)
4565 var self
= ev
.data
.self
;
4567 if (s
.selectedIndex
== (s
.options
.length
- 1))
4569 ev
.data
.select
.hide();
4570 ev
.data
.input
.show().focus();
4572 var v
= ev
.data
.input
.val();
4573 ev
.data
.input
.val(' ');
4574 ev
.data
.input
.val(v
);
4576 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
4578 ev
.data
.input
.val('');
4582 ev
.data
.input
.val(ev
.data
.select
.val());
4589 var val
= this.value
;
4590 var self
= ev
.data
.self
;
4592 ev
.data
.select
.empty();
4594 if (self
.options
.optional
)
4597 .text(_luci2
.tr('-- please choose --'))
4598 .appendTo(ev
.data
.select
);
4601 for (var i
= 0; i
< self
.choices
.length
; i
++)
4603 if (self
.choices
[i
][0] == val
)
4607 .attr('value', self
.choices
[i
][0])
4608 .text(self
.choices
[i
][1])
4609 .appendTo(ev
.data
.select
);
4612 if (!seen
&& val
!= '')
4616 .appendTo(ev
.data
.select
);
4620 .text(_luci2
.tr('-- custom --'))
4621 .appendTo(ev
.data
.select
);
4623 ev
.data
.input
.hide();
4624 ev
.data
.select
.val(val
).show().focus();
4627 _enter: function(ev
)
4632 ev
.preventDefault();
4633 ev
.data
.self
._blur(ev
);
4637 widget: function(sid
)
4639 var d
= $('<div />')
4640 .attr('id', this.id(sid
));
4642 var t
= $('<input />')
4643 .attr('type', 'text')
4647 var s
= $('<select />')
4652 input
: this.validator(sid
, t
),
4653 select
: this.validator(sid
, s
)
4656 s
.change(evdata
, this._change
);
4657 t
.blur(evdata
, this._blur
);
4658 t
.keydown(evdata
, this._enter
);
4660 t
.val(this.ucivalue(sid
));
4666 value: function(k
, v
)
4671 this.choices
.push([k
, v
|| k
]);
4675 formvalue: function(sid
)
4677 var v
= $('#' + this.id(sid
)).children('input').val();
4678 return (v
== '') ? undefined : v
;
4682 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
4683 _redraw: function(focus
, add
, del
, s
)
4685 var v
= s
.values
|| [ ];
4688 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
4690 v
.push(this.value
|| '');
4693 $(s
.parent
).empty();
4698 v
.splice(focus
, 0, '');
4700 else if (v
.length
== 0)
4706 for (var i
= 0; i
< v
.length
; i
++)
4713 remove
: ((i
+1) < v
.length
)
4718 btn
= _luci2
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
4720 btn
= _luci2
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
4724 var txt
= $('<input />')
4725 .addClass('form-control')
4726 .attr('type', 'text')
4729 var sel
= $('<select />')
4730 .addClass('form-control');
4733 .addClass('input-group')
4736 .append($('<span />')
4737 .addClass('input-group-btn')
4739 .appendTo(s
.parent
);
4741 evdata
.input
= this.validator(s
.sid
, txt
, true);
4742 evdata
.select
= this.validator(s
.sid
, sel
, true);
4744 sel
.change(evdata
, this._change
);
4745 txt
.blur(evdata
, this._blur
);
4746 txt
.keydown(evdata
, this._keydown
);
4751 if (i
== focus
|| -(i
+1) == focus
)
4758 var f
= $('<input />')
4759 .attr('type', 'text')
4761 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
4762 .addClass('form-control')
4763 .keydown(evdata
, this._keydown
)
4764 .keypress(evdata
, this._keypress
)
4768 .addClass('input-group')
4770 .append($('<span />')
4771 .addClass('input-group-btn')
4773 .appendTo(s
.parent
);
4779 else if (-(i
+1) == focus
)
4783 /* force cursor to end */
4789 evdata
.input
= this.validator(s
.sid
, f
, true);
4800 _keypress: function(ev
)
4804 /* backspace, delete */
4807 if (ev
.data
.input
.val() == '')
4809 ev
.preventDefault();
4815 /* enter, arrow up, arrow down */
4819 ev
.preventDefault();
4826 _keydown: function(ev
)
4828 var input
= ev
.data
.input
;
4832 /* backspace, delete */
4835 if (input
.val().length
== 0)
4837 ev
.preventDefault();
4839 var index
= ev
.data
.index
;
4845 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
4853 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4858 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
4859 if (prev
.is(':visible'))
4862 prev
.next('select').focus();
4867 var next
= input
.parent().nextAll('div.input-group:first').children('input');
4868 if (next
.is(':visible'))
4871 next
.next('select').focus();
4878 _btnclick: function(ev
)
4880 if (!this.getAttribute('disabled'))
4884 var index
= ev
.data
.index
;
4885 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
4889 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4896 widget: function(sid
)
4898 this.options
.optional
= true;
4900 var v
= this.ucivalue(sid
);
4903 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4905 var d
= $('<div />')
4906 .attr('id', this.id(sid
))
4907 .addClass('cbi-input-dynlist');
4909 this._redraw(NaN
, -1, -1, {
4919 ucivalue: function(sid
)
4921 var v
= this.callSuper('ucivalue', sid
);
4924 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4929 formvalue: function(sid
)
4932 var fields
= $('#' + this.id(sid
) + ' > input');
4934 for (var i
= 0; i
< fields
.length
; i
++)
4935 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
4936 rv
.push(fields
[i
].value
);
4942 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
4943 widget: function(sid
)
4946 .addClass('form-control-static')
4947 .attr('id', this.id(sid
))
4948 .html(this.ucivalue(sid
));
4951 formvalue: function(sid
)
4953 return this.ucivalue(sid
);
4957 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
4962 if (!self
.interfaces
)
4964 self
.interfaces
= [ ];
4965 return _luci2
.network
.getNetworkStatus().then(function(ifaces
) {
4966 self
.interfaces
= ifaces
;
4974 _device_icon: function(dev
)
4976 var type
= 'ethernet';
4977 var desc
= _luci2
.tr('Ethernet device');
4979 if (dev
.type
== 'IP tunnel')
4982 desc
= _luci2
.tr('Tunnel interface');
4984 else if (dev
['bridge-members'])
4987 desc
= _luci2
.tr('Bridge');
4989 else if (dev
.wireless
)
4992 desc
= _luci2
.tr('Wireless Network');
4994 else if (dev
.device
.indexOf('.') > 0)
4997 desc
= _luci2
.tr('VLAN interface');
5001 .attr('src', _luci2
.globals
.resource
+ '/icons/' + type
+ (dev
.up
? '' : '_disabled') + '.png')
5002 .attr('title', '%s (%s)'.format(desc
, dev
.device
));
5005 widget: function(sid
)
5007 var id
= this.id(sid
);
5008 var ul
= $('<ul />')
5010 .addClass('list-unstyled');
5012 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
5013 var value
= this.ucivalue(sid
);
5016 if (!this.options
.multiple
)
5017 check
[value
] = true;
5019 for (var i
= 0; i
< value
.length
; i
++)
5020 check
[value
[i
]] = true;
5022 if (this.interfaces
)
5024 for (var i
= 0; i
< this.interfaces
.length
; i
++)
5026 var iface
= this.interfaces
[i
];
5027 var badge
= $('<span />')
5029 .text('%s: '.format(iface
['interface']));
5031 if (iface
.device
&& iface
.device
.subdevices
)
5032 for (var j
= 0; j
< iface
.device
.subdevices
.length
; j
++)
5033 badge
.append(this._device_icon(iface
.device
.subdevices
[j
]));
5034 else if (iface
.device
)
5035 badge
.append(this._device_icon(iface
.device
));
5037 badge
.append($('<em />').text(_luci2
.tr('(No devices attached)')));
5040 .append($('<label />')
5041 .addClass(itype
+ ' inline')
5042 .append($('<input />')
5043 .attr('name', itype
+ id
)
5044 .attr('type', itype
)
5045 .attr('value', iface
['interface'])
5046 .prop('checked', !!check
[iface
['interface']]))
5052 if (!this.options
.multiple
)
5055 .append($('<label />')
5056 .addClass(itype
+ ' inline text-muted')
5057 .append($('<input />')
5058 .attr('name', itype
+ id
)
5059 .attr('type', itype
)
5061 .prop('checked', !value
))
5062 .append(_luci2
.tr('unspecified')))
5069 ucivalue: function(sid
)
5071 var v
= this.callSuper('ucivalue', sid
);
5073 if (!this.options
.multiple
)
5079 else if (typeof(v
) == 'string')
5082 return v
? v
[0] : undefined;
5089 if (typeof(v
) == 'string')
5090 v
= v
.match(/\S+/g);
5096 formvalue: function(sid
)
5098 var inputs
= $('#' + this.id(sid
) + ' input');
5100 if (!this.options
.multiple
)
5102 for (var i
= 0; i
< inputs
.length
; i
++)
5103 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
5104 return inputs
[i
].value
;
5111 for (var i
= 0; i
< inputs
.length
; i
++)
5112 if (inputs
[i
].checked
)
5113 rv
.push(inputs
[i
].value
);
5115 return rv
.length
? rv
: undefined;
5120 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
5123 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
5125 for (var i
= 1; i
< arguments
.length
; i
++)
5126 s
.push(arguments
[i
].replace(/\./g, '_'));
5131 option: function(widget
, name
, options
)
5133 if (this.tabs
.length
== 0)
5134 this.tab({ id
: '__default__', selected
: true });
5136 return this.taboption('__default__', widget
, name
, options
);
5139 tab: function(options
)
5141 if (options
.selected
)
5142 this.tabs
.selected
= this.tabs
.length
;
5146 caption
: options
.caption
,
5147 description
: options
.description
,
5153 taboption: function(tabid
, widget
, name
, options
)
5156 for (var i
= 0; i
< this.tabs
.length
; i
++)
5158 if (this.tabs
[i
].id
== tabid
)
5166 throw 'Cannot append to unknown tab ' + tabid
;
5168 var w
= widget
? new widget(name
, options
) : null;
5170 if (!(w
instanceof _luci2
.cbi
.AbstractValue
))
5171 throw 'Widget must be an instance of AbstractValue';
5176 this.fields
[name
] = w
;
5182 ucipackages: function(pkg
)
5184 for (var i
= 0; i
< this.tabs
.length
; i
++)
5185 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
5186 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
5187 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
5190 formvalue: function()
5194 this.sections(function(s
) {
5195 var sid
= s
['.name'];
5196 var sv
= rv
[sid
] || (rv
[sid
] = { });
5198 for (var i
= 0; i
< this.tabs
.length
; i
++)
5199 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
5201 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
5202 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
5209 validate_section: function(sid
)
5211 var inst
= this.instance
[sid
];
5214 var badge
= $('#' + this.id('teaser', sid
)).children('span:first');
5216 for (var i
= 0; i
< this.tabs
.length
; i
++)
5219 var stbadge
= $('#' + this.id('nodetab', sid
, this.tabs
[i
].id
)).children('span:first');
5221 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
5222 if (!this.tabs
[i
].fields
[j
].validate(sid
))
5228 .attr('title', _luci2
.trp('1 Error', '%d Errors', inval
).format(inval
));
5238 .attr('title', _luci2
.trp('1 Error', '%d Errors', invals
).format(invals
));
5245 validate: function()
5247 this.error_count
= 0;
5249 var as
= this.sections();
5251 for (var i
= 0; i
< as
.length
; i
++)
5253 var invals
= this.validate_section(as
[i
]['.name']);
5256 this.error_count
+= invals
;
5259 var badge
= $('#' + this.id('sectiontab')).children('span:first');
5261 if (this.error_count
> 0)
5263 .text(this.error_count
)
5264 .attr('title', _luci2
.trp('1 Error', '%d Errors', this.error_count
).format(this.error_count
));
5268 return (this.error_count
== 0);
5272 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
5273 init: function(uci_type
, options
)
5275 this.uci_type
= uci_type
;
5276 this.options
= options
;
5279 this.error_count
= 0;
5280 this.active_panel
= 0;
5281 this.active_tab
= { };
5284 filter: function(section
)
5289 sections: function(cb
)
5291 var s1
= this.map
.ucisections(this.map
.uci_package
);
5294 for (var i
= 0; i
< s1
.length
; i
++)
5295 if (s1
[i
]['.type'] == this.uci_type
)
5296 if (this.filter(s1
[i
]))
5299 if (typeof(cb
) == 'function')
5300 for (var i
= 0; i
< s2
.length
; i
++)
5301 cb
.apply(this, [ s2
[i
] ]);
5308 this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
5311 remove: function(sid
)
5313 this.map
.remove(this.map
.uci_package
, sid
);
5316 _ev_add: function(ev
)
5319 var name
= undefined;
5320 var self
= ev
.data
.self
;
5322 if (addb
.prev().prop('nodeName') == 'INPUT')
5323 name
= addb
.prev().val();
5325 if (addb
.prop('disabled') || name
=== '')
5328 _luci2
.ui
.saveScrollTop();
5330 self
.active_panel
= -1;
5335 _luci2
.ui
.restoreScrollTop();
5338 _ev_remove: function(ev
)
5340 var self
= ev
.data
.self
;
5341 var sid
= ev
.data
.sid
;
5343 _luci2
.ui
.saveScrollTop();
5349 _luci2
.ui
.restoreScrollTop();
5351 ev
.stopPropagation();
5354 _ev_sid: function(ev
)
5356 var self
= ev
.data
.self
;
5358 var addb
= text
.next();
5359 var errt
= addb
.next();
5360 var name
= text
.val();
5363 if (!/^[a-zA-Z0-9_]*$/.test(name
))
5365 errt
.text(_luci2
.tr('Invalid section name')).show();
5366 text
.addClass('error');
5367 addb
.prop('disabled', true);
5371 for (var sid
in self
.map
.uci
.values
[self
.map
.uci_package
])
5378 for (var sid
in self
.map
.uci
.creates
[self
.map
.uci_package
])
5387 errt
.text(_luci2
.tr('Name already used')).show();
5388 text
.addClass('error');
5389 addb
.prop('disabled', true);
5393 errt
.text('').hide();
5394 text
.removeClass('error');
5395 addb
.prop('disabled', false);
5399 _ev_tab: function(ev
)
5401 var self
= ev
.data
.self
;
5402 var sid
= ev
.data
.sid
;
5405 self
.active_tab
[sid
] = parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
5408 _ev_panel_collapse: function(ev
)
5410 var self
= ev
.data
.self
;
5412 var this_panel
= $(ev
.target
);
5413 var this_toggle
= this_panel
.prevAll('[data-toggle="collapse"]:first');
5415 var prev_toggle
= $($(ev
.delegateTarget
).find('[data-toggle="collapse"]:eq(%d)'.format(self
.active_panel
)));
5416 var prev_panel
= $(prev_toggle
.attr('data-target'));
5420 .addClass('collapse');
5422 prev_toggle
.find('.luci2-section-teaser')
5424 .children('span:last')
5426 .append(self
.teaser(prev_panel
.attr('data-luci2-sid')));
5428 this_toggle
.find('.luci2-section-teaser')
5431 self
.active_panel
= parseInt(this_panel
.attr('data-luci2-panel-index'));
5435 _ev_panel_open: function(ev
)
5437 var self
= ev
.data
.self
;
5438 var panel
= $($(this).attr('data-target'));
5439 var index
= parseInt(panel
.attr('data-luci2-panel-index'));
5441 if (index
== self
.active_panel
)
5442 ev
.stopPropagation();
5445 _ev_sort: function(ev
)
5447 var self
= ev
.data
.self
;
5448 var cur_idx
= ev
.data
.index
;
5449 var new_idx
= cur_idx
+ (ev
.data
.up
? -1 : 1);
5450 var s
= self
.sections();
5452 if (new_idx
>= 0 && new_idx
< s
.length
)
5454 var tmp
= s
[cur_idx
]['.index'];
5456 s
[cur_idx
]['.index'] = s
[new_idx
]['.index'];
5457 s
[new_idx
]['.index'] = tmp
;
5459 if (self
.active_panel
== cur_idx
)
5460 self
.active_panel
= new_idx
;
5461 else if (self
.active_panel
== new_idx
)
5462 self
.active_panel
= cur_idx
;
5464 self
.map
.uci
.reorder
= true;
5470 ev
.stopPropagation();
5473 teaser: function(sid
)
5475 var tf
= this.teaser_fields
;
5479 tf
= this.teaser_fields
= [ ];
5481 if ($.isArray(this.options
.teasers
))
5483 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
5485 var f
= this.options
.teasers
[i
];
5486 if (f
instanceof _luci2
.cbi
.AbstractValue
)
5488 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof _luci2
.cbi
.AbstractValue
)
5489 tf
.push(this.fields
[f
]);
5494 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
5495 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
5496 tf
.push(this.tabs
[i
].fields
[j
]);
5502 for (var i
= 0; i
< tf
.length
; i
++)
5504 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
5507 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
5508 var v
= tf
[i
].textvalue(sid
);
5510 if (typeof(v
) == 'undefined')
5513 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
5519 _render_add: function()
5521 if (!this.options
.addremove
)
5524 var text
= _luci2
.tr('Add section');
5525 var ttip
= _luci2
.tr('Create new section...');
5527 if ($.isArray(this.options
.add_caption
))
5528 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
5529 else if (typeof(this.options
.add_caption
) == 'string')
5530 text
= this.options
.add_caption
, ttip
= '';
5532 var add
= $('<div />');
5534 if (this.options
.anonymous
=== false)
5537 .addClass('cbi-input-text')
5538 .attr('type', 'text')
5539 .attr('placeholder', ttip
)
5540 .blur({ self
: this }, this._ev_sid
)
5541 .keyup({ self
: this }, this._ev_sid
)
5545 .attr('src', _luci2
.globals
.resource
+ '/icons/cbi/add.gif')
5546 .attr('title', text
)
5547 .addClass('cbi-button')
5548 .click({ self
: this }, this._ev_add
)
5552 .addClass('cbi-value-error')
5558 _luci2
.ui
.button(text
, 'success', ttip
)
5559 .click({ self
: this }, this._ev_add
)
5566 _render_remove: function(sid
, index
)
5568 if (!this.options
.addremove
)
5571 var text
= _luci2
.tr('Remove');
5572 var ttip
= _luci2
.tr('Remove this section');
5574 if ($.isArray(this.options
.remove_caption
))
5575 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
5576 else if (typeof(this.options
.remove_caption
) == 'string')
5577 text
= this.options
.remove_caption
, ttip
= '';
5579 return _luci2
.ui
.button(text
, 'danger', ttip
)
5580 .click({ self
: this, sid
: sid
, index
: index
}, this._ev_remove
);
5583 _render_sort: function(sid
, index
)
5585 if (!this.options
.sortable
)
5588 var b1
= _luci2
.ui
.button('↑', 'info', _luci2
.tr('Move up'))
5589 .click({ self
: this, index
: index
, up
: true }, this._ev_sort
);
5591 var b2
= _luci2
.ui
.button('↓', 'info', _luci2
.tr('Move down'))
5592 .click({ self
: this, index
: index
, up
: false }, this._ev_sort
);
5597 _render_caption: function()
5600 .addClass('panel-title')
5601 .append(this.label('caption') || this.uci_type
);
5604 _render_description: function()
5606 var text
= this.label('description');
5610 .addClass('luci2-section-description')
5616 _render_teaser: function(sid
, index
)
5618 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5621 .attr('id', this.id('teaser', sid
))
5622 .addClass('luci2-section-teaser well well-sm')
5623 .append($('<span />')
5625 .append($('<span />'));
5631 _render_head: function(condensed
)
5637 .addClass('panel-heading')
5638 .append(this._render_caption())
5639 .append(this._render_description());
5642 _render_tab_description: function(sid
, index
, tab_index
)
5644 var tab
= this.tabs
[tab_index
];
5646 if (typeof(tab
.description
) == 'string')
5649 .addClass('cbi-tab-descr')
5650 .text(tab
.description
);
5656 _render_tab_head: function(sid
, index
, tab_index
)
5658 var tab
= this.tabs
[tab_index
];
5659 var cur
= this.active_tab
[sid
] || 0;
5661 var tabh
= $('<li />')
5663 .attr('id', this.id('nodetab', sid
, tab
.id
))
5664 .attr('href', '#' + this.id('node', sid
, tab
.id
))
5665 .attr('data-toggle', 'tab')
5666 .attr('data-luci2-tab-index', tab_index
)
5667 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
5668 .append($('<span />')
5670 .on('shown.bs.tab', { self
: this, sid
: sid
}, this._ev_tab
));
5672 if (cur
== tab_index
)
5673 tabh
.addClass('active');
5678 _render_tab_body: function(sid
, index
, tab_index
)
5680 var tab
= this.tabs
[tab_index
];
5681 var cur
= this.active_tab
[sid
] || 0;
5683 var tabb
= $('<div />')
5684 .addClass('tab-pane')
5685 .attr('id', this.id('node', sid
, tab
.id
))
5686 .attr('data-luci2-tab-index', tab_index
)
5687 .append(this._render_tab_description(sid
, index
, tab_index
));
5689 if (cur
== tab_index
)
5690 tabb
.addClass('active');
5692 for (var i
= 0; i
< tab
.fields
.length
; i
++)
5693 tabb
.append(tab
.fields
[i
].render(sid
));
5698 _render_section_head: function(sid
, index
)
5700 var head
= $('<div />')
5701 .addClass('luci2-section-header')
5702 .append(this._render_teaser(sid
, index
))
5703 .append($('<div />')
5704 .addClass('btn-group')
5705 .append(this._render_sort(sid
, index
))
5706 .append(this._render_remove(sid
, index
)));
5708 if (this.options
.collabsible
)
5710 head
.attr('data-toggle', 'collapse')
5711 .attr('data-parent', this.id('sectiongroup'))
5712 .attr('data-target', '#' + this.id('panel', sid
))
5713 .on('click', { self
: this }, this._ev_panel_open
);
5719 _render_section_body: function(sid
, index
)
5721 var body
= $('<div />')
5722 .attr('id', this.id('panel', sid
))
5723 .attr('data-luci2-panel-index', index
)
5724 .attr('data-luci2-sid', sid
);
5726 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5728 body
.addClass('panel-collapse collapse');
5730 if (index
== this.active_panel
)
5731 body
.addClass('in');
5734 var tab_heads
= $('<ul />')
5735 .addClass('nav nav-tabs');
5737 var tab_bodies
= $('<div />')
5738 .addClass('form-horizontal tab-content')
5741 for (var j
= 0; j
< this.tabs
.length
; j
++)
5743 tab_heads
.append(this._render_tab_head(sid
, index
, j
));
5744 tab_bodies
.append(this._render_tab_body(sid
, index
, j
));
5747 body
.append(tab_bodies
);
5749 if (this.tabs
.length
<= 1)
5755 _render_body: function(condensed
)
5757 var s
= this.sections();
5759 if (this.active_panel
< 0)
5760 this.active_panel
+= s
.length
;
5761 else if (this.active_panel
>= s
.length
)
5762 this.active_panel
= s
.length
- 1;
5764 var body
= $('<ul />')
5765 .addClass('list-group');
5767 if (this.options
.collabsible
)
5769 body
.attr('id', this.id('sectiongroup'))
5770 .on('show.bs.collapse', { self
: this }, this._ev_panel_collapse
);
5775 body
.append($('<li />')
5776 .addClass('list-group-item text-muted')
5777 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.')))
5780 for (var i
= 0; i
< s
.length
; i
++)
5782 var sid
= s
[i
]['.name'];
5783 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5785 body
.append($('<li />')
5786 .addClass('list-group-item')
5787 .append(this._render_section_head(sid
, i
))
5788 .append(this._render_section_body(sid
, i
)));
5794 render: function(condensed
)
5796 this.instance
= { };
5798 var panel
= $('<div />')
5799 .addClass('panel panel-default')
5800 .append(this._render_head(condensed
))
5801 .append(this._render_body(condensed
));
5803 if (this.options
.addremove
)
5804 panel
.append($('<div />')
5805 .addClass('panel-footer')
5806 .append(this._render_add()));
5813 var s
= this.sections();
5815 for (var i
= 0; i
< s
.length
; i
++)
5817 var sid
= s
[i
]['.name'];
5819 this.validate_section(sid
);
5821 if (i
!= this.active_panel
)
5822 $('#' + this.id('teaser', sid
)).children('span:last')
5823 .append(this.teaser(sid
));
5825 $('#' + this.id('teaser', sid
))
5831 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
5832 _render_table_head: function()
5834 var thead
= $('<thead />')
5836 .addClass('cbi-section-table-titles'));
5838 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5839 thead
.children().append($('<th />')
5840 .addClass('cbi-section-table-cell')
5841 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5842 .append(this.tabs
[0].fields
[j
].label('caption')));
5844 if (this.options
.addremove
!== false || this.options
.sortable
)
5845 thead
.children().append($('<th />')
5846 .addClass('cbi-section-table-cell')
5852 _render_table_row: function(sid
, index
)
5854 var row
= $('<tr />')
5855 .attr('data-luci2-sid', sid
);
5857 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5859 row
.append($('<td />')
5860 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5861 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
5864 if (this.options
.addremove
!== false || this.options
.sortable
)
5866 row
.append($('<td />')
5867 .addClass('text-right')
5868 .append($('<div />')
5869 .addClass('btn-group')
5870 .append(this._render_sort(sid
, index
))
5871 .append(this._render_remove(sid
, index
))));
5877 _render_table_body: function()
5879 var s
= this.sections();
5881 var tbody
= $('<tbody />');
5885 var cols
= this.tabs
[0].fields
.length
;
5887 if (this.options
.addremove
!== false || this.options
.sortable
)
5890 tbody
.append($('<tr />')
5892 .addClass('text-muted')
5893 .attr('colspan', cols
)
5894 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.'))));
5897 for (var i
= 0; i
< s
.length
; i
++)
5899 var sid
= s
[i
]['.name'];
5900 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5902 tbody
.append(this._render_table_row(sid
, i
));
5908 _render_body: function(condensed
)
5910 return $('<table />')
5911 .addClass('table table-condensed table-hover')
5912 .append(this._render_table_head())
5913 .append(this._render_table_body());
5917 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
5918 sections: function(cb
)
5921 var pkg
= this.map
.uci
.values
[this.map
.uci_package
];
5924 if (pkg
[s
]['.name'] == this.uci_type
)
5930 if (typeof(cb
) == 'function' && sa
.length
> 0)
5931 cb
.apply(this, [ sa
[0] ]);
5937 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
5938 sections: function(cb
)
5940 if (typeof(cb
) == 'function')
5941 cb
.apply(this, [ { '.name': this.uci_type
} ]);
5943 return [ { '.name': this.uci_type
} ];
5947 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
5948 init: function(uci_package
, options
)
5952 this.uci_package
= uci_package
;
5953 this.sections
= [ ];
5954 this.options
= _luci2
.defaults(options
, {
5955 save: function() { },
5956 prepare: function() {
5957 return _luci2
.uci
.writable(function(writable
) {
5958 self
.options
.readonly
= !writable
;
5964 _load_cb: function(packages
)
5966 for (var i
= 0; i
< packages
.length
; i
++)
5968 this.uci
.values
[packages
[i
]['.package']] = packages
[i
];
5969 delete packages
[i
]['.package'];
5972 var deferreds
= [ _luci2
.deferrable(this.options
.prepare()) ];
5974 for (var i
= 0; i
< this.sections
.length
; i
++)
5976 for (var f
in this.sections
[i
].fields
)
5978 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
5981 var s
= this.sections
[i
].sections();
5982 for (var j
= 0; j
< s
.length
; j
++)
5984 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
5985 if (_luci2
.isDeferred(rv
))
5991 return $.when
.apply($, deferreds
);
6009 for (var i
= 0; i
< this.sections
.length
; i
++)
6010 this.sections
[i
].ucipackages(packages
);
6012 packages
[this.uci_package
] = true;
6016 for (var pkg
in packages
)
6017 _luci2
.uci
.get_all(pkg
);
6019 return _luci2
.rpc
.flush().then(function(packages
) {
6020 return self
._load_cb(packages
);
6024 _ev_tab: function(ev
)
6026 var self
= ev
.data
.self
;
6029 self
.active_tab
= parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
6032 _render_tab_head: function(tab_index
)
6034 var section
= this.sections
[tab_index
];
6035 var cur
= this.active_tab
|| 0;
6037 var tabh
= $('<li />')
6039 .attr('id', section
.id('sectiontab'))
6040 .attr('href', '#' + section
.id('section'))
6041 .attr('data-toggle', 'tab')
6042 .attr('data-luci2-tab-index', tab_index
)
6043 .text(section
.label('caption') + ' ')
6044 .append($('<span />')
6046 .on('shown.bs.tab', { self
: this }, this._ev_tab
));
6048 if (cur
== tab_index
)
6049 tabh
.addClass('active');
6054 _render_tab_body: function(tab_index
)
6056 var section
= this.sections
[tab_index
];
6057 var desc
= section
.label('description');
6058 var cur
= this.active_tab
|| 0;
6060 var tabb
= $('<div />')
6061 .addClass('tab-pane')
6062 .attr('id', section
.id('section'))
6063 .attr('data-luci2-tab-index', tab_index
);
6065 if (cur
== tab_index
)
6066 tabb
.addClass('active');
6069 tabb
.append($('<p />')
6072 var s
= section
.render(this.options
.tabbed
);
6074 if (this.options
.readonly
|| section
.options
.readonly
)
6075 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
6082 _render_body: function()
6084 var tabs
= $('<ul />')
6085 .addClass('nav nav-tabs');
6087 var body
= $('<div />')
6090 for (var i
= 0; i
< this.sections
.length
; i
++)
6092 tabs
.append(this._render_tab_head(i
));
6093 body
.append(this._render_tab_body(i
));
6096 if (this.options
.tabbed
)
6097 body
.addClass('tab-content');
6106 var map
= $('<form />');
6108 if (typeof(this.options
.caption
) == 'string')
6109 map
.append($('<h2 />')
6110 .text(this.options
.caption
));
6112 if (typeof(this.options
.description
) == 'string')
6113 map
.append($('<p />')
6114 .text(this.options
.description
));
6116 map
.append(this._render_body());
6118 if (this.options
.pageaction
!== false)
6120 map
.append($('<div />')
6121 .addClass('panel panel-default panel-body text-right')
6122 .append($('<div />')
6123 .addClass('btn-group')
6124 .append(_luci2
.ui
.button(_luci2
.tr('Save & Apply'), 'primary')
6125 .click({ self
: this }, function(ev
) { }))
6126 .append(_luci2
.ui
.button(_luci2
.tr('Save'), 'default')
6127 .click({ self
: this }, function(ev
) { ev
.data
.self
.send(); }))
6128 .append(_luci2
.ui
.button(_luci2
.tr('Reset'), 'default')
6129 .click({ self
: this }, function(ev
) { ev
.data
.self
.insertInto(ev
.data
.self
.target
); }))));
6137 for (var i
= 0; i
< this.sections
.length
; i
++)
6138 this.sections
[i
].finish();
6145 this.target
.hide().empty().append(this.render());
6150 section: function(widget
, uci_type
, options
)
6152 var w
= widget
? new widget(uci_type
, options
) : null;
6154 if (!(w
instanceof _luci2
.cbi
.AbstractSection
))
6155 throw 'Widget must be an instance of AbstractSection';
6158 w
.index
= this.sections
.length
;
6160 this.sections
.push(w
);
6164 formvalue: function()
6168 for (var i
= 0; i
< this.sections
.length
; i
++)
6170 var sids
= this.sections
[i
].formvalue();
6171 for (var sid
in sids
)
6173 var s
= rv
[sid
] || (rv
[sid
] = { });
6174 $.extend(s
, sids
[sid
]);
6181 add: function(conf
, type
, name
)
6183 var c
= this.uci
.creates
;
6184 var s
= '.new.%d'.format(this.uci
.newid
++);
6193 '.anonymous': !name
,
6194 '.index': 1000 + this.uci
.newid
6200 remove: function(conf
, sid
)
6202 var n
= this.uci
.creates
;
6203 var c
= this.uci
.changes
;
6204 var d
= this.uci
.deletes
;
6206 /* requested deletion of a just created section */
6207 if (sid
.indexOf('.new.') == 0)
6210 delete n
[conf
][sid
];
6215 delete c
[conf
][sid
];
6220 d
[conf
][sid
] = true;
6224 ucisections: function(conf
, cb
)
6227 var pkg
= this.uci
.values
[conf
];
6228 var crt
= this.uci
.creates
[conf
];
6229 var del
= this.uci
.deletes
[conf
];
6235 if (!del
|| del
[s
] !== true)
6242 sa
.sort(function(a
, b
) {
6243 return a
['.index'] - b
['.index'];
6246 for (var i
= 0; i
< sa
.length
; i
++)
6247 sa
[i
]['.index'] = i
;
6249 if (typeof(cb
) == 'function')
6250 for (var i
= 0; i
< sa
.length
; i
++)
6251 cb
.apply(this, [ sa
[i
] ]);
6256 get: function(conf
, sid
, opt
)
6258 var v
= this.uci
.values
;
6259 var n
= this.uci
.creates
;
6260 var c
= this.uci
.changes
;
6261 var d
= this.uci
.deletes
;
6263 /* requested option in a just created section */
6264 if (sid
.indexOf('.new.') == 0)
6269 if (typeof(opt
) == 'undefined')
6270 return (n
[conf
][sid
] || { });
6272 return n
[conf
][sid
][opt
];
6275 /* requested an option value */
6276 if (typeof(opt
) != 'undefined')
6278 /* check whether option was deleted */
6279 if (d
[conf
] && d
[conf
][sid
])
6281 if (d
[conf
][sid
] === true)
6284 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
6285 if (d
[conf
][sid
][i
] == opt
)
6289 /* check whether option was changed */
6290 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
6291 return c
[conf
][sid
][opt
];
6293 /* return base value */
6294 if (v
[conf
] && v
[conf
][sid
])
6295 return v
[conf
][sid
][opt
];
6300 /* requested an entire section */
6302 return (v
[conf
][sid
] || { });
6307 set: function(conf
, sid
, opt
, val
)
6309 var n
= this.uci
.creates
;
6310 var c
= this.uci
.changes
;
6311 var d
= this.uci
.deletes
;
6313 if (sid
.indexOf('.new.') == 0)
6315 if (n
[conf
] && n
[conf
][sid
])
6317 if (typeof(val
) != 'undefined')
6318 n
[conf
][sid
][opt
] = val
;
6320 delete n
[conf
][sid
][opt
];
6323 else if (typeof(val
) != 'undefined')
6331 c
[conf
][sid
][opt
] = val
;
6341 d
[conf
][sid
].push(opt
);
6345 validate: function()
6349 for (var i
= 0; i
< this.sections
.length
; i
++)
6351 if (!this.sections
[i
].validate())
6360 if (this.options
.readonly
)
6361 return _luci2
.deferrable();
6363 var deferreds
= [ _luci2
.deferrable(this.options
.save()) ];
6365 for (var i
= 0; i
< this.sections
.length
; i
++)
6367 if (this.sections
[i
].options
.readonly
)
6370 for (var f
in this.sections
[i
].fields
)
6372 if (typeof(this.sections
[i
].fields
[f
].save
) != 'function')
6375 var s
= this.sections
[i
].sections();
6376 for (var j
= 0; j
< s
.length
; j
++)
6378 var rv
= this.sections
[i
].fields
[f
].save(s
[j
]['.name']);
6379 if (_luci2
.isDeferred(rv
))
6385 return $.when
.apply($, deferreds
);
6388 _send_uci_reorder: function()
6390 if (!this.uci
.reorder
)
6391 return _luci2
.deferrable();
6396 gather all created and existing sections, sort them according
6397 to their index value and issue an uci order call
6399 for (var c
in this.uci
.values
)
6403 if (this.uci
.creates
&& this.uci
.creates
[c
])
6404 for (var s
in this.uci
.creates
[c
])
6405 o
.push(this.uci
.creates
[c
][s
]);
6407 for (var s
in this.uci
.values
[c
])
6408 o
.push(this.uci
.values
[c
][s
]);
6412 o
.sort(function(a
, b
) {
6413 return (a
['.index'] - b
['.index']);
6418 for (var i
= 0; i
< o
.length
; i
++)
6419 sids
.push(o
[i
]['.name']);
6421 _luci2
.uci
.order(c
, sids
);
6425 return _luci2
.rpc
.flush();
6428 _send_uci: function()
6435 if (this.uci
.creates
)
6436 for (var c
in this.uci
.creates
)
6437 for (var s
in this.uci
.creates
[c
])
6444 for (var k
in this.uci
.creates
[c
][s
])
6447 r
.type
= this.uci
.creates
[c
][s
][k
];
6448 else if (k
== '.create')
6449 r
.name
= this.uci
.creates
[c
][s
][k
];
6450 else if (k
.charAt(0) != '.')
6451 r
.values
[k
] = this.uci
.creates
[c
][s
][k
];
6454 snew
.push(this.uci
.creates
[c
][s
]);
6456 _luci2
.uci
.add(r
.config
, r
.type
, r
.name
, r
.values
);
6459 if (this.uci
.changes
)
6460 for (var c
in this.uci
.changes
)
6461 for (var s
in this.uci
.changes
[c
])
6462 _luci2
.uci
.set(c
, s
, this.uci
.changes
[c
][s
]);
6464 if (this.uci
.deletes
)
6465 for (var c
in this.uci
.deletes
)
6466 for (var s
in this.uci
.deletes
[c
])
6468 var o
= this.uci
.deletes
[c
][s
];
6469 _luci2
.uci
['delete'](c
, s
, (o
=== true) ? undefined : o
);
6472 return _luci2
.rpc
.flush().then(function(responses
) {
6474 array "snew" holds references to the created uci sections,
6475 use it to assign the returned names of the new sections
6477 for (var i
= 0; i
< snew
.length
; i
++)
6478 snew
[i
]['.name'] = responses
[i
];
6480 return self
._send_uci_reorder();
6486 if (!this.validate())
6487 return _luci2
.deferrable();
6491 _luci2
.ui
.saveScrollTop();
6492 _luci2
.ui
.loading(true);
6494 return this.save().then(function() {
6495 return self
._send_uci();
6496 }).then(function() {
6497 return _luci2
.ui
.updateChanges();
6498 }).then(function() {
6500 }).then(function() {
6504 _luci2
.ui
.loading(false);
6505 _luci2
.ui
.restoreScrollTop();
6509 insertInto: function(id
)
6512 self
.target
= $(id
);
6514 _luci2
.ui
.loading(true);
6517 return self
.load().then(function() {
6518 self
.target
.empty().append(self
.render());
6522 _luci2
.ui
.loading(false);