2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String
.prototype.format = function()
15 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g
, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
27 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
29 while ((a
= re
.exec(str
)) != null)
32 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
33 var pPrecision
= a
[6], pType
= a
[7];
43 if (numSubstitutions
< arguments
.length
)
45 var param
= arguments
[numSubstitutions
++];
48 if (pPad
&& pPad
.substr(0,1) == "'")
49 pad
= leftpart
.substr(1,1);
53 var justifyRight
= true;
54 if (pJustify
&& pJustify
=== "-")
59 minLength
= parseInt(pMinLength
);
62 if (pPrecision
&& pType
== 'f')
63 precision
= parseInt(pPrecision
.substring(1));
70 subst
= (parseInt(param
) || 0).toString(2);
74 subst
= String
.fromCharCode(parseInt(param
) || 0);
78 subst
= (parseInt(param
) || 0);
82 subst
= Math
.abs(parseInt(param
) || 0);
86 subst
= (precision
> -1)
87 ? ((parseFloat(param
) || 0.0)).toFixed(precision
)
88 : (parseFloat(param
) || 0.0);
92 subst
= (parseInt(param
) || 0).toString(8);
100 subst
= ('' + (parseInt(param
) || 0).toString(16)).toLowerCase();
104 subst
= ('' + (parseInt(param
) || 0).toString(16)).toUpperCase();
108 subst
= esc(param
, html_esc
);
112 subst
= esc(param
, quot_esc
);
116 subst
= String
.serialize(param
);
123 var ts
= (param
|| 0);
126 tm
= Math
.floor(ts
/ 60);
131 th
= Math
.floor(tm
/ 60);
136 td
= Math
.floor(th
/ 24);
141 ? '%dd %dh %dm %ds'.format(td
, th
, tm
, ts
)
142 : '%dh %dm %ds'.format(th
, tm
, ts
);
147 var mf
= pMinLength
? parseInt(pMinLength
) : 1000;
148 var pr
= pPrecision
? Math
.floor(10*parseFloat('0'+pPrecision
)) : 2;
151 var val
= parseFloat(param
|| 0);
152 var units
= [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
157 subst
= val
.toFixed(pr
) + ' ' + units
[i
];
161 subst
= (typeof(subst
) == 'undefined') ? '' : subst
.toString();
163 if (minLength
> 0 && pad
.length
> 0)
164 for (var i
= 0; i
< (minLength
- subst
.length
); i
++)
165 subst
= justifyRight
? (pad
+ subst
) : (subst
+ pad
);
169 out
+= leftpart
+ subst
;
170 str
= str
.substr(m
.length
);
180 var Class = function() { };
182 Class
.extend = function(properties
)
184 Class
.initializing
= true;
186 var prototype = new this();
187 var superprot
= this.prototype;
189 Class
.initializing
= false;
191 $.extend(prototype, properties
, {
192 callSuper: function() {
194 var meth
= arguments
[0];
196 if (typeof(superprot
[meth
]) != 'function')
199 for (var i
= 1; i
< arguments
.length
; i
++)
200 args
.push(arguments
[i
]);
202 return superprot
[meth
].apply(this, args
);
208 this.options
= arguments
[0] || { };
210 if (!Class
.initializing
&& typeof(this.init
) == 'function')
211 this.init
.apply(this, arguments
);
214 _class
.prototype = prototype;
215 _class
.prototype.constructor = _class
;
217 _class
.extend
= Class
.extend
;
222 this.defaults = function(obj
, def
)
225 if (typeof(obj
[key
]) == 'undefined')
231 this.isDeferred = function(x
)
233 return (typeof(x
) == 'object' &&
234 typeof(x
.then
) == 'function' &&
235 typeof(x
.promise
) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments
[0]))
243 var d
= $.Deferred();
244 d
.resolve
.apply(d
, arguments
);
253 plural: function(n
) { return 0 + (n
!= 1) },
256 if (_luci2
.i18n
.loaded
)
259 var lang
= (navigator
.userLanguage
|| navigator
.language
|| 'en').toLowerCase();
260 var langs
= (lang
.indexOf('-') > -1) ? [ lang
, lang
.split(/-/)[0] ] : [ lang
];
262 for (var i
= 0; i
< langs
.length
; i
++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2
.globals
.resource
, langs
[i
]), {
267 success: function(data
) {
268 $.extend(_luci2
.i18n
.catalog
, data
);
270 var pe
= _luci2
.i18n
.catalog
[''];
273 delete _luci2
.i18n
.catalog
[''];
275 var pf
= new Function('n', 'return 0 + (' + pe
+ ')');
276 _luci2
.i18n
.plural
= pf
;
282 _luci2
.i18n
.loaded
= true;
287 this.tr = function(msgid
)
291 var msgstr
= _luci2
.i18n
.catalog
[msgid
];
293 if (typeof(msgstr
) == 'undefined')
295 else if (typeof(msgstr
) == 'string')
301 this.trp = function(msgid
, msgid_plural
, count
)
305 var msgstr
= _luci2
.i18n
.catalog
[msgid
];
307 if (typeof(msgstr
) == 'undefined')
308 return (count
== 1) ? msgid
: msgid_plural
;
309 else if (typeof(msgstr
) == 'string')
312 return msgstr
[_luci2
.i18n
.plural(count
)];
315 this.trc = function(msgctx
, msgid
)
319 var msgstr
= _luci2
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
321 if (typeof(msgstr
) == 'undefined')
323 else if (typeof(msgstr
) == 'string')
329 this.trcp = function(msgctx
, msgid
, msgid_plural
, count
)
333 var msgstr
= _luci2
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
335 if (typeof(msgstr
) == 'undefined')
336 return (count
== 1) ? msgid
: msgid_plural
;
337 else if (typeof(msgstr
) == 'string')
340 return msgstr
[_luci2
.i18n
.plural(count
)];
343 this.setHash = function(key
, value
)
346 var data
= this.getHash(undefined);
348 if (typeof(value
) == 'undefined')
359 for (var i
= 0; i
< keys
.length
; i
++)
364 h
+= keys
[i
] + ':' + data
[keys
[i
]];
368 location
.hash
= '#' + h
;
373 this.getHash = function(key
)
376 var tuples
= (location
.hash
|| '#').substring(1).split(/,/);
378 for (var i
= 0; i
< tuples
.length
; i
++)
380 var tuple
= tuples
[i
].split(/:/);
381 if (tuple
.length
== 2)
382 data
[tuple
[0]] = tuple
[1];
385 if (typeof(key
) != 'undefined')
394 sid
: '00000000000000000000000000000000'
403 _call: function(req
, cb
)
405 return $.ajax('/ubus', {
407 contentType
: 'application/json',
408 data
: JSON
.stringify(req
),
411 timeout
: _luci2
.globals
.timeout
415 _list_cb: function(msg
)
417 /* verify message frame */
418 if (typeof(msg
) != 'object' || msg
.jsonrpc
!= '2.0' || !msg
.id
)
419 throw 'Invalid JSON response';
424 _call_cb: function(msg
)
427 var type
= Object
.prototype.toString
;
432 for (var i
= 0; i
< msg
.length
; i
++)
434 /* verify message frame */
435 if (typeof(msg
[i
]) != 'object' || msg
[i
].jsonrpc
!= '2.0' || !msg
[i
].id
)
436 throw 'Invalid JSON response';
438 /* fetch related request info */
439 var req
= _luci2
.rpc
._requests
[msg
[i
].id
];
440 if (typeof(req
) != 'object')
441 throw 'No related request for JSON response';
443 /* fetch response attribute and verify returned type */
446 if ($.isArray(msg
[i
].result
) && msg
[i
].result
[0] == 0)
447 ret
= (msg
[i
].result
.length
> 1) ? msg
[i
].result
[1] : msg
[i
].result
[0];
451 for (var key
in req
.expect
)
453 if (typeof(ret
) != 'undefined' && key
!= '')
456 if (typeof(ret
) == 'undefined' || type
.call(ret
) != type
.call(req
.expect
[key
]))
457 ret
= req
.expect
[key
];
464 if (typeof(req
.filter
) == 'function')
467 req
.priv
[1] = req
.params
;
468 ret
= req
.filter
.apply(_luci2
.rpc
, req
.priv
);
471 /* store response data */
472 if (typeof(req
.index
) == 'number')
473 data
[req
.index
] = ret
;
477 /* delete request object */
478 delete _luci2
.rpc
._requests
[msg
[i
].id
];
487 for (var i
= 0; i
< arguments
.length
; i
++)
488 params
[i
] = arguments
[i
];
494 params
: (params
.length
> 0) ? params
: undefined
497 return this._call(msg
, this._list_cb
);
502 if (!$.isArray(this._batch
))
508 if (!$.isArray(this._batch
))
509 return _luci2
.deferrable([ ]);
511 var req
= this._batch
;
515 return this._call(req
, this._call_cb
);
518 declare: function(options
)
523 /* build parameter object */
526 if ($.isArray(options
.params
))
527 for (p_off
= 0; p_off
< options
.params
.length
; p_off
++)
528 params
[options
.params
[p_off
]] = arguments
[p_off
];
530 /* all remaining arguments are private args */
531 var priv
= [ undefined, undefined ];
532 for (; p_off
< arguments
.length
; p_off
++)
533 priv
.push(arguments
[p_off
]);
535 /* store request info */
536 var req
= _rpc
._requests
[_rpc
._id
] = {
537 expect
: options
.expect
,
538 filter
: options
.filter
,
543 /* build message object */
556 /* when a batch is in progress then store index in request data
557 * and push message object onto the stack */
558 if ($.isArray(_rpc
._batch
))
560 req
.index
= _rpc
._batch
.push(msg
) - 1;
561 return _luci2
.deferrable(msg
);
565 return _rpc
._call(msg
, _rpc
._call_cb
);
574 return _luci2
.session
.access('ubus', 'uci', 'commit');
577 add
: _luci2
.rpc
.declare({
580 params
: [ 'config', 'type', 'name', 'values' ],
581 expect
: { section
: '' }
589 configs
: _luci2
.rpc
.declare({
592 expect
: { configs
: [ ] }
595 _changes
: _luci2
.rpc
.declare({
598 params
: [ 'config' ],
599 expect
: { changes
: [ ] }
602 changes: function(config
)
604 if (typeof(config
) == 'string')
605 return this._changes(config
);
608 return this.configs().then(function(configs
) {
610 configlist
= configs
;
612 for (var i
= 0; i
< configs
.length
; i
++)
613 _luci2
.uci
._changes(configs
[i
]);
615 return _luci2
.rpc
.flush();
616 }).then(function(changes
) {
619 for (var i
= 0; i
< configlist
.length
; i
++)
620 if (changes
[i
].length
)
621 rv
[configlist
[i
]] = changes
[i
];
627 commit
: _luci2
.rpc
.declare({
633 _delete_one
: _luci2
.rpc
.declare({
636 params
: [ 'config', 'section', 'option' ]
639 _delete_multiple
: _luci2
.rpc
.declare({
642 params
: [ 'config', 'section', 'options' ]
645 'delete': function(config
, section
, option
)
647 if ($.isArray(option
))
648 return this._delete_multiple(config
, section
, option
);
650 return this._delete_one(config
, section
, option
);
653 delete_all
: _luci2
.rpc
.declare({
656 params
: [ 'config', 'type', 'match' ]
659 _foreach
: _luci2
.rpc
.declare({
662 params
: [ 'config', 'type' ],
663 expect
: { values
: { } }
666 foreach: function(config
, type
, cb
)
668 return this._foreach(config
, type
).then(function(sections
) {
669 for (var s
in sections
)
674 get: _luci2
.rpc
.declare({
677 params
: [ 'config', 'section', 'option' ],
679 filter: function(data
, params
) {
680 if (typeof(params
.option
) == 'undefined')
681 return data
.values
? data
.values
['.type'] : undefined;
687 get_all
: _luci2
.rpc
.declare({
690 params
: [ 'config', 'section' ],
691 expect
: { values
: { } },
692 filter: function(data
, params
) {
693 if (typeof(params
.section
) == 'string')
694 data
['.section'] = params
.section
;
695 else if (typeof(params
.config
) == 'string')
696 data
['.package'] = params
.config
;
701 get_first: function(config
, type
, option
)
703 return this._foreach(config
, type
).then(function(sections
) {
704 for (var s
in sections
)
706 var val
= (typeof(option
) == 'string') ? sections
[s
][option
] : sections
[s
]['.name'];
708 if (typeof(val
) != 'undefined')
716 section
: _luci2
.rpc
.declare({
719 params
: [ 'config', 'type', 'name', 'values' ],
720 expect
: { section
: '' }
723 _set
: _luci2
.rpc
.declare({
726 params
: [ 'config', 'section', 'values' ]
729 set: function(config
, section
, option
, value
)
731 if (typeof(value
) == 'undefined' && typeof(option
) == 'string')
732 return this.section(config
, section
, option
); /* option -> type */
733 else if ($.isPlainObject(option
))
734 return this._set(config
, section
, option
); /* option -> values */
737 values
[option
] = value
;
739 return this._set(config
, section
, values
);
742 order
: _luci2
.rpc
.declare({
745 params
: [ 'config', 'sections' ]
750 listNetworkNames: function() {
751 return _luci2
.rpc
.list('network.interface.*').then(function(list
) {
753 for (var name
in list
)
754 if (name
!= 'network.interface.loopback')
755 names
.push(name
.substring(18));
761 listDeviceNames
: _luci2
.rpc
.declare({
762 object
: 'network.device',
765 filter: function(data
) {
767 for (var name
in data
)
775 getNetworkStatus: function()
780 return this.listNetworkNames().then(function(names
) {
783 for (var i
= 0; i
< names
.length
; i
++)
784 _luci2
.network
.getInterfaceStatus(names
[i
]);
786 return _luci2
.rpc
.flush();
787 }).then(function(networks
) {
788 for (var i
= 0; i
< networks
.length
; i
++)
790 var net
= nets
[i
] = networks
[i
];
791 var dev
= net
.l3_device
|| net
.l2_device
;
793 net
.device
= devs
[dev
] || (devs
[dev
] = { });
798 for (var dev
in devs
)
799 _luci2
.network
.getDeviceStatus(dev
);
801 return _luci2
.rpc
.flush();
802 }).then(function(devices
) {
805 for (var i
= 0; i
< devices
.length
; i
++)
807 var brm
= devices
[i
]['bridge-members'];
808 delete devices
[i
]['bridge-members'];
810 $.extend(devs
[devices
[i
]['device']], devices
[i
]);
815 devs
[devices
[i
]['device']].subdevices
= [ ];
817 for (var j
= 0; j
< brm
.length
; j
++)
822 _luci2
.network
.getDeviceStatus(brm
[j
]);
825 devs
[devices
[i
]['device']].subdevices
[j
] = devs
[brm
[j
]];
829 return _luci2
.rpc
.flush();
830 }).then(function(subdevices
) {
831 for (var i
= 0; i
< subdevices
.length
; i
++)
832 $.extend(devs
[subdevices
[i
]['device']], subdevices
[i
]);
836 for (var dev
in devs
)
837 _luci2
.wireless
.getDeviceStatus(dev
);
839 return _luci2
.rpc
.flush();
840 }).then(function(wifidevices
) {
841 for (var i
= 0; i
< wifidevices
.length
; i
++)
843 devs
[wifidevices
[i
]['device']].wireless
= wifidevices
[i
];
845 nets
.sort(function(a
, b
) {
846 if (a
['interface'] < b
['interface'])
848 else if (a
['interface'] > b
['interface'])
858 findWanInterfaces: function(cb
)
860 return this.listNetworkNames().then(function(names
) {
863 for (var i
= 0; i
< names
.length
; i
++)
864 _luci2
.network
.getInterfaceStatus(names
[i
]);
866 return _luci2
.rpc
.flush();
867 }).then(function(interfaces
) {
868 var rv
= [ undefined, undefined ];
870 for (var i
= 0; i
< interfaces
.length
; i
++)
872 if (!interfaces
[i
].route
)
875 for (var j
= 0; j
< interfaces
[i
].route
.length
; j
++)
877 var rt
= interfaces
[i
].route
[j
];
879 if (typeof(rt
.table
) != 'undefined')
882 if (rt
.target
== '0.0.0.0' && rt
.mask
== 0)
883 rv
[0] = interfaces
[i
];
884 else if (rt
.target
== '::' && rt
.mask
== 0)
885 rv
[1] = interfaces
[i
];
893 getDHCPLeases
: _luci2
.rpc
.declare({
894 object
: 'luci2.network',
895 method
: 'dhcp_leases',
896 expect
: { leases
: [ ] }
899 getDHCPv6Leases
: _luci2
.rpc
.declare({
900 object
: 'luci2.network',
901 method
: 'dhcp6_leases',
902 expect
: { leases
: [ ] }
905 getRoutes
: _luci2
.rpc
.declare({
906 object
: 'luci2.network',
908 expect
: { routes
: [ ] }
911 getIPv6Routes
: _luci2
.rpc
.declare({
912 object
: 'luci2.network',
914 expect
: { routes
: [ ] }
917 getARPTable
: _luci2
.rpc
.declare({
918 object
: 'luci2.network',
920 expect
: { entries
: [ ] }
923 getInterfaceStatus
: _luci2
.rpc
.declare({
924 object
: 'network.interface',
926 params
: [ 'interface' ],
928 filter: function(data
, params
) {
929 data
['interface'] = params
['interface'];
930 data
['l2_device'] = data
['device'];
931 delete data
['device'];
936 getDeviceStatus
: _luci2
.rpc
.declare({
937 object
: 'network.device',
941 filter: function(data
, params
) {
942 data
['device'] = params
['name'];
947 getConntrackCount
: _luci2
.rpc
.declare({
948 object
: 'luci2.network',
949 method
: 'conntrack_count',
950 expect
: { '': { count
: 0, limit
: 0 } }
953 listSwitchNames
: _luci2
.rpc
.declare({
954 object
: 'luci2.network',
955 method
: 'switch_list',
956 expect
: { switches
: [ ] }
959 getSwitchInfo
: _luci2
.rpc
.declare({
960 object
: 'luci2.network',
961 method
: 'switch_info',
962 params
: [ 'switch' ],
963 expect
: { info
: { } },
964 filter: function(data
, params
) {
965 data
['attrs'] = data
['switch'];
966 data
['vlan_attrs'] = data
['vlan'];
967 data
['port_attrs'] = data
['port'];
968 data
['switch'] = params
['switch'];
977 getSwitchStatus
: _luci2
.rpc
.declare({
978 object
: 'luci2.network',
979 method
: 'switch_status',
980 params
: [ 'switch' ],
981 expect
: { ports
: [ ] }
985 runPing
: _luci2
.rpc
.declare({
986 object
: 'luci2.network',
989 expect
: { '': { code
: -1 } }
992 runPing6
: _luci2
.rpc
.declare({
993 object
: 'luci2.network',
996 expect
: { '': { code
: -1 } }
999 runTraceroute
: _luci2
.rpc
.declare({
1000 object
: 'luci2.network',
1001 method
: 'traceroute',
1003 expect
: { '': { code
: -1 } }
1006 runTraceroute6
: _luci2
.rpc
.declare({
1007 object
: 'luci2.network',
1008 method
: 'traceroute6',
1010 expect
: { '': { code
: -1 } }
1013 runNslookup
: _luci2
.rpc
.declare({
1014 object
: 'luci2.network',
1017 expect
: { '': { code
: -1 } }
1021 setUp
: _luci2
.rpc
.declare({
1022 object
: 'luci2.network',
1025 expect
: { '': { code
: -1 } }
1028 setDown
: _luci2
.rpc
.declare({
1029 object
: 'luci2.network',
1032 expect
: { '': { code
: -1 } }
1037 listDeviceNames
: _luci2
.rpc
.declare({
1040 expect
: { 'devices': [ ] },
1041 filter: function(data
) {
1047 getDeviceStatus
: _luci2
.rpc
.declare({
1050 params
: [ 'device' ],
1051 expect
: { '': { } },
1052 filter: function(data
, params
) {
1053 if (!$.isEmptyObject(data
))
1055 data
['device'] = params
['device'];
1062 getAssocList
: _luci2
.rpc
.declare({
1064 method
: 'assoclist',
1065 params
: [ 'device' ],
1066 expect
: { results
: [ ] },
1067 filter: function(data
, params
) {
1068 for (var i
= 0; i
< data
.length
; i
++)
1069 data
[i
]['device'] = params
['device'];
1071 data
.sort(function(a
, b
) {
1072 if (a
.bssid
< b
.bssid
)
1074 else if (a
.bssid
> b
.bssid
)
1084 getWirelessStatus: function() {
1085 return this.listDeviceNames().then(function(names
) {
1088 for (var i
= 0; i
< names
.length
; i
++)
1089 _luci2
.wireless
.getDeviceStatus(names
[i
]);
1091 return _luci2
.rpc
.flush();
1092 }).then(function(networks
) {
1096 'country', 'channel', 'frequency', 'frequency_offset',
1097 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1101 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1102 'signal', 'noise', 'bitrate', 'encryption'
1105 for (var i
= 0; i
< networks
.length
; i
++)
1107 var phy
= rv
[networks
[i
].phy
] || (
1108 rv
[networks
[i
].phy
] = { networks
: [ ] }
1112 device
: networks
[i
].device
1115 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1116 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1118 for (var j
= 0; j
< net_attrs
.length
; j
++)
1119 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1121 phy
.networks
.push(net
);
1128 getAssocLists: function()
1130 return this.listDeviceNames().then(function(names
) {
1133 for (var i
= 0; i
< names
.length
; i
++)
1134 _luci2
.wireless
.getAssocList(names
[i
]);
1136 return _luci2
.rpc
.flush();
1137 }).then(function(assoclists
) {
1140 for (var i
= 0; i
< assoclists
.length
; i
++)
1141 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1142 rv
.push(assoclists
[i
][j
]);
1148 formatEncryption: function(enc
)
1150 var format_list = function(l
, s
)
1153 for (var i
= 0; i
< l
.length
; i
++)
1154 rv
.push(l
[i
].toUpperCase());
1155 return rv
.join(s
? s
: ', ');
1158 if (!enc
|| !enc
.enabled
)
1159 return _luci2
.tr('None');
1163 if (enc
.wep
.length
== 2)
1164 return _luci2
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1165 else if (enc
.wep
[0] == 'shared')
1166 return _luci2
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1168 return _luci2
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1172 if (enc
.wpa
.length
== 2)
1173 return _luci2
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1174 format_list(enc
.authentication
, '/'),
1175 format_list(enc
.ciphers
, ', ')
1177 else if (enc
.wpa
[0] == 2)
1178 return 'WPA2 %s (%s)'.format(
1179 format_list(enc
.authentication
, '/'),
1180 format_list(enc
.ciphers
, ', ')
1183 return 'WPA %s (%s)'.format(
1184 format_list(enc
.authentication
, '/'),
1185 format_list(enc
.ciphers
, ', ')
1189 return _luci2
.tr('Unknown');
1194 getZoneColor: function(zone
)
1196 if ($.isPlainObject(zone
))
1201 else if (zone
== 'wan')
1204 for (var i
= 0, hash
= 0;
1206 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1208 for (var i
= 0, color
= '#';
1210 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1215 findZoneByNetwork: function(network
)
1218 var zone
= undefined;
1220 return _luci2
.uci
.foreach('firewall', 'zone', function(z
) {
1221 if (!z
.name
|| !z
.network
)
1224 if (!$.isArray(z
.network
))
1225 z
.network
= z
.network
.split(/\s+/);
1227 for (var i
= 0; i
< z
.network
.length
; i
++)
1229 if (z
.network
[i
] == network
)
1235 }).then(function() {
1237 zone
.color
= self
.getZoneColor(zone
);
1245 getSystemInfo
: _luci2
.rpc
.declare({
1251 getBoardInfo
: _luci2
.rpc
.declare({
1257 getDiskInfo
: _luci2
.rpc
.declare({
1258 object
: 'luci2.system',
1263 getInfo: function(cb
)
1267 this.getSystemInfo();
1268 this.getBoardInfo();
1271 return _luci2
.rpc
.flush().then(function(info
) {
1274 $.extend(rv
, info
[0]);
1275 $.extend(rv
, info
[1]);
1276 $.extend(rv
, info
[2]);
1282 getProcessList
: _luci2
.rpc
.declare({
1283 object
: 'luci2.system',
1284 method
: 'process_list',
1285 expect
: { processes
: [ ] },
1286 filter: function(data
) {
1287 data
.sort(function(a
, b
) { return a
.pid
- b
.pid
});
1292 getSystemLog
: _luci2
.rpc
.declare({
1293 object
: 'luci2.system',
1298 getKernelLog
: _luci2
.rpc
.declare({
1299 object
: 'luci2.system',
1304 getZoneInfo: function(cb
)
1306 return $.getJSON(_luci2
.globals
.resource
+ '/zoneinfo.json', cb
);
1309 sendSignal
: _luci2
.rpc
.declare({
1310 object
: 'luci2.system',
1311 method
: 'process_signal',
1312 params
: [ 'pid', 'signal' ],
1313 filter: function(data
) {
1318 initList
: _luci2
.rpc
.declare({
1319 object
: 'luci2.system',
1320 method
: 'init_list',
1321 expect
: { initscripts
: [ ] },
1322 filter: function(data
) {
1323 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
1328 initEnabled: function(init
, cb
)
1330 return this.initList().then(function(list
) {
1331 for (var i
= 0; i
< list
.length
; i
++)
1332 if (list
[i
].name
== init
)
1333 return !!list
[i
].enabled
;
1339 initRun
: _luci2
.rpc
.declare({
1340 object
: 'luci2.system',
1341 method
: 'init_action',
1342 params
: [ 'name', 'action' ],
1343 filter: function(data
) {
1348 initStart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'start', cb
) },
1349 initStop: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'stop', cb
) },
1350 initRestart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'restart', cb
) },
1351 initReload: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'reload', cb
) },
1352 initEnable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'enable', cb
) },
1353 initDisable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'disable', cb
) },
1356 getRcLocal
: _luci2
.rpc
.declare({
1357 object
: 'luci2.system',
1358 method
: 'rclocal_get',
1359 expect
: { data
: '' }
1362 setRcLocal
: _luci2
.rpc
.declare({
1363 object
: 'luci2.system',
1364 method
: 'rclocal_set',
1369 getCrontab
: _luci2
.rpc
.declare({
1370 object
: 'luci2.system',
1371 method
: 'crontab_get',
1372 expect
: { data
: '' }
1375 setCrontab
: _luci2
.rpc
.declare({
1376 object
: 'luci2.system',
1377 method
: 'crontab_set',
1382 getSSHKeys
: _luci2
.rpc
.declare({
1383 object
: 'luci2.system',
1384 method
: 'sshkeys_get',
1385 expect
: { keys
: [ ] }
1388 setSSHKeys
: _luci2
.rpc
.declare({
1389 object
: 'luci2.system',
1390 method
: 'sshkeys_set',
1395 setPassword
: _luci2
.rpc
.declare({
1396 object
: 'luci2.system',
1397 method
: 'password_set',
1398 params
: [ 'user', 'password' ]
1402 listLEDs
: _luci2
.rpc
.declare({
1403 object
: 'luci2.system',
1405 expect
: { leds
: [ ] }
1408 listUSBDevices
: _luci2
.rpc
.declare({
1409 object
: 'luci2.system',
1411 expect
: { devices
: [ ] }
1415 testUpgrade
: _luci2
.rpc
.declare({
1416 object
: 'luci2.system',
1417 method
: 'upgrade_test',
1421 startUpgrade
: _luci2
.rpc
.declare({
1422 object
: 'luci2.system',
1423 method
: 'upgrade_start',
1427 cleanUpgrade
: _luci2
.rpc
.declare({
1428 object
: 'luci2.system',
1429 method
: 'upgrade_clean'
1433 restoreBackup
: _luci2
.rpc
.declare({
1434 object
: 'luci2.system',
1435 method
: 'backup_restore'
1438 cleanBackup
: _luci2
.rpc
.declare({
1439 object
: 'luci2.system',
1440 method
: 'backup_clean'
1444 getBackupConfig
: _luci2
.rpc
.declare({
1445 object
: 'luci2.system',
1446 method
: 'backup_config_get',
1447 expect
: { config
: '' }
1450 setBackupConfig
: _luci2
.rpc
.declare({
1451 object
: 'luci2.system',
1452 method
: 'backup_config_set',
1457 listBackup
: _luci2
.rpc
.declare({
1458 object
: 'luci2.system',
1459 method
: 'backup_list',
1460 expect
: { files
: [ ] }
1464 testReset
: _luci2
.rpc
.declare({
1465 object
: 'luci2.system',
1466 method
: 'reset_test',
1467 expect
: { supported
: false }
1470 startReset
: _luci2
.rpc
.declare({
1471 object
: 'luci2.system',
1472 method
: 'reset_start'
1476 performReboot
: _luci2
.rpc
.declare({
1477 object
: 'luci2.system',
1483 updateLists
: _luci2
.rpc
.declare({
1484 object
: 'luci2.opkg',
1489 _allPackages
: _luci2
.rpc
.declare({
1490 object
: 'luci2.opkg',
1492 params
: [ 'offset', 'limit', 'pattern' ],
1496 _installedPackages
: _luci2
.rpc
.declare({
1497 object
: 'luci2.opkg',
1498 method
: 'list_installed',
1499 params
: [ 'offset', 'limit', 'pattern' ],
1503 _findPackages
: _luci2
.rpc
.declare({
1504 object
: 'luci2.opkg',
1506 params
: [ 'offset', 'limit', 'pattern' ],
1510 _fetchPackages: function(action
, offset
, limit
, pattern
)
1514 return action(offset
, limit
, pattern
).then(function(list
) {
1515 if (!list
.total
|| !list
.packages
)
1516 return { length
: 0, total
: 0 };
1518 packages
.push
.apply(packages
, list
.packages
);
1519 packages
.total
= list
.total
;
1524 if (packages
.length
>= limit
)
1529 for (var i
= offset
+ packages
.length
; i
< limit
; i
+= 100)
1530 action(i
, (Math
.min(i
+ 100, limit
) % 100) || 100, pattern
);
1532 return _luci2
.rpc
.flush();
1533 }).then(function(lists
) {
1534 for (var i
= 0; i
< lists
.length
; i
++)
1536 if (!lists
[i
].total
|| !lists
[i
].packages
)
1539 packages
.push
.apply(packages
, lists
[i
].packages
);
1540 packages
.total
= lists
[i
].total
;
1547 listPackages: function(offset
, limit
, pattern
)
1549 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._allPackages
, offset
, limit
, pattern
);
1552 installedPackages: function(offset
, limit
, pattern
)
1554 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._installedPackages
, offset
, limit
, pattern
);
1557 findPackages: function(offset
, limit
, pattern
)
1559 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._findPackages
, offset
, limit
, pattern
);
1562 installPackage
: _luci2
.rpc
.declare({
1563 object
: 'luci2.opkg',
1565 params
: [ 'package' ],
1569 removePackage
: _luci2
.rpc
.declare({
1570 object
: 'luci2.opkg',
1572 params
: [ 'package' ],
1576 getConfig
: _luci2
.rpc
.declare({
1577 object
: 'luci2.opkg',
1578 method
: 'config_get',
1579 expect
: { config
: '' }
1582 setConfig
: _luci2
.rpc
.declare({
1583 object
: 'luci2.opkg',
1584 method
: 'config_set',
1591 login
: _luci2
.rpc
.declare({
1594 params
: [ 'username', 'password' ],
1598 access
: _luci2
.rpc
.declare({
1601 params
: [ 'scope', 'object', 'function' ],
1602 expect
: { access
: false }
1607 return _luci2
.session
.access('ubus', 'session', 'access');
1610 startHeartbeat: function()
1612 this._hearbeatInterval
= window
.setInterval(function() {
1613 _luci2
.session
.isAlive().then(function(alive
) {
1616 _luci2
.session
.stopHeartbeat();
1617 _luci2
.ui
.login(true);
1621 }, _luci2
.globals
.timeout
* 2);
1624 stopHeartbeat: function()
1626 if (typeof(this._hearbeatInterval
) != 'undefined')
1628 window
.clearInterval(this._hearbeatInterval
);
1629 delete this._hearbeatInterval
;
1636 saveScrollTop: function()
1638 this._scroll_top
= $(document
).scrollTop();
1641 restoreScrollTop: function()
1643 if (typeof(this._scroll_top
) == 'undefined')
1646 $(document
).scrollTop(this._scroll_top
);
1648 delete this._scroll_top
;
1651 loading: function(enable
)
1653 var win
= $(window
);
1654 var body
= $('body');
1656 var state
= _luci2
.ui
._loading
|| (_luci2
.ui
._loading
= {
1658 .addClass('modal fade')
1659 .append($('<div />')
1660 .addClass('modal-dialog')
1661 .append($('<div />')
1662 .addClass('modal-content luci2-modal-loader')
1663 .append($('<div />')
1664 .addClass('modal-body')
1665 .text(_luci2
.tr('Loading data…')))))
1673 state
.modal
.modal(enable
? 'show' : 'hide');
1676 dialog: function(title
, content
, options
)
1678 var win
= $(window
);
1679 var body
= $('body');
1681 var state
= _luci2
.ui
._dialog
|| (_luci2
.ui
._dialog
= {
1682 dialog
: $('<div />')
1683 .addClass('modal fade')
1684 .append($('<div />')
1685 .addClass('modal-dialog')
1686 .append($('<div />')
1687 .addClass('modal-content')
1688 .append($('<div />')
1689 .addClass('modal-header')
1691 .addClass('modal-title'))
1692 .append($('<div />')
1693 .addClass('modal-body'))
1694 .append($('<div />')
1695 .addClass('modal-footer')
1696 .append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1698 $(this).parents('div.modal').modal('hide');
1703 if (typeof(options
) != 'object')
1706 if (title
=== false)
1708 state
.dialog
.modal('hide');
1713 var cnt
= state
.dialog
.children().children().children('div.modal-body');
1714 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
1718 if (options
.style
== 'confirm')
1720 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Ok'), 'primary')
1721 .click(options
.confirm
|| function() { _luci2
.ui
.dialog(false) }));
1723 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Cancel'), 'default')
1724 .click(options
.cancel
|| function() { _luci2
.ui
.dialog(false) }));
1726 else if (options
.style
== 'close')
1728 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1729 .click(options
.close
|| function() { _luci2
.ui
.dialog(false) }));
1731 else if (options
.style
== 'wait')
1733 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
1734 .attr('disabled', true));
1737 state
.dialog
.find('h4:first').text(title
);
1738 state
.dialog
.modal('show');
1740 cnt
.empty().append(content
);
1743 upload: function(title
, content
, options
)
1745 var state
= _luci2
.ui
._upload
|| (_luci2
.ui
._upload
= {
1747 .attr('method', 'post')
1748 .attr('action', '/cgi-bin/luci-upload')
1749 .attr('enctype', 'multipart/form-data')
1750 .attr('target', 'cbi-fileupload-frame')
1752 .append($('<input />')
1753 .attr('type', 'hidden')
1754 .attr('name', 'sessionid'))
1755 .append($('<input />')
1756 .attr('type', 'hidden')
1757 .attr('name', 'filename'))
1758 .append($('<input />')
1759 .attr('type', 'file')
1760 .attr('name', 'filedata')
1761 .addClass('cbi-input-file'))
1762 .append($('<div />')
1763 .css('width', '100%')
1764 .addClass('progress progress-striped active')
1765 .append($('<div />')
1766 .addClass('progress-bar')
1767 .css('width', '100%')))
1768 .append($('<iframe />')
1769 .addClass('pull-right')
1770 .attr('name', 'cbi-fileupload-frame')
1771 .css('width', '1px')
1772 .css('height', '1px')
1773 .css('visibility', 'hidden')),
1775 finish_cb: function(ev
) {
1776 $(this).off('load');
1778 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
1779 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
1780 body
= body
.firstChild
;
1784 json
= $.parseJSON(body
.innerHTML
);
1787 message
: _luci2
.tr('Invalid server response received'),
1788 error
: [ -1, _luci2
.tr('Invalid data') ]
1794 L
.ui
.dialog(L
.tr('File upload'), [
1795 $('<p />').text(_luci2
.tr('The file upload failed with the server response below:')),
1796 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
1797 $('<p />').text(_luci2
.tr('In case of network problems try uploading the file again.'))
1798 ], { style
: 'close' });
1800 else if (typeof(state
.success_cb
) == 'function')
1802 state
.success_cb(json
);
1806 confirm_cb: function() {
1807 var f
= state
.form
.find('.cbi-input-file');
1808 var b
= state
.form
.find('.progress');
1809 var p
= state
.form
.find('p');
1814 state
.form
.find('iframe').on('load', state
.finish_cb
);
1815 state
.form
.submit();
1819 p
.text(_luci2
.tr('File upload in progress …'));
1821 state
.form
.parent().parent().find('button').prop('disabled', true);
1825 state
.form
.find('.progress').hide();
1826 state
.form
.find('.cbi-input-file').val('').show();
1827 state
.form
.find('p').text(content
|| _luci2
.tr('Select the file to upload and press "%s" to proceed.').format(_luci2
.tr('Ok')));
1829 state
.form
.find('[name=sessionid]').val(_luci2
.globals
.sid
);
1830 state
.form
.find('[name=filename]').val(options
.filename
);
1832 state
.success_cb
= options
.success
;
1834 _luci2
.ui
.dialog(title
|| _luci2
.tr('File upload'), state
.form
, {
1836 confirm
: state
.confirm_cb
1840 reconnect: function()
1842 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1843 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
1844 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
1846 var interval
, timeout
;
1849 _luci2
.tr('Waiting for device'), [
1850 $('<p />').text(_luci2
.tr('Please stand by while the device is reconfiguring …')),
1852 .css('width', '100%')
1853 .addClass('progressbar')
1854 .addClass('intermediate')
1855 .append($('<div />')
1856 .css('width', '100%'))
1857 ], { style
: 'wait' }
1860 for (var i
= 0; i
< protocols
.length
; i
++)
1861 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
1863 //_luci2.network.getNetworkStatus(function(s) {
1864 // for (var i = 0; i < protocols.length; i++)
1866 // for (var j = 0; j < s.length; j++)
1868 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1869 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1871 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1872 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1875 //}).then(function() {
1876 images
.on('load', function() {
1877 var url
= this.getAttribute('url');
1878 _luci2
.session
.isAlive().then(function(access
) {
1881 window
.clearTimeout(timeout
);
1882 window
.clearInterval(interval
);
1883 _luci2
.ui
.dialog(false);
1888 location
.href
= url
;
1893 interval
= window
.setInterval(function() {
1894 images
.each(function() {
1895 this.setAttribute('src', this.getAttribute('url') + _luci2
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
1899 timeout
= window
.setTimeout(function() {
1900 window
.clearInterval(interval
);
1904 _luci2
.tr('Device not responding'),
1905 _luci2
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1912 login: function(invalid
)
1914 var state
= _luci2
.ui
._login
|| (_luci2
.ui
._login
= {
1917 .attr('method', 'post')
1919 .addClass('alert-message')
1920 .text(_luci2
.tr('Wrong username or password given!')))
1922 .append($('<label />')
1923 .text(_luci2
.tr('Username'))
1924 .append($('<br />'))
1925 .append($('<input />')
1926 .attr('type', 'text')
1927 .attr('name', 'username')
1928 .attr('value', 'root')
1929 .addClass('form-control')
1930 .keypress(function(ev
) {
1931 if (ev
.which
== 10 || ev
.which
== 13)
1935 .append($('<label />')
1936 .text(_luci2
.tr('Password'))
1937 .append($('<br />'))
1938 .append($('<input />')
1939 .attr('type', 'password')
1940 .attr('name', 'password')
1941 .addClass('form-control')
1942 .keypress(function(ev
) {
1943 if (ev
.which
== 10 || ev
.which
== 13)
1947 .text(_luci2
.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2
.tr('Ok')))),
1949 response_cb: function(response
) {
1950 if (!response
.ubus_rpc_session
)
1952 _luci2
.ui
.login(true);
1956 _luci2
.globals
.sid
= response
.ubus_rpc_session
;
1957 _luci2
.setHash('id', _luci2
.globals
.sid
);
1958 _luci2
.session
.startHeartbeat();
1959 _luci2
.ui
.dialog(false);
1960 state
.deferred
.resolve();
1964 confirm_cb: function() {
1965 var u
= state
.form
.find('[name=username]').val();
1966 var p
= state
.form
.find('[name=password]').val();
1972 _luci2
.tr('Logging in'), [
1973 $('<p />').text(_luci2
.tr('Log in in progress …')),
1975 .css('width', '100%')
1976 .addClass('progressbar')
1977 .addClass('intermediate')
1978 .append($('<div />')
1979 .css('width', '100%'))
1980 ], { style
: 'wait' }
1983 _luci2
.globals
.sid
= '00000000000000000000000000000000';
1984 _luci2
.session
.login(u
, p
).then(state
.response_cb
);
1988 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
1989 state
.deferred
= $.Deferred();
1991 /* try to find sid from hash */
1992 var sid
= _luci2
.getHash('id');
1993 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
1995 _luci2
.globals
.sid
= sid
;
1996 _luci2
.session
.isAlive().then(function(access
) {
1999 _luci2
.session
.startHeartbeat();
2000 state
.deferred
.resolve();
2004 _luci2
.setHash('id', undefined);
2009 return state
.deferred
;
2013 state
.form
.find('.alert-message').show();
2015 state
.form
.find('.alert-message').hide();
2017 _luci2
.ui
.dialog(_luci2
.tr('Authorization Required'), state
.form
, {
2019 confirm
: state
.confirm_cb
2022 state
.form
.find('[name=password]').focus();
2024 return state
.deferred
;
2027 cryptPassword
: _luci2
.rpc
.declare({
2031 expect
: { crypt
: '' }
2035 _acl_merge_scope: function(acl_scope
, scope
)
2037 if ($.isArray(scope
))
2039 for (var i
= 0; i
< scope
.length
; i
++)
2040 acl_scope
[scope
[i
]] = true;
2042 else if ($.isPlainObject(scope
))
2044 for (var object_name
in scope
)
2046 if (!$.isArray(scope
[object_name
]))
2049 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
2051 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
2052 acl_object
[scope
[object_name
][i
]] = true;
2057 _acl_merge_permission: function(acl_perm
, perm
)
2059 if ($.isPlainObject(perm
))
2061 for (var scope_name
in perm
)
2063 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
2064 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
2069 _acl_merge_group: function(acl_group
, group
)
2071 if ($.isPlainObject(group
))
2073 if (!acl_group
.description
)
2074 acl_group
.description
= group
.description
;
2078 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
2079 this._acl_merge_permission(acl_perm
, group
.read
);
2084 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
2085 this._acl_merge_permission(acl_perm
, group
.write
);
2090 _acl_merge_tree: function(acl_tree
, tree
)
2092 if ($.isPlainObject(tree
))
2094 for (var group_name
in tree
)
2096 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
2097 this._acl_merge_group(acl_group
, tree
[group_name
]);
2102 listAvailableACLs
: _luci2
.rpc
.declare({
2105 expect
: { acls
: [ ] },
2106 filter: function(trees
) {
2108 for (var i
= 0; i
< trees
.length
; i
++)
2109 _luci2
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
2114 renderMainMenu
: _luci2
.rpc
.declare({
2117 expect
: { menu
: { } },
2118 filter: function(entries
) {
2119 _luci2
.globals
.mainMenu
= new _luci2
.ui
.menu();
2120 _luci2
.globals
.mainMenu
.entries(entries
);
2124 .append(_luci2
.globals
.mainMenu
.render(0, 1));
2128 renderViewMenu: function()
2132 .append(_luci2
.globals
.mainMenu
.render(2, 900));
2135 renderView: function()
2137 var node
= arguments
[0];
2138 var name
= node
.view
.split(/\//).join('.');
2141 for (var i
= 1; i
< arguments
.length
; i
++)
2142 args
.push(arguments
[i
]);
2144 if (_luci2
.globals
.currentView
)
2145 _luci2
.globals
.currentView
.finish();
2147 _luci2
.ui
.renderViewMenu();
2150 _luci2
._views
= { };
2152 _luci2
.setHash('view', node
.view
);
2154 if (_luci2
._views
[name
] instanceof _luci2
.ui
.view
)
2156 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2157 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2160 var url
= _luci2
.globals
.resource
+ '/view/' + name
+ '.js';
2162 return $.ajax(url
, {
2166 }).then(function(data
) {
2168 var viewConstructorSource
= (
2169 '(function(L, $) { ' +
2171 '})(_luci2, $);\n\n' +
2173 ).format(data
, url
);
2175 var viewConstructor
= eval(viewConstructorSource
);
2177 _luci2
._views
[name
] = new viewConstructor({
2179 acls
: node
.write
|| { }
2182 _luci2
.globals
.currentView
= _luci2
._views
[name
];
2183 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
2186 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
2189 return $.Deferred().resolve();
2193 updateHostname: function()
2195 return _luci2
.system
.getBoardInfo().then(function(info
) {
2197 $('#hostname').text(info
.hostname
);
2201 updateChanges: function()
2203 return _luci2
.uci
.changes().then(function(changes
) {
2207 for (var config
in changes
)
2211 for (var i
= 0; i
< changes
[config
].length
; i
++)
2213 var c
= changes
[config
][i
];
2222 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
2224 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
2229 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
2231 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2235 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
2239 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2243 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2248 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
2250 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
2255 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
2256 n
+= changes
[config
].length
;
2267 .text(_luci2
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
))
2268 .click(function(ev
) {
2269 _luci2
.ui
.dialog(_luci2
.tr('Staged configuration changes'), html
, { style
: 'close' });
2270 ev
.preventDefault();
2280 _luci2
.ui
.loading(true);
2283 _luci2
.ui
.updateHostname(),
2284 _luci2
.ui
.updateChanges(),
2285 _luci2
.ui
.renderMainMenu()
2287 _luci2
.ui
.renderView(_luci2
.globals
.defaultNode
).then(function() {
2288 _luci2
.ui
.loading(false);
2293 button: function(label
, style
, title
)
2295 style
= style
|| 'default';
2297 return $('<button />')
2298 .attr('type', 'button')
2299 .attr('title', title
? title
: '')
2300 .addClass('btn btn-' + style
)
2305 this.ui
.AbstractWidget
= Class
.extend({
2306 i18n: function(text
) {
2311 var key
= arguments
[0];
2314 for (var i
= 1; i
< arguments
.length
; i
++)
2315 args
.push(arguments
[i
]);
2317 switch (typeof(this.options
[key
]))
2323 return this.options
[key
].apply(this, args
);
2326 return ''.format
.apply('' + this.options
[key
], args
);
2330 toString: function() {
2331 return $('<div />').append(this.render()).html();
2334 insertInto: function(id
) {
2335 return $(id
).empty().append(this.render());
2338 appendTo: function(id
) {
2339 return $(id
).append(this.render());
2343 this.ui
.view
= this.ui
.AbstractWidget
.extend({
2344 _fetch_template: function()
2346 return $.ajax(_luci2
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
2350 success: function(data
) {
2351 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
2352 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
2359 return _luci2
.tr(p2
);
2362 return _luci2
.globals
[p2
] || '';
2365 return '(?' + match
+ ')';
2369 $('#maincontent').append(data
);
2376 throw "Not implemented";
2381 var container
= $('#maincontent');
2386 container
.append($('<h2 />').append(this.title
));
2388 if (this.description
)
2389 container
.append($('<p />').append(this.description
));
2394 for (var i
= 0; i
< arguments
.length
; i
++)
2395 args
.push(arguments
[i
]);
2397 return this._fetch_template().then(function() {
2398 return _luci2
.deferrable(self
.execute
.apply(self
, args
));
2402 repeat: function(func
, interval
)
2406 if (!self
._timeouts
)
2407 self
._timeouts
= [ ];
2409 var index
= self
._timeouts
.length
;
2411 if (typeof(interval
) != 'number')
2414 var setTimer
, runTimer
;
2416 setTimer = function() {
2418 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
2421 runTimer = function() {
2422 _luci2
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
2430 if ($.isArray(this._timeouts
))
2432 for (var i
= 0; i
< this._timeouts
.length
; i
++)
2433 window
.clearTimeout(this._timeouts
[i
]);
2435 delete this._timeouts
;
2440 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
2445 entries: function(entries
)
2447 for (var entry
in entries
)
2449 var path
= entry
.split(/\//);
2450 var node
= this._nodes
;
2452 for (i
= 0; i
< path
.length
; i
++)
2457 if (!node
.childs
[path
[i
]])
2458 node
.childs
[path
[i
]] = { };
2460 node
= node
.childs
[path
[i
]];
2463 $.extend(node
, entries
[entry
]);
2467 _indexcmp: function(a
, b
)
2469 var x
= a
.index
|| 0;
2470 var y
= b
.index
|| 0;
2474 firstChildView: function(node
)
2480 for (var child
in (node
.childs
|| { }))
2481 nodes
.push(node
.childs
[child
]);
2483 nodes
.sort(this._indexcmp
);
2485 for (var i
= 0; i
< nodes
.length
; i
++)
2487 var child
= this.firstChildView(nodes
[i
]);
2490 for (var key
in child
)
2491 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
2492 node
[key
] = child
[key
];
2501 _onclick: function(ev
)
2503 _luci2
.ui
.loading(true);
2504 _luci2
.ui
.renderView(ev
.data
).then(function() {
2505 _luci2
.ui
.loading(false);
2508 ev
.preventDefault();
2512 _render: function(childs
, level
, min
, max
)
2515 for (var node
in childs
)
2517 var child
= this.firstChildView(childs
[node
]);
2519 nodes
.push(childs
[node
]);
2522 nodes
.sort(this._indexcmp
);
2524 var list
= $('<ul />');
2527 list
.addClass('nav').addClass('navbar-nav');
2528 else if (level
== 1)
2529 list
.addClass('dropdown-menu').addClass('navbar-inverse');
2531 for (var i
= 0; i
< nodes
.length
; i
++)
2533 if (!_luci2
.globals
.defaultNode
)
2535 var v
= _luci2
.getHash('view');
2536 if (!v
|| v
== nodes
[i
].view
)
2537 _luci2
.globals
.defaultNode
= nodes
[i
];
2540 var item
= $('<li />')
2543 .text(_luci2
.tr(nodes
[i
].title
)))
2546 if (nodes
[i
].childs
&& level
< max
)
2548 item
.addClass('dropdown');
2551 .addClass('dropdown-toggle')
2552 .attr('data-toggle', 'dropdown')
2553 .append('<b class="caret"></b>');
2555 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
2559 item
.find('a').click(nodes
[i
], this._onclick
);
2566 render: function(min
, max
)
2568 var top
= min
? this.getNode(_luci2
.globals
.defaultNode
.view
, min
) : this._nodes
;
2569 return this._render(top
.childs
, 0, min
, max
);
2572 getNode: function(path
, max
)
2574 var p
= path
.split(/\//);
2575 var n
= this._nodes
;
2577 if (typeof(max
) == 'undefined')
2580 for (var i
= 0; i
< max
; i
++)
2582 if (!n
.childs
[p
[i
]])
2592 this.ui
.table
= this.ui
.AbstractWidget
.extend({
2598 row: function(values
)
2600 if ($.isArray(values
))
2602 this._rows
.push(values
);
2604 else if ($.isPlainObject(values
))
2607 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2609 var col
= this.options
.columns
[i
];
2611 if (typeof col
.key
== 'string')
2612 v
.push(values
[col
.key
]);
2620 rows: function(rows
)
2622 for (var i
= 0; i
< rows
.length
; i
++)
2626 render: function(id
)
2628 var fieldset
= document
.createElement('fieldset');
2629 fieldset
.className
= 'cbi-section';
2631 if (this.options
.caption
)
2633 var legend
= document
.createElement('legend');
2634 $(legend
).append(this.options
.caption
);
2635 fieldset
.appendChild(legend
);
2638 var table
= document
.createElement('table');
2639 table
.className
= 'table table-condensed table-hover';
2641 var has_caption
= false;
2642 var has_description
= false;
2644 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2645 if (this.options
.columns
[i
].caption
)
2650 else if (this.options
.columns
[i
].description
)
2652 has_description
= true;
2658 var tr
= table
.insertRow(-1);
2659 tr
.className
= 'cbi-section-table-titles';
2661 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2663 var col
= this.options
.columns
[i
];
2664 var th
= document
.createElement('th');
2665 th
.className
= 'cbi-section-table-cell';
2670 th
.style
.width
= col
.width
;
2673 th
.style
.textAlign
= col
.align
;
2676 $(th
).append(col
.caption
);
2680 if (has_description
)
2682 var tr
= table
.insertRow(-1);
2683 tr
.className
= 'cbi-section-table-descr';
2685 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
2687 var col
= this.options
.columns
[i
];
2688 var th
= document
.createElement('th');
2689 th
.className
= 'cbi-section-table-cell';
2694 th
.style
.width
= col
.width
;
2697 th
.style
.textAlign
= col
.align
;
2699 if (col
.description
)
2700 $(th
).append(col
.description
);
2704 if (this._rows
.length
== 0)
2706 if (this.options
.placeholder
)
2708 var tr
= table
.insertRow(-1);
2709 var td
= tr
.insertCell(-1);
2710 td
.className
= 'cbi-section-table-cell';
2712 td
.colSpan
= this.options
.columns
.length
;
2713 $(td
).append(this.options
.placeholder
);
2718 for (var i
= 0; i
< this._rows
.length
; i
++)
2720 var tr
= table
.insertRow(-1);
2722 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
2724 var col
= this.options
.columns
[j
];
2725 var td
= tr
.insertCell(-1);
2727 var val
= this._rows
[i
][j
];
2729 if (typeof(val
) == 'undefined')
2730 val
= col
.placeholder
;
2732 if (typeof(val
) == 'undefined')
2736 td
.style
.width
= col
.width
;
2739 td
.style
.textAlign
= col
.align
;
2741 if (typeof col
.format
== 'string')
2742 $(td
).append(col
.format
.format(val
));
2743 else if (typeof col
.format
== 'function')
2744 $(td
).append(col
.format(val
, i
));
2752 fieldset
.appendChild(table
);
2758 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
2761 var vn
= parseInt(this.options
.value
) || 0;
2762 var mn
= parseInt(this.options
.max
) || 100;
2763 var pc
= Math
.floor((100 / mn
) * vn
);
2767 if (typeof(this.options
.format
) == 'string')
2768 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
2769 else if (typeof(this.options
.format
) == 'function')
2770 text
= this.options
.format(pc
);
2772 text
= '%.2f%%'.format(pc
);
2775 .addClass('progress')
2776 .append($('<div />')
2777 .addClass('progress-bar')
2778 .addClass('progress-bar-info')
2779 .css('width', pc
+ '%'))
2780 .append($('<small />')
2785 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
2788 var l2dev
= this.options
.l2_device
|| this.options
.device
;
2789 var l3dev
= this.options
.l3_device
;
2790 var dev
= l3dev
|| l2dev
|| '?';
2792 var span
= document
.createElement('span');
2793 span
.className
= 'badge';
2795 if (typeof(this.options
.signal
) == 'number' ||
2796 typeof(this.options
.noise
) == 'number')
2799 if (typeof(this.options
.signal
) != 'undefined' &&
2800 typeof(this.options
.noise
) != 'undefined')
2802 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
2815 span
.appendChild(document
.createElement('img'));
2816 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
2819 span
.title
= _luci2
.tr('No signal');
2821 span
.title
= '%s: %d %s / %s: %d %s'.format(
2822 _luci2
.tr('Signal'), this.options
.signal
, _luci2
.tr('dBm'),
2823 _luci2
.tr('Noise'), this.options
.noise
, _luci2
.tr('dBm')
2828 var type
= 'ethernet';
2829 var desc
= _luci2
.tr('Ethernet device');
2834 desc
= _luci2
.tr('Tunnel interface');
2836 else if (dev
.indexOf('br-') == 0)
2839 desc
= _luci2
.tr('Bridge');
2841 else if (dev
.indexOf('.') > 0)
2844 desc
= _luci2
.tr('VLAN interface');
2846 else if (dev
.indexOf('wlan') == 0 ||
2847 dev
.indexOf('ath') == 0 ||
2848 dev
.indexOf('wl') == 0)
2851 desc
= _luci2
.tr('Wireless Network');
2854 span
.appendChild(document
.createElement('img'));
2855 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
2859 $(span
).append(' ');
2860 $(span
).append(dev
);
2866 var type = function(f
, l
)
2876 _luci2
.cbi
.validation
.message
= _luci2
.tr(msg
);
2879 compile: function(code
)
2884 var types
= _luci2
.cbi
.validation
.types
;
2889 for (var i
= 0; i
< code
.length
; i
++)
2897 switch (code
.charCodeAt(i
))
2909 var label
= code
.substring(pos
, i
);
2910 label
= label
.replace(/\\(.)/g, '$1');
2911 label
= label
.replace(/^[ \t]+/g, '');
2912 label
= label
.replace(/[ \t]+$/g, '');
2914 if (label
&& !isNaN(label
))
2916 stack
.push(parseFloat(label
));
2918 else if (label
.match(/^(['"]).*\1$/))
2920 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
2922 else if (typeof types
[label
] == 'function')
2924 stack
.push(types
[label
]);
2929 throw "Syntax error, unhandled token '"+label
+"'";
2934 depth
+= (code
.charCodeAt(i
) == 40);
2940 if (typeof stack
[stack
.length
-2] != 'function')
2941 throw "Syntax error, argument list follows non-function";
2943 stack
[stack
.length
-1] =
2944 _luci2
.cbi
.validation
.compile(code
.substring(pos
, i
));
2957 var validation
= this.cbi
.validation
;
2959 validation
.types
= {
2960 'integer': function()
2962 if (this.match(/^-?[0-9]+$/) != null)
2965 validation
.i18n('Must be a valid integer');
2969 'uinteger': function()
2971 if (validation
.types
['integer'].apply(this) && (this >= 0))
2974 validation
.i18n('Must be a positive integer');
2980 if (!isNaN(parseFloat(this)))
2983 validation
.i18n('Must be a valid number');
2987 'ufloat': function()
2989 if (validation
.types
['float'].apply(this) && (this >= 0))
2992 validation
.i18n('Must be a positive number');
2996 'ipaddr': function()
2998 if (validation
.types
['ip4addr'].apply(this) ||
2999 validation
.types
['ip6addr'].apply(this))
3002 validation
.i18n('Must be a valid IP address');
3006 'ip4addr': function()
3008 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
3010 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
3011 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
3012 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
3013 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
3014 ((RegExp
.$6.indexOf('.') < 0)
3015 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
3016 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
3020 validation
.i18n('Must be a valid IPv4 address');
3024 'ip6addr': function()
3026 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
3028 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
3030 var addr
= RegExp
.$1;
3037 if (addr
.indexOf('.') > 0)
3039 var off
= addr
.lastIndexOf(':');
3041 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
3043 validation
.i18n('Must be a valid IPv6 address');
3047 addr
= addr
.substr(0, off
) + ':0:0';
3050 if (addr
.indexOf('::') >= 0)
3055 for (var i
= 1; i
< (addr
.length
-1); i
++)
3056 if (addr
.charAt(i
) == ':')
3061 validation
.i18n('Must be a valid IPv6 address');
3065 for (var i
= 0; i
< (7 - colons
); i
++)
3068 if (addr
.match(/^(.*?)::(.*?)$/))
3069 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
3070 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
3073 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3076 validation
.i18n('Must be a valid IPv6 address');
3081 validation
.i18n('Must be a valid IPv6 address');
3087 if (validation
.types
['integer'].apply(this) &&
3088 (this >= 0) && (this <= 65535))
3091 validation
.i18n('Must be a valid port number');
3095 'portrange': function()
3097 if (this.match(/^(\d+)-(\d+)$/))
3102 if (validation
.types
['port'].apply(p1
) &&
3103 validation
.types
['port'].apply(p2
) &&
3104 (parseInt(p1
) <= parseInt(p2
)))
3107 else if (validation
.types
['port'].apply(this))
3112 validation
.i18n('Must be a valid port range');
3116 'macaddr': function()
3118 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3121 validation
.i18n('Must be a valid MAC address');
3127 if (validation
.types
['hostname'].apply(this) ||
3128 validation
.types
['ipaddr'].apply(this))
3131 validation
.i18n('Must be a valid hostname or IP address');
3135 'hostname': function()
3137 if ((this.length
<= 253) &&
3138 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3139 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3140 this.match(/[^0-9.]/)))))
3143 validation
.i18n('Must be a valid host name');
3147 'network': function()
3149 if (validation
.types
['uciname'].apply(this) ||
3150 validation
.types
['host'].apply(this))
3153 validation
.i18n('Must be a valid network name');
3157 'wpakey': function()
3161 if ((v
.length
== 64)
3162 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
3163 : ((v
.length
>= 8) && (v
.length
<= 63)))
3166 validation
.i18n('Must be a valid WPA key');
3170 'wepkey': function()
3174 if (v
.substr(0,2) == 's:')
3177 if (((v
.length
== 10) || (v
.length
== 26))
3178 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
3179 : ((v
.length
== 5) || (v
.length
== 13)))
3182 validation
.i18n('Must be a valid WEP key');
3186 'uciname': function()
3188 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3191 validation
.i18n('Must be a valid UCI identifier');
3195 'range': function(min
, max
)
3197 var val
= parseFloat(this);
3199 if (validation
.types
['integer'].apply(this) &&
3200 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
3203 validation
.i18n('Must be a number between %d and %d');
3207 'min': function(min
)
3209 var val
= parseFloat(this);
3211 if (validation
.types
['integer'].apply(this) &&
3212 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
3215 validation
.i18n('Must be a number greater or equal to %d');
3219 'max': function(max
)
3221 var val
= parseFloat(this);
3223 if (validation
.types
['integer'].apply(this) &&
3224 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
3227 validation
.i18n('Must be a number lower or equal to %d');
3231 'rangelength': function(min
, max
)
3233 var val
= '' + this;
3235 if (!isNaN(min
) && !isNaN(max
) &&
3236 (val
.length
>= min
) && (val
.length
<= max
))
3239 validation
.i18n('Must be between %d and %d characters');
3243 'minlength': function(min
)
3245 var val
= '' + this;
3247 if (!isNaN(min
) && (val
.length
>= min
))
3250 validation
.i18n('Must be at least %d characters');
3254 'maxlength': function(max
)
3256 var val
= '' + this;
3258 if (!isNaN(max
) && (val
.length
<= max
))
3261 validation
.i18n('Must be at most %d characters');
3269 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3271 delete validation
.message
;
3273 if (typeof(arguments
[i
]) != 'function')
3275 if (arguments
[i
] == this)
3279 else if (arguments
[i
].apply(this, arguments
[i
+1]))
3284 if (validation
.message
)
3285 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3288 validation
.message
= msgs
.join( _luci2
.tr(' - or - '));
3296 for (var i
= 0; i
< arguments
.length
; i
+= 2)
3298 delete validation
.message
;
3300 if (typeof arguments
[i
] != 'function')
3302 if (arguments
[i
] != this)
3306 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
3311 if (validation
.message
)
3312 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
3315 validation
.message
= msgs
.join(', ');
3321 return validation
.types
['or'].apply(
3322 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
3325 'list': function(subvalidator
, subargs
)
3327 if (typeof subvalidator
!= 'function')
3330 var tokens
= this.match(/[^ \t]+/g);
3331 for (var i
= 0; i
< tokens
.length
; i
++)
3332 if (!subvalidator
.apply(tokens
[i
], subargs
))
3338 'phonedigit': function()
3340 if (this.match(/^[0-9\*#!\.]+$/) != null)
3343 validation
.i18n('Must be a valid phone number digit');
3347 'string': function()
3354 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
3355 init: function(name
, options
)
3358 this.instance
= { };
3359 this.dependencies
= [ ];
3360 this.rdependency
= { };
3362 this.options
= _luci2
.defaults(options
, {
3372 return this.section
.id('field', sid
|| '__unknown__', this.name
);
3375 render: function(sid
, condensed
)
3377 var i
= this.instance
[sid
] = { };
3379 i
.top
= $('<div />');
3383 i
.top
.addClass('form-group');
3385 if (typeof(this.options
.caption
) == 'string')
3387 .addClass('col-lg-2 control-label')
3388 .attr('for', this.id(sid
))
3389 .text(this.options
.caption
)
3393 i
.error
= $('<div />')
3395 .addClass('label label-danger');
3397 i
.widget
= $('<div />')
3399 .append(this.widget(sid
))
3405 i
.widget
.addClass('col-lg-5');
3408 .addClass('col-lg-5')
3409 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
3416 ucipath: function(sid
)
3419 config
: (this.options
.uci_package
|| this.map
.uci_package
),
3420 section
: (this.options
.uci_section
|| sid
),
3421 option
: (this.options
.uci_option
|| this.name
)
3425 ucivalue: function(sid
)
3427 var uci
= this.ucipath(sid
);
3428 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
3430 if (typeof(val
) == 'undefined')
3431 return this.options
.initial
;
3436 formvalue: function(sid
)
3438 var v
= $('#' + this.id(sid
)).val();
3439 return (v
=== '') ? undefined : v
;
3442 textvalue: function(sid
)
3444 var v
= this.formvalue(sid
);
3446 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3447 v
= this.ucivalue(sid
);
3449 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
3450 v
= this.options
.placeholder
;
3452 if (typeof(v
) == 'undefined' || v
=== '')
3455 if (typeof(v
) == 'string' && $.isArray(this.choices
))
3457 for (var i
= 0; i
< this.choices
.length
; i
++)
3458 if (v
=== this.choices
[i
][0])
3459 return this.choices
[i
][1];
3461 else if (v
=== true)
3462 return _luci2
.tr('yes');
3463 else if (v
=== false)
3464 return _luci2
.tr('no');
3465 else if ($.isArray(v
))
3466 return v
.join(', ');
3471 changed: function(sid
)
3473 var a
= this.ucivalue(sid
);
3474 var b
= this.formvalue(sid
);
3476 if (typeof(a
) != typeof(b
))
3479 if (typeof(a
) == 'object')
3481 if (a
.length
!= b
.length
)
3484 for (var i
= 0; i
< a
.length
; i
++)
3496 var uci
= this.ucipath(sid
);
3498 if (this.instance
[sid
].disabled
)
3500 if (!this.options
.keep
)
3501 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3506 var chg
= this.changed(sid
);
3507 var val
= this.formvalue(sid
);
3510 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
3515 _ev_validate: function(ev
)
3519 var val
= d
.elem
.val();
3520 var vstack
= d
.vstack
;
3522 if (vstack
&& typeof(vstack
[0]) == 'function')
3524 delete validation
.message
;
3526 if ((val
.length
== 0 && !d
.opt
))
3528 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
3529 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3531 d
.inst
.error
.text(_luci2
.tr('Field must not be empty')).show();
3534 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
3536 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
3537 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3539 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1])).show();
3544 d
.elem
.parents('div.form-group, td').first().removeClass('luci2-form-error');
3545 d
.elem
.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
3547 if (d
.multi
&& d
.inst
.widget
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
3550 d
.inst
.error
.text('').hide();
3555 for (var field
in d
.self
.rdependency
)
3556 d
.self
.rdependency
[field
].toggle(d
.sid
);
3561 validator: function(sid
, elem
, multi
)
3563 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
3567 if (typeof(this.options
.datatype
) == 'string')
3570 vstack
= _luci2
.cbi
.validation
.compile(this.options
.datatype
);
3573 else if (typeof(this.options
.datatype
) == 'function')
3575 var vfunc
= this.options
.datatype
;
3576 vstack
= [ function(elem
) {
3577 var rv
= vfunc(this, elem
);
3579 validation
.message
= rv
;
3580 return (rv
=== true);
3590 inst
: this.instance
[sid
],
3591 opt
: this.options
.optional
3594 if (elem
.prop('tagName') == 'SELECT')
3596 elem
.change(evdata
, this._ev_validate
);
3598 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
3600 elem
.click(evdata
, this._ev_validate
);
3601 elem
.blur(evdata
, this._ev_validate
);
3605 elem
.keyup(evdata
, this._ev_validate
);
3606 elem
.blur(evdata
, this._ev_validate
);
3609 elem
.attr('cbi-validate', true).on('validate', evdata
, this._ev_validate
);
3614 validate: function(sid
)
3616 var i
= this.instance
[sid
];
3618 i
.widget
.find('[cbi-validate]').trigger('validate');
3620 return (i
.disabled
|| i
.error
.text() == '');
3623 depends: function(d
, v
)
3630 for (var i
= 0; i
< d
.length
; i
++)
3632 if (typeof(d
[i
]) == 'string')
3634 else if (d
[i
] instanceof _luci2
.cbi
.AbstractValue
)
3635 dep
[d
[i
].name
] = true;
3638 else if (d
instanceof _luci2
.cbi
.AbstractValue
)
3641 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
3643 else if (typeof(d
) == 'object')
3647 else if (typeof(d
) == 'string')
3650 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
3653 if (!dep
|| $.isEmptyObject(dep
))
3656 for (var field
in dep
)
3658 var f
= this.section
.fields
[field
];
3660 f
.rdependency
[this.name
] = this;
3665 if ($.isEmptyObject(dep
))
3668 this.dependencies
.push(dep
);
3673 toggle: function(sid
)
3675 var d
= this.dependencies
;
3676 var i
= this.instance
[sid
];
3681 for (var n
= 0; n
< d
.length
; n
++)
3685 for (var field
in d
[n
])
3687 var val
= this.section
.fields
[field
].formvalue(sid
);
3688 var cmp
= d
[n
][field
];
3690 if (typeof(cmp
) == 'boolean')
3692 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
3698 else if (typeof(cmp
) == 'string')
3706 else if (typeof(cmp
) == 'function')
3714 else if (cmp
instanceof RegExp
)
3739 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
3746 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
3747 widget: function(sid
)
3749 var o
= this.options
;
3751 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
3752 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
3754 var i
= $('<input />')
3755 .attr('id', this.id(sid
))
3756 .attr('type', 'checkbox')
3757 .prop('checked', this.ucivalue(sid
));
3760 .addClass('checkbox')
3761 .append(this.validator(sid
, i
));
3764 ucivalue: function(sid
)
3766 var v
= this.callSuper('ucivalue', sid
);
3768 if (typeof(v
) == 'boolean')
3771 return (v
== this.options
.enabled
);
3774 formvalue: function(sid
)
3776 var v
= $('#' + this.id(sid
)).prop('checked');
3778 if (typeof(v
) == 'undefined')
3779 return !!this.options
.initial
;
3786 var uci
= this.ucipath(sid
);
3788 if (this.instance
[sid
].disabled
)
3790 if (!this.options
.keep
)
3791 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3796 var chg
= this.changed(sid
);
3797 var val
= this.formvalue(sid
);
3801 if (this.options
.optional
&& val
== this.options
.initial
)
3802 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
3804 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
3811 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
3812 widget: function(sid
)
3814 var i
= $('<input />')
3815 .addClass('form-control')
3816 .attr('id', this.id(sid
))
3817 .attr('type', 'text')
3818 .attr('placeholder', this.options
.placeholder
)
3819 .val(this.ucivalue(sid
));
3821 return this.validator(sid
, i
);
3825 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
3826 widget: function(sid
)
3828 var i
= $('<input />')
3829 .addClass('form-control')
3830 .attr('id', this.id(sid
))
3831 .attr('type', 'password')
3832 .attr('placeholder', this.options
.placeholder
)
3833 .val(this.ucivalue(sid
));
3835 var t
= $('<span />')
3836 .addClass('input-group-btn')
3837 .append(_luci2
.ui
.button(_luci2
.tr('Reveal'), 'default')
3838 .click(function(ev
) {
3840 var i
= b
.parent().prev();
3841 var t
= i
.attr('type');
3842 b
.text(t
== 'password' ? _luci2
.tr('Hide') : _luci2
.tr('Reveal'));
3843 i
.attr('type', (t
== 'password') ? 'text' : 'password');
3847 this.validator(sid
, i
);
3850 .addClass('input-group')
3856 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
3857 widget: function(sid
)
3859 var s
= $('<select />')
3860 .addClass('form-control');
3862 if (this.options
.optional
)
3865 .text(_luci2
.tr('-- Please choose --'))
3869 for (var i
= 0; i
< this.choices
.length
; i
++)
3871 .attr('value', this.choices
[i
][0])
3872 .text(this.choices
[i
][1])
3875 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
3877 return this.validator(sid
, s
);
3880 value: function(k
, v
)
3885 this.choices
.push([k
, v
|| k
]);
3890 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
3891 widget: function(sid
)
3893 var v
= this.ucivalue(sid
);
3894 var t
= $('<div />').attr('id', this.id(sid
));
3897 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
3900 for (var i
= 0; i
< v
.length
; i
++)
3904 for (var i
= 0; i
< this.choices
.length
; i
++)
3907 .addClass('checkbox')
3908 .append($('<input />')
3909 .attr('type', 'checkbox')
3910 .attr('value', this.choices
[i
][0])
3911 .prop('checked', s
[this.choices
[i
][0]]))
3912 .append(this.choices
[i
][1])
3919 formvalue: function(sid
)
3922 var fields
= $('#' + this.id(sid
) + ' > label > input');
3924 for (var i
= 0; i
< fields
.length
; i
++)
3925 if (fields
[i
].checked
)
3926 rv
.push(fields
[i
].getAttribute('value'));
3931 textvalue: function(sid
)
3933 var v
= this.formvalue(sid
);
3937 for (var i
= 0; i
< this.choices
.length
; i
++)
3938 c
[this.choices
[i
][0]] = this.choices
[i
][1];
3942 for (var i
= 0; i
< v
.length
; i
++)
3943 t
.push(c
[v
[i
]] || v
[i
]);
3945 return t
.join(', ');
3949 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
3950 _change: function(ev
)
3953 var self
= ev
.data
.self
;
3955 if (s
.selectedIndex
== (s
.options
.length
- 1))
3957 ev
.data
.select
.hide();
3958 ev
.data
.input
.show().focus();
3960 var v
= ev
.data
.input
.val();
3961 ev
.data
.input
.val(' ');
3962 ev
.data
.input
.val(v
);
3964 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
3966 ev
.data
.input
.val('');
3970 ev
.data
.input
.val(ev
.data
.select
.val());
3977 var val
= this.value
;
3978 var self
= ev
.data
.self
;
3980 ev
.data
.select
.empty();
3982 if (self
.options
.optional
)
3985 .text(_luci2
.tr('-- please choose --'))
3986 .appendTo(ev
.data
.select
);
3989 for (var i
= 0; i
< self
.choices
.length
; i
++)
3991 if (self
.choices
[i
][0] == val
)
3995 .attr('value', self
.choices
[i
][0])
3996 .text(self
.choices
[i
][1])
3997 .appendTo(ev
.data
.select
);
4000 if (!seen
&& val
!= '')
4004 .appendTo(ev
.data
.select
);
4008 .text(_luci2
.tr('-- custom --'))
4009 .appendTo(ev
.data
.select
);
4011 ev
.data
.input
.hide();
4012 ev
.data
.select
.val(val
).show().focus();
4015 _enter: function(ev
)
4020 ev
.preventDefault();
4021 ev
.data
.self
._blur(ev
);
4025 widget: function(sid
)
4027 var d
= $('<div />')
4028 .attr('id', this.id(sid
));
4030 var t
= $('<input />')
4031 .attr('type', 'text')
4035 var s
= $('<select />')
4040 input
: this.validator(sid
, t
),
4041 select
: this.validator(sid
, s
)
4044 s
.change(evdata
, this._change
);
4045 t
.blur(evdata
, this._blur
);
4046 t
.keydown(evdata
, this._enter
);
4048 t
.val(this.ucivalue(sid
));
4054 value: function(k
, v
)
4059 this.choices
.push([k
, v
|| k
]);
4063 formvalue: function(sid
)
4065 var v
= $('#' + this.id(sid
)).children('input').val();
4066 return (v
== '') ? undefined : v
;
4070 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
4071 _redraw: function(focus
, add
, del
, s
)
4073 var v
= s
.values
|| [ ];
4076 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
4078 v
.push(this.value
|| '');
4081 $(s
.parent
).empty();
4086 v
.splice(focus
, 0, '');
4088 else if (v
.length
== 0)
4094 for (var i
= 0; i
< v
.length
; i
++)
4101 remove
: ((i
+1) < v
.length
)
4106 btn
= _luci2
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
4108 btn
= _luci2
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
4112 var txt
= $('<input />')
4113 .addClass('form-control')
4114 .attr('type', 'text')
4117 var sel
= $('<select />')
4118 .addClass('form-control');
4121 .addClass('input-group')
4124 .append($('<span />')
4125 .addClass('input-group-btn')
4127 .appendTo(s
.parent
);
4129 evdata
.input
= this.validator(s
.sid
, txt
, true);
4130 evdata
.select
= this.validator(s
.sid
, sel
, true);
4132 sel
.change(evdata
, this._change
);
4133 txt
.blur(evdata
, this._blur
);
4134 txt
.keydown(evdata
, this._keydown
);
4139 if (i
== focus
|| -(i
+1) == focus
)
4146 var f
= $('<input />')
4147 .attr('type', 'text')
4149 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
4150 .addClass('form-control')
4151 .keydown(evdata
, this._keydown
)
4152 .keypress(evdata
, this._keypress
)
4156 .addClass('input-group')
4158 .append($('<span />')
4159 .addClass('input-group-btn')
4161 .appendTo(s
.parent
);
4167 else if (-(i
+1) == focus
)
4171 /* force cursor to end */
4177 evdata
.input
= this.validator(s
.sid
, f
, true);
4188 _keypress: function(ev
)
4192 /* backspace, delete */
4195 if (ev
.data
.input
.val() == '')
4197 ev
.preventDefault();
4203 /* enter, arrow up, arrow down */
4207 ev
.preventDefault();
4214 _keydown: function(ev
)
4216 var input
= ev
.data
.input
;
4220 /* backspace, delete */
4223 if (input
.val().length
== 0)
4225 ev
.preventDefault();
4227 var index
= ev
.data
.index
;
4233 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
4241 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4246 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
4247 if (prev
.is(':visible'))
4250 prev
.next('select').focus();
4255 var next
= input
.parent().nextAll('div.input-group:first').children('input');
4256 if (next
.is(':visible'))
4259 next
.next('select').focus();
4266 _btnclick: function(ev
)
4268 if (!this.getAttribute('disabled'))
4272 var index
= ev
.data
.index
;
4273 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
4277 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
4284 widget: function(sid
)
4286 this.options
.optional
= true;
4288 var v
= this.ucivalue(sid
);
4291 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4293 var d
= $('<div />')
4294 .attr('id', this.id(sid
))
4295 .addClass('cbi-input-dynlist');
4297 this._redraw(NaN
, -1, -1, {
4307 ucivalue: function(sid
)
4309 var v
= this.callSuper('ucivalue', sid
);
4312 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
4317 formvalue: function(sid
)
4320 var fields
= $('#' + this.id(sid
) + ' > input');
4322 for (var i
= 0; i
< fields
.length
; i
++)
4323 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
4324 rv
.push(fields
[i
].value
);
4330 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
4331 widget: function(sid
)
4334 .addClass('form-control-static')
4335 .attr('id', this.id(sid
))
4336 .html(this.ucivalue(sid
));
4339 formvalue: function(sid
)
4341 return this.ucivalue(sid
);
4345 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
4350 if (!self
.interfaces
)
4352 self
.interfaces
= [ ];
4353 return _luci2
.network
.getNetworkStatus().then(function(ifaces
) {
4354 self
.interfaces
= ifaces
;
4362 _device_icon: function(dev
)
4364 var type
= 'ethernet';
4365 var desc
= _luci2
.tr('Ethernet device');
4367 if (dev
.type
== 'IP tunnel')
4370 desc
= _luci2
.tr('Tunnel interface');
4372 else if (dev
['bridge-members'])
4375 desc
= _luci2
.tr('Bridge');
4377 else if (dev
.wireless
)
4380 desc
= _luci2
.tr('Wireless Network');
4382 else if (dev
.device
.indexOf('.') > 0)
4385 desc
= _luci2
.tr('VLAN interface');
4389 .attr('src', _luci2
.globals
.resource
+ '/icons/' + type
+ (dev
.up
? '' : '_disabled') + '.png')
4390 .attr('title', '%s (%s)'.format(desc
, dev
.device
));
4393 widget: function(sid
)
4395 var id
= this.id(sid
);
4396 var ul
= $('<ul />')
4398 .addClass('list-unstyled');
4400 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
4401 var value
= this.ucivalue(sid
);
4404 if (!this.options
.multiple
)
4405 check
[value
] = true;
4407 for (var i
= 0; i
< value
.length
; i
++)
4408 check
[value
[i
]] = true;
4410 if (this.interfaces
)
4412 for (var i
= 0; i
< this.interfaces
.length
; i
++)
4414 var iface
= this.interfaces
[i
];
4415 var badge
= $('<span />')
4417 .text('%s: '.format(iface
['interface']));
4419 if (iface
.device
&& iface
.device
.subdevices
)
4420 for (var j
= 0; j
< iface
.device
.subdevices
.length
; j
++)
4421 badge
.append(this._device_icon(iface
.device
.subdevices
[j
]));
4422 else if (iface
.device
)
4423 badge
.append(this._device_icon(iface
.device
));
4425 badge
.append($('<em />').text(_luci2
.tr('(No devices attached)')));
4428 .append($('<label />')
4429 .addClass(itype
+ ' inline')
4430 .append($('<input />')
4431 .attr('name', itype
+ id
)
4432 .attr('type', itype
)
4433 .attr('value', iface
['interface'])
4434 .prop('checked', !!check
[iface
['interface']]))
4440 if (!this.options
.multiple
)
4443 .append($('<label />')
4444 .addClass(itype
+ ' inline text-muted')
4445 .append($('<input />')
4446 .attr('name', itype
+ id
)
4447 .attr('type', itype
)
4449 .prop('checked', !value
))
4450 .append(_luci2
.tr('unspecified')))
4457 ucivalue: function(sid
)
4459 var v
= this.callSuper('ucivalue', sid
);
4461 if (!this.options
.multiple
)
4467 else if (typeof(v
) == 'string')
4470 return v
? v
[0] : undefined;
4477 if (typeof(v
) == 'string')
4478 v
= v
.match(/\S+/g);
4484 formvalue: function(sid
)
4486 var inputs
= $('#' + this.id(sid
) + ' input');
4488 if (!this.options
.multiple
)
4490 for (var i
= 0; i
< inputs
.length
; i
++)
4491 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
4492 return inputs
[i
].value
;
4499 for (var i
= 0; i
< inputs
.length
; i
++)
4500 if (inputs
[i
].checked
)
4501 rv
.push(inputs
[i
].value
);
4503 return rv
.length
? rv
: undefined;
4508 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
4511 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
4513 for (var i
= 1; i
< arguments
.length
; i
++)
4514 s
.push(arguments
[i
].replace(/\./g, '_'));
4519 option: function(widget
, name
, options
)
4521 if (this.tabs
.length
== 0)
4522 this.tab({ id
: '__default__', selected
: true });
4524 return this.taboption('__default__', widget
, name
, options
);
4527 tab: function(options
)
4529 if (options
.selected
)
4530 this.tabs
.selected
= this.tabs
.length
;
4534 caption
: options
.caption
,
4535 description
: options
.description
,
4541 taboption: function(tabid
, widget
, name
, options
)
4544 for (var i
= 0; i
< this.tabs
.length
; i
++)
4546 if (this.tabs
[i
].id
== tabid
)
4554 throw 'Cannot append to unknown tab ' + tabid
;
4556 var w
= widget
? new widget(name
, options
) : null;
4558 if (!(w
instanceof _luci2
.cbi
.AbstractValue
))
4559 throw 'Widget must be an instance of AbstractValue';
4564 this.fields
[name
] = w
;
4570 ucipackages: function(pkg
)
4572 for (var i
= 0; i
< this.tabs
.length
; i
++)
4573 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4574 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
4575 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
4578 formvalue: function()
4582 this.sections(function(s
) {
4583 var sid
= s
['.name'];
4584 var sv
= rv
[sid
] || (rv
[sid
] = { });
4586 for (var i
= 0; i
< this.tabs
.length
; i
++)
4587 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4589 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
4590 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
4597 validate_section: function(sid
)
4599 var inst
= this.instance
[sid
];
4602 var badge
= $('#' + this.id('teaser', sid
)).children('span:first');
4604 for (var i
= 0; i
< this.tabs
.length
; i
++)
4607 var stbadge
= $('#' + this.id('nodetab', sid
, this.tabs
[i
].id
)).children('span:first');
4609 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
4610 if (!this.tabs
[i
].fields
[j
].validate(sid
))
4616 .attr('title', _luci2
.trp('1 Error', '%d Errors', inval
).format(inval
));
4626 .attr('title', _luci2
.trp('1 Error', '%d Errors', invals
).format(invals
));
4633 validate: function()
4635 this.error_count
= 0;
4637 var as
= this.sections();
4639 for (var i
= 0; i
< as
.length
; i
++)
4641 var invals
= this.validate_section(as
[i
]['.name']);
4644 this.error_count
+= invals
;
4647 var badge
= $('#' + this.id('sectiontab')).children('span:first');
4649 if (this.error_count
> 0)
4651 .text(this.error_count
)
4652 .attr('title', _luci2
.trp('1 Error', '%d Errors', this.error_count
).format(this.error_count
));
4656 return (this.error_count
== 0);
4660 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
4661 init: function(uci_type
, options
)
4663 this.uci_type
= uci_type
;
4664 this.options
= options
;
4667 this.error_count
= 0;
4668 this.active_panel
= 0;
4669 this.active_tab
= { };
4672 filter: function(section
)
4677 sections: function(cb
)
4679 var s1
= this.map
.ucisections(this.map
.uci_package
);
4682 for (var i
= 0; i
< s1
.length
; i
++)
4683 if (s1
[i
]['.type'] == this.uci_type
)
4684 if (this.filter(s1
[i
]))
4687 if (typeof(cb
) == 'function')
4688 for (var i
= 0; i
< s2
.length
; i
++)
4689 cb
.apply(this, [ s2
[i
] ]);
4696 this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
4699 remove: function(sid
)
4701 this.map
.remove(this.map
.uci_package
, sid
);
4704 _ev_add: function(ev
)
4707 var name
= undefined;
4708 var self
= ev
.data
.self
;
4710 if (addb
.prev().prop('nodeName') == 'INPUT')
4711 name
= addb
.prev().val();
4713 if (addb
.prop('disabled') || name
=== '')
4716 _luci2
.ui
.saveScrollTop();
4718 self
.active_panel
= -1;
4723 _luci2
.ui
.restoreScrollTop();
4726 _ev_remove: function(ev
)
4728 var self
= ev
.data
.self
;
4729 var sid
= ev
.data
.sid
;
4731 _luci2
.ui
.saveScrollTop();
4737 _luci2
.ui
.restoreScrollTop();
4739 ev
.stopPropagation();
4742 _ev_sid: function(ev
)
4744 var self
= ev
.data
.self
;
4746 var addb
= text
.next();
4747 var errt
= addb
.next();
4748 var name
= text
.val();
4751 if (!/^[a-zA-Z0-9_]*$/.test(name
))
4753 errt
.text(_luci2
.tr('Invalid section name')).show();
4754 text
.addClass('error');
4755 addb
.prop('disabled', true);
4759 for (var sid
in self
.map
.uci
.values
[self
.map
.uci_package
])
4766 for (var sid
in self
.map
.uci
.creates
[self
.map
.uci_package
])
4775 errt
.text(_luci2
.tr('Name already used')).show();
4776 text
.addClass('error');
4777 addb
.prop('disabled', true);
4781 errt
.text('').hide();
4782 text
.removeClass('error');
4783 addb
.prop('disabled', false);
4787 _ev_tab: function(ev
)
4789 var self
= ev
.data
.self
;
4790 var sid
= ev
.data
.sid
;
4793 self
.active_tab
[sid
] = parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
4796 _ev_panel_collapse: function(ev
)
4798 var self
= ev
.data
.self
;
4800 var this_panel
= $(ev
.target
);
4801 var this_toggle
= this_panel
.prevAll('[data-toggle="collapse"]:first');
4803 var prev_toggle
= $($(ev
.delegateTarget
).find('[data-toggle="collapse"]:eq(%d)'.format(self
.active_panel
)));
4804 var prev_panel
= $(prev_toggle
.attr('data-target'));
4808 .addClass('collapse');
4810 prev_toggle
.find('.luci2-section-teaser')
4812 .children('span:last')
4814 .append(self
.teaser(prev_panel
.attr('data-luci2-sid')));
4816 this_toggle
.find('.luci2-section-teaser')
4819 self
.active_panel
= parseInt(this_panel
.attr('data-luci2-panel-index'));
4823 _ev_panel_open: function(ev
)
4825 var self
= ev
.data
.self
;
4826 var panel
= $($(this).attr('data-target'));
4827 var index
= parseInt(panel
.attr('data-luci2-panel-index'));
4829 if (index
== self
.active_panel
)
4830 ev
.stopPropagation();
4833 _ev_sort: function(ev
)
4835 var self
= ev
.data
.self
;
4836 var cur_idx
= ev
.data
.index
;
4837 var new_idx
= cur_idx
+ (ev
.data
.up
? -1 : 1);
4838 var s
= self
.sections();
4840 if (new_idx
>= 0 && new_idx
< s
.length
)
4842 var tmp
= s
[cur_idx
]['.index'];
4844 s
[cur_idx
]['.index'] = s
[new_idx
]['.index'];
4845 s
[new_idx
]['.index'] = tmp
;
4847 if (self
.active_panel
== cur_idx
)
4848 self
.active_panel
= new_idx
;
4849 else if (self
.active_panel
== new_idx
)
4850 self
.active_panel
= cur_idx
;
4852 self
.map
.uci
.reorder
= true;
4858 ev
.stopPropagation();
4861 teaser: function(sid
)
4863 var tf
= this.teaser_fields
;
4867 tf
= this.teaser_fields
= [ ];
4869 if ($.isArray(this.options
.teasers
))
4871 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
4873 var f
= this.options
.teasers
[i
];
4874 if (f
instanceof _luci2
.cbi
.AbstractValue
)
4876 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof _luci2
.cbi
.AbstractValue
)
4877 tf
.push(this.fields
[f
]);
4882 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
4883 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
4884 tf
.push(this.tabs
[i
].fields
[j
]);
4890 for (var i
= 0; i
< tf
.length
; i
++)
4892 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
4895 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
4896 var v
= tf
[i
].textvalue(sid
);
4898 if (typeof(v
) == 'undefined')
4901 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
4907 _render_add: function()
4909 if (!this.options
.addremove
)
4912 var text
= _luci2
.tr('Add section');
4913 var ttip
= _luci2
.tr('Create new section...');
4915 if ($.isArray(this.options
.add_caption
))
4916 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
4917 else if (typeof(this.options
.add_caption
) == 'string')
4918 text
= this.options
.add_caption
, ttip
= '';
4920 var add
= $('<div />');
4922 if (this.options
.anonymous
=== false)
4925 .addClass('cbi-input-text')
4926 .attr('type', 'text')
4927 .attr('placeholder', ttip
)
4928 .blur({ self
: this }, this._ev_sid
)
4929 .keyup({ self
: this }, this._ev_sid
)
4933 .attr('src', _luci2
.globals
.resource
+ '/icons/cbi/add.gif')
4934 .attr('title', text
)
4935 .addClass('cbi-button')
4936 .click({ self
: this }, this._ev_add
)
4940 .addClass('cbi-value-error')
4946 _luci2
.ui
.button(text
, 'success', ttip
)
4947 .click({ self
: this }, this._ev_add
)
4954 _render_remove: function(sid
, index
)
4956 if (!this.options
.addremove
)
4959 var text
= _luci2
.tr('Remove');
4960 var ttip
= _luci2
.tr('Remove this section');
4962 if ($.isArray(this.options
.remove_caption
))
4963 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
4964 else if (typeof(this.options
.remove_caption
) == 'string')
4965 text
= this.options
.remove_caption
, ttip
= '';
4967 return _luci2
.ui
.button(text
, 'danger', ttip
)
4968 .click({ self
: this, sid
: sid
, index
: index
}, this._ev_remove
);
4971 _render_sort: function(sid
, index
)
4973 if (!this.options
.sortable
)
4976 var b1
= _luci2
.ui
.button('↑', 'info', _luci2
.tr('Move up'))
4977 .click({ self
: this, index
: index
, up
: true }, this._ev_sort
);
4979 var b2
= _luci2
.ui
.button('↓', 'info', _luci2
.tr('Move down'))
4980 .click({ self
: this, index
: index
, up
: false }, this._ev_sort
);
4985 _render_caption: function()
4988 .addClass('panel-title')
4989 .append(this.label('caption') || this.uci_type
);
4992 _render_description: function()
4994 var text
= this.label('description');
4998 .addClass('luci2-section-description')
5004 _render_teaser: function(sid
, index
)
5006 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5009 .attr('id', this.id('teaser', sid
))
5010 .addClass('luci2-section-teaser well well-sm')
5011 .append($('<span />')
5013 .append($('<span />'));
5019 _render_head: function(condensed
)
5025 .addClass('panel-heading')
5026 .append(this._render_caption())
5027 .append(this._render_description());
5030 _render_tab_description: function(sid
, index
, tab_index
)
5032 var tab
= this.tabs
[tab_index
];
5034 if (typeof(tab
.description
) == 'string')
5037 .addClass('cbi-tab-descr')
5038 .text(tab
.description
);
5044 _render_tab_head: function(sid
, index
, tab_index
)
5046 var tab
= this.tabs
[tab_index
];
5047 var cur
= this.active_tab
[sid
] || 0;
5049 var tabh
= $('<li />')
5051 .attr('id', this.id('nodetab', sid
, tab
.id
))
5052 .attr('href', '#' + this.id('node', sid
, tab
.id
))
5053 .attr('data-toggle', 'tab')
5054 .attr('data-luci2-tab-index', tab_index
)
5055 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
5056 .append($('<span />')
5058 .on('shown.bs.tab', { self
: this, sid
: sid
}, this._ev_tab
));
5060 if (cur
== tab_index
)
5061 tabh
.addClass('active');
5066 _render_tab_body: function(sid
, index
, tab_index
)
5068 var tab
= this.tabs
[tab_index
];
5069 var cur
= this.active_tab
[sid
] || 0;
5071 var tabb
= $('<div />')
5072 .addClass('tab-pane')
5073 .attr('id', this.id('node', sid
, tab
.id
))
5074 .attr('data-luci2-tab-index', tab_index
)
5075 .append(this._render_tab_description(sid
, index
, tab_index
));
5077 if (cur
== tab_index
)
5078 tabb
.addClass('active');
5080 for (var i
= 0; i
< tab
.fields
.length
; i
++)
5081 tabb
.append(tab
.fields
[i
].render(sid
));
5086 _render_section_head: function(sid
, index
)
5088 var head
= $('<div />')
5089 .addClass('luci2-section-header')
5090 .append(this._render_teaser(sid
, index
))
5091 .append($('<div />')
5092 .addClass('btn-group')
5093 .append(this._render_sort(sid
, index
))
5094 .append(this._render_remove(sid
, index
)));
5096 if (this.options
.collabsible
)
5098 head
.attr('data-toggle', 'collapse')
5099 .attr('data-parent', this.id('sectiongroup'))
5100 .attr('data-target', '#' + this.id('panel', sid
))
5101 .on('click', { self
: this }, this._ev_panel_open
);
5107 _render_section_body: function(sid
, index
)
5109 var body
= $('<div />')
5110 .attr('id', this.id('panel', sid
))
5111 .attr('data-luci2-panel-index', index
)
5112 .attr('data-luci2-sid', sid
);
5114 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
5116 body
.addClass('panel-collapse collapse');
5118 if (index
== this.active_panel
)
5119 body
.addClass('in');
5122 var tab_heads
= $('<ul />')
5123 .addClass('nav nav-tabs');
5125 var tab_bodies
= $('<div />')
5126 .addClass('form-horizontal tab-content')
5129 for (var j
= 0; j
< this.tabs
.length
; j
++)
5131 tab_heads
.append(this._render_tab_head(sid
, index
, j
));
5132 tab_bodies
.append(this._render_tab_body(sid
, index
, j
));
5135 body
.append(tab_bodies
);
5137 if (this.tabs
.length
<= 1)
5143 _render_body: function(condensed
)
5145 var s
= this.sections();
5147 if (this.active_panel
< 0)
5148 this.active_panel
+= s
.length
;
5149 else if (this.active_panel
>= s
.length
)
5150 this.active_panel
= s
.length
- 1;
5152 var body
= $('<ul />')
5153 .addClass('list-group');
5155 if (this.options
.collabsible
)
5157 body
.attr('id', this.id('sectiongroup'))
5158 .on('show.bs.collapse', { self
: this }, this._ev_panel_collapse
);
5163 body
.append($('<li />')
5164 .addClass('list-group-item text-muted')
5165 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.')))
5168 for (var i
= 0; i
< s
.length
; i
++)
5170 var sid
= s
[i
]['.name'];
5171 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5173 body
.append($('<li />')
5174 .addClass('list-group-item')
5175 .append(this._render_section_head(sid
, i
))
5176 .append(this._render_section_body(sid
, i
)));
5182 render: function(condensed
)
5184 this.instance
= { };
5186 var panel
= $('<div />')
5187 .addClass('panel panel-default')
5188 .append(this._render_head(condensed
))
5189 .append(this._render_body(condensed
));
5191 if (this.options
.addremove
)
5192 panel
.append($('<div />')
5193 .addClass('panel-footer')
5194 .append(this._render_add()));
5201 var s
= this.sections();
5203 for (var i
= 0; i
< s
.length
; i
++)
5205 var sid
= s
[i
]['.name'];
5207 this.validate_section(sid
);
5209 if (i
!= this.active_panel
)
5210 $('#' + this.id('teaser', sid
)).children('span:last')
5211 .append(this.teaser(sid
));
5213 $('#' + this.id('teaser', sid
))
5219 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
5220 _render_table_head: function()
5222 var thead
= $('<thead />')
5224 .addClass('cbi-section-table-titles'));
5226 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5227 thead
.children().append($('<th />')
5228 .addClass('cbi-section-table-cell')
5229 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5230 .append(this.tabs
[0].fields
[j
].label('caption')));
5232 if (this.options
.addremove
!== false || this.options
.sortable
)
5233 thead
.children().append($('<th />')
5234 .addClass('cbi-section-table-cell')
5240 _render_table_row: function(sid
, index
)
5242 var row
= $('<tr />')
5243 .attr('data-luci2-sid', sid
);
5245 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
5247 row
.append($('<td />')
5248 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
5249 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
5252 if (this.options
.addremove
!== false || this.options
.sortable
)
5254 row
.append($('<td />')
5255 .addClass('text-right')
5256 .append($('<div />')
5257 .addClass('btn-group')
5258 .append(this._render_sort(sid
, index
))
5259 .append(this._render_remove(sid
, index
))));
5265 _render_table_body: function()
5267 var s
= this.sections();
5269 var tbody
= $('<tbody />');
5273 var cols
= this.tabs
[0].fields
.length
;
5275 if (this.options
.addremove
!== false || this.options
.sortable
)
5278 tbody
.append($('<tr />')
5280 .addClass('text-muted')
5281 .attr('colspan', cols
)
5282 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.'))));
5285 for (var i
= 0; i
< s
.length
; i
++)
5287 var sid
= s
[i
]['.name'];
5288 var inst
= this.instance
[sid
] = { tabs
: [ ] };
5290 tbody
.append(this._render_table_row(sid
, i
));
5296 _render_body: function(condensed
)
5298 return $('<table />')
5299 .addClass('table table-condensed table-hover')
5300 .append(this._render_table_head())
5301 .append(this._render_table_body());
5305 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
5306 sections: function(cb
)
5309 var pkg
= this.map
.uci
.values
[this.map
.uci_package
];
5312 if (pkg
[s
]['.name'] == this.uci_type
)
5318 if (typeof(cb
) == 'function' && sa
.length
> 0)
5319 cb
.apply(this, [ sa
[0] ]);
5325 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
5326 sections: function(cb
)
5328 if (typeof(cb
) == 'function')
5329 cb
.apply(this, [ { '.name': this.uci_type
} ]);
5331 return [ { '.name': this.uci_type
} ];
5335 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
5336 init: function(uci_package
, options
)
5340 this.uci_package
= uci_package
;
5341 this.sections
= [ ];
5342 this.options
= _luci2
.defaults(options
, {
5343 save: function() { },
5344 prepare: function() {
5345 return _luci2
.uci
.writable(function(writable
) {
5346 self
.options
.readonly
= !writable
;
5352 _load_cb: function(packages
)
5354 for (var i
= 0; i
< packages
.length
; i
++)
5356 this.uci
.values
[packages
[i
]['.package']] = packages
[i
];
5357 delete packages
[i
]['.package'];
5360 var deferreds
= [ _luci2
.deferrable(this.options
.prepare()) ];
5362 for (var i
= 0; i
< this.sections
.length
; i
++)
5364 for (var f
in this.sections
[i
].fields
)
5366 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
5369 var s
= this.sections
[i
].sections();
5370 for (var j
= 0; j
< s
.length
; j
++)
5372 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
5373 if (_luci2
.isDeferred(rv
))
5379 return $.when
.apply($, deferreds
);
5397 for (var i
= 0; i
< this.sections
.length
; i
++)
5398 this.sections
[i
].ucipackages(packages
);
5400 packages
[this.uci_package
] = true;
5404 for (var pkg
in packages
)
5405 _luci2
.uci
.get_all(pkg
);
5407 return _luci2
.rpc
.flush().then(function(packages
) {
5408 return self
._load_cb(packages
);
5412 _ev_tab: function(ev
)
5414 var self
= ev
.data
.self
;
5417 self
.active_tab
= parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
5420 _render_tab_head: function(tab_index
)
5422 var section
= this.sections
[tab_index
];
5423 var cur
= this.active_tab
|| 0;
5425 var tabh
= $('<li />')
5427 .attr('id', section
.id('sectiontab'))
5428 .attr('href', '#' + section
.id('section'))
5429 .attr('data-toggle', 'tab')
5430 .attr('data-luci2-tab-index', tab_index
)
5431 .text(section
.label('caption') + ' ')
5432 .append($('<span />')
5434 .on('shown.bs.tab', { self
: this }, this._ev_tab
));
5436 if (cur
== tab_index
)
5437 tabh
.addClass('active');
5442 _render_tab_body: function(tab_index
)
5444 var section
= this.sections
[tab_index
];
5445 var desc
= section
.label('description');
5446 var cur
= this.active_tab
|| 0;
5448 var tabb
= $('<div />')
5449 .addClass('tab-pane')
5450 .attr('id', section
.id('section'))
5451 .attr('data-luci2-tab-index', tab_index
);
5453 if (cur
== tab_index
)
5454 tabb
.addClass('active');
5457 tabb
.append($('<p />')
5460 var s
= section
.render(this.options
.tabbed
);
5462 if (this.options
.readonly
|| section
.options
.readonly
)
5463 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
5470 _render_body: function()
5472 var tabs
= $('<ul />')
5473 .addClass('nav nav-tabs');
5475 var body
= $('<div />')
5478 for (var i
= 0; i
< this.sections
.length
; i
++)
5480 tabs
.append(this._render_tab_head(i
));
5481 body
.append(this._render_tab_body(i
));
5484 if (this.options
.tabbed
)
5485 body
.addClass('tab-content');
5494 var map
= $('<form />');
5496 if (typeof(this.options
.caption
) == 'string')
5497 map
.append($('<h2 />')
5498 .text(this.options
.caption
));
5500 if (typeof(this.options
.description
) == 'string')
5501 map
.append($('<p />')
5502 .text(this.options
.description
));
5504 map
.append(this._render_body());
5506 if (this.options
.pageaction
!== false)
5508 map
.append($('<div />')
5509 .addClass('panel panel-default panel-body text-right')
5510 .append($('<div />')
5511 .addClass('btn-group')
5512 .append(_luci2
.ui
.button(_luci2
.tr('Save & Apply'), 'primary')
5513 .click({ self
: this }, function(ev
) { }))
5514 .append(_luci2
.ui
.button(_luci2
.tr('Save'), 'default')
5515 .click({ self
: this }, function(ev
) { ev
.data
.self
.send(); }))
5516 .append(_luci2
.ui
.button(_luci2
.tr('Reset'), 'default')
5517 .click({ self
: this }, function(ev
) { ev
.data
.self
.insertInto(ev
.data
.self
.target
); }))));
5525 for (var i
= 0; i
< this.sections
.length
; i
++)
5526 this.sections
[i
].finish();
5533 this.target
.hide().empty().append(this.render());
5538 section: function(widget
, uci_type
, options
)
5540 var w
= widget
? new widget(uci_type
, options
) : null;
5542 if (!(w
instanceof _luci2
.cbi
.AbstractSection
))
5543 throw 'Widget must be an instance of AbstractSection';
5546 w
.index
= this.sections
.length
;
5548 this.sections
.push(w
);
5552 formvalue: function()
5556 for (var i
= 0; i
< this.sections
.length
; i
++)
5558 var sids
= this.sections
[i
].formvalue();
5559 for (var sid
in sids
)
5561 var s
= rv
[sid
] || (rv
[sid
] = { });
5562 $.extend(s
, sids
[sid
]);
5569 add: function(conf
, type
, name
)
5571 var c
= this.uci
.creates
;
5572 var s
= '.new.%d'.format(this.uci
.newid
++);
5581 '.anonymous': !name
,
5582 '.index': 1000 + this.uci
.newid
5588 remove: function(conf
, sid
)
5590 var n
= this.uci
.creates
;
5591 var c
= this.uci
.changes
;
5592 var d
= this.uci
.deletes
;
5594 /* requested deletion of a just created section */
5595 if (sid
.indexOf('.new.') == 0)
5598 delete n
[conf
][sid
];
5603 delete c
[conf
][sid
];
5608 d
[conf
][sid
] = true;
5612 ucisections: function(conf
, cb
)
5615 var pkg
= this.uci
.values
[conf
];
5616 var crt
= this.uci
.creates
[conf
];
5617 var del
= this.uci
.deletes
[conf
];
5623 if (!del
|| del
[s
] !== true)
5630 sa
.sort(function(a
, b
) {
5631 return a
['.index'] - b
['.index'];
5634 for (var i
= 0; i
< sa
.length
; i
++)
5635 sa
[i
]['.index'] = i
;
5637 if (typeof(cb
) == 'function')
5638 for (var i
= 0; i
< sa
.length
; i
++)
5639 cb
.apply(this, [ sa
[i
] ]);
5644 get: function(conf
, sid
, opt
)
5646 var v
= this.uci
.values
;
5647 var n
= this.uci
.creates
;
5648 var c
= this.uci
.changes
;
5649 var d
= this.uci
.deletes
;
5651 /* requested option in a just created section */
5652 if (sid
.indexOf('.new.') == 0)
5657 if (typeof(opt
) == 'undefined')
5658 return (n
[conf
][sid
] || { });
5660 return n
[conf
][sid
][opt
];
5663 /* requested an option value */
5664 if (typeof(opt
) != 'undefined')
5666 /* check whether option was deleted */
5667 if (d
[conf
] && d
[conf
][sid
])
5669 if (d
[conf
][sid
] === true)
5672 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
5673 if (d
[conf
][sid
][i
] == opt
)
5677 /* check whether option was changed */
5678 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
5679 return c
[conf
][sid
][opt
];
5681 /* return base value */
5682 if (v
[conf
] && v
[conf
][sid
])
5683 return v
[conf
][sid
][opt
];
5688 /* requested an entire section */
5690 return (v
[conf
][sid
] || { });
5695 set: function(conf
, sid
, opt
, val
)
5697 var n
= this.uci
.creates
;
5698 var c
= this.uci
.changes
;
5699 var d
= this.uci
.deletes
;
5701 if (sid
.indexOf('.new.') == 0)
5703 if (n
[conf
] && n
[conf
][sid
])
5705 if (typeof(val
) != 'undefined')
5706 n
[conf
][sid
][opt
] = val
;
5708 delete n
[conf
][sid
][opt
];
5711 else if (typeof(val
) != 'undefined')
5719 c
[conf
][sid
][opt
] = val
;
5729 d
[conf
][sid
].push(opt
);
5733 validate: function()
5737 for (var i
= 0; i
< this.sections
.length
; i
++)
5739 if (!this.sections
[i
].validate())
5748 if (this.options
.readonly
)
5749 return _luci2
.deferrable();
5751 var deferreds
= [ _luci2
.deferrable(this.options
.save()) ];
5753 for (var i
= 0; i
< this.sections
.length
; i
++)
5755 if (this.sections
[i
].options
.readonly
)
5758 for (var f
in this.sections
[i
].fields
)
5760 if (typeof(this.sections
[i
].fields
[f
].save
) != 'function')
5763 var s
= this.sections
[i
].sections();
5764 for (var j
= 0; j
< s
.length
; j
++)
5766 var rv
= this.sections
[i
].fields
[f
].save(s
[j
]['.name']);
5767 if (_luci2
.isDeferred(rv
))
5773 return $.when
.apply($, deferreds
);
5776 _send_uci_reorder: function()
5778 if (!this.uci
.reorder
)
5779 return _luci2
.deferrable();
5784 gather all created and existing sections, sort them according
5785 to their index value and issue an uci order call
5787 for (var c
in this.uci
.values
)
5791 if (this.uci
.creates
&& this.uci
.creates
[c
])
5792 for (var s
in this.uci
.creates
[c
])
5793 o
.push(this.uci
.creates
[c
][s
]);
5795 for (var s
in this.uci
.values
[c
])
5796 o
.push(this.uci
.values
[c
][s
]);
5800 o
.sort(function(a
, b
) {
5801 return (a
['.index'] - b
['.index']);
5806 for (var i
= 0; i
< o
.length
; i
++)
5807 sids
.push(o
[i
]['.name']);
5809 _luci2
.uci
.order(c
, sids
);
5813 return _luci2
.rpc
.flush();
5816 _send_uci: function()
5823 if (this.uci
.creates
)
5824 for (var c
in this.uci
.creates
)
5825 for (var s
in this.uci
.creates
[c
])
5832 for (var k
in this.uci
.creates
[c
][s
])
5835 r
.type
= this.uci
.creates
[c
][s
][k
];
5836 else if (k
== '.create')
5837 r
.name
= this.uci
.creates
[c
][s
][k
];
5838 else if (k
.charAt(0) != '.')
5839 r
.values
[k
] = this.uci
.creates
[c
][s
][k
];
5842 snew
.push(this.uci
.creates
[c
][s
]);
5844 _luci2
.uci
.add(r
.config
, r
.type
, r
.name
, r
.values
);
5847 if (this.uci
.changes
)
5848 for (var c
in this.uci
.changes
)
5849 for (var s
in this.uci
.changes
[c
])
5850 _luci2
.uci
.set(c
, s
, this.uci
.changes
[c
][s
]);
5852 if (this.uci
.deletes
)
5853 for (var c
in this.uci
.deletes
)
5854 for (var s
in this.uci
.deletes
[c
])
5856 var o
= this.uci
.deletes
[c
][s
];
5857 _luci2
.uci
['delete'](c
, s
, (o
=== true) ? undefined : o
);
5860 return _luci2
.rpc
.flush().then(function(responses
) {
5862 array "snew" holds references to the created uci sections,
5863 use it to assign the returned names of the new sections
5865 for (var i
= 0; i
< snew
.length
; i
++)
5866 snew
[i
]['.name'] = responses
[i
];
5868 return self
._send_uci_reorder();
5874 if (!this.validate())
5875 return _luci2
.deferrable();
5879 _luci2
.ui
.saveScrollTop();
5880 _luci2
.ui
.loading(true);
5882 return this.save().then(function() {
5883 return self
._send_uci();
5884 }).then(function() {
5885 return _luci2
.ui
.updateChanges();
5886 }).then(function() {
5888 }).then(function() {
5892 _luci2
.ui
.loading(false);
5893 _luci2
.ui
.restoreScrollTop();
5897 insertInto: function(id
)
5900 self
.target
= $(id
);
5902 _luci2
.ui
.loading(true);
5905 return self
.load().then(function() {
5906 self
.target
.empty().append(self
.render());
5910 _luci2
.ui
.loading(false);