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
= arguments
.callee
;
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
;
371 this.getHash = function(key
)
374 var tuples
= (location
.hash
|| '#').substring(1).split(/,/);
376 for (var i
= 0; i
< tuples
.length
; i
++)
378 var tuple
= tuples
[i
].split(/:/);
379 if (tuple
.length
== 2)
380 data
[tuple
[0]] = tuple
[1];
383 if (typeof(key
) != 'undefined')
392 sid
: '00000000000000000000000000000000'
401 _call: function(req
, cb
)
403 return $.ajax('/ubus', {
405 contentType
: 'application/json',
406 data
: JSON
.stringify(req
),
409 timeout
: _luci2
.globals
.timeout
413 _list_cb: function(msg
)
415 /* verify message frame */
416 if (typeof(msg
) != 'object' || msg
.jsonrpc
!= '2.0' || !msg
.id
)
417 throw 'Invalid JSON response';
422 _call_cb: function(msg
)
425 var type
= Object
.prototype.toString
;
430 for (var i
= 0; i
< msg
.length
; i
++)
432 /* verify message frame */
433 if (typeof(msg
[i
]) != 'object' || msg
[i
].jsonrpc
!= '2.0' || !msg
[i
].id
)
434 throw 'Invalid JSON response';
436 /* fetch related request info */
437 var req
= _luci2
.rpc
._requests
[msg
[i
].id
];
438 if (typeof(req
) != 'object')
439 throw 'No related request for JSON response';
441 /* fetch response attribute and verify returned type */
444 if ($.isArray(msg
[i
].result
) && msg
[i
].result
[0] == 0)
445 ret
= (msg
[i
].result
.length
> 1) ? msg
[i
].result
[1] : msg
[i
].result
[0];
449 for (var key
in req
.expect
)
451 if (typeof(ret
) != 'undefined' && key
!= '')
454 if (type
.call(ret
) != type
.call(req
.expect
[key
]))
455 ret
= req
.expect
[key
];
462 if (typeof(req
.filter
) == 'function')
465 req
.priv
[1] = req
.params
;
466 ret
= req
.filter
.apply(_luci2
.rpc
, req
.priv
);
469 /* store response data */
470 if (typeof(req
.index
) == 'number')
471 data
[req
.index
] = ret
;
475 /* delete request object */
476 delete _luci2
.rpc
._requests
[msg
[i
].id
];
485 for (var i
= 0; i
< arguments
.length
; i
++)
486 params
[i
] = arguments
[i
];
492 params
: (params
.length
> 0) ? params
: undefined
495 return this._call(msg
, this._list_cb
);
500 if (!$.isArray(this._batch
))
506 if (!$.isArray(this._batch
))
507 return _luci2
.deferrable([ ]);
509 var req
= this._batch
;
513 return this._call(req
, this._call_cb
);
516 declare: function(options
)
521 /* build parameter object */
524 if ($.isArray(options
.params
))
525 for (p_off
= 0; p_off
< options
.params
.length
; p_off
++)
526 params
[options
.params
[p_off
]] = arguments
[p_off
];
528 /* all remaining arguments are private args */
529 var priv
= [ undefined, undefined ];
530 for (; p_off
< arguments
.length
; p_off
++)
531 priv
.push(arguments
[p_off
]);
533 /* store request info */
534 var req
= _rpc
._requests
[_rpc
._id
] = {
535 expect
: options
.expect
,
536 filter
: options
.filter
,
541 /* build message object */
554 /* when a batch is in progress then store index in request data
555 * and push message object onto the stack */
556 if ($.isArray(_rpc
._batch
))
558 req
.index
= _rpc
._batch
.push(msg
) - 1;
559 return _luci2
.deferrable(msg
);
563 return _rpc
._call(msg
, _rpc
._call_cb
);
572 return _luci2
.session
.access('ubus', 'uci', 'commit');
575 add
: _luci2
.rpc
.declare({
578 params
: [ 'config', 'type', 'name', 'values' ],
579 expect
: { section
: '' }
587 changes
: _luci2
.rpc
.declare({
590 params
: [ 'config' ],
591 expect
: { changes
: [ ] }
594 commit
: _luci2
.rpc
.declare({
600 _delete_one
: _luci2
.rpc
.declare({
603 params
: [ 'config', 'section', 'option' ]
606 _delete_multiple
: _luci2
.rpc
.declare({
609 params
: [ 'config', 'section', 'options' ]
612 'delete': function(config
, section
, option
)
614 if ($.isArray(option
))
615 return this._delete_multiple(config
, section
, option
);
617 return this._delete_one(config
, section
, option
);
620 delete_all
: _luci2
.rpc
.declare({
623 params
: [ 'config', 'type', 'match' ]
626 _foreach
: _luci2
.rpc
.declare({
629 params
: [ 'config', 'type' ],
630 expect
: { values
: { } }
633 foreach: function(config
, type
, cb
)
635 return this._foreach(config
, type
).then(function(sections
) {
636 for (var s
in sections
)
641 get: _luci2
.rpc
.declare({
644 params
: [ 'config', 'section', 'option' ],
646 filter: function(data
, params
) {
647 if (typeof(params
.option
) == 'undefined')
648 return data
.values
? data
.values
['.type'] : undefined;
654 get_all
: _luci2
.rpc
.declare({
657 params
: [ 'config', 'section' ],
658 expect
: { values
: { } },
659 filter: function(data
, params
) {
660 if (typeof(params
.section
) == 'string')
661 data
['.section'] = params
.section
;
662 else if (typeof(params
.config
) == 'string')
663 data
['.package'] = params
.config
;
668 get_first: function(config
, type
, option
)
670 return this._foreach(config
, type
).then(function(sections
) {
671 for (var s
in sections
)
673 var val
= (typeof(option
) == 'string') ? sections
[s
][option
] : sections
[s
]['.name'];
675 if (typeof(val
) != 'undefined')
683 section
: _luci2
.rpc
.declare({
686 params
: [ 'config', 'type', 'name', 'values' ],
687 expect
: { section
: '' }
690 _set
: _luci2
.rpc
.declare({
693 params
: [ 'config', 'section', 'values' ]
696 set: function(config
, section
, option
, value
)
698 if (typeof(value
) == 'undefined' && typeof(option
) == 'string')
699 return this.section(config
, section
, option
); /* option -> type */
700 else if ($.isPlainObject(option
))
701 return this._set(config
, section
, option
); /* option -> values */
704 values
[option
] = value
;
706 return this._set(config
, section
, values
);
709 order
: _luci2
.rpc
.declare({
712 params
: [ 'config', 'sections' ]
717 listNetworkNames: function() {
718 return _luci2
.rpc
.list('network.interface.*').then(function(list
) {
720 for (var name
in list
)
721 if (name
!= 'network.interface.loopback')
722 names
.push(name
.substring(18));
728 listDeviceNames
: _luci2
.rpc
.declare({
729 object
: 'network.device',
732 filter: function(data
) {
734 for (var name
in data
)
742 getNetworkStatus: function()
747 return this.listNetworkNames().then(function(names
) {
750 for (var i
= 0; i
< names
.length
; i
++)
751 _luci2
.network
.getInterfaceStatus(names
[i
]);
753 return _luci2
.rpc
.flush();
754 }).then(function(networks
) {
755 for (var i
= 0; i
< networks
.length
; i
++)
757 var net
= nets
[i
] = networks
[i
];
758 var dev
= net
.l3_device
|| net
.l2_device
;
760 net
.device
= devs
[dev
] = { };
765 for (var dev
in devs
)
766 _luci2
.network
.listDeviceNamestatus(dev
);
768 return _luci2
.rpc
.flush();
769 }).then(function(devices
) {
772 for (var i
= 0; i
< devices
.length
; i
++)
774 var brm
= devices
[i
]['bridge-members'];
775 delete devices
[i
]['bridge-members'];
777 $.extend(devs
[devices
[i
]['device']], devices
[i
]);
782 devs
[devices
[i
]['device']].subdevices
= [ ];
784 for (var j
= 0; j
< brm
.length
; j
++)
789 _luci2
.network
.listDeviceNamestatus(brm
[j
]);
792 devs
[devices
[i
]['device']].subdevices
[j
] = devs
[brm
[j
]];
796 return _luci2
.rpc
.flush();
797 }).then(function(subdevices
) {
798 for (var i
= 0; i
< subdevices
.length
; i
++)
799 $.extend(devs
[subdevices
[i
]['device']], subdevices
[i
]);
803 for (var dev
in devs
)
804 _luci2
.wireless
.getDeviceStatus(dev
);
806 return _luci2
.rpc
.flush();
807 }).then(function(wifidevices
) {
808 for (var i
= 0; i
< wifidevices
.length
; i
++)
810 devs
[wifidevices
[i
]['device']].wireless
= wifidevices
[i
];
812 nets
.sort(function(a
, b
) {
813 if (a
['interface'] < b
['interface'])
815 else if (a
['interface'] > b
['interface'])
825 findWanInterfaces: function(cb
)
827 return this.listNetworkNames().then(function(names
) {
830 for (var i
= 0; i
< names
.length
; i
++)
831 _luci2
.network
.getInterfaceStatus(names
[i
]);
833 return _luci2
.rpc
.flush();
834 }).then(function(interfaces
) {
835 var rv
= [ undefined, undefined ];
837 for (var i
= 0; i
< interfaces
.length
; i
++)
839 for (var j
= 0; j
< interfaces
[i
].route
.length
; j
++)
841 var rt
= interfaces
[i
].route
[j
];
843 if (typeof(rt
.table
) != 'undefined')
846 if (rt
.target
== '0.0.0.0' && rt
.mask
== 0)
847 rv
[0] = interfaces
[i
];
848 else if (rt
.target
== '::' && rt
.mask
== 0)
849 rv
[1] = interfaces
[i
];
857 getDHCPLeases
: _luci2
.rpc
.declare({
858 object
: 'luci2.network',
859 method
: 'dhcp_leases',
860 expect
: { leases
: [ ] }
863 getDHCPv6Leases
: _luci2
.rpc
.declare({
864 object
: 'luci2.network',
865 method
: 'dhcp6_leases',
866 expect
: { leases
: [ ] }
869 getRoutes
: _luci2
.rpc
.declare({
870 object
: 'luci2.network',
872 expect
: { routes
: [ ] }
875 getIPv6Routes
: _luci2
.rpc
.declare({
876 object
: 'luci2.network',
878 expect
: { routes
: [ ] }
881 getARPTable
: _luci2
.rpc
.declare({
882 object
: 'luci2.network',
884 expect
: { entries
: [ ] }
887 getInterfaceStatus
: _luci2
.rpc
.declare({
888 object
: 'network.interface',
890 params
: [ 'interface' ],
892 filter: function(data
, params
) {
893 data
['interface'] = params
['interface'];
894 data
['l2_device'] = data
['device'];
895 delete data
['device'];
900 listDeviceNamestatus
: _luci2
.rpc
.declare({
901 object
: 'network.device',
905 filter: function(data
, params
) {
906 data
['device'] = params
['name'];
911 getConntrackCount
: _luci2
.rpc
.declare({
912 object
: 'luci2.network',
913 method
: 'conntrack_count',
914 expect
: { '': { count
: 0, limit
: 0 } }
919 listDeviceNames
: _luci2
.rpc
.declare({
922 expect
: { 'devices': [ ] },
923 filter: function(data
) {
929 getDeviceStatus
: _luci2
.rpc
.declare({
932 params
: [ 'device' ],
934 filter: function(data
, params
) {
935 if (!$.isEmptyObject(data
))
937 data
['device'] = params
['device'];
944 getAssocList
: _luci2
.rpc
.declare({
947 params
: [ 'device' ],
948 expect
: { results
: [ ] },
949 filter: function(data
, params
) {
950 for (var i
= 0; i
< data
.length
; i
++)
951 data
[i
]['device'] = params
['device'];
953 data
.sort(function(a
, b
) {
954 if (a
.bssid
< b
.bssid
)
956 else if (a
.bssid
> b
.bssid
)
966 getWirelessStatus: function() {
967 return this.listDeviceNames().then(function(names
) {
970 for (var i
= 0; i
< names
.length
; i
++)
971 _luci2
.wireless
.getDeviceStatus(names
[i
]);
973 return _luci2
.rpc
.flush();
974 }).then(function(networks
) {
978 'country', 'channel', 'frequency', 'frequency_offset',
979 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
983 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
984 'signal', 'noise', 'bitrate', 'encryption'
987 for (var i
= 0; i
< networks
.length
; i
++)
989 var phy
= rv
[networks
[i
].phy
] || (
990 rv
[networks
[i
].phy
] = { networks
: [ ] }
994 device
: networks
[i
].device
997 for (var j
= 0; j
< phy_attrs
.length
; j
++)
998 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1000 for (var j
= 0; j
< net_attrs
.length
; j
++)
1001 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1003 phy
.networks
.push(net
);
1010 getAssocLists: function()
1012 return this.listDeviceNames().then(function(names
) {
1015 for (var i
= 0; i
< names
.length
; i
++)
1016 _luci2
.wireless
.getAssocList(names
[i
]);
1018 return _luci2
.rpc
.flush();
1019 }).then(function(assoclists
) {
1022 for (var i
= 0; i
< assoclists
.length
; i
++)
1023 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1024 rv
.push(assoclists
[i
][j
]);
1030 formatEncryption: function(enc
)
1032 var format_list = function(l
, s
)
1035 for (var i
= 0; i
< l
.length
; i
++)
1036 rv
.push(l
[i
].toUpperCase());
1037 return rv
.join(s
? s
: ', ');
1040 if (!enc
|| !enc
.enabled
)
1041 return _luci2
.tr('None');
1045 if (enc
.wep
.length
== 2)
1046 return _luci2
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1047 else if (enc
.wep
[0] == 'shared')
1048 return _luci2
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1050 return _luci2
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1054 if (enc
.wpa
.length
== 2)
1055 return _luci2
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1056 format_list(enc
.authentication
, '/'),
1057 format_list(enc
.ciphers
, ', ')
1059 else if (enc
.wpa
[0] == 2)
1060 return 'WPA2 %s (%s)'.format(
1061 format_list(enc
.authentication
, '/'),
1062 format_list(enc
.ciphers
, ', ')
1065 return 'WPA %s (%s)'.format(
1066 format_list(enc
.authentication
, '/'),
1067 format_list(enc
.ciphers
, ', ')
1071 return _luci2
.tr('Unknown');
1076 getSystemInfo
: _luci2
.rpc
.declare({
1082 getBoardInfo
: _luci2
.rpc
.declare({
1088 getDiskInfo
: _luci2
.rpc
.declare({
1089 object
: 'luci2.system',
1094 getInfo: function(cb
)
1098 this.getSystemInfo();
1099 this.getBoardInfo();
1102 return _luci2
.rpc
.flush().then(function(info
) {
1105 $.extend(rv
, info
[0]);
1106 $.extend(rv
, info
[1]);
1107 $.extend(rv
, info
[2]);
1113 getProcessList
: _luci2
.rpc
.declare({
1114 object
: 'luci2.system',
1115 method
: 'process_list',
1116 expect
: { processes
: [ ] },
1117 filter: function(data
) {
1118 data
.sort(function(a
, b
) { return a
.pid
- b
.pid
});
1123 getSystemLog
: _luci2
.rpc
.declare({
1124 object
: 'luci2.system',
1129 getKernelLog
: _luci2
.rpc
.declare({
1130 object
: 'luci2.system',
1135 getZoneInfo: function(cb
)
1137 return $.getJSON(_luci2
.globals
.resource
+ '/zoneinfo.json', cb
);
1140 sendSignal
: _luci2
.rpc
.declare({
1141 object
: 'luci2.system',
1142 method
: 'process_signal',
1143 params
: [ 'pid', 'signal' ],
1144 filter: function(data
) {
1149 initList
: _luci2
.rpc
.declare({
1150 object
: 'luci2.system',
1151 method
: 'init_list',
1152 expect
: { initscripts
: [ ] },
1153 filter: function(data
) {
1154 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
1159 initEnabled: function(init
, cb
)
1161 return this.initList().then(function(list
) {
1162 for (var i
= 0; i
< list
.length
; i
++)
1163 if (list
[i
].name
== init
)
1164 return !!list
[i
].enabled
;
1170 initRun
: _luci2
.rpc
.declare({
1171 object
: 'luci2.system',
1172 method
: 'init_action',
1173 params
: [ 'name', 'action' ],
1174 filter: function(data
) {
1179 initStart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'start', cb
) },
1180 initStop: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'stop', cb
) },
1181 initRestart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'restart', cb
) },
1182 initReload: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'reload', cb
) },
1183 initEnable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'enable', cb
) },
1184 initDisable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'disable', cb
) },
1187 getRcLocal
: _luci2
.rpc
.declare({
1188 object
: 'luci2.system',
1189 method
: 'rclocal_get',
1190 expect
: { data
: '' }
1193 setRcLocal
: _luci2
.rpc
.declare({
1194 object
: 'luci2.system',
1195 method
: 'rclocal_set',
1200 getCrontab
: _luci2
.rpc
.declare({
1201 object
: 'luci2.system',
1202 method
: 'crontab_get',
1203 expect
: { data
: '' }
1206 setCrontab
: _luci2
.rpc
.declare({
1207 object
: 'luci2.system',
1208 method
: 'crontab_set',
1213 getSSHKeys
: _luci2
.rpc
.declare({
1214 object
: 'luci2.system',
1215 method
: 'sshkeys_get',
1216 expect
: { keys
: [ ] }
1219 setSSHKeys
: _luci2
.rpc
.declare({
1220 object
: 'luci2.system',
1221 method
: 'sshkeys_set',
1226 setPassword
: _luci2
.rpc
.declare({
1227 object
: 'luci2.system',
1228 method
: 'password_set',
1229 params
: [ 'user', 'password' ]
1233 listLEDs
: _luci2
.rpc
.declare({
1234 object
: 'luci2.system',
1236 expect
: { leds
: [ ] }
1239 listUSBDevices
: _luci2
.rpc
.declare({
1240 object
: 'luci2.system',
1242 expect
: { devices
: [ ] }
1246 testUpgrade
: _luci2
.rpc
.declare({
1247 object
: 'luci2.system',
1248 method
: 'upgrade_test',
1252 startUpgrade
: _luci2
.rpc
.declare({
1253 object
: 'luci2.system',
1254 method
: 'upgrade_start',
1258 cleanUpgrade
: _luci2
.rpc
.declare({
1259 object
: 'luci2.system',
1260 method
: 'upgrade_clean'
1264 restoreBackup
: _luci2
.rpc
.declare({
1265 object
: 'luci2.system',
1266 method
: 'backup_restore'
1269 cleanBackup
: _luci2
.rpc
.declare({
1270 object
: 'luci2.system',
1271 method
: 'backup_clean'
1275 getBackupConfig
: _luci2
.rpc
.declare({
1276 object
: 'luci2.system',
1277 method
: 'backup_config_get',
1278 expect
: { config
: '' }
1281 setBackupConfig
: _luci2
.rpc
.declare({
1282 object
: 'luci2.system',
1283 method
: 'backup_config_set',
1288 listBackup
: _luci2
.rpc
.declare({
1289 object
: 'luci2.system',
1290 method
: 'backup_list',
1291 expect
: { files
: [ ] }
1295 performReboot
: _luci2
.rpc
.declare({
1296 object
: 'luci2.system',
1302 updateLists
: _luci2
.rpc
.declare({
1303 object
: 'luci2.opkg',
1308 _allPackages
: _luci2
.rpc
.declare({
1309 object
: 'luci2.opkg',
1311 params
: [ 'offset', 'limit', 'pattern' ],
1315 _installedPackages
: _luci2
.rpc
.declare({
1316 object
: 'luci2.opkg',
1317 method
: 'list_installed',
1318 params
: [ 'offset', 'limit', 'pattern' ],
1322 _findPackages
: _luci2
.rpc
.declare({
1323 object
: 'luci2.opkg',
1325 params
: [ 'offset', 'limit', 'pattern' ],
1329 _fetchPackages: function(action
, offset
, limit
, pattern
)
1333 return action(offset
, limit
, pattern
).then(function(list
) {
1334 if (!list
.total
|| !list
.packages
)
1335 return { length
: 0, total
: 0 };
1337 packages
.push
.apply(packages
, list
.packages
);
1338 packages
.total
= list
.total
;
1343 if (packages
.length
>= limit
)
1348 for (var i
= offset
+ packages
.length
; i
< limit
; i
+= 100)
1349 action(i
, (Math
.min(i
+ 100, limit
) % 100) || 100, pattern
);
1351 return _luci2
.rpc
.flush();
1352 }).then(function(lists
) {
1353 for (var i
= 0; i
< lists
.length
; i
++)
1355 if (!lists
[i
].total
|| !lists
[i
].packages
)
1358 packages
.push
.apply(packages
, lists
[i
].packages
);
1359 packages
.total
= lists
[i
].total
;
1366 listPackages: function(offset
, limit
, pattern
)
1368 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._allPackages
, offset
, limit
, pattern
);
1371 installedPackages: function(offset
, limit
, pattern
)
1373 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._installedPackages
, offset
, limit
, pattern
);
1376 findPackages: function(offset
, limit
, pattern
)
1378 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._findPackages
, offset
, limit
, pattern
);
1381 installPackage
: _luci2
.rpc
.declare({
1382 object
: 'luci2.opkg',
1384 params
: [ 'package' ],
1388 removePackage
: _luci2
.rpc
.declare({
1389 object
: 'luci2.opkg',
1391 params
: [ 'package' ],
1395 getConfig
: _luci2
.rpc
.declare({
1396 object
: 'luci2.opkg',
1397 method
: 'config_get',
1398 expect
: { config
: '' }
1401 setConfig
: _luci2
.rpc
.declare({
1402 object
: 'luci2.opkg',
1403 method
: 'config_set',
1410 login
: _luci2
.rpc
.declare({
1413 params
: [ 'username', 'password' ],
1417 access
: _luci2
.rpc
.declare({
1420 params
: [ 'scope', 'object', 'function' ],
1421 expect
: { access
: false }
1426 return _luci2
.session
.access('ubus', 'session', 'access');
1429 startHeartbeat: function()
1431 this._hearbeatInterval
= window
.setInterval(function() {
1432 _luci2
.session
.isAlive().then(function(alive
) {
1435 _luci2
.session
.stopHeartbeat();
1436 _luci2
.ui
.login(true);
1440 }, _luci2
.globals
.timeout
* 2);
1443 stopHeartbeat: function()
1445 if (typeof(this._hearbeatInterval
) != 'undefined')
1447 window
.clearInterval(this._hearbeatInterval
);
1448 delete this._hearbeatInterval
;
1455 loading: function(enable
)
1457 var win
= $(window
);
1458 var body
= $('body');
1459 var div
= _luci2
._modal
|| (
1460 _luci2
._modal
= $('<div />')
1461 .addClass('cbi-modal-loader')
1462 .append($('<div />').text(_luci2
.tr('Loading data...')))
1468 body
.css('overflow', 'hidden');
1469 body
.css('padding', 0);
1470 body
.css('width', win
.width());
1471 body
.css('height', win
.height());
1472 div
.css('width', win
.width());
1473 div
.css('height', win
.height());
1479 body
.css('overflow', '');
1480 body
.css('padding', '');
1481 body
.css('width', '');
1482 body
.css('height', '');
1486 dialog: function(title
, content
, options
)
1488 var win
= $(window
);
1489 var body
= $('body');
1490 var div
= _luci2
._dialog
|| (
1491 _luci2
._dialog
= $('<div />')
1492 .addClass('cbi-modal-dialog')
1493 .append($('<div />')
1494 .append($('<div />')
1495 .addClass('cbi-modal-dialog-header'))
1496 .append($('<div />')
1497 .addClass('cbi-modal-dialog-body'))
1498 .append($('<div />')
1499 .addClass('cbi-modal-dialog-footer')
1500 .append($('<button />')
1501 .addClass('cbi-button')
1502 .text(_luci2
.tr('Close'))
1505 .css('overflow', '')
1510 $(this).parent().parent().parent().hide();
1515 if (typeof(options
) != 'object')
1518 if (title
=== false)
1521 .css('overflow', '')
1526 _luci2
._dialog
.hide();
1531 var cnt
= div
.children().children('div.cbi-modal-dialog-body');
1532 var ftr
= div
.children().children('div.cbi-modal-dialog-footer');
1536 if (options
.style
== 'confirm')
1538 ftr
.append($('<button />')
1539 .addClass('cbi-button')
1540 .text(_luci2
.tr('Ok'))
1541 .click(options
.confirm
|| function() { _luci2
.ui
.dialog(false) }));
1543 ftr
.append($('<button />')
1544 .addClass('cbi-button')
1545 .text(_luci2
.tr('Cancel'))
1546 .click(options
.cancel
|| function() { _luci2
.ui
.dialog(false) }));
1548 else if (options
.style
== 'close')
1550 ftr
.append($('<button />')
1551 .addClass('cbi-button')
1552 .text(_luci2
.tr('Close'))
1553 .click(options
.close
|| function() { _luci2
.ui
.dialog(false) }));
1555 else if (options
.style
== 'wait')
1557 ftr
.append($('<button />')
1558 .addClass('cbi-button')
1559 .text(_luci2
.tr('Close'))
1560 .attr('disabled', true));
1563 div
.find('div.cbi-modal-dialog-header').text(title
);
1567 .css('max-height', Math
.floor(win
.height() * 0.70) + 'px')
1572 .css('margin-top', -Math
.floor(div
.children().height() / 2) + 'px');
1574 body
.css('overflow', 'hidden');
1575 body
.css('padding', 0);
1576 body
.css('width', win
.width());
1577 body
.css('height', win
.height());
1578 div
.css('width', win
.width());
1579 div
.css('height', win
.height());
1582 upload: function(title
, content
, options
)
1584 var form
= _luci2
._upload
|| (
1585 _luci2
._upload
= $('<form />')
1586 .attr('method', 'post')
1587 .attr('action', '/cgi-bin/luci-upload')
1588 .attr('enctype', 'multipart/form-data')
1589 .attr('target', 'cbi-fileupload-frame')
1591 .append($('<input />')
1592 .attr('type', 'hidden')
1593 .attr('name', 'sessionid')
1594 .attr('value', _luci2
.globals
.sid
))
1595 .append($('<input />')
1596 .attr('type', 'hidden')
1597 .attr('name', 'filename')
1598 .attr('value', options
.filename
))
1599 .append($('<input />')
1600 .attr('type', 'file')
1601 .attr('name', 'filedata')
1602 .addClass('cbi-input-file'))
1603 .append($('<div />')
1604 .css('width', '100%')
1605 .addClass('progressbar')
1606 .addClass('intermediate')
1607 .append($('<div />')
1608 .css('width', '100%')))
1609 .append($('<iframe />')
1610 .attr('name', 'cbi-fileupload-frame')
1611 .css('width', '1px')
1612 .css('height', '1px')
1613 .css('visibility', 'hidden'))
1616 var finish
= _luci2
._upload_finish_cb
|| (
1617 _luci2
._upload_finish_cb = function(ev
) {
1618 $(this).off('load');
1620 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
1621 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
1622 body
= body
.firstChild
;
1626 json
= $.parseJSON(body
.innerHTML
);
1629 message
: _luci2
.tr('Invalid server response received'),
1630 error
: [ -1, _luci2
.tr('Invalid data') ]
1636 L
.ui
.dialog(L
.tr('File upload'), [
1637 $('<p />').text(_luci2
.tr('The file upload failed with the server response below:')),
1638 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
1639 $('<p />').text(_luci2
.tr('In case of network problems try uploading the file again.'))
1640 ], { style
: 'close' });
1642 else if (typeof(ev
.data
.cb
) == 'function')
1649 var confirm
= _luci2
._upload_confirm_cb
|| (
1650 _luci2
._upload_confirm_cb = function() {
1651 var d
= _luci2
._upload
;
1652 var f
= d
.find('.cbi-input-file');
1653 var b
= d
.find('.progressbar');
1654 var p
= d
.find('p');
1659 d
.find('iframe').on('load', { cb
: options
.success
}, finish
);
1664 p
.text(_luci2
.tr('File upload in progress …'));
1666 _luci2
._dialog
.find('button').prop('disabled', true);
1670 _luci2
._upload
.find('.progressbar').hide();
1671 _luci2
._upload
.find('.cbi-input-file').val('').show();
1672 _luci2
._upload
.find('p').text(content
|| _luci2
.tr('Select the file to upload and press "%s" to proceed.').format(_luci2
.tr('Ok')));
1674 _luci2
.ui
.dialog(title
|| _luci2
.tr('File upload'), _luci2
._upload
, {
1680 reconnect: function()
1682 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1683 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
1684 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
1686 var interval
, timeout
;
1689 _luci2
.tr('Waiting for device'), [
1690 $('<p />').text(_luci2
.tr('Please stand by while the device is reconfiguring …')),
1692 .css('width', '100%')
1693 .addClass('progressbar')
1694 .addClass('intermediate')
1695 .append($('<div />')
1696 .css('width', '100%'))
1697 ], { style
: 'wait' }
1700 for (var i
= 0; i
< protocols
.length
; i
++)
1701 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
1703 //_luci2.network.getNetworkStatus(function(s) {
1704 // for (var i = 0; i < protocols.length; i++)
1706 // for (var j = 0; j < s.length; j++)
1708 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1709 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1711 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1712 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1715 //}).then(function() {
1716 images
.on('load', function() {
1717 var url
= this.getAttribute('url');
1718 _luci2
.session
.isAlive().then(function(access
) {
1721 window
.clearTimeout(timeout
);
1722 window
.clearInterval(interval
);
1723 _luci2
.ui
.dialog(false);
1728 location
.href
= url
;
1733 interval
= window
.setInterval(function() {
1734 images
.each(function() {
1735 this.setAttribute('src', this.getAttribute('url') + _luci2
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
1739 timeout
= window
.setTimeout(function() {
1740 window
.clearInterval(interval
);
1744 _luci2
.tr('Device not responding'),
1745 _luci2
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1752 login: function(invalid
)
1754 if (!_luci2
._login_deferred
|| _luci2
._login_deferred
.state() != 'pending')
1755 _luci2
._login_deferred
= $.Deferred();
1757 /* try to find sid from hash */
1758 var sid
= _luci2
.getHash('id');
1759 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
1761 _luci2
.globals
.sid
= sid
;
1762 _luci2
.session
.isAlive().then(function(access
) {
1765 _luci2
.session
.startHeartbeat();
1766 _luci2
._login_deferred
.resolve();
1770 _luci2
.setHash('id', undefined);
1775 return _luci2
._login_deferred
;
1778 var form
= _luci2
._login
|| (
1779 _luci2
._login
= $('<div />')
1781 .addClass('alert-message')
1782 .text(_luci2
.tr('Wrong username or password given!')))
1784 .append($('<label />')
1785 .text(_luci2
.tr('Username'))
1786 .append($('<br />'))
1787 .append($('<input />')
1788 .attr('type', 'text')
1789 .attr('name', 'username')
1790 .attr('value', 'root')
1791 .addClass('cbi-input-text'))))
1793 .append($('<label />')
1794 .text(_luci2
.tr('Password'))
1795 .append($('<br />'))
1796 .append($('<input />')
1797 .attr('type', 'password')
1798 .attr('name', 'password')
1799 .addClass('cbi-input-password'))))
1801 .text(_luci2
.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2
.tr('Ok'))))
1804 var response_cb
= _luci2
._login_response_cb
|| (
1805 _luci2
._login_response_cb = function(response
) {
1806 if (!response
.ubus_rpc_session
)
1808 _luci2
.ui
.login(true);
1812 _luci2
.globals
.sid
= response
.ubus_rpc_session
;
1813 _luci2
.setHash('id', _luci2
.globals
.sid
);
1814 _luci2
.session
.startHeartbeat();
1815 _luci2
.ui
.dialog(false);
1816 _luci2
._login_deferred
.resolve();
1821 var confirm_cb
= _luci2
._login_confirm_cb
|| (
1822 _luci2
._login_confirm_cb = function() {
1823 var d
= _luci2
._login
;
1824 var u
= d
.find('[name=username]').val();
1825 var p
= d
.find('[name=password]').val();
1831 _luci2
.tr('Logging in'), [
1832 $('<p />').text(_luci2
.tr('Log in in progress …')),
1834 .css('width', '100%')
1835 .addClass('progressbar')
1836 .addClass('intermediate')
1837 .append($('<div />')
1838 .css('width', '100%'))
1839 ], { style
: 'wait' }
1842 _luci2
.globals
.sid
= '00000000000000000000000000000000';
1843 _luci2
.session
.login(u
, p
).then(response_cb
);
1848 form
.find('.alert-message').show();
1850 form
.find('.alert-message').hide();
1852 _luci2
.ui
.dialog(_luci2
.tr('Authorization Required'), form
, {
1857 return _luci2
._login_deferred
;
1861 _acl_merge_scope: function(acl_scope
, scope
)
1863 if ($.isArray(scope
))
1865 for (var i
= 0; i
< scope
.length
; i
++)
1866 acl_scope
[scope
[i
]] = true;
1868 else if ($.isPlainObject(scope
))
1870 for (var object_name
in scope
)
1872 if (!$.isArray(scope
[object_name
]))
1875 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
1877 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
1878 acl_object
[scope
[object_name
][i
]] = true;
1883 _acl_merge_permission: function(acl_perm
, perm
)
1885 if ($.isPlainObject(perm
))
1887 for (var scope_name
in perm
)
1889 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
1890 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
1895 _acl_merge_group: function(acl_group
, group
)
1897 if ($.isPlainObject(group
))
1899 if (!acl_group
.description
)
1900 acl_group
.description
= group
.description
;
1904 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
1905 this._acl_merge_permission(acl_perm
, group
.read
);
1910 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
1911 this._acl_merge_permission(acl_perm
, group
.write
);
1916 _acl_merge_tree: function(acl_tree
, tree
)
1918 if ($.isPlainObject(tree
))
1920 for (var group_name
in tree
)
1922 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
1923 this._acl_merge_group(acl_group
, tree
[group_name
]);
1928 listAvailableACLs
: _luci2
.rpc
.declare({
1931 expect
: { acls
: [ ] },
1932 filter: function(trees
) {
1934 for (var i
= 0; i
< trees
.length
; i
++)
1935 _luci2
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
1940 renderMainMenu
: _luci2
.rpc
.declare({
1943 expect
: { menu
: { } },
1944 filter: function(entries
) {
1945 _luci2
.globals
.mainMenu
= new _luci2
.ui
.menu();
1946 _luci2
.globals
.mainMenu
.entries(entries
);
1950 .append(_luci2
.globals
.mainMenu
.render(0, 1));
1954 renderViewMenu: function()
1958 .append(_luci2
.globals
.mainMenu
.render(2, 900));
1961 renderView: function(node
)
1963 var name
= node
.view
.split(/\//).join('.');
1965 _luci2
.ui
.renderViewMenu();
1968 _luci2
._views
= { };
1970 _luci2
.setHash('view', node
.view
);
1972 if (_luci2
._views
[name
] instanceof _luci2
.ui
.view
)
1973 return _luci2
._views
[name
].render();
1975 return $.ajax(_luci2
.globals
.resource
+ '/view/' + name
+ '.js', {
1979 }).then(function(data
) {
1981 var viewConstructor
= (new Function(['L', '$'], 'return ' + data
))(_luci2
, $);
1983 _luci2
._views
[name
] = new viewConstructor({
1985 acls
: node
.write
|| { }
1988 return _luci2
._views
[name
].render();
1992 return $.Deferred().resolve();
1998 _luci2
.ui
.loading(true);
2001 _luci2
.ui
.renderMainMenu()
2003 _luci2
.ui
.renderView(_luci2
.globals
.defaultNode
).then(function() {
2004 _luci2
.ui
.loading(false);
2010 var AbstractWidget
= Class
.extend({
2011 i18n: function(text
) {
2015 toString: function() {
2016 var x
= document
.createElement('div');
2017 x
.appendChild(this.render());
2022 insertInto: function(id
) {
2023 return $(id
).empty().append(this.render());
2027 this.ui
.view
= AbstractWidget
.extend({
2028 _fetch_template: function()
2030 return $.ajax(_luci2
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
2034 success: function(data
) {
2035 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
2036 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
2043 return _luci2
.tr(p2
);
2046 return _luci2
.globals
[p2
] || '';
2049 return '(?' + match
+ ')';
2053 $('#maincontent').append(data
);
2060 throw "Not implemented";
2065 var container
= $('#maincontent');
2070 container
.append($('<h2 />').append(this.title
));
2072 if (this.description
)
2073 container
.append($('<div />').addClass('cbi-map-descr').append(this.description
));
2076 return this._fetch_template().then(function() {
2077 return _luci2
.deferrable(self
.execute());
2082 this.ui
.menu
= AbstractWidget
.extend({
2087 entries: function(entries
)
2089 for (var entry
in entries
)
2091 var path
= entry
.split(/\//);
2092 var node
= this._nodes
;
2094 for (i
= 0; i
< path
.length
; i
++)
2099 if (!node
.childs
[path
[i
]])
2100 node
.childs
[path
[i
]] = { };
2102 node
= node
.childs
[path
[i
]];
2105 $.extend(node
, entries
[entry
]);
2109 _indexcmp: function(a
, b
)
2111 var x
= a
.index
|| 0;
2112 var y
= b
.index
|| 0;
2116 firstChildView: function(node
)
2122 for (var child
in (node
.childs
|| { }))
2123 nodes
.push(node
.childs
[child
]);
2125 nodes
.sort(this._indexcmp
);
2127 for (var i
= 0; i
< nodes
.length
; i
++)
2129 var child
= this.firstChildView(nodes
[i
]);
2132 $.extend(node
, child
);
2140 _onclick: function(ev
)
2142 _luci2
.ui
.loading(true);
2143 _luci2
.ui
.renderView(ev
.data
).then(function() {
2144 _luci2
.ui
.loading(false);
2147 ev
.preventDefault();
2151 _render: function(childs
, level
, min
, max
)
2154 for (var node
in childs
)
2156 var child
= this.firstChildView(childs
[node
]);
2158 nodes
.push(childs
[node
]);
2161 nodes
.sort(this._indexcmp
);
2163 var list
= $('<ul />');
2166 list
.addClass('nav');
2167 else if (level
== 1)
2168 list
.addClass('dropdown-menu');
2170 for (var i
= 0; i
< nodes
.length
; i
++)
2172 if (!_luci2
.globals
.defaultNode
)
2174 var v
= _luci2
.getHash('view');
2175 if (!v
|| v
== nodes
[i
].view
)
2176 _luci2
.globals
.defaultNode
= nodes
[i
];
2179 var item
= $('<li />')
2182 .text(_luci2
.tr(nodes
[i
].title
))
2183 .click(nodes
[i
], this._onclick
))
2186 if (nodes
[i
].childs
&& level
< max
)
2188 item
.addClass('dropdown');
2189 item
.find('a').addClass('menu');
2190 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
2197 render: function(min
, max
)
2199 var top
= min
? this.getNode(_luci2
.globals
.defaultNode
.view
, min
) : this._nodes
;
2200 return this._render(top
.childs
, 0, min
, max
);
2203 getNode: function(path
, max
)
2205 var p
= path
.split(/\//);
2206 var n
= this._nodes
;
2208 if (typeof(max
) == 'undefined')
2211 for (var i
= 0; i
< max
; i
++)
2213 if (!n
.childs
[p
[i
]])
2223 this.ui
.table
= AbstractWidget
.extend({
2229 row: function(values
)
2231 if ($.isArray(values
))
2233 this._rows
.push(values
);
2235 else if ($.isPlainObject(values
))
2238 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2240 var col
= this.options
.columns
[i
];
2242 if (typeof col
.key
== 'string')
2243 v
.push(values
[col
.key
]);
2251 rows: function(rows
)
2253 for (var i
= 0; i
< rows
.length
; i
++)
2257 render: function(id
)
2259 var fieldset
= document
.createElement('fieldset');
2260 fieldset
.className
= 'cbi-section';
2262 if (this.options
.caption
)
2264 var legend
= document
.createElement('legend');
2265 $(legend
).append(this.options
.caption
);
2266 fieldset
.appendChild(legend
);
2269 var table
= document
.createElement('table');
2270 table
.className
= 'cbi-section-table';
2272 var has_caption
= false;
2273 var has_description
= false;
2275 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2276 if (this.options
.columns
[i
].caption
)
2281 else if (this.options
.columns
[i
].description
)
2283 has_description
= true;
2289 var tr
= table
.insertRow(-1);
2290 tr
.className
= 'cbi-section-table-titles';
2292 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2294 var col
= this.options
.columns
[i
];
2295 var th
= document
.createElement('th');
2296 th
.className
= 'cbi-section-table-cell';
2301 th
.style
.width
= col
.width
;
2304 th
.style
.textAlign
= col
.align
;
2307 $(th
).append(col
.caption
);
2311 if (has_description
)
2313 var tr
= table
.insertRow(-1);
2314 tr
.className
= 'cbi-section-table-descr';
2316 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2318 var col
= this.options
.columns
[i
];
2319 var th
= document
.createElement('th');
2320 th
.className
= 'cbi-section-table-cell';
2325 th
.style
.width
= col
.width
;
2328 th
.style
.textAlign
= col
.align
;
2330 if (col
.description
)
2331 $(th
).append(col
.description
);
2335 if (this._rows
.length
== 0)
2337 if (this.options
.placeholder
)
2339 var tr
= table
.insertRow(-1);
2340 var td
= tr
.insertCell(-1);
2341 td
.className
= 'cbi-section-table-cell';
2343 td
.colSpan
= this.options
.columns
.length
;
2344 $(td
).append(this.options
.placeholder
);
2349 for (var i
= 0; i
< this._rows
.length
; i
++)
2351 var tr
= table
.insertRow(-1);
2353 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
2355 var col
= this.options
.columns
[j
];
2356 var td
= tr
.insertCell(-1);
2358 var val
= this._rows
[i
][j
];
2360 if (typeof(val
) == 'undefined')
2361 val
= col
.placeholder
;
2363 if (typeof(val
) == 'undefined')
2367 td
.style
.width
= col
.width
;
2370 td
.style
.textAlign
= col
.align
;
2372 if (typeof col
.format
== 'string')
2373 $(td
).append(col
.format
.format(val
));
2374 else if (typeof col
.format
== 'function')
2375 $(td
).append(col
.format(val
, i
));
2383 fieldset
.appendChild(table
);
2389 this.ui
.progress
= AbstractWidget
.extend({
2392 var vn
= parseInt(this.options
.value
) || 0;
2393 var mn
= parseInt(this.options
.max
) || 100;
2394 var pc
= Math
.floor((100 / mn
) * vn
);
2396 var bar
= document
.createElement('div');
2397 bar
.className
= 'progressbar';
2399 bar
.appendChild(document
.createElement('div'));
2400 bar
.lastChild
.appendChild(document
.createElement('div'));
2401 bar
.lastChild
.style
.width
= pc
+ '%';
2403 if (typeof(this.options
.format
) == 'string')
2404 $(bar
.lastChild
.lastChild
).append(this.options
.format
.format(this.options
.value
, this.options
.max
, pc
));
2405 else if (typeof(this.options
.format
) == 'function')
2406 $(bar
.lastChild
.lastChild
).append(this.options
.format(pc
));
2408 $(bar
.lastChild
.lastChild
).append('%.2f%%'.format(pc
));
2414 this.ui
.devicebadge
= AbstractWidget
.extend({
2417 var dev
= this.options
.l3_device
|| this.options
.device
|| '?';
2419 var span
= document
.createElement('span');
2420 span
.className
= 'ifacebadge';
2422 if (typeof(this.options
.signal
) == 'number' ||
2423 typeof(this.options
.noise
) == 'number')
2426 if (typeof(this.options
.signal
) != 'undefined' &&
2427 typeof(this.options
.noise
) != 'undefined')
2429 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
2442 span
.appendChild(document
.createElement('img'));
2443 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
2446 span
.title
= _luci2
.tr('No signal');
2448 span
.title
= '%s: %d %s / %s: %d %s'.format(
2449 _luci2
.tr('Signal'), this.options
.signal
, _luci2
.tr('dBm'),
2450 _luci2
.tr('Noise'), this.options
.noise
, _luci2
.tr('dBm')
2455 var type
= 'ethernet';
2456 var desc
= _luci2
.tr('Ethernet device');
2458 if (this.options
.l3_device
!= this.options
.device
)
2461 desc
= _luci2
.tr('Tunnel interface');
2463 else if (dev
.indexOf('br-') == 0)
2466 desc
= _luci2
.tr('Bridge');
2468 else if (dev
.indexOf('.') > 0)
2471 desc
= _luci2
.tr('VLAN interface');
2473 else if (dev
.indexOf('wlan') == 0 ||
2474 dev
.indexOf('ath') == 0 ||
2475 dev
.indexOf('wl') == 0)
2478 desc
= _luci2
.tr('Wireless Network');
2481 span
.appendChild(document
.createElement('img'));
2482 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
2486 $(span
).append(' ');
2487 $(span
).append(dev
);
2493 var type = function(f
, l
)
2503 _luci2
.cbi
.validation
.message
= _luci2
.tr(msg
);
2506 compile: function(code
)
2511 var types
= _luci2
.cbi
.validation
.types
;
2516 for (var i
= 0; i
< code
.length
; i
++)
2524 switch (code
.charCodeAt(i
))
2536 var label
= code
.substring(pos
, i
);
2537 label
= label
.replace(/\\(.)/g, '$1');
2538 label
= label
.replace(/^[ \t]+/g, '');
2539 label
= label
.replace(/[ \t]+$/g, '');
2541 if (label
&& !isNaN(label
))
2543 stack
.push(parseFloat(label
));
2545 else if (label
.match(/^(['"]).*\1$/))
2547 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
2549 else if (typeof types
[label
] == 'function')
2551 stack
.push(types
[label
]);
2556 throw "Syntax error, unhandled token '"+label
+"'";
2561 depth
+= (code
.charCodeAt(i
) == 40);
2567 if (typeof stack
[stack
.length
-2] != 'function')
2568 throw "Syntax error, argument list follows non-function";
2570 stack
[stack
.length
-1] =
2571 arguments
.callee(code
.substring(pos
, i
));
2584 var validation
= this.cbi
.validation
;
2586 validation
.types
= {
2587 'integer': function()
2589 if (this.match(/^-?[0-9]+$/) != null)
2592 validation
.i18n('Must be a valid integer');
2596 'uinteger': function()
2598 if (validation
.types
['integer'].apply(this) && (this >= 0))
2601 validation
.i18n('Must be a positive integer');
2607 if (!isNaN(parseFloat(this)))
2610 validation
.i18n('Must be a valid number');
2614 'ufloat': function()
2616 if (validation
.types
['float'].apply(this) && (this >= 0))
2619 validation
.i18n('Must be a positive number');
2623 'ipaddr': function()
2625 if (validation
.types
['ip4addr'].apply(this) ||
2626 validation
.types
['ip6addr'].apply(this))
2629 validation
.i18n('Must be a valid IP address');
2633 'ip4addr': function()
2635 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2637 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
2638 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
2639 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
2640 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
2641 ((RegExp
.$6.indexOf('.') < 0)
2642 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
2643 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
2647 validation
.i18n('Must be a valid IPv4 address');
2651 'ip6addr': function()
2653 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2655 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
2657 var addr
= RegExp
.$1;
2664 if (addr
.indexOf('.') > 0)
2666 var off
= addr
.lastIndexOf(':');
2668 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
2670 validation
.i18n('Must be a valid IPv6 address');
2674 addr
= addr
.substr(0, off
) + ':0:0';
2677 if (addr
.indexOf('::') >= 0)
2682 for (var i
= 1; i
< (addr
.length
-1); i
++)
2683 if (addr
.charAt(i
) == ':')
2688 validation
.i18n('Must be a valid IPv6 address');
2692 for (var i
= 0; i
< (7 - colons
); i
++)
2695 if (addr
.match(/^(.*?)::(.*?)$/))
2696 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
2697 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
2700 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2703 validation
.i18n('Must be a valid IPv6 address');
2713 if (validation
.types
['integer'].apply(this) &&
2714 (this >= 0) && (this <= 65535))
2717 validation
.i18n('Must be a valid port number');
2721 'portrange': function()
2723 if (this.match(/^(\d+)-(\d+)$/))
2728 if (validation
.types
['port'].apply(p1
) &&
2729 validation
.types
['port'].apply(p2
) &&
2730 (parseInt(p1
) <= parseInt(p2
)))
2733 else if (validation
.types
['port'].apply(this))
2738 validation
.i18n('Must be a valid port range');
2742 'macaddr': function()
2744 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2747 validation
.i18n('Must be a valid MAC address');
2753 if (validation
.types
['hostname'].apply(this) ||
2754 validation
.types
['ipaddr'].apply(this))
2757 validation
.i18n('Must be a valid hostname or IP address');
2761 'hostname': function()
2763 if ((this.length
<= 253) &&
2764 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2765 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2766 this.match(/[^0-9.]/)))))
2769 validation
.i18n('Must be a valid host name');
2773 'network': function()
2775 if (validation
.types
['uciname'].apply(this) ||
2776 validation
.types
['host'].apply(this))
2779 validation
.i18n('Must be a valid network name');
2783 'wpakey': function()
2787 if ((v
.length
== 64)
2788 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
2789 : ((v
.length
>= 8) && (v
.length
<= 63)))
2792 validation
.i18n('Must be a valid WPA key');
2796 'wepkey': function()
2800 if (v
.substr(0,2) == 's:')
2803 if (((v
.length
== 10) || (v
.length
== 26))
2804 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
2805 : ((v
.length
== 5) || (v
.length
== 13)))
2808 validation
.i18n('Must be a valid WEP key');
2812 'uciname': function()
2814 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2817 validation
.i18n('Must be a valid UCI identifier');
2821 'range': function(min
, max
)
2823 var val
= parseFloat(this);
2825 if (validation
.types
['integer'].apply(this) &&
2826 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
2829 validation
.i18n('Must be a number between %d and %d');
2833 'min': function(min
)
2835 var val
= parseFloat(this);
2837 if (validation
.types
['integer'].apply(this) &&
2838 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
2841 validation
.i18n('Must be a number greater or equal to %d');
2845 'max': function(max
)
2847 var val
= parseFloat(this);
2849 if (validation
.types
['integer'].apply(this) &&
2850 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
2853 validation
.i18n('Must be a number lower or equal to %d');
2857 'rangelength': function(min
, max
)
2859 var val
= '' + this;
2861 if (!isNaN(min
) && !isNaN(max
) &&
2862 (val
.length
>= min
) && (val
.length
<= max
))
2865 validation
.i18n('Must be between %d and %d characters');
2869 'minlength': function(min
)
2871 var val
= '' + this;
2873 if (!isNaN(min
) && (val
.length
>= min
))
2876 validation
.i18n('Must be at least %d characters');
2880 'maxlength': function(max
)
2882 var val
= '' + this;
2884 if (!isNaN(max
) && (val
.length
<= max
))
2887 validation
.i18n('Must be at most %d characters');
2895 for (var i
= 0; i
< arguments
.length
; i
+= 2)
2897 delete validation
.message
;
2899 if (typeof(arguments
[i
]) != 'function')
2901 if (arguments
[i
] == this)
2905 else if (arguments
[i
].apply(this, arguments
[i
+1]))
2910 if (validation
.message
)
2911 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
2914 validation
.message
= msgs
.join( _luci2
.tr(' - or - '));
2922 for (var i
= 0; i
< arguments
.length
; i
+= 2)
2924 delete validation
.message
;
2926 if (typeof arguments
[i
] != 'function')
2928 if (arguments
[i
] != this)
2932 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
2937 if (validation
.message
)
2938 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
2941 validation
.message
= msgs
.join(', ');
2947 return validation
.types
['or'].apply(
2948 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
2951 'list': function(subvalidator
, subargs
)
2953 if (typeof subvalidator
!= 'function')
2956 var tokens
= this.match(/[^ \t]+/g);
2957 for (var i
= 0; i
< tokens
.length
; i
++)
2958 if (!subvalidator
.apply(tokens
[i
], subargs
))
2964 'phonedigit': function()
2966 if (this.match(/^[0-9\*#!\.]+$/) != null)
2969 validation
.i18n('Must be a valid phone number digit');
2973 'string': function()
2980 var AbstractValue
= AbstractWidget
.extend({
2981 init: function(name
, options
)
2984 this.instance
= { };
2985 this.dependencies
= [ ];
2986 this.rdependency
= { };
2988 this.options
= _luci2
.defaults(options
, {
2998 return this.section
.id('field', sid
|| '__unknown__', this.name
);
3001 render: function(sid
)
3003 var i
= this.instance
[sid
] = { };
3005 i
.top
= $('<div />').addClass('cbi-value');
3007 if (typeof(this.options
.caption
) == 'string')
3009 .addClass('cbi-value-title')
3010 .attr('for', this.id(sid
))
3011 .text(this.options
.caption
)
3014 i
.widget
= $('<div />').addClass('cbi-value-field').append(this.widget(sid
)).appendTo(i
.top
);
3015 i
.error
= $('<div />').addClass('cbi-value-error').appendTo(i
.top
);
3017 if (typeof(this.options
.description
) == 'string')
3019 .addClass('cbi-value-description')
3020 .text(this.options
.description
)
3026 ucipath: function(sid
)
3029 config
: (this.options
.uci_package
|| this.map
.uci_package
),
3030 section
: (this.options
.uci_section
|| sid
),
3031 option
: (this.options
.uci_option
|| this.name
)
3035 ucivalue: function(sid
)
3037 var uci
= this.ucipath(sid
);
3038 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
3040 if (typeof(val
) == 'undefined')
3041 return this.options
.initial
;
3046 formvalue: function(sid
)
3048 var v
= $('#' + this.id(sid
)).val();
3049 return (v
=== '') ? undefined : v
;
3052 textvalue: function(sid
)
3054 var v
= this.formvalue(sid
);
3056 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3057 v
= this.ucivalue(sid
);
3059 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3060 v
= this.options
.placeholder
;
3062 if (typeof(v
) == 'undefined' || v
=== '')
3065 if (typeof(v
) == 'string' && $.isArray(this.choices
))
3067 for (var i
= 0; i
< this.choices
.length
; i
++)
3068 if (v
=== this.choices
[i
][0])
3069 return this.choices
[i
][1];
3071 else if (v
=== true)
3072 return _luci2
.tr('yes');
3073 else if (v
=== false)
3074 return _luci2
.tr('no');
3075 else if ($.isArray(v
))
3076 return v
.join(', ');
3081 changed: function(sid
)
3083 var a
= this.ucivalue(sid
);
3084 var b
= this.formvalue(sid
);
3086 if (typeof(a
) != typeof(b
))
3089 if (typeof(a
) == 'object')
3091 if (a
.length
!= b
.length
)
3094 for (var i
= 0; i
< a
.length
; i
++)
3106 var uci
= this.ucipath(sid
);
3108 if (this.instance
[sid
].disabled
)
3110 if (!this.options
.keep
)
3111 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3116 var chg
= this.changed(sid
);
3117 var val
= this.formvalue(sid
);
3120 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
3125 validator: function(sid
, elem
, multi
)
3127 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
3131 if (typeof(this.options
.datatype
) == 'string')
3134 vstack
= _luci2
.cbi
.validation
.compile(this.options
.datatype
);
3137 else if (typeof(this.options
.datatype
) == 'function')
3139 var vfunc
= this.options
.datatype
;
3140 vstack
= [ function(elem
) {
3141 var rv
= vfunc(this, elem
);
3143 validation
.message
= rv
;
3144 return (rv
=== true);
3153 inst
: this.instance
[sid
],
3154 opt
: this.options
.optional
3157 var validator = function(ev
)
3161 var val
= d
.elem
.val();
3163 if (vstack
&& typeof(vstack
[0]) == 'function')
3165 delete validation
.message
;
3167 if ((val
.length
== 0 && !d
.opt
))
3169 d
.elem
.addClass('error');
3170 d
.inst
.top
.addClass('error');
3171 d
.inst
.error
.text(_luci2
.tr('Field must not be empty'));
3174 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
3176 d
.elem
.addClass('error');
3177 d
.inst
.top
.addClass('error');
3178 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1]));
3183 d
.elem
.removeClass('error');
3185 if (d
.multi
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
3191 d
.inst
.top
.removeClass('error');
3192 d
.inst
.error
.text('');
3199 for (var field
in d
.self
.rdependency
)
3200 d
.self
.rdependency
[field
].toggle(d
.sid
);
3206 if (elem
.prop('tagName') == 'SELECT')
3208 elem
.change(evdata
, validator
);
3210 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
3212 elem
.click(evdata
, validator
);
3213 elem
.blur(evdata
, validator
);
3217 elem
.keyup(evdata
, validator
);
3218 elem
.blur(evdata
, validator
);
3221 elem
.attr('cbi-validate', true).on('validate', evdata
, validator
);
3226 validate: function(sid
)
3228 var i
= this.instance
[sid
];
3230 i
.widget
.find('[cbi-validate]').trigger('validate');
3232 return (i
.disabled
|| i
.error
.text() == '');
3235 depends: function(d
, v
)
3242 for (var i
= 0; i
< d
.length
; i
++)
3244 if (typeof(d
[i
]) == 'string')
3246 else if (d
[i
] instanceof AbstractValue
)
3247 dep
[d
[i
].name
] = true;
3250 else if (d
instanceof AbstractValue
)
3253 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
3255 else if (typeof(d
) == 'object')
3259 else if (typeof(d
) == 'string')
3262 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
3265 if (!dep
|| $.isEmptyObject(dep
))
3268 for (var field
in dep
)
3270 var f
= this.section
.fields
[field
];
3272 f
.rdependency
[this.name
] = this;
3277 if ($.isEmptyObject(dep
))
3280 this.dependencies
.push(dep
);
3285 toggle: function(sid
)
3287 var d
= this.dependencies
;
3288 var i
= this.instance
[sid
];
3293 for (var n
= 0; n
< d
.length
; n
++)
3297 for (var field
in d
[n
])
3299 var val
= this.section
.fields
[field
].formvalue(sid
);
3300 var cmp
= d
[n
][field
];
3302 if (typeof(cmp
) == 'boolean')
3304 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
3310 else if (typeof(cmp
) == 'string')
3318 else if (typeof(cmp
) == 'function')
3326 else if (cmp
instanceof RegExp
)
3351 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
3358 this.cbi
.CheckboxValue
= AbstractValue
.extend({
3359 widget: function(sid
)
3361 var o
= this.options
;
3363 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
3364 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
3366 var i
= $('<input />')
3367 .attr('id', this.id(sid
))
3368 .attr('type', 'checkbox')
3369 .prop('checked', this.ucivalue(sid
));
3371 return this.validator(sid
, i
);
3374 ucivalue: function(sid
)
3376 var v
= this.callSuper('ucivalue', sid
);
3378 if (typeof(v
) == 'boolean')
3381 return (v
== this.options
.enabled
);
3384 formvalue: function(sid
)
3386 var v
= $('#' + this.id(sid
)).prop('checked');
3388 if (typeof(v
) == 'undefined')
3389 return !!this.options
.initial
;
3396 var uci
= this.ucipath(sid
);
3398 if (this.instance
[sid
].disabled
)
3400 if (!this.options
.keep
)
3401 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3406 var chg
= this.changed(sid
);
3407 var val
= this.formvalue(sid
);
3411 val
= val
? this.options
.enabled
: this.options
.disabled
;
3413 if (this.options
.optional
&& val
== this.options
.initial
)
3414 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3416 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
3423 this.cbi
.InputValue
= AbstractValue
.extend({
3424 widget: function(sid
)
3426 var i
= $('<input />')
3427 .attr('id', this.id(sid
))
3428 .attr('type', 'text')
3429 .attr('placeholder', this.options
.placeholder
)
3430 .val(this.ucivalue(sid
));
3432 return this.validator(sid
, i
);
3436 this.cbi
.PasswordValue
= AbstractValue
.extend({
3437 widget: function(sid
)
3439 var i
= $('<input />')
3440 .attr('id', this.id(sid
))
3441 .attr('type', 'password')
3442 .attr('placeholder', this.options
.placeholder
)
3443 .val(this.ucivalue(sid
));
3445 var t
= $('<img />')
3446 .attr('src', _luci2
.globals
.resource
+ '/icons/cbi/reload.gif')
3447 .attr('title', _luci2
.tr('Reveal or hide password'))
3448 .addClass('cbi-button')
3449 .click(function(ev
) {
3450 var i
= $(this).prev();
3451 var t
= i
.attr('type');
3452 i
.attr('type', (t
== 'password') ? 'text' : 'password');
3456 this.validator(sid
, i
);
3459 .addClass('cbi-input-password')
3465 this.cbi
.ListValue
= AbstractValue
.extend({
3466 widget: function(sid
)
3468 var s
= $('<select />');
3470 if (this.options
.optional
)
3473 .text(_luci2
.tr('-- Please choose --'))
3477 for (var i
= 0; i
< this.choices
.length
; i
++)
3479 .attr('value', this.choices
[i
][0])
3480 .text(this.choices
[i
][1])
3483 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
3485 return this.validator(sid
, s
);
3488 value: function(k
, v
)
3493 this.choices
.push([k
, v
|| k
]);
3498 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
3499 widget: function(sid
)
3501 var v
= this.ucivalue(sid
);
3502 var t
= $('<div />').attr('id', this.id(sid
));
3505 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
3508 for (var i
= 0; i
< v
.length
; i
++)
3512 for (var i
= 0; i
< this.choices
.length
; i
++)
3515 .append($('<input />')
3516 .addClass('cbi-input-checkbox')
3517 .attr('type', 'checkbox')
3518 .attr('value', this.choices
[i
][0])
3519 .prop('checked', s
[this.choices
[i
][0]]))
3520 .append(this.choices
[i
][1])
3530 formvalue: function(sid
)
3533 var fields
= $('#' + this.id(sid
) + ' > label > input');
3535 for (var i
= 0; i
< fields
.length
; i
++)
3536 if (fields
[i
].checked
)
3537 rv
.push(fields
[i
].getAttribute('value'));
3542 textvalue: function(sid
)
3544 var v
= this.formvalue(sid
);
3548 for (var i
= 0; i
< this.choices
.length
; i
++)
3549 c
[this.choices
[i
][0]] = this.choices
[i
][1];
3553 for (var i
= 0; i
< v
.length
; i
++)
3554 t
.push(c
[v
[i
]] || v
[i
]);
3556 return t
.join(', ');
3560 this.cbi
.ComboBox
= AbstractValue
.extend({
3561 _change: function(ev
)
3564 var self
= ev
.data
.self
;
3566 if (s
.selectedIndex
== (s
.options
.length
- 1))
3568 ev
.data
.select
.hide();
3569 ev
.data
.input
.show().focus();
3571 var v
= ev
.data
.input
.val();
3572 ev
.data
.input
.val(' ');
3573 ev
.data
.input
.val(v
);
3575 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
3577 ev
.data
.input
.val('');
3581 ev
.data
.input
.val(ev
.data
.select
.val());
3588 var val
= this.value
;
3589 var self
= ev
.data
.self
;
3591 ev
.data
.select
.empty();
3593 if (self
.options
.optional
)
3596 .text(_luci2
.tr('-- please choose --'))
3597 .appendTo(ev
.data
.select
);
3600 for (var i
= 0; i
< self
.choices
.length
; i
++)
3602 if (self
.choices
[i
][0] == val
)
3606 .attr('value', self
.choices
[i
][0])
3607 .text(self
.choices
[i
][1])
3608 .appendTo(ev
.data
.select
);
3611 if (!seen
&& val
!= '')
3615 .appendTo(ev
.data
.select
);
3619 .text(_luci2
.tr('-- custom --'))
3620 .appendTo(ev
.data
.select
);
3622 ev
.data
.input
.hide();
3623 ev
.data
.select
.val(val
).show().focus();
3626 _enter: function(ev
)
3631 ev
.preventDefault();
3632 ev
.data
.self
._blur(ev
);
3636 widget: function(sid
)
3638 var d
= $('<div />')
3639 .attr('id', this.id(sid
));
3641 var t
= $('<input />')
3642 .attr('type', 'text')
3646 var s
= $('<select />')
3651 input
: this.validator(sid
, t
),
3652 select
: this.validator(sid
, s
)
3655 s
.change(evdata
, this._change
);
3656 t
.blur(evdata
, this._blur
);
3657 t
.keydown(evdata
, this._enter
);
3659 t
.val(this.ucivalue(sid
));
3665 value: function(k
, v
)
3670 this.choices
.push([k
, v
|| k
]);
3674 formvalue: function(sid
)
3676 var v
= $('#' + this.id(sid
)).children('input').val();
3677 return (v
== '') ? undefined : v
;
3681 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
3682 _redraw: function(focus
, add
, del
, s
)
3684 var v
= s
.values
|| [ ];
3687 $(s
.parent
).children('input').each(function(i
) {
3689 v
.push(this.value
|| '');
3692 $(s
.parent
).empty();
3697 v
.splice(focus
, 0, '');
3699 else if (v
.length
== 0)
3705 for (var i
= 0; i
< v
.length
; i
++)
3716 var txt
= $('<input />')
3717 .attr('type', 'text')
3719 .appendTo(s
.parent
);
3721 var sel
= $('<select />')
3722 .appendTo(s
.parent
);
3724 evdata
.input
= this.validator(s
.sid
, txt
, true);
3725 evdata
.select
= this.validator(s
.sid
, sel
, true);
3727 sel
.change(evdata
, this._change
);
3728 txt
.blur(evdata
, this._blur
);
3729 txt
.keydown(evdata
, this._keydown
);
3734 if (i
== focus
|| -(i
+1) == focus
)
3741 var f
= $('<input />')
3742 .attr('type', 'text')
3744 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
3745 .addClass('cbi-input-text')
3746 .keydown(evdata
, this._keydown
)
3747 .keypress(evdata
, this._keypress
)
3750 f
.appendTo(s
.parent
);
3756 else if (-(i
+1) == focus
)
3760 /* force cursor to end */
3766 evdata
.input
= this.validator(s
.sid
, f
, true);
3772 .attr('src', _luci2
.globals
.resource
+ ((i
+1) < v
.length
? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
3773 .attr('title', (i
+1) < v
.length
? _luci2
.tr('Remove entry') : _luci2
.tr('Add entry'))
3774 .addClass('cbi-button')
3775 .click(evdata
, this._btnclick
)
3776 .appendTo(s
.parent
);
3779 .appendTo(s
.parent
);
3787 _keypress: function(ev
)
3791 /* backspace, delete */
3794 if (ev
.data
.input
.val() == '')
3796 ev
.preventDefault();
3802 /* enter, arrow up, arrow down */
3806 ev
.preventDefault();
3813 _keydown: function(ev
)
3815 var input
= ev
.data
.input
;
3819 /* backspace, delete */
3822 if (input
.val().length
== 0)
3824 ev
.preventDefault();
3826 var index
= ev
.data
.index
;
3832 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
3840 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
3845 var prev
= input
.prevAll('input:first');
3846 if (prev
.is(':visible'))
3849 prev
.next('select').focus();
3854 var next
= input
.nextAll('input:first');
3855 if (next
.is(':visible'))
3858 next
.next('select').focus();
3865 _btnclick: function(ev
)
3867 if (!this.getAttribute('disabled'))
3869 if (ev
.target
.src
.indexOf('remove') > -1)
3871 var index
= ev
.data
.index
;
3872 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
3876 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
3883 widget: function(sid
)
3885 this.options
.optional
= true;
3887 var v
= this.ucivalue(sid
);
3890 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
3892 var d
= $('<div />')
3893 .attr('id', this.id(sid
))
3894 .addClass('cbi-input-dynlist');
3896 this._redraw(NaN
, -1, -1, {
3906 ucivalue: function(sid
)
3908 var v
= this.callSuper('ucivalue', sid
);
3911 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
3916 formvalue: function(sid
)
3919 var fields
= $('#' + this.id(sid
) + ' > input');
3921 for (var i
= 0; i
< fields
.length
; i
++)
3922 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
3923 rv
.push(fields
[i
].value
);
3929 this.cbi
.DummyValue
= AbstractValue
.extend({
3930 widget: function(sid
)
3933 .addClass('cbi-value-dummy')
3934 .attr('id', this.id(sid
))
3935 .html(this.ucivalue(sid
));
3938 formvalue: function(sid
)
3940 return this.ucivalue(sid
);
3944 this.cbi
.NetworkList
= AbstractValue
.extend({
3949 if (!self
.interfaces
)
3951 self
.interfaces
= [ ];
3952 return _luci2
.network
.getNetworkStatus().then(function(ifaces
) {
3953 self
.interfaces
= ifaces
;
3961 _device_icon: function(dev
)
3963 var type
= 'ethernet';
3964 var desc
= _luci2
.tr('Ethernet device');
3966 if (dev
.type
== 'IP tunnel')
3969 desc
= _luci2
.tr('Tunnel interface');
3971 else if (dev
['bridge-members'])
3974 desc
= _luci2
.tr('Bridge');
3976 else if (dev
.wireless
)
3979 desc
= _luci2
.tr('Wireless Network');
3981 else if (dev
.device
.indexOf('.') > 0)
3984 desc
= _luci2
.tr('VLAN interface');
3988 .attr('src', _luci2
.globals
.resource
+ '/icons/' + type
+ (dev
.up
? '' : '_disabled') + '.png')
3989 .attr('title', '%s (%s)'.format(desc
, dev
.device
));
3992 widget: function(sid
)
3994 var id
= this.id(sid
);
3995 var ul
= $('<ul />')
3997 .addClass('cbi-input-networks');
3999 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
4000 var value
= this.ucivalue(sid
);
4003 if (!this.options
.multiple
)
4004 check
[value
] = true;
4006 for (var i
= 0; i
< value
.length
; i
++)
4007 check
[value
[i
]] = true;
4009 if (this.interfaces
)
4011 for (var i
= 0; i
< this.interfaces
.length
; i
++)
4013 var iface
= this.interfaces
[i
];
4014 var badge
= $('<span />')
4015 .addClass('ifacebadge')
4016 .text('%s: '.format(iface
['interface']));
4018 if (iface
.device
&& iface
.device
.subdevices
)
4019 for (var j
= 0; j
< iface
.device
.subdevices
.length
; j
++)
4020 badge
.append(this._device_icon(iface
.device
.subdevices
[j
]));
4021 else if (iface
.device
)
4022 badge
.append(this._device_icon(iface
.device
));
4024 badge
.append($('<em />').text(_luci2
.tr('(No devices attached)')));
4027 .append($('<label />')
4028 .append($('<input />')
4029 .attr('name', itype
+ id
)
4030 .attr('type', itype
)
4031 .attr('value', iface
['interface'])
4032 .prop('checked', !!check
[iface
['interface']])
4033 .addClass('cbi-input-' + itype
))
4039 if (!this.options
.multiple
)
4042 .append($('<label />')
4043 .append($('<input />')
4044 .attr('name', itype
+ id
)
4045 .attr('type', itype
)
4047 .prop('checked', !value
)
4048 .addClass('cbi-input-' + itype
))
4049 .append(_luci2
.tr('unspecified')))
4056 ucivalue: function(sid
)
4058 var v
= this.callSuper('ucivalue', sid
);
4060 if (!this.options
.multiple
)
4066 else if (typeof(v
) == 'string')
4069 return v
? v
[0] : undefined;
4076 if (typeof(v
) == 'string')
4077 v
= v
.match(/\S+/g);
4083 formvalue: function(sid
)
4085 var inputs
= $('#' + this.id(sid
) + ' input');
4087 if (!this.options
.multiple
)
4089 for (var i
= 0; i
< inputs
.length
; i
++)
4090 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
4091 return inputs
[i
].value
;
4098 for (var i
= 0; i
< inputs
.length
; i
++)
4099 if (inputs
[i
].checked
)
4100 rv
.push(inputs
[i
].value
);
4102 return rv
.length
? rv
: undefined;
4107 var AbstractSection
= AbstractWidget
.extend({
4110 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
4112 for (var i
= 1; i
< arguments
.length
; i
++)
4113 s
.push(arguments
[i
].replace(/\./g, '_'));
4118 option: function(widget
, name
, options
)
4120 if (this.tabs
.length
== 0)
4121 this.tab({ id
: '__default__', selected
: true });
4123 return this.taboption('__default__', widget
, name
, options
);
4126 tab: function(options
)
4128 if (options
.selected
)
4129 this.tabs
.selected
= this.tabs
.length
;
4133 caption
: options
.caption
,
4134 description
: options
.description
,
4140 taboption: function(tabid
, widget
, name
, options
)
4143 for (var i
= 0; i
< this.tabs
.length
; i
++)
4145 if (this.tabs
[i
].id
== tabid
)
4153 throw 'Cannot append to unknown tab ' + tabid
;
4155 var w
= widget
? new widget(name
, options
) : null;
4157 if (!(w
instanceof AbstractValue
))
4158 throw 'Widget must be an instance of AbstractValue';
4163 this.fields
[name
] = w
;
4169 ucipackages: function(pkg
)
4171 for (var i
= 0; i
< this.tabs
.length
; i
++)
4172 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4173 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
4174 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
4177 formvalue: function()
4181 this.sections(function(s
) {
4182 var sid
= s
['.name'];
4183 var sv
= rv
[sid
] || (rv
[sid
] = { });
4185 for (var i
= 0; i
< this.tabs
.length
; i
++)
4186 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4188 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
4189 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
4196 validate: function(sid
)
4202 var as
= this.sections();
4203 for (var i
= 0; i
< as
.length
; i
++)
4204 if (!this.validate(as
[i
]['.name']))
4209 var inst
= this.instance
[sid
];
4210 var sv
= rv
[sid
] || (rv
[sid
] = { });
4213 var legend
= $('#' + this.id('sort', sid
)).find('legend:first');
4215 legend
.children('span').detach();
4217 for (var i
= 0; i
< this.tabs
.length
; i
++)
4220 var tab
= $('#' + this.id('tabhead', sid
, this.tabs
[i
].id
));
4222 tab
.children('span').detach();
4224 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4225 if (!this.tabs
[i
].fields
[j
].validate(sid
))
4232 .attr('title', _luci2
.tr('%d Errors'.format(inval
)))
4245 .attr('title', _luci2
.tr('%d Errors'.format(invals
)))
4253 this.cbi
.TypedSection
= AbstractSection
.extend({
4254 init: function(uci_type
, options
)
4256 this.uci_type
= uci_type
;
4257 this.options
= options
;
4260 this.active_panel
= 0;
4261 this.active_tab
= { };
4264 filter: function(section
)
4269 sections: function(cb
)
4271 var s1
= this.map
.ucisections(this.map
.uci_package
);
4274 for (var i
= 0; i
< s1
.length
; i
++)
4275 if (s1
[i
]['.type'] == this.uci_type
)
4276 if (this.filter(s1
[i
]))
4279 if (typeof(cb
) == 'function')
4280 for (var i
= 0; i
< s2
.length
; i
++)
4281 cb
.apply(this, [ s2
[i
] ]);
4288 this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
4291 remove: function(sid
)
4293 this.map
.remove(this.map
.uci_package
, sid
);
4299 var name
= undefined;
4300 var self
= ev
.data
.self
;
4302 if (addb
.prev().prop('nodeName') == 'INPUT')
4303 name
= addb
.prev().val();
4305 if (addb
.prop('disabled') || name
=== '')
4308 self
.active_panel
= -1;
4314 _remove: function(ev
)
4316 var self
= ev
.data
.self
;
4317 var sid
= ev
.data
.sid
;
4323 ev
.stopPropagation();
4328 var self
= ev
.data
.self
;
4330 var addb
= text
.next();
4331 var errt
= addb
.next();
4332 var name
= text
.val();
4335 if (!/^[a-zA-Z0-9_]*$/.test(name
))
4337 errt
.text(_luci2
.tr('Invalid section name')).show();
4338 text
.addClass('error');
4339 addb
.prop('disabled', true);
4343 for (var sid
in self
.map
.uci
.values
[self
.map
.uci_package
])
4350 for (var sid
in self
.map
.uci
.creates
[self
.map
.uci_package
])
4359 errt
.text(_luci2
.tr('Name already used')).show();
4360 text
.addClass('error');
4361 addb
.prop('disabled', true);
4365 errt
.text('').hide();
4366 text
.removeClass('error');
4367 addb
.prop('disabled', false);
4371 teaser: function(sid
)
4373 var tf
= this.teaser_fields
;
4377 tf
= this.teaser_fields
= [ ];
4379 if ($.isArray(this.options
.teasers
))
4381 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
4383 var f
= this.options
.teasers
[i
];
4384 if (f
instanceof AbstractValue
)
4386 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof AbstractValue
)
4387 tf
.push(this.fields
[f
]);
4392 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
4393 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
4394 tf
.push(this.tabs
[i
].fields
[j
]);
4400 for (var i
= 0; i
< tf
.length
; i
++)
4402 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
4405 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
4406 var v
= tf
[i
].textvalue(sid
);
4408 if (typeof(v
) == 'undefined')
4411 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
4417 _render_add: function()
4419 var text
= _luci2
.tr('Add section');
4420 var ttip
= _luci2
.tr('Create new section...');
4422 if ($.isArray(this.options
.add_caption
))
4423 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
4424 else if (typeof(this.options
.add_caption
) == 'string')
4425 text
= this.options
.add_caption
, ttip
= '';
4427 var add
= $('<div />').addClass('cbi-section-add');
4429 if (this.options
.anonymous
=== false)
4432 .addClass('cbi-input-text')
4433 .attr('type', 'text')
4434 .attr('placeholder', ttip
)
4435 .blur({ self
: this }, this._sid
)
4436 .keyup({ self
: this }, this._sid
)
4440 .attr('src', _luci2
.globals
.resource
+ '/icons/cbi/add.gif')
4441 .attr('title', text
)
4442 .addClass('cbi-button')
4443 .click({ self
: this }, this._add
)
4447 .addClass('cbi-value-error')
4454 .attr('type', 'button')
4455 .addClass('cbi-button')
4456 .addClass('cbi-button-add')
4457 .val(text
).attr('title', ttip
)
4458 .click({ self
: this }, this._add
)
4465 _render_remove: function(sid
)
4467 var text
= _luci2
.tr('Remove');
4468 var ttip
= _luci2
.tr('Remove this section');
4470 if ($.isArray(this.options
.remove_caption
))
4471 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
4472 else if (typeof(this.options
.remove_caption
) == 'string')
4473 text
= this.options
.remove_caption
, ttip
= '';
4475 return $('<input />')
4476 .attr('type', 'button')
4477 .addClass('cbi-button')
4478 .addClass('cbi-button-remove')
4479 .val(text
).attr('title', ttip
)
4480 .click({ self
: this, sid
: sid
}, this._remove
);
4483 _render_caption: function(sid
)
4485 if (typeof(this.options
.caption
) == 'string')
4487 return $('<legend />')
4488 .text(this.options
.caption
.format(sid
));
4490 else if (typeof(this.options
.caption
) == 'function')
4492 return $('<legend />')
4493 .text(this.options
.caption
.call(this, sid
));
4501 var allsections
= $();
4502 var panel_index
= 0;
4504 this.instance
= { };
4506 var s
= this.sections();
4510 var fieldset
= $('<fieldset />')
4511 .addClass('cbi-section');
4513 var head
= $('<div />')
4514 .addClass('cbi-section-head')
4515 .appendTo(fieldset
);
4517 head
.append(this._render_caption(undefined));
4519 if (typeof(this.options
.description
) == 'string')
4522 .addClass('cbi-section-descr')
4523 .text(this.options
.description
)
4527 allsections
= allsections
.add(fieldset
);
4530 for (var i
= 0; i
< s
.length
; i
++)
4532 var sid
= s
[i
]['.name'];
4533 var inst
= this.instance
[sid
] = { tabs
: [ ] };
4535 var fieldset
= $('<fieldset />')
4536 .attr('id', this.id('sort', sid
))
4537 .addClass('cbi-section');
4539 var head
= $('<div />')
4540 .addClass('cbi-section-head')
4541 .attr('cbi-section-num', this.index
)
4542 .attr('cbi-section-id', sid
);
4544 head
.append(this._render_caption(sid
));
4546 if (typeof(this.options
.description
) == 'string')
4549 .addClass('cbi-section-descr')
4550 .text(this.options
.description
)
4555 if ((s
.length
> 1 && this.options
.collabsible
) || this.map
.options
.collabsible
)
4556 teaser
= $('<div />')
4557 .addClass('cbi-section-teaser')
4560 if (this.options
.addremove
)
4562 .addClass('cbi-section-remove')
4564 .append(this._render_remove(sid
))
4567 var body
= $('<div />')
4568 .attr('index', panel_index
++);
4570 var fields
= $('<fieldset />')
4571 .addClass('cbi-section-node');
4573 if (this.tabs
.length
> 1)
4575 var menu
= $('<ul />')
4576 .addClass('cbi-tabmenu');
4578 for (var j
= 0; j
< this.tabs
.length
; j
++)
4580 var tabid
= this.id('tab', sid
, this.tabs
[j
].id
);
4581 var theadid
= this.id('tabhead', sid
, this.tabs
[j
].id
);
4583 var tabc
= $('<div />')
4584 .addClass('cbi-tabcontainer')
4588 if (typeof(this.tabs
[j
].description
) == 'string')
4591 .addClass('cbi-tab-descr')
4592 .text(this.tabs
[j
].description
)
4596 for (var k
= 0; k
< this.tabs
[j
].fields
.length
; k
++)
4597 this.tabs
[j
].fields
[k
].render(sid
).appendTo(tabc
);
4599 tabc
.appendTo(fields
);
4602 $('<li />').attr('id', theadid
).append(
4604 .text(this.tabs
[j
].caption
.format(this.tabs
[j
].id
))
4605 .attr('href', '#' + tabid
)
4609 menu
.appendTo(body
);
4612 fields
.appendTo(body
);
4615 var t
= body
.tabs({ active
: this.active_tab
[sid
] });
4617 t
.on('tabsactivate', { self
: this, sid
: sid
}, function(ev
, ui
) {
4620 d
.self
.active_tab
[d
.sid
] = parseInt(ui
.newPanel
.attr('index'));
4625 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
4626 this.tabs
[0].fields
[j
].render(sid
).appendTo(fields
);
4628 fields
.appendTo(body
);
4632 head
.appendTo(fieldset
);
4635 body
.appendTo(fieldset
);
4638 allsections
= allsections
.add(fieldset
);
4641 //this.validate(sid);
4644 // teaser.append(this.teaser(sid));
4647 if (this.options
.collabsible
&& s
.length
> 1)
4649 var a
= $('<div />').append(allsections
).accordion({
4650 header
: '> fieldset > div.cbi-section-head',
4651 heightStyle
: 'content',
4652 active
: this.active_panel
4655 a
.on('accordionbeforeactivate', { self
: this }, function(ev
, ui
) {
4656 var h
= ui
.oldHeader
;
4657 var s
= ev
.data
.self
;
4658 var i
= h
.attr('cbi-section-id');
4660 h
.children('.cbi-section-teaser').empty().append(s
.teaser(i
));
4664 a
.on('accordionactivate', { self
: this }, function(ev
, ui
) {
4665 ev
.data
.self
.active_panel
= parseInt(ui
.newPanel
.attr('index'));
4668 if (this.options
.sortable
)
4670 var s
= a
.sortable({
4672 handle
: 'div.cbi-section-head'
4675 s
.on('sortupdate', { self
: this, ids
: s
.sortable('toArray') }, function(ev
, ui
) {
4677 for (var i
= 0; i
< ev
.data
.ids
.length
; i
++)
4678 sections
.push(ev
.data
.ids
[i
].substring(ev
.data
.ids
[i
].lastIndexOf('.') + 1));
4679 _luci2
.uci
.order(ev
.data
.self
.map
.uci_package
, sections
);
4682 s
.on('sortstop', function(ev
, ui
) {
4683 ui
.item
.children('div.cbi-section-head').triggerHandler('focusout');
4687 if (this.options
.addremove
)
4688 this._render_add().appendTo(a
);
4693 if (this.options
.addremove
)
4694 allsections
= allsections
.add(this._render_add());
4701 var s
= this.sections();
4703 for (var i
= 0; i
< s
.length
; i
++)
4705 var sid
= s
[i
]['.name'];
4709 $('#' + this.id('sort', sid
))
4710 .children('.cbi-section-head')
4711 .children('.cbi-section-teaser')
4712 .append(this.teaser(sid
));
4717 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
4720 var allsections
= $();
4721 var panel_index
= 0;
4723 this.instance
= { };
4725 var s
= this.sections();
4727 var fieldset
= $('<fieldset />')
4728 .addClass('cbi-section');
4730 fieldset
.append(this._render_caption(sid
));
4732 if (typeof(this.options
.description
) == 'string')
4735 .addClass('cbi-section-descr')
4736 .text(this.options
.description
)
4737 .appendTo(fieldset
);
4740 var fields
= $('<div />')
4741 .addClass('cbi-section-node')
4742 .appendTo(fieldset
);
4744 var table
= $('<table />')
4745 .addClass('cbi-section-table')
4748 var thead
= $('<thead />')
4749 .append($('<tr />').addClass('cbi-section-table-titles'))
4752 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
4754 .addClass('cbi-section-table-cell')
4755 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
4756 .append(this.tabs
[0].fields
[j
].options
.caption
)
4757 .appendTo(thead
.children());
4759 if (this.options
.sortable
)
4760 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead
.children());
4762 if (this.options
.addremove
!== false)
4763 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead
.children());
4765 var tbody
= $('<tbody />')
4771 .addClass('cbi-section-table-row')
4774 .addClass('cbi-section-table-cell')
4775 .addClass('cbi-section-table-placeholder')
4776 .attr('colspan', thead
.children().children().length
)
4777 .text(this.options
.placeholder
|| _luci2
.tr('This section contains no values yet')))
4781 for (var i
= 0; i
< s
.length
; i
++)
4783 var sid
= s
[i
]['.name'];
4784 var inst
= this.instance
[sid
] = { tabs
: [ ] };
4786 var row
= $('<tr />')
4787 .addClass('cbi-section-table-row')
4790 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
4793 .addClass('cbi-section-table-cell')
4794 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
4795 .append(this.tabs
[0].fields
[j
].render(sid
, true))
4799 if (this.options
.sortable
)
4802 .addClass('cbi-section-table-cell')
4803 .addClass('cbi-section-table-sort')
4804 .append($('<img />').attr('src', _luci2
.globals
.resource
+ '/icons/cbi/up.gif').attr('title', _luci2
.tr('Drag to sort')))
4805 .append($('<br />'))
4806 .append($('<img />').attr('src', _luci2
.globals
.resource
+ '/icons/cbi/down.gif').attr('title', _luci2
.tr('Drag to sort')))
4810 if (this.options
.addremove
!== false)
4813 .addClass('cbi-section-table-cell')
4814 .append(this._render_remove(sid
))
4823 if (this.options
.sortable
)
4825 var s
= tbody
.sortable({
4826 handle
: 'td.cbi-section-table-sort'
4829 s
.on('sortupdate', { self
: this, ids
: s
.sortable('toArray') }, function(ev
, ui
) {
4831 for (var i
= 0; i
< ev
.data
.ids
.length
; i
++)
4832 sections
.push(ev
.data
.ids
[i
].substring(ev
.data
.ids
[i
].lastIndexOf('.') + 1));
4833 _luci2
.uci
.order(ev
.data
.self
.map
.uci_package
, sections
);
4836 s
.on('sortstop', function(ev
, ui
) {
4837 ui
.item
.children('div.cbi-section-head').triggerHandler('focusout');
4841 if (this.options
.addremove
)
4842 this._render_add().appendTo(fieldset
);
4844 fields
= table
= thead
= tbody
= null;
4850 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
4851 sections: function(cb
)
4854 var pkg
= this.map
.uci
.values
[this.map
.uci_package
];
4857 if (pkg
[s
]['.name'] == this.uci_type
)
4863 if (typeof(cb
) == 'function' && sa
.length
> 0)
4864 cb
.apply(this, [ sa
[0] ]);
4870 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
4871 sections: function(cb
)
4873 if (typeof(cb
) == 'function')
4874 cb
.apply(this, [ { '.name': this.uci_type
} ]);
4876 return [ { '.name': this.uci_type
} ];
4880 this.cbi
.Map
= AbstractWidget
.extend({
4881 init: function(uci_package
, options
)
4885 this.uci_package
= uci_package
;
4886 this.sections
= [ ];
4887 this.options
= _luci2
.defaults(options
, {
4888 save: function() { },
4889 prepare: function() {
4890 return _luci2
.uci
.writable(function(writable
) {
4891 self
.options
.readonly
= !writable
;
4907 this.active_panel
= 0;
4911 for (var i
= 0; i
< this.sections
.length
; i
++)
4912 this.sections
[i
].ucipackages(packages
);
4914 packages
[this.uci_package
] = true;
4916 var load_cb
= this._load_cb
|| (this._load_cb
= $.proxy(function(packages
) {
4917 for (var i
= 0; i
< packages
.length
; i
++)
4919 this.uci
.values
[packages
[i
]['.package']] = packages
[i
];
4920 delete packages
[i
]['.package'];
4923 var deferreds
= [ _luci2
.deferrable(this.options
.prepare()) ];
4925 for (var i
= 0; i
< this.sections
.length
; i
++)
4927 for (var f
in this.sections
[i
].fields
)
4929 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
4932 var s
= this.sections
[i
].sections();
4933 for (var j
= 0; j
< s
.length
; j
++)
4935 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
4936 if (_luci2
.isDeferred(rv
))
4942 return $.when
.apply($, deferreds
);
4947 for (var pkg
in packages
)
4948 _luci2
.uci
.get_all(pkg
);
4950 return _luci2
.rpc
.flush().then(load_cb
);
4955 var map
= $('<div />').addClass('cbi-map');
4957 if (typeof(this.options
.caption
) == 'string')
4958 $('<h2 />').text(this.options
.caption
).appendTo(map
);
4960 if (typeof(this.options
.description
) == 'string')
4961 $('<div />').addClass('cbi-map-descr').text(this.options
.description
).appendTo(map
);
4963 var sections
= $('<div />').appendTo(map
);
4965 for (var i
= 0; i
< this.sections
.length
; i
++)
4967 var s
= this.sections
[i
].render();
4969 if (this.options
.readonly
|| this.sections
[i
].options
.readonly
)
4970 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
4972 s
.appendTo(sections
);
4974 if (this.sections
[i
].options
.active
)
4975 this.active_panel
= i
;
4978 if (this.options
.collabsible
)
4980 var a
= sections
.accordion({
4981 header
: '> fieldset > div.cbi-section-head',
4982 heightStyle
: 'content',
4983 active
: this.active_panel
4986 a
.on('accordionbeforeactivate', { self
: this }, function(ev
, ui
) {
4987 var h
= ui
.oldHeader
;
4988 var s
= ev
.data
.self
.sections
[parseInt(h
.attr('cbi-section-num'))];
4989 var i
= h
.attr('cbi-section-id');
4991 h
.children('.cbi-section-teaser').empty().append(s
.teaser(i
));
4993 for (var i
= 0; i
< ev
.data
.self
.sections
.length
; i
++)
4994 ev
.data
.self
.sections
[i
].validate();
4997 a
.on('accordionactivate', { self
: this }, function(ev
, ui
) {
4998 ev
.data
.self
.active_panel
= parseInt(ui
.newPanel
.attr('index'));
5002 if (this.options
.pageaction
!== false)
5004 var a
= $('<div />')
5005 .addClass('cbi-page-actions')
5009 .addClass('cbi-button').addClass('cbi-button-apply')
5010 .attr('type', 'button')
5011 .val(_luci2
.tr('Save & Apply'))
5015 .addClass('cbi-button').addClass('cbi-button-save')
5016 .attr('type', 'button')
5017 .val(_luci2
.tr('Save'))
5018 .click({ self
: this }, function(ev
) { ev
.data
.self
.send(); })
5022 .addClass('cbi-button').addClass('cbi-button-reset')
5023 .attr('type', 'button')
5024 .val(_luci2
.tr('Reset'))
5025 .click({ self
: this }, function(ev
) { ev
.data
.self
.insertInto(ev
.data
.self
.target
); })
5031 var top
= $('<form />').append(map
);
5040 for (var i
= 0; i
< this.sections
.length
; i
++)
5041 this.sections
[i
].finish();
5048 this.target
.hide().empty().append(this.render());
5053 section: function(widget
, uci_type
, options
)
5055 var w
= widget
? new widget(uci_type
, options
) : null;
5057 if (!(w
instanceof AbstractSection
))
5058 throw 'Widget must be an instance of AbstractSection';
5061 w
.index
= this.sections
.length
;
5063 this.sections
.push(w
);
5067 formvalue: function()
5071 for (var i
= 0; i
< this.sections
.length
; i
++)
5073 var sids
= this.sections
[i
].formvalue();
5074 for (var sid
in sids
)
5076 var s
= rv
[sid
] || (rv
[sid
] = { });
5077 $.extend(s
, sids
[sid
]);
5084 add: function(conf
, type
, name
)
5086 var c
= this.uci
.creates
;
5087 var s
= '.new.%d'.format(this.uci
.newid
++);
5102 remove: function(conf
, sid
)
5104 var n
= this.uci
.creates
;
5105 var c
= this.uci
.changes
;
5106 var d
= this.uci
.deletes
;
5108 /* requested deletion of a just created section */
5109 if (sid
.indexOf('.new.') == 0)
5112 delete n
[conf
][sid
];
5117 delete c
[conf
][sid
];
5122 d
[conf
][sid
] = true;
5126 ucisections: function(conf
, cb
)
5129 var pkg
= this.uci
.values
[conf
];
5130 var crt
= this.uci
.creates
[conf
];
5131 var del
= this.uci
.deletes
[conf
];
5137 if (!del
|| del
[s
] !== true)
5140 sa
.sort(function(a
, b
) { return a
['.index'] - b
['.index'] });
5146 if (typeof(cb
) == 'function')
5147 for (var i
= 0; i
< sa
.length
; i
++)
5148 cb
.apply(this, [ sa
[i
] ]);
5153 get: function(conf
, sid
, opt
)
5155 var v
= this.uci
.values
;
5156 var n
= this.uci
.creates
;
5157 var c
= this.uci
.changes
;
5158 var d
= this.uci
.deletes
;
5160 /* requested option in a just created section */
5161 if (sid
.indexOf('.new.') == 0)
5166 if (typeof(opt
) == 'undefined')
5167 return (n
[conf
][sid
] || { });
5169 return n
[conf
][sid
][opt
];
5172 /* requested an option value */
5173 if (typeof(opt
) != 'undefined')
5175 /* check whether option was deleted */
5176 if (d
[conf
] && d
[conf
][sid
])
5178 if (d
[conf
][sid
] === true)
5181 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
5182 if (d
[conf
][sid
][i
] == opt
)
5186 /* check whether option was changed */
5187 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
5188 return c
[conf
][sid
][opt
];
5190 /* return base value */
5191 if (v
[conf
] && v
[conf
][sid
])
5192 return v
[conf
][sid
][opt
];
5197 /* requested an entire section */
5199 return (v
[conf
][sid
] || { });
5204 set: function(conf
, sid
, opt
, val
)
5206 var n
= this.uci
.creates
;
5207 var c
= this.uci
.changes
;
5208 var d
= this.uci
.deletes
;
5210 if (sid
.indexOf('.new.') == 0)
5212 if (n
[conf
] && n
[conf
][sid
])
5214 if (typeof(val
) != 'undefined')
5215 n
[conf
][sid
][opt
] = val
;
5217 delete n
[conf
][sid
][opt
];
5220 else if (typeof(val
) != 'undefined')
5228 c
[conf
][sid
][opt
] = val
;
5238 d
[conf
][sid
].push(opt
);
5242 validate: function()
5246 for (var i
= 0; i
< this.sections
.length
; i
++)
5247 if (!this.sections
[i
].validate())
5255 if (this.options
.readonly
)
5256 return _luci2
.deferrable();
5258 var deferreds
= [ _luci2
.deferrable(this.options
.save()) ];
5260 for (var i
= 0; i
< this.sections
.length
; i
++)
5262 if (this.sections
[i
].options
.readonly
)
5265 for (var f
in this.sections
[i
].fields
)
5267 if (typeof(this.sections
[i
].fields
[f
].save
) != 'function')
5270 var s
= this.sections
[i
].sections();
5271 for (var j
= 0; j
< s
.length
; j
++)
5273 var rv
= this.sections
[i
].fields
[f
].save(s
[j
]['.name']);
5274 if (_luci2
.isDeferred(rv
))
5280 return $.when
.apply($, deferreds
);
5285 if (!this.validate())
5286 return _luci2
.deferrable();
5288 var send_cb
= this._send_cb
|| (this._send_cb
= $.proxy(function() {
5291 if (this.uci
.creates
)
5292 for (var c
in this.uci
.creates
)
5293 for (var s
in this.uci
.creates
[c
])
5300 for (var k
in this.uci
.creates
[c
][s
])
5303 r
.type
= this.uci
.creates
[c
][s
][k
];
5304 else if (k
== '.create')
5305 r
.name
= this.uci
.creates
[c
][s
][k
];
5306 else if (k
.charAt(0) != '.')
5307 r
.values
[k
] = this.uci
.creates
[c
][s
][k
];
5310 _luci2
.uci
.add(r
.config
, r
.type
, r
.name
, r
.values
);
5313 if (this.uci
.changes
)
5314 for (var c
in this.uci
.changes
)
5315 for (var s
in this.uci
.changes
[c
])
5316 _luci2
.uci
.set(c
, s
, this.uci
.changes
[c
][s
]);
5318 if (this.uci
.deletes
)
5319 for (var c
in this.uci
.deletes
)
5320 for (var s
in this.uci
.deletes
[c
])
5322 var o
= this.uci
.deletes
[c
][s
];
5323 _luci2
.uci
['delete'](c
, s
, (o
=== true) ? undefined : o
);
5326 return _luci2
.rpc
.flush();
5331 _luci2
.ui
.loading(true);
5333 return this.save().then(send_cb
).then(function() {
5335 }).then(function() {
5339 _luci2
.ui
.loading(false);
5343 dialog: function(id
)
5345 var d
= $('<div />');
5349 .attr('src', _luci2
.globals
.resource
+ '/icons/loading.gif')
5350 .css('vertical-align', 'middle')
5351 .css('padding-right', '10px')
5354 p
.append(_luci2
.tr('Loading data...'));
5365 $(this).parent().children('.ui-dialog-titlebar').hide();
5370 insertInto: function(id
)
5373 self
.target
= $(id
);
5375 _luci2
.ui
.loading(true);
5378 return self
.load().then(function() {
5379 self
.target
.empty().append(self
.render());
5383 _luci2
.ui
.loading(false);