2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String.prototype.format = function()
15 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27 var a = b = [], numSubstitutions = 0, numMatches = 0;
29 while ((a = re.exec(str)) != null)
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
43 if (numSubstitutions < arguments.length)
45 var param = arguments[numSubstitutions++];
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
59 minLength = parseInt(pMinLength);
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
70 subst = (parseInt(param) || 0).toString(2);
74 subst = String.fromCharCode(parseInt(param) || 0);
78 subst = (parseInt(param) || 0);
82 subst = Math.abs(parseInt(param) || 0);
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
92 subst = (parseInt(param) || 0).toString(8);
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
108 subst = esc(param, html_esc);
112 subst = esc(param, quot_esc);
116 subst = String.serialize(param);
123 var ts = (param || 0);
126 tm = Math.floor(ts / 60);
131 th = Math.floor(tm / 60);
136 td = Math.floor(th / 24);
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i = 0; (i < units.length) && (val > mf); i++)
157 subst = val.toFixed(pr) + ' ' + units[i];
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
169 out += leftpart + subst;
170 str = str.substr(m.length);
180 var Class = function() { };
182 Class.extend = function(properties)
184 Class.initializing = true;
186 var prototype = new this();
187 var superprot = this.prototype;
189 Class.initializing = false;
191 $.extend(prototype, properties, {
192 callSuper: function() {
194 var meth = arguments[0];
196 if (typeof(superprot[meth]) != 'function')
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
202 return superprot[meth].apply(this, args);
208 this.options = arguments[0] || { };
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
217 _class.extend = arguments.callee;
222 this.defaults = function(obj, def)
225 if (typeof(obj[key]) == 'undefined')
231 this.isDeferred = function(x)
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments[0]))
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
253 plural: function(n) { return 0 + (n != 1) },
256 if (_luci2.i18n.loaded)
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
270 var pe = _luci2.i18n.catalog[''];
273 delete _luci2.i18n.catalog[''];
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
282 _luci2.i18n.loaded = true;
287 this.tr = function(msgid)
291 var msgstr = _luci2.i18n.catalog[msgid];
293 if (typeof(msgstr) == 'undefined')
295 else if (typeof(msgstr) == 'string')
301 this.trp = function(msgid, msgid_plural, count)
305 var msgstr = _luci2.i18n.catalog[msgid];
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
312 return msgstr[_luci2.i18n.plural(count)];
315 this.trc = function(msgctx, msgid)
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
321 if (typeof(msgstr) == 'undefined')
323 else if (typeof(msgstr) == 'string')
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
340 return msgstr[_luci2.i18n.plural(count)];
343 this.setHash = function(key, value)
346 var data = this.getHash(undefined);
348 if (typeof(value) == 'undefined')
359 for (var i = 0; i < keys.length; i++)
364 h += keys[i] + ':' + data[keys[i]];
368 location.hash = '#' + h;
371 this.getHash = function(key)
374 var tuples = (location.hash || '#').substring(1).split(/,/);
376 for (var i = 0; i < tuples.length; i++)
378 var tuple = tuples[i].split(/:/);
379 if (tuple.length == 2)
380 data[tuple[0]] = tuple[1];
383 if (typeof(key) != 'undefined')
392 sid: '00000000000000000000000000000000'
401 _call: function(req, cb)
403 return $.ajax('/ubus', {
405 contentType: 'application/json',
406 data: JSON.stringify(req),
409 timeout: _luci2.globals.timeout
413 _list_cb: function(msg)
415 /* verify message frame */
416 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
417 throw 'Invalid JSON response';
422 _call_cb: function(msg)
425 var type = Object.prototype.toString;
430 for (var i = 0; i < msg.length; i++)
432 /* verify message frame */
433 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
434 throw 'Invalid JSON response';
436 /* fetch related request info */
437 var req = _luci2.rpc._requests[msg[i].id];
438 if (typeof(req) != 'object')
439 throw 'No related request for JSON response';
441 /* fetch response attribute and verify returned type */
444 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
445 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
449 for (var key in req.expect)
451 if (typeof(ret) != 'undefined' && key != '')
454 if (type.call(ret) != type.call(req.expect[key]))
455 ret = req.expect[key];
462 if (typeof(req.filter) == 'function')
465 req.priv[1] = req.params;
466 ret = req.filter.apply(_luci2.rpc, req.priv);
469 /* store response data */
470 if (typeof(req.index) == 'number')
471 data[req.index] = ret;
475 /* delete request object */
476 delete _luci2.rpc._requests[msg[i].id];
485 for (var i = 0; i < arguments.length; i++)
486 params[i] = arguments[i];
492 params: (params.length > 0) ? params : undefined
495 return this._call(msg, this._list_cb);
500 if (!$.isArray(this._batch))
506 if (!$.isArray(this._batch))
507 return _luci2.deferrable([ ]);
509 var req = this._batch;
513 return this._call(req, this._call_cb);
516 declare: function(options)
521 /* build parameter object */
524 if ($.isArray(options.params))
525 for (p_off = 0; p_off < options.params.length; p_off++)
526 params[options.params[p_off]] = arguments[p_off];
528 /* all remaining arguments are private args */
529 var priv = [ undefined, undefined ];
530 for (; p_off < arguments.length; p_off++)
531 priv.push(arguments[p_off]);
533 /* store request info */
534 var req = _rpc._requests[_rpc._id] = {
535 expect: options.expect,
536 filter: options.filter,
541 /* build message object */
554 /* when a batch is in progress then store index in request data
555 * and push message object onto the stack */
556 if ($.isArray(_rpc._batch))
558 req.index = _rpc._batch.push(msg) - 1;
559 return _luci2.deferrable(msg);
563 return _rpc._call(msg, _rpc._call_cb);
572 return _luci2.session.access('ubus', 'uci', 'commit');
575 add: _luci2.rpc.declare({
578 params: [ 'config', 'type', 'name', 'values' ],
579 expect: { section: '' }
587 configs: _luci2.rpc.declare({
590 expect: { configs: [ ] }
593 _changes: _luci2.rpc.declare({
596 params: [ 'config' ],
597 expect: { changes: [ ] }
600 changes: function(config)
602 if (typeof(config) == 'string')
603 return this._changes(config);
606 return this.configs().then(function(configs) {
608 configlist = configs;
610 for (var i = 0; i < configs.length; i++)
611 _luci2.uci._changes(configs[i]);
613 return _luci2.rpc.flush();
614 }).then(function(changes) {
617 for (var i = 0; i < configlist.length; i++)
618 if (changes[i].length)
619 rv[configlist[i]] = changes[i];
625 commit: _luci2.rpc.declare({
631 _delete_one: _luci2.rpc.declare({
634 params: [ 'config', 'section', 'option' ]
637 _delete_multiple: _luci2.rpc.declare({
640 params: [ 'config', 'section', 'options' ]
643 'delete': function(config, section, option)
645 if ($.isArray(option))
646 return this._delete_multiple(config, section, option);
648 return this._delete_one(config, section, option);
651 delete_all: _luci2.rpc.declare({
654 params: [ 'config', 'type', 'match' ]
657 _foreach: _luci2.rpc.declare({
660 params: [ 'config', 'type' ],
661 expect: { values: { } }
664 foreach: function(config, type, cb)
666 return this._foreach(config, type).then(function(sections) {
667 for (var s in sections)
672 get: _luci2.rpc.declare({
675 params: [ 'config', 'section', 'option' ],
677 filter: function(data, params) {
678 if (typeof(params.option) == 'undefined')
679 return data.values ? data.values['.type'] : undefined;
685 get_all: _luci2.rpc.declare({
688 params: [ 'config', 'section' ],
689 expect: { values: { } },
690 filter: function(data, params) {
691 if (typeof(params.section) == 'string')
692 data['.section'] = params.section;
693 else if (typeof(params.config) == 'string')
694 data['.package'] = params.config;
699 get_first: function(config, type, option)
701 return this._foreach(config, type).then(function(sections) {
702 for (var s in sections)
704 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
706 if (typeof(val) != 'undefined')
714 section: _luci2.rpc.declare({
717 params: [ 'config', 'type', 'name', 'values' ],
718 expect: { section: '' }
721 _set: _luci2.rpc.declare({
724 params: [ 'config', 'section', 'values' ]
727 set: function(config, section, option, value)
729 if (typeof(value) == 'undefined' && typeof(option) == 'string')
730 return this.section(config, section, option); /* option -> type */
731 else if ($.isPlainObject(option))
732 return this._set(config, section, option); /* option -> values */
735 values[option] = value;
737 return this._set(config, section, values);
740 order: _luci2.rpc.declare({
743 params: [ 'config', 'sections' ]
748 listNetworkNames: function() {
749 return _luci2.rpc.list('network.interface.*').then(function(list) {
751 for (var name in list)
752 if (name != 'network.interface.loopback')
753 names.push(name.substring(18));
759 listDeviceNames: _luci2.rpc.declare({
760 object: 'network.device',
763 filter: function(data) {
765 for (var name in data)
773 getNetworkStatus: function()
778 return this.listNetworkNames().then(function(names) {
781 for (var i = 0; i < names.length; i++)
782 _luci2.network.getInterfaceStatus(names[i]);
784 return _luci2.rpc.flush();
785 }).then(function(networks) {
786 for (var i = 0; i < networks.length; i++)
788 var net = nets[i] = networks[i];
789 var dev = net.l3_device || net.l2_device;
791 net.device = devs[dev] || (devs[dev] = { });
796 for (var dev in devs)
797 _luci2.network.getDeviceStatus(dev);
799 return _luci2.rpc.flush();
800 }).then(function(devices) {
803 for (var i = 0; i < devices.length; i++)
805 var brm = devices[i]['bridge-members'];
806 delete devices[i]['bridge-members'];
808 $.extend(devs[devices[i]['device']], devices[i]);
813 devs[devices[i]['device']].subdevices = [ ];
815 for (var j = 0; j < brm.length; j++)
820 _luci2.network.getDeviceStatus(brm[j]);
823 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
827 return _luci2.rpc.flush();
828 }).then(function(subdevices) {
829 for (var i = 0; i < subdevices.length; i++)
830 $.extend(devs[subdevices[i]['device']], subdevices[i]);
834 for (var dev in devs)
835 _luci2.wireless.getDeviceStatus(dev);
837 return _luci2.rpc.flush();
838 }).then(function(wifidevices) {
839 for (var i = 0; i < wifidevices.length; i++)
841 devs[wifidevices[i]['device']].wireless = wifidevices[i];
843 nets.sort(function(a, b) {
844 if (a['interface'] < b['interface'])
846 else if (a['interface'] > b['interface'])
856 findWanInterfaces: function(cb)
858 return this.listNetworkNames().then(function(names) {
861 for (var i = 0; i < names.length; i++)
862 _luci2.network.getInterfaceStatus(names[i]);
864 return _luci2.rpc.flush();
865 }).then(function(interfaces) {
866 var rv = [ undefined, undefined ];
868 for (var i = 0; i < interfaces.length; i++)
870 if (!interfaces[i].route)
873 for (var j = 0; j < interfaces[i].route.length; j++)
875 var rt = interfaces[i].route[j];
877 if (typeof(rt.table) != 'undefined')
880 if (rt.target == '0.0.0.0' && rt.mask == 0)
881 rv[0] = interfaces[i];
882 else if (rt.target == '::' && rt.mask == 0)
883 rv[1] = interfaces[i];
891 getDHCPLeases: _luci2.rpc.declare({
892 object: 'luci2.network',
893 method: 'dhcp_leases',
894 expect: { leases: [ ] }
897 getDHCPv6Leases: _luci2.rpc.declare({
898 object: 'luci2.network',
899 method: 'dhcp6_leases',
900 expect: { leases: [ ] }
903 getRoutes: _luci2.rpc.declare({
904 object: 'luci2.network',
906 expect: { routes: [ ] }
909 getIPv6Routes: _luci2.rpc.declare({
910 object: 'luci2.network',
912 expect: { routes: [ ] }
915 getARPTable: _luci2.rpc.declare({
916 object: 'luci2.network',
918 expect: { entries: [ ] }
921 getInterfaceStatus: _luci2.rpc.declare({
922 object: 'network.interface',
924 params: [ 'interface' ],
926 filter: function(data, params) {
927 data['interface'] = params['interface'];
928 data['l2_device'] = data['device'];
929 delete data['device'];
934 getDeviceStatus: _luci2.rpc.declare({
935 object: 'network.device',
939 filter: function(data, params) {
940 data['device'] = params['name'];
945 getConntrackCount: _luci2.rpc.declare({
946 object: 'luci2.network',
947 method: 'conntrack_count',
948 expect: { '': { count: 0, limit: 0 } }
951 listSwitchNames: _luci2.rpc.declare({
952 object: 'luci2.network',
953 method: 'switch_list',
954 expect: { switches: [ ] }
957 getSwitchInfo: _luci2.rpc.declare({
958 object: 'luci2.network',
959 method: 'switch_info',
960 params: [ 'switch' ],
961 expect: { info: { } },
962 filter: function(data, params) {
963 data['attrs'] = data['switch'];
964 data['vlan_attrs'] = data['vlan'];
965 data['port_attrs'] = data['port'];
966 data['switch'] = params['switch'];
975 getSwitchStatus: _luci2.rpc.declare({
976 object: 'luci2.network',
977 method: 'switch_status',
978 params: [ 'switch' ],
979 expect: { ports: [ ] }
983 runPing: _luci2.rpc.declare({
984 object: 'luci2.network',
987 expect: { '': { code: -1 } }
990 runPing6: _luci2.rpc.declare({
991 object: 'luci2.network',
994 expect: { '': { code: -1 } }
997 runTraceroute: _luci2.rpc.declare({
998 object: 'luci2.network',
999 method: 'traceroute',
1001 expect: { '': { code: -1 } }
1004 runTraceroute6: _luci2.rpc.declare({
1005 object: 'luci2.network',
1006 method: 'traceroute6',
1008 expect: { '': { code: -1 } }
1011 runNslookup: _luci2.rpc.declare({
1012 object: 'luci2.network',
1015 expect: { '': { code: -1 } }
1019 setUp: _luci2.rpc.declare({
1020 object: 'luci2.network',
1023 expect: { '': { code: -1 } }
1026 setDown: _luci2.rpc.declare({
1027 object: 'luci2.network',
1030 expect: { '': { code: -1 } }
1035 listDeviceNames: _luci2.rpc.declare({
1038 expect: { 'devices': [ ] },
1039 filter: function(data) {
1045 getDeviceStatus: _luci2.rpc.declare({
1048 params: [ 'device' ],
1049 expect: { '': { } },
1050 filter: function(data, params) {
1051 if (!$.isEmptyObject(data))
1053 data['device'] = params['device'];
1060 getAssocList: _luci2.rpc.declare({
1062 method: 'assoclist',
1063 params: [ 'device' ],
1064 expect: { results: [ ] },
1065 filter: function(data, params) {
1066 for (var i = 0; i < data.length; i++)
1067 data[i]['device'] = params['device'];
1069 data.sort(function(a, b) {
1070 if (a.bssid < b.bssid)
1072 else if (a.bssid > b.bssid)
1082 getWirelessStatus: function() {
1083 return this.listDeviceNames().then(function(names) {
1086 for (var i = 0; i < names.length; i++)
1087 _luci2.wireless.getDeviceStatus(names[i]);
1089 return _luci2.rpc.flush();
1090 }).then(function(networks) {
1094 'country', 'channel', 'frequency', 'frequency_offset',
1095 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1099 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1100 'signal', 'noise', 'bitrate', 'encryption'
1103 for (var i = 0; i < networks.length; i++)
1105 var phy = rv[networks[i].phy] || (
1106 rv[networks[i].phy] = { networks: [ ] }
1110 device: networks[i].device
1113 for (var j = 0; j < phy_attrs.length; j++)
1114 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1116 for (var j = 0; j < net_attrs.length; j++)
1117 net[net_attrs[j]] = networks[i][net_attrs[j]];
1119 phy.networks.push(net);
1126 getAssocLists: function()
1128 return this.listDeviceNames().then(function(names) {
1131 for (var i = 0; i < names.length; i++)
1132 _luci2.wireless.getAssocList(names[i]);
1134 return _luci2.rpc.flush();
1135 }).then(function(assoclists) {
1138 for (var i = 0; i < assoclists.length; i++)
1139 for (var j = 0; j < assoclists[i].length; j++)
1140 rv.push(assoclists[i][j]);
1146 formatEncryption: function(enc)
1148 var format_list = function(l, s)
1151 for (var i = 0; i < l.length; i++)
1152 rv.push(l[i].toUpperCase());
1153 return rv.join(s ? s : ', ');
1156 if (!enc || !enc.enabled)
1157 return _luci2.tr('None');
1161 if (enc.wep.length == 2)
1162 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1163 else if (enc.wep[0] == 'shared')
1164 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1166 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1170 if (enc.wpa.length == 2)
1171 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1172 format_list(enc.authentication, '/'),
1173 format_list(enc.ciphers, ', ')
1175 else if (enc.wpa[0] == 2)
1176 return 'WPA2 %s (%s)'.format(
1177 format_list(enc.authentication, '/'),
1178 format_list(enc.ciphers, ', ')
1181 return 'WPA %s (%s)'.format(
1182 format_list(enc.authentication, '/'),
1183 format_list(enc.ciphers, ', ')
1187 return _luci2.tr('Unknown');
1192 getZoneColor: function(zone)
1194 if ($.isPlainObject(zone))
1199 else if (zone == 'wan')
1202 for (var i = 0, hash = 0;
1204 hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1206 for (var i = 0, color = '#';
1208 color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1213 findZoneByNetwork: function(network)
1216 var zone = undefined;
1218 return _luci2.uci.foreach('firewall', 'zone', function(z) {
1219 if (!z.name || !z.network)
1222 if (!$.isArray(z.network))
1223 z.network = z.network.split(/\s+/);
1225 for (var i = 0; i < z.network.length; i++)
1227 if (z.network[i] == network)
1233 }).then(function() {
1235 zone.color = self.getZoneColor(zone);
1243 getSystemInfo: _luci2.rpc.declare({
1249 getBoardInfo: _luci2.rpc.declare({
1255 getDiskInfo: _luci2.rpc.declare({
1256 object: 'luci2.system',
1261 getInfo: function(cb)
1265 this.getSystemInfo();
1266 this.getBoardInfo();
1269 return _luci2.rpc.flush().then(function(info) {
1272 $.extend(rv, info[0]);
1273 $.extend(rv, info[1]);
1274 $.extend(rv, info[2]);
1280 getProcessList: _luci2.rpc.declare({
1281 object: 'luci2.system',
1282 method: 'process_list',
1283 expect: { processes: [ ] },
1284 filter: function(data) {
1285 data.sort(function(a, b) { return a.pid - b.pid });
1290 getSystemLog: _luci2.rpc.declare({
1291 object: 'luci2.system',
1296 getKernelLog: _luci2.rpc.declare({
1297 object: 'luci2.system',
1302 getZoneInfo: function(cb)
1304 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1307 sendSignal: _luci2.rpc.declare({
1308 object: 'luci2.system',
1309 method: 'process_signal',
1310 params: [ 'pid', 'signal' ],
1311 filter: function(data) {
1316 initList: _luci2.rpc.declare({
1317 object: 'luci2.system',
1318 method: 'init_list',
1319 expect: { initscripts: [ ] },
1320 filter: function(data) {
1321 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1326 initEnabled: function(init, cb)
1328 return this.initList().then(function(list) {
1329 for (var i = 0; i < list.length; i++)
1330 if (list[i].name == init)
1331 return !!list[i].enabled;
1337 initRun: _luci2.rpc.declare({
1338 object: 'luci2.system',
1339 method: 'init_action',
1340 params: [ 'name', 'action' ],
1341 filter: function(data) {
1346 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1347 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1348 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1349 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1350 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1351 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1354 getRcLocal: _luci2.rpc.declare({
1355 object: 'luci2.system',
1356 method: 'rclocal_get',
1357 expect: { data: '' }
1360 setRcLocal: _luci2.rpc.declare({
1361 object: 'luci2.system',
1362 method: 'rclocal_set',
1367 getCrontab: _luci2.rpc.declare({
1368 object: 'luci2.system',
1369 method: 'crontab_get',
1370 expect: { data: '' }
1373 setCrontab: _luci2.rpc.declare({
1374 object: 'luci2.system',
1375 method: 'crontab_set',
1380 getSSHKeys: _luci2.rpc.declare({
1381 object: 'luci2.system',
1382 method: 'sshkeys_get',
1383 expect: { keys: [ ] }
1386 setSSHKeys: _luci2.rpc.declare({
1387 object: 'luci2.system',
1388 method: 'sshkeys_set',
1393 setPassword: _luci2.rpc.declare({
1394 object: 'luci2.system',
1395 method: 'password_set',
1396 params: [ 'user', 'password' ]
1400 listLEDs: _luci2.rpc.declare({
1401 object: 'luci2.system',
1403 expect: { leds: [ ] }
1406 listUSBDevices: _luci2.rpc.declare({
1407 object: 'luci2.system',
1409 expect: { devices: [ ] }
1413 testUpgrade: _luci2.rpc.declare({
1414 object: 'luci2.system',
1415 method: 'upgrade_test',
1419 startUpgrade: _luci2.rpc.declare({
1420 object: 'luci2.system',
1421 method: 'upgrade_start',
1425 cleanUpgrade: _luci2.rpc.declare({
1426 object: 'luci2.system',
1427 method: 'upgrade_clean'
1431 restoreBackup: _luci2.rpc.declare({
1432 object: 'luci2.system',
1433 method: 'backup_restore'
1436 cleanBackup: _luci2.rpc.declare({
1437 object: 'luci2.system',
1438 method: 'backup_clean'
1442 getBackupConfig: _luci2.rpc.declare({
1443 object: 'luci2.system',
1444 method: 'backup_config_get',
1445 expect: { config: '' }
1448 setBackupConfig: _luci2.rpc.declare({
1449 object: 'luci2.system',
1450 method: 'backup_config_set',
1455 listBackup: _luci2.rpc.declare({
1456 object: 'luci2.system',
1457 method: 'backup_list',
1458 expect: { files: [ ] }
1462 testReset: _luci2.rpc.declare({
1463 object: 'luci2.system',
1464 method: 'reset_test',
1465 expect: { supported: false }
1468 startReset: _luci2.rpc.declare({
1469 object: 'luci2.system',
1470 method: 'reset_start'
1474 performReboot: _luci2.rpc.declare({
1475 object: 'luci2.system',
1481 updateLists: _luci2.rpc.declare({
1482 object: 'luci2.opkg',
1487 _allPackages: _luci2.rpc.declare({
1488 object: 'luci2.opkg',
1490 params: [ 'offset', 'limit', 'pattern' ],
1494 _installedPackages: _luci2.rpc.declare({
1495 object: 'luci2.opkg',
1496 method: 'list_installed',
1497 params: [ 'offset', 'limit', 'pattern' ],
1501 _findPackages: _luci2.rpc.declare({
1502 object: 'luci2.opkg',
1504 params: [ 'offset', 'limit', 'pattern' ],
1508 _fetchPackages: function(action, offset, limit, pattern)
1512 return action(offset, limit, pattern).then(function(list) {
1513 if (!list.total || !list.packages)
1514 return { length: 0, total: 0 };
1516 packages.push.apply(packages, list.packages);
1517 packages.total = list.total;
1522 if (packages.length >= limit)
1527 for (var i = offset + packages.length; i < limit; i += 100)
1528 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1530 return _luci2.rpc.flush();
1531 }).then(function(lists) {
1532 for (var i = 0; i < lists.length; i++)
1534 if (!lists[i].total || !lists[i].packages)
1537 packages.push.apply(packages, lists[i].packages);
1538 packages.total = lists[i].total;
1545 listPackages: function(offset, limit, pattern)
1547 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1550 installedPackages: function(offset, limit, pattern)
1552 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1555 findPackages: function(offset, limit, pattern)
1557 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1560 installPackage: _luci2.rpc.declare({
1561 object: 'luci2.opkg',
1563 params: [ 'package' ],
1567 removePackage: _luci2.rpc.declare({
1568 object: 'luci2.opkg',
1570 params: [ 'package' ],
1574 getConfig: _luci2.rpc.declare({
1575 object: 'luci2.opkg',
1576 method: 'config_get',
1577 expect: { config: '' }
1580 setConfig: _luci2.rpc.declare({
1581 object: 'luci2.opkg',
1582 method: 'config_set',
1589 login: _luci2.rpc.declare({
1592 params: [ 'username', 'password' ],
1596 access: _luci2.rpc.declare({
1599 params: [ 'scope', 'object', 'function' ],
1600 expect: { access: false }
1605 return _luci2.session.access('ubus', 'session', 'access');
1608 startHeartbeat: function()
1610 this._hearbeatInterval = window.setInterval(function() {
1611 _luci2.session.isAlive().then(function(alive) {
1614 _luci2.session.stopHeartbeat();
1615 _luci2.ui.login(true);
1619 }, _luci2.globals.timeout * 2);
1622 stopHeartbeat: function()
1624 if (typeof(this._hearbeatInterval) != 'undefined')
1626 window.clearInterval(this._hearbeatInterval);
1627 delete this._hearbeatInterval;
1634 saveScrollTop: function()
1636 this._scroll_top = $(document).scrollTop();
1639 restoreScrollTop: function()
1641 if (typeof(this._scroll_top) == 'undefined')
1644 $(document).scrollTop(this._scroll_top);
1646 delete this._scroll_top;
1649 loading: function(enable)
1651 var win = $(window);
1652 var body = $('body');
1654 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1656 .addClass('cbi-modal-loader')
1657 .append($('<div />').text(_luci2.tr('Loading data...')))
1663 body.css('overflow', 'hidden');
1664 body.css('padding', 0);
1665 body.css('width', win.width());
1666 body.css('height', win.height());
1667 state.modal.css('width', win.width());
1668 state.modal.css('height', win.height());
1674 body.css('overflow', '');
1675 body.css('padding', '');
1676 body.css('width', '');
1677 body.css('height', '');
1681 dialog: function(title, content, options)
1683 var win = $(window);
1684 var body = $('body');
1686 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1687 dialog: $('<div />')
1688 .addClass('cbi-modal-dialog')
1689 .append($('<div />')
1690 .append($('<div />')
1691 .addClass('cbi-modal-dialog-header'))
1692 .append($('<div />')
1693 .addClass('cbi-modal-dialog-body'))
1694 .append($('<div />')
1695 .addClass('cbi-modal-dialog-footer')
1696 .append($('<button />')
1697 .addClass('cbi-button')
1698 .text(_luci2.tr('Close'))
1701 .css('overflow', '')
1706 $(this).parent().parent().parent().hide();
1711 if (typeof(options) != 'object')
1714 if (title === false)
1717 .css('overflow', '')
1722 state.dialog.hide();
1727 var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1728 var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1732 if (options.style == 'confirm')
1734 ftr.append($('<button />')
1735 .addClass('cbi-button')
1736 .text(_luci2.tr('Ok'))
1737 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1739 ftr.append($('<button />')
1740 .addClass('cbi-button')
1741 .text(_luci2.tr('Cancel'))
1742 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1744 else if (options.style == 'close')
1746 ftr.append($('<button />')
1747 .addClass('cbi-button')
1748 .text(_luci2.tr('Close'))
1749 .click(options.close || function() { _luci2.ui.dialog(false) }));
1751 else if (options.style == 'wait')
1753 ftr.append($('<button />')
1754 .addClass('cbi-button')
1755 .text(_luci2.tr('Close'))
1756 .attr('disabled', true));
1759 state.dialog.find('div.cbi-modal-dialog-header').text(title);
1760 state.dialog.show();
1763 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1767 state.dialog.children()
1768 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1770 body.css('overflow', 'hidden');
1771 body.css('padding', 0);
1772 body.css('width', win.width());
1773 body.css('height', win.height());
1774 state.dialog.css('width', win.width());
1775 state.dialog.css('height', win.height());
1778 upload: function(title, content, options)
1780 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1782 .attr('method', 'post')
1783 .attr('action', '/cgi-bin/luci-upload')
1784 .attr('enctype', 'multipart/form-data')
1785 .attr('target', 'cbi-fileupload-frame')
1787 .append($('<input />')
1788 .attr('type', 'hidden')
1789 .attr('name', 'sessionid'))
1790 .append($('<input />')
1791 .attr('type', 'hidden')
1792 .attr('name', 'filename'))
1793 .append($('<input />')
1794 .attr('type', 'file')
1795 .attr('name', 'filedata')
1796 .addClass('cbi-input-file'))
1797 .append($('<div />')
1798 .css('width', '100%')
1799 .addClass('progressbar')
1800 .addClass('intermediate')
1801 .append($('<div />')
1802 .css('width', '100%')))
1803 .append($('<iframe />')
1804 .attr('name', 'cbi-fileupload-frame')
1805 .css('width', '1px')
1806 .css('height', '1px')
1807 .css('visibility', 'hidden')),
1809 finish_cb: function(ev) {
1810 $(this).off('load');
1812 var body = (this.contentDocument || this.contentWindow.document).body;
1813 if (body.firstChild.tagName.toLowerCase() == 'pre')
1814 body = body.firstChild;
1818 json = $.parseJSON(body.innerHTML);
1821 message: _luci2.tr('Invalid server response received'),
1822 error: [ -1, _luci2.tr('Invalid data') ]
1828 L.ui.dialog(L.tr('File upload'), [
1829 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1830 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1831 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1832 ], { style: 'close' });
1834 else if (typeof(state.success_cb) == 'function')
1836 state.success_cb(json);
1840 confirm_cb: function() {
1841 var f = state.form.find('.cbi-input-file');
1842 var b = state.form.find('.progressbar');
1843 var p = state.form.find('p');
1848 state.form.find('iframe').on('load', state.finish_cb);
1849 state.form.submit();
1853 p.text(_luci2.tr('File upload in progress …'));
1855 state.form.parent().parent().find('button').prop('disabled', true);
1859 state.form.find('.progressbar').hide();
1860 state.form.find('.cbi-input-file').val('').show();
1861 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1863 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1864 state.form.find('[name=filename]').val(options.filename);
1866 state.success_cb = options.success;
1868 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1870 confirm: state.confirm_cb
1874 reconnect: function()
1876 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1877 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1878 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1880 var interval, timeout;
1883 _luci2.tr('Waiting for device'), [
1884 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1886 .css('width', '100%')
1887 .addClass('progressbar')
1888 .addClass('intermediate')
1889 .append($('<div />')
1890 .css('width', '100%'))
1891 ], { style: 'wait' }
1894 for (var i = 0; i < protocols.length; i++)
1895 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1897 //_luci2.network.getNetworkStatus(function(s) {
1898 // for (var i = 0; i < protocols.length; i++)
1900 // for (var j = 0; j < s.length; j++)
1902 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1903 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1905 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1906 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1909 //}).then(function() {
1910 images.on('load', function() {
1911 var url = this.getAttribute('url');
1912 _luci2.session.isAlive().then(function(access) {
1915 window.clearTimeout(timeout);
1916 window.clearInterval(interval);
1917 _luci2.ui.dialog(false);
1922 location.href = url;
1927 interval = window.setInterval(function() {
1928 images.each(function() {
1929 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1933 timeout = window.setTimeout(function() {
1934 window.clearInterval(interval);
1938 _luci2.tr('Device not responding'),
1939 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1946 login: function(invalid)
1948 var state = _luci2.ui._login || (_luci2.ui._login = {
1951 .attr('method', 'post')
1953 .addClass('alert-message')
1954 .text(_luci2.tr('Wrong username or password given!')))
1956 .append($('<label />')
1957 .text(_luci2.tr('Username'))
1958 .append($('<br />'))
1959 .append($('<input />')
1960 .attr('type', 'text')
1961 .attr('name', 'username')
1962 .attr('value', 'root')
1963 .addClass('cbi-input-text')
1964 .keypress(function(ev) {
1965 if (ev.which == 10 || ev.which == 13)
1969 .append($('<label />')
1970 .text(_luci2.tr('Password'))
1971 .append($('<br />'))
1972 .append($('<input />')
1973 .attr('type', 'password')
1974 .attr('name', 'password')
1975 .addClass('cbi-input-password')
1976 .keypress(function(ev) {
1977 if (ev.which == 10 || ev.which == 13)
1981 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1983 response_cb: function(response) {
1984 if (!response.ubus_rpc_session)
1986 _luci2.ui.login(true);
1990 _luci2.globals.sid = response.ubus_rpc_session;
1991 _luci2.setHash('id', _luci2.globals.sid);
1992 _luci2.session.startHeartbeat();
1993 _luci2.ui.dialog(false);
1994 state.deferred.resolve();
1998 confirm_cb: function() {
1999 var u = state.form.find('[name=username]').val();
2000 var p = state.form.find('[name=password]').val();
2006 _luci2.tr('Logging in'), [
2007 $('<p />').text(_luci2.tr('Log in in progress …')),
2009 .css('width', '100%')
2010 .addClass('progressbar')
2011 .addClass('intermediate')
2012 .append($('<div />')
2013 .css('width', '100%'))
2014 ], { style: 'wait' }
2017 _luci2.globals.sid = '00000000000000000000000000000000';
2018 _luci2.session.login(u, p).then(state.response_cb);
2022 if (!state.deferred || state.deferred.state() != 'pending')
2023 state.deferred = $.Deferred();
2025 /* try to find sid from hash */
2026 var sid = _luci2.getHash('id');
2027 if (sid && sid.match(/^[a-f0-9]{32}$/))
2029 _luci2.globals.sid = sid;
2030 _luci2.session.isAlive().then(function(access) {
2033 _luci2.session.startHeartbeat();
2034 state.deferred.resolve();
2038 _luci2.setHash('id', undefined);
2043 return state.deferred;
2047 state.form.find('.alert-message').show();
2049 state.form.find('.alert-message').hide();
2051 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2053 confirm: state.confirm_cb
2056 state.form.find('[name=password]').focus();
2058 return state.deferred;
2061 cryptPassword: _luci2.rpc.declare({
2065 expect: { crypt: '' }
2069 _acl_merge_scope: function(acl_scope, scope)
2071 if ($.isArray(scope))
2073 for (var i = 0; i < scope.length; i++)
2074 acl_scope[scope[i]] = true;
2076 else if ($.isPlainObject(scope))
2078 for (var object_name in scope)
2080 if (!$.isArray(scope[object_name]))
2083 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2085 for (var i = 0; i < scope[object_name].length; i++)
2086 acl_object[scope[object_name][i]] = true;
2091 _acl_merge_permission: function(acl_perm, perm)
2093 if ($.isPlainObject(perm))
2095 for (var scope_name in perm)
2097 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2098 this._acl_merge_scope(acl_scope, perm[scope_name]);
2103 _acl_merge_group: function(acl_group, group)
2105 if ($.isPlainObject(group))
2107 if (!acl_group.description)
2108 acl_group.description = group.description;
2112 var acl_perm = acl_group.read || (acl_group.read = { });
2113 this._acl_merge_permission(acl_perm, group.read);
2118 var acl_perm = acl_group.write || (acl_group.write = { });
2119 this._acl_merge_permission(acl_perm, group.write);
2124 _acl_merge_tree: function(acl_tree, tree)
2126 if ($.isPlainObject(tree))
2128 for (var group_name in tree)
2130 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2131 this._acl_merge_group(acl_group, tree[group_name]);
2136 listAvailableACLs: _luci2.rpc.declare({
2139 expect: { acls: [ ] },
2140 filter: function(trees) {
2142 for (var i = 0; i < trees.length; i++)
2143 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2148 renderMainMenu: _luci2.rpc.declare({
2151 expect: { menu: { } },
2152 filter: function(entries) {
2153 _luci2.globals.mainMenu = new _luci2.ui.menu();
2154 _luci2.globals.mainMenu.entries(entries);
2158 .append(_luci2.globals.mainMenu.render(0, 1));
2162 renderViewMenu: function()
2166 .append(_luci2.globals.mainMenu.render(2, 900));
2169 renderView: function()
2171 var node = arguments[0];
2172 var name = node.view.split(/\//).join('.');
2175 for (var i = 1; i < arguments.length; i++)
2176 args.push(arguments[i]);
2178 if (_luci2.globals.currentView)
2179 _luci2.globals.currentView.finish();
2181 _luci2.ui.renderViewMenu();
2184 _luci2._views = { };
2186 _luci2.setHash('view', node.view);
2188 if (_luci2._views[name] instanceof _luci2.ui.view)
2190 _luci2.globals.currentView = _luci2._views[name];
2191 return _luci2._views[name].render.apply(_luci2._views[name], args);
2194 var url = _luci2.globals.resource + '/view/' + name + '.js';
2196 return $.ajax(url, {
2200 }).then(function(data) {
2202 var viewConstructorSource = (
2203 '(function(L, $) { ' +
2205 '})(_luci2, $);\n\n' +
2207 ).format(data, url);
2209 var viewConstructor = eval(viewConstructorSource);
2211 _luci2._views[name] = new viewConstructor({
2213 acls: node.write || { }
2216 _luci2.globals.currentView = _luci2._views[name];
2217 return _luci2._views[name].render.apply(_luci2._views[name], args);
2220 alert('Unable to instantiate view "%s": %s'.format(url, e));
2223 return $.Deferred().resolve();
2227 updateHostname: function()
2229 return _luci2.system.getBoardInfo().then(function(info) {
2231 $('#hostname').text(info.hostname);
2235 updateChanges: function()
2237 return _luci2.uci.changes().then(function(changes) {
2241 for (var config in changes)
2245 for (var i = 0; i < changes[config].length; i++)
2247 var c = changes[config][i];
2256 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2258 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2263 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2265 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2269 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2273 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2277 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2282 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2284 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2289 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2290 n += changes[config].length;
2301 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2302 .click(function(ev) {
2303 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2304 ev.preventDefault();
2314 _luci2.ui.loading(true);
2317 _luci2.ui.updateHostname(),
2318 _luci2.ui.updateChanges(),
2319 _luci2.ui.renderMainMenu()
2321 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2322 _luci2.ui.loading(false);
2328 var AbstractWidget = Class.extend({
2329 i18n: function(text) {
2333 toString: function() {
2334 var x = document.createElement('div');
2335 x.appendChild(this.render());
2340 insertInto: function(id) {
2341 return $(id).empty().append(this.render());
2344 appendTo: function(id) {
2345 return $(id).append(this.render());
2349 this.ui.view = AbstractWidget.extend({
2350 _fetch_template: function()
2352 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2356 success: function(data) {
2357 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2358 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2365 return _luci2.tr(p2);
2368 return _luci2.globals[p2] || '';
2371 return '(?' + match + ')';
2375 $('#maincontent').append(data);
2382 throw "Not implemented";
2387 var container = $('#maincontent');
2392 container.append($('<h2 />').append(this.title));
2394 if (this.description)
2395 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2400 for (var i = 0; i < arguments.length; i++)
2401 args.push(arguments[i]);
2403 return this._fetch_template().then(function() {
2404 return _luci2.deferrable(self.execute.apply(self, args));
2408 repeat: function(func, interval)
2412 if (!self._timeouts)
2413 self._timeouts = [ ];
2415 var index = self._timeouts.length;
2417 if (typeof(interval) != 'number')
2420 var setTimer, runTimer;
2422 setTimer = function() {
2423 self._timeouts[index] = window.setTimeout(runTimer, interval);
2426 runTimer = function() {
2427 _luci2.deferrable(func.call(self)).then(setTimer);
2435 if ($.isArray(this._timeouts))
2437 for (var i = 0; i < this._timeouts.length; i++)
2438 window.clearTimeout(this._timeouts[i]);
2440 delete this._timeouts;
2445 this.ui.menu = AbstractWidget.extend({
2450 entries: function(entries)
2452 for (var entry in entries)
2454 var path = entry.split(/\//);
2455 var node = this._nodes;
2457 for (i = 0; i < path.length; i++)
2462 if (!node.childs[path[i]])
2463 node.childs[path[i]] = { };
2465 node = node.childs[path[i]];
2468 $.extend(node, entries[entry]);
2472 _indexcmp: function(a, b)
2474 var x = a.index || 0;
2475 var y = b.index || 0;
2479 firstChildView: function(node)
2485 for (var child in (node.childs || { }))
2486 nodes.push(node.childs[child]);
2488 nodes.sort(this._indexcmp);
2490 for (var i = 0; i < nodes.length; i++)
2492 var child = this.firstChildView(nodes[i]);
2495 for (var key in child)
2496 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2497 node[key] = child[key];
2506 _onclick: function(ev)
2508 _luci2.ui.loading(true);
2509 _luci2.ui.renderView(ev.data).then(function() {
2510 _luci2.ui.loading(false);
2513 ev.preventDefault();
2517 _render: function(childs, level, min, max)
2520 for (var node in childs)
2522 var child = this.firstChildView(childs[node]);
2524 nodes.push(childs[node]);
2527 nodes.sort(this._indexcmp);
2529 var list = $('<ul />');
2532 list.addClass('nav');
2533 else if (level == 1)
2534 list.addClass('dropdown-menu');
2536 for (var i = 0; i < nodes.length; i++)
2538 if (!_luci2.globals.defaultNode)
2540 var v = _luci2.getHash('view');
2541 if (!v || v == nodes[i].view)
2542 _luci2.globals.defaultNode = nodes[i];
2545 var item = $('<li />')
2548 .text(_luci2.tr(nodes[i].title))
2549 .click(nodes[i], this._onclick))
2552 if (nodes[i].childs && level < max)
2554 item.addClass('dropdown');
2555 item.find('a').addClass('menu');
2556 item.append(this._render(nodes[i].childs, level + 1));
2563 render: function(min, max)
2565 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2566 return this._render(top.childs, 0, min, max);
2569 getNode: function(path, max)
2571 var p = path.split(/\//);
2572 var n = this._nodes;
2574 if (typeof(max) == 'undefined')
2577 for (var i = 0; i < max; i++)
2579 if (!n.childs[p[i]])
2589 this.ui.table = AbstractWidget.extend({
2595 row: function(values)
2597 if ($.isArray(values))
2599 this._rows.push(values);
2601 else if ($.isPlainObject(values))
2604 for (var i = 0; i < this.options.columns.length; i++)
2606 var col = this.options.columns[i];
2608 if (typeof col.key == 'string')
2609 v.push(values[col.key]);
2617 rows: function(rows)
2619 for (var i = 0; i < rows.length; i++)
2623 render: function(id)
2625 var fieldset = document.createElement('fieldset');
2626 fieldset.className = 'cbi-section';
2628 if (this.options.caption)
2630 var legend = document.createElement('legend');
2631 $(legend).append(this.options.caption);
2632 fieldset.appendChild(legend);
2635 var table = document.createElement('table');
2636 table.className = 'cbi-section-table';
2638 var has_caption = false;
2639 var has_description = false;
2641 for (var i = 0; i < this.options.columns.length; i++)
2642 if (this.options.columns[i].caption)
2647 else if (this.options.columns[i].description)
2649 has_description = true;
2655 var tr = table.insertRow(-1);
2656 tr.className = 'cbi-section-table-titles';
2658 for (var i = 0; i < this.options.columns.length; i++)
2660 var col = this.options.columns[i];
2661 var th = document.createElement('th');
2662 th.className = 'cbi-section-table-cell';
2667 th.style.width = col.width;
2670 th.style.textAlign = col.align;
2673 $(th).append(col.caption);
2677 if (has_description)
2679 var tr = table.insertRow(-1);
2680 tr.className = 'cbi-section-table-descr';
2682 for (var i = 0; i < this.options.columns.length; i++)
2684 var col = this.options.columns[i];
2685 var th = document.createElement('th');
2686 th.className = 'cbi-section-table-cell';
2691 th.style.width = col.width;
2694 th.style.textAlign = col.align;
2696 if (col.description)
2697 $(th).append(col.description);
2701 if (this._rows.length == 0)
2703 if (this.options.placeholder)
2705 var tr = table.insertRow(-1);
2706 var td = tr.insertCell(-1);
2707 td.className = 'cbi-section-table-cell';
2709 td.colSpan = this.options.columns.length;
2710 $(td).append(this.options.placeholder);
2715 for (var i = 0; i < this._rows.length; i++)
2717 var tr = table.insertRow(-1);
2719 for (var j = 0; j < this.options.columns.length; j++)
2721 var col = this.options.columns[j];
2722 var td = tr.insertCell(-1);
2724 var val = this._rows[i][j];
2726 if (typeof(val) == 'undefined')
2727 val = col.placeholder;
2729 if (typeof(val) == 'undefined')
2733 td.style.width = col.width;
2736 td.style.textAlign = col.align;
2738 if (typeof col.format == 'string')
2739 $(td).append(col.format.format(val));
2740 else if (typeof col.format == 'function')
2741 $(td).append(col.format(val, i));
2749 fieldset.appendChild(table);
2755 this.ui.progress = AbstractWidget.extend({
2758 var vn = parseInt(this.options.value) || 0;
2759 var mn = parseInt(this.options.max) || 100;
2760 var pc = Math.floor((100 / mn) * vn);
2762 var bar = document.createElement('div');
2763 bar.className = 'progressbar';
2765 bar.appendChild(document.createElement('div'));
2766 bar.lastChild.appendChild(document.createElement('div'));
2767 bar.lastChild.style.width = pc + '%';
2769 if (typeof(this.options.format) == 'string')
2770 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2771 else if (typeof(this.options.format) == 'function')
2772 $(bar.lastChild.lastChild).append(this.options.format(pc));
2774 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2780 this.ui.devicebadge = AbstractWidget.extend({
2783 var l2dev = this.options.l2_device || this.options.device;
2784 var l3dev = this.options.l3_device;
2785 var dev = l3dev || l2dev || '?';
2787 var span = document.createElement('span');
2788 span.className = 'ifacebadge';
2790 if (typeof(this.options.signal) == 'number' ||
2791 typeof(this.options.noise) == 'number')
2794 if (typeof(this.options.signal) != 'undefined' &&
2795 typeof(this.options.noise) != 'undefined')
2797 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2810 span.appendChild(document.createElement('img'));
2811 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2814 span.title = _luci2.tr('No signal');
2816 span.title = '%s: %d %s / %s: %d %s'.format(
2817 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2818 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2823 var type = 'ethernet';
2824 var desc = _luci2.tr('Ethernet device');
2829 desc = _luci2.tr('Tunnel interface');
2831 else if (dev.indexOf('br-') == 0)
2834 desc = _luci2.tr('Bridge');
2836 else if (dev.indexOf('.') > 0)
2839 desc = _luci2.tr('VLAN interface');
2841 else if (dev.indexOf('wlan') == 0 ||
2842 dev.indexOf('ath') == 0 ||
2843 dev.indexOf('wl') == 0)
2846 desc = _luci2.tr('Wireless Network');
2849 span.appendChild(document.createElement('img'));
2850 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2854 $(span).append(' ');
2855 $(span).append(dev);
2861 var type = function(f, l)
2871 _luci2.cbi.validation.message = _luci2.tr(msg);
2874 compile: function(code)
2879 var types = _luci2.cbi.validation.types;
2884 for (var i = 0; i < code.length; i++)
2892 switch (code.charCodeAt(i))
2904 var label = code.substring(pos, i);
2905 label = label.replace(/\\(.)/g, '$1');
2906 label = label.replace(/^[ \t]+/g, '');
2907 label = label.replace(/[ \t]+$/g, '');
2909 if (label && !isNaN(label))
2911 stack.push(parseFloat(label));
2913 else if (label.match(/^(['"]).*\1$/))
2915 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2917 else if (typeof types[label] == 'function')
2919 stack.push(types[label]);
2924 throw "Syntax error, unhandled token '"+label+"'";
2929 depth += (code.charCodeAt(i) == 40);
2935 if (typeof stack[stack.length-2] != 'function')
2936 throw "Syntax error, argument list follows non-function";
2938 stack[stack.length-1] =
2939 arguments.callee(code.substring(pos, i));
2952 var validation = this.cbi.validation;
2954 validation.types = {
2955 'integer': function()
2957 if (this.match(/^-?[0-9]+$/) != null)
2960 validation.i18n('Must be a valid integer');
2964 'uinteger': function()
2966 if (validation.types['integer'].apply(this) && (this >= 0))
2969 validation.i18n('Must be a positive integer');
2975 if (!isNaN(parseFloat(this)))
2978 validation.i18n('Must be a valid number');
2982 'ufloat': function()
2984 if (validation.types['float'].apply(this) && (this >= 0))
2987 validation.i18n('Must be a positive number');
2991 'ipaddr': function()
2993 if (validation.types['ip4addr'].apply(this) ||
2994 validation.types['ip6addr'].apply(this))
2997 validation.i18n('Must be a valid IP address');
3001 'ip4addr': function()
3003 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
3005 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
3006 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
3007 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
3008 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
3009 ((RegExp.$6.indexOf('.') < 0)
3010 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
3011 : (validation.types['ip4addr'].apply(RegExp.$6))))
3015 validation.i18n('Must be a valid IPv4 address');
3019 'ip6addr': function()
3021 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
3023 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
3025 var addr = RegExp.$1;
3032 if (addr.indexOf('.') > 0)
3034 var off = addr.lastIndexOf(':');
3036 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
3038 validation.i18n('Must be a valid IPv6 address');
3042 addr = addr.substr(0, off) + ':0:0';
3045 if (addr.indexOf('::') >= 0)
3050 for (var i = 1; i < (addr.length-1); i++)
3051 if (addr.charAt(i) == ':')
3056 validation.i18n('Must be a valid IPv6 address');
3060 for (var i = 0; i < (7 - colons); i++)
3063 if (addr.match(/^(.*?)::(.*?)$/))
3064 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
3065 (RegExp.$2 ? ':' + RegExp.$2 : '');
3068 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3071 validation.i18n('Must be a valid IPv6 address');
3076 validation.i18n('Must be a valid IPv6 address');
3082 if (validation.types['integer'].apply(this) &&
3083 (this >= 0) && (this <= 65535))
3086 validation.i18n('Must be a valid port number');
3090 'portrange': function()
3092 if (this.match(/^(\d+)-(\d+)$/))
3097 if (validation.types['port'].apply(p1) &&
3098 validation.types['port'].apply(p2) &&
3099 (parseInt(p1) <= parseInt(p2)))
3102 else if (validation.types['port'].apply(this))
3107 validation.i18n('Must be a valid port range');
3111 'macaddr': function()
3113 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3116 validation.i18n('Must be a valid MAC address');
3122 if (validation.types['hostname'].apply(this) ||
3123 validation.types['ipaddr'].apply(this))
3126 validation.i18n('Must be a valid hostname or IP address');
3130 'hostname': function()
3132 if ((this.length <= 253) &&
3133 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3134 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3135 this.match(/[^0-9.]/)))))
3138 validation.i18n('Must be a valid host name');
3142 'network': function()
3144 if (validation.types['uciname'].apply(this) ||
3145 validation.types['host'].apply(this))
3148 validation.i18n('Must be a valid network name');
3152 'wpakey': function()
3156 if ((v.length == 64)
3157 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
3158 : ((v.length >= 8) && (v.length <= 63)))
3161 validation.i18n('Must be a valid WPA key');
3165 'wepkey': function()
3169 if (v.substr(0,2) == 's:')
3172 if (((v.length == 10) || (v.length == 26))
3173 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
3174 : ((v.length == 5) || (v.length == 13)))
3177 validation.i18n('Must be a valid WEP key');
3181 'uciname': function()
3183 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3186 validation.i18n('Must be a valid UCI identifier');
3190 'range': function(min, max)
3192 var val = parseFloat(this);
3194 if (validation.types['integer'].apply(this) &&
3195 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
3198 validation.i18n('Must be a number between %d and %d');
3202 'min': function(min)
3204 var val = parseFloat(this);
3206 if (validation.types['integer'].apply(this) &&
3207 !isNaN(min) && !isNaN(val) && (val >= min))
3210 validation.i18n('Must be a number greater or equal to %d');
3214 'max': function(max)
3216 var val = parseFloat(this);
3218 if (validation.types['integer'].apply(this) &&
3219 !isNaN(max) && !isNaN(val) && (val <= max))
3222 validation.i18n('Must be a number lower or equal to %d');
3226 'rangelength': function(min, max)
3228 var val = '' + this;
3230 if (!isNaN(min) && !isNaN(max) &&
3231 (val.length >= min) && (val.length <= max))
3234 validation.i18n('Must be between %d and %d characters');
3238 'minlength': function(min)
3240 var val = '' + this;
3242 if (!isNaN(min) && (val.length >= min))
3245 validation.i18n('Must be at least %d characters');
3249 'maxlength': function(max)
3251 var val = '' + this;
3253 if (!isNaN(max) && (val.length <= max))
3256 validation.i18n('Must be at most %d characters');
3264 for (var i = 0; i < arguments.length; i += 2)
3266 delete validation.message;
3268 if (typeof(arguments[i]) != 'function')
3270 if (arguments[i] == this)
3274 else if (arguments[i].apply(this, arguments[i+1]))
3279 if (validation.message)
3280 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3283 validation.message = msgs.join( _luci2.tr(' - or - '));
3291 for (var i = 0; i < arguments.length; i += 2)
3293 delete validation.message;
3295 if (typeof arguments[i] != 'function')
3297 if (arguments[i] != this)
3301 else if (!arguments[i].apply(this, arguments[i+1]))
3306 if (validation.message)
3307 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3310 validation.message = msgs.join(', ');
3316 return validation.types['or'].apply(
3317 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3320 'list': function(subvalidator, subargs)
3322 if (typeof subvalidator != 'function')
3325 var tokens = this.match(/[^ \t]+/g);
3326 for (var i = 0; i < tokens.length; i++)
3327 if (!subvalidator.apply(tokens[i], subargs))
3333 'phonedigit': function()
3335 if (this.match(/^[0-9\*#!\.]+$/) != null)
3338 validation.i18n('Must be a valid phone number digit');
3342 'string': function()
3349 this.cbi.AbstractValue = AbstractWidget.extend({
3350 init: function(name, options)
3353 this.instance = { };
3354 this.dependencies = [ ];
3355 this.rdependency = { };
3357 this.options = _luci2.defaults(options, {
3367 return this.section.id('field', sid || '__unknown__', this.name);
3370 render: function(sid)
3372 var i = this.instance[sid] = { };
3374 i.top = $('<div />').addClass('cbi-value');
3376 if (typeof(this.options.caption) == 'string')
3378 .addClass('cbi-value-title')
3379 .attr('for', this.id(sid))
3380 .text(this.options.caption)
3383 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
3384 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
3386 if (typeof(this.options.description) == 'string')
3388 .addClass('cbi-value-description')
3389 .text(this.options.description)
3395 ucipath: function(sid)
3398 config: (this.options.uci_package || this.map.uci_package),
3399 section: (this.options.uci_section || sid),
3400 option: (this.options.uci_option || this.name)
3404 ucivalue: function(sid)
3406 var uci = this.ucipath(sid);
3407 var val = this.map.get(uci.config, uci.section, uci.option);
3409 if (typeof(val) == 'undefined')
3410 return this.options.initial;
3415 formvalue: function(sid)
3417 var v = $('#' + this.id(sid)).val();
3418 return (v === '') ? undefined : v;
3421 textvalue: function(sid)
3423 var v = this.formvalue(sid);
3425 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3426 v = this.ucivalue(sid);
3428 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3429 v = this.options.placeholder;
3431 if (typeof(v) == 'undefined' || v === '')
3434 if (typeof(v) == 'string' && $.isArray(this.choices))
3436 for (var i = 0; i < this.choices.length; i++)
3437 if (v === this.choices[i][0])
3438 return this.choices[i][1];
3440 else if (v === true)
3441 return _luci2.tr('yes');
3442 else if (v === false)
3443 return _luci2.tr('no');
3444 else if ($.isArray(v))
3445 return v.join(', ');
3450 changed: function(sid)
3452 var a = this.ucivalue(sid);
3453 var b = this.formvalue(sid);
3455 if (typeof(a) != typeof(b))
3458 if (typeof(a) == 'object')
3460 if (a.length != b.length)
3463 for (var i = 0; i < a.length; i++)
3475 var uci = this.ucipath(sid);
3477 if (this.instance[sid].disabled)
3479 if (!this.options.keep)
3480 return this.map.set(uci.config, uci.section, uci.option, undefined);
3485 var chg = this.changed(sid);
3486 var val = this.formvalue(sid);
3489 this.map.set(uci.config, uci.section, uci.option, val);
3494 validator: function(sid, elem, multi)
3496 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3500 if (typeof(this.options.datatype) == 'string')
3503 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3506 else if (typeof(this.options.datatype) == 'function')
3508 var vfunc = this.options.datatype;
3509 vstack = [ function(elem) {
3510 var rv = vfunc(this, elem);
3512 validation.message = rv;
3513 return (rv === true);
3522 inst: this.instance[sid],
3523 opt: this.options.optional
3526 var validator = function(ev)
3530 var val = d.elem.val();
3532 if (vstack && typeof(vstack[0]) == 'function')
3534 delete validation.message;
3536 if ((val.length == 0 && !d.opt))
3538 d.elem.addClass('error');
3539 d.inst.top.addClass('error');
3540 d.inst.error.text(_luci2.tr('Field must not be empty'));
3543 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3545 d.elem.addClass('error');
3546 d.inst.top.addClass('error');
3547 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3552 d.elem.removeClass('error');
3554 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3560 d.inst.top.removeClass('error');
3561 d.inst.error.text('');
3568 for (var field in d.self.rdependency)
3569 d.self.rdependency[field].toggle(d.sid);
3575 if (elem.prop('tagName') == 'SELECT')
3577 elem.change(evdata, validator);
3579 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3581 elem.click(evdata, validator);
3582 elem.blur(evdata, validator);
3586 elem.keyup(evdata, validator);
3587 elem.blur(evdata, validator);
3590 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3595 validate: function(sid)
3597 var i = this.instance[sid];
3599 i.widget.find('[cbi-validate]').trigger('validate');
3601 return (i.disabled || i.error.text() == '');
3604 depends: function(d, v)
3611 for (var i = 0; i < d.length; i++)
3613 if (typeof(d[i]) == 'string')
3615 else if (d[i] instanceof _luci2.cbi.AbstractValue)
3616 dep[d[i].name] = true;
3619 else if (d instanceof _luci2.cbi.AbstractValue)
3622 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3624 else if (typeof(d) == 'object')
3628 else if (typeof(d) == 'string')
3631 dep[d] = (typeof(v) == 'undefined') ? true : v;
3634 if (!dep || $.isEmptyObject(dep))
3637 for (var field in dep)
3639 var f = this.section.fields[field];
3641 f.rdependency[this.name] = this;
3646 if ($.isEmptyObject(dep))
3649 this.dependencies.push(dep);
3654 toggle: function(sid)
3656 var d = this.dependencies;
3657 var i = this.instance[sid];
3662 for (var n = 0; n < d.length; n++)
3666 for (var field in d[n])
3668 var val = this.section.fields[field].formvalue(sid);
3669 var cmp = d[n][field];
3671 if (typeof(cmp) == 'boolean')
3673 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3679 else if (typeof(cmp) == 'string')
3687 else if (typeof(cmp) == 'function')
3695 else if (cmp instanceof RegExp)
3720 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3727 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
3728 widget: function(sid)
3730 var o = this.options;
3732 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3733 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3735 var i = $('<input />')
3736 .attr('id', this.id(sid))
3737 .attr('type', 'checkbox')
3738 .prop('checked', this.ucivalue(sid));
3740 return this.validator(sid, i);
3743 ucivalue: function(sid)
3745 var v = this.callSuper('ucivalue', sid);
3747 if (typeof(v) == 'boolean')
3750 return (v == this.options.enabled);
3753 formvalue: function(sid)
3755 var v = $('#' + this.id(sid)).prop('checked');
3757 if (typeof(v) == 'undefined')
3758 return !!this.options.initial;
3765 var uci = this.ucipath(sid);
3767 if (this.instance[sid].disabled)
3769 if (!this.options.keep)
3770 return this.map.set(uci.config, uci.section, uci.option, undefined);
3775 var chg = this.changed(sid);
3776 var val = this.formvalue(sid);
3780 if (this.options.optional && val == this.options.initial)
3781 this.map.set(uci.config, uci.section, uci.option, undefined);
3783 this.map.set(uci.config, uci.section, uci.option, val ? this.options.enabled : this.options.disabled);
3790 this.cbi.InputValue = this.cbi.AbstractValue.extend({
3791 widget: function(sid)
3793 var i = $('<input />')
3794 .attr('id', this.id(sid))
3795 .attr('type', 'text')
3796 .attr('placeholder', this.options.placeholder)
3797 .val(this.ucivalue(sid));
3799 return this.validator(sid, i);
3803 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
3804 widget: function(sid)
3806 var i = $('<input />')
3807 .attr('id', this.id(sid))
3808 .attr('type', 'password')
3809 .attr('placeholder', this.options.placeholder)
3810 .val(this.ucivalue(sid));
3812 var t = $('<img />')
3813 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3814 .attr('title', _luci2.tr('Reveal or hide password'))
3815 .addClass('cbi-button')
3816 .click(function(ev) {
3817 var i = $(this).prev();
3818 var t = i.attr('type');
3819 i.attr('type', (t == 'password') ? 'text' : 'password');
3823 this.validator(sid, i);
3826 .addClass('cbi-input-password')
3832 this.cbi.ListValue = this.cbi.AbstractValue.extend({
3833 widget: function(sid)
3835 var s = $('<select />');
3837 if (this.options.optional)
3840 .text(_luci2.tr('-- Please choose --'))
3844 for (var i = 0; i < this.choices.length; i++)
3846 .attr('value', this.choices[i][0])
3847 .text(this.choices[i][1])
3850 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3852 return this.validator(sid, s);
3855 value: function(k, v)
3860 this.choices.push([k, v || k]);
3865 this.cbi.MultiValue = this.cbi.ListValue.extend({
3866 widget: function(sid)
3868 var v = this.ucivalue(sid);
3869 var t = $('<div />').attr('id', this.id(sid));
3872 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3875 for (var i = 0; i < v.length; i++)
3879 for (var i = 0; i < this.choices.length; i++)
3882 .append($('<input />')
3883 .addClass('cbi-input-checkbox')
3884 .attr('type', 'checkbox')
3885 .attr('value', this.choices[i][0])
3886 .prop('checked', s[this.choices[i][0]]))
3887 .append(this.choices[i][1])
3897 formvalue: function(sid)
3900 var fields = $('#' + this.id(sid) + ' > label > input');
3902 for (var i = 0; i < fields.length; i++)
3903 if (fields[i].checked)
3904 rv.push(fields[i].getAttribute('value'));
3909 textvalue: function(sid)
3911 var v = this.formvalue(sid);
3915 for (var i = 0; i < this.choices.length; i++)
3916 c[this.choices[i][0]] = this.choices[i][1];
3920 for (var i = 0; i < v.length; i++)
3921 t.push(c[v[i]] || v[i]);
3923 return t.join(', ');
3927 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
3928 _change: function(ev)
3931 var self = ev.data.self;
3933 if (s.selectedIndex == (s.options.length - 1))
3935 ev.data.select.hide();
3936 ev.data.input.show().focus();
3938 var v = ev.data.input.val();
3939 ev.data.input.val(' ');
3940 ev.data.input.val(v);
3942 else if (self.options.optional && s.selectedIndex == 0)
3944 ev.data.input.val('');
3948 ev.data.input.val(ev.data.select.val());
3955 var val = this.value;
3956 var self = ev.data.self;
3958 ev.data.select.empty();
3960 if (self.options.optional)
3963 .text(_luci2.tr('-- please choose --'))
3964 .appendTo(ev.data.select);
3967 for (var i = 0; i < self.choices.length; i++)
3969 if (self.choices[i][0] == val)
3973 .attr('value', self.choices[i][0])
3974 .text(self.choices[i][1])
3975 .appendTo(ev.data.select);
3978 if (!seen && val != '')
3982 .appendTo(ev.data.select);
3986 .text(_luci2.tr('-- custom --'))
3987 .appendTo(ev.data.select);
3989 ev.data.input.hide();
3990 ev.data.select.val(val).show().focus();
3993 _enter: function(ev)
3998 ev.preventDefault();
3999 ev.data.self._blur(ev);
4003 widget: function(sid)
4005 var d = $('<div />')
4006 .attr('id', this.id(sid));
4008 var t = $('<input />')
4009 .attr('type', 'text')
4013 var s = $('<select />')
4018 input: this.validator(sid, t),
4019 select: this.validator(sid, s)
4022 s.change(evdata, this._change);
4023 t.blur(evdata, this._blur);
4024 t.keydown(evdata, this._enter);
4026 t.val(this.ucivalue(sid));
4032 value: function(k, v)
4037 this.choices.push([k, v || k]);
4041 formvalue: function(sid)
4043 var v = $('#' + this.id(sid)).children('input').val();
4044 return (v == '') ? undefined : v;
4048 this.cbi.DynamicList = this.cbi.ComboBox.extend({
4049 _redraw: function(focus, add, del, s)
4051 var v = s.values || [ ];
4054 $(s.parent).children('input').each(function(i) {
4056 v.push(this.value || '');
4059 $(s.parent).empty();
4064 v.splice(focus, 0, '');
4066 else if (v.length == 0)
4072 for (var i = 0; i < v.length; i++)
4083 var txt = $('<input />')
4084 .attr('type', 'text')
4086 .appendTo(s.parent);
4088 var sel = $('<select />')
4089 .appendTo(s.parent);
4091 evdata.input = this.validator(s.sid, txt, true);
4092 evdata.select = this.validator(s.sid, sel, true);
4094 sel.change(evdata, this._change);
4095 txt.blur(evdata, this._blur);
4096 txt.keydown(evdata, this._keydown);
4101 if (i == focus || -(i+1) == focus)
4108 var f = $('<input />')
4109 .attr('type', 'text')
4111 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
4112 .addClass('cbi-input-text')
4113 .keydown(evdata, this._keydown)
4114 .keypress(evdata, this._keypress)
4117 f.appendTo(s.parent);
4123 else if (-(i+1) == focus)
4127 /* force cursor to end */
4133 evdata.input = this.validator(s.sid, f, true);
4139 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
4140 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
4141 .addClass('cbi-button')
4142 .click(evdata, this._btnclick)
4143 .appendTo(s.parent);
4146 .appendTo(s.parent);
4154 _keypress: function(ev)
4158 /* backspace, delete */
4161 if (ev.data.input.val() == '')
4163 ev.preventDefault();
4169 /* enter, arrow up, arrow down */
4173 ev.preventDefault();
4180 _keydown: function(ev)
4182 var input = ev.data.input;
4186 /* backspace, delete */
4189 if (input.val().length == 0)
4191 ev.preventDefault();
4193 var index = ev.data.index;
4199 ev.data.self._redraw(focus, -1, index, ev.data);
4207 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4212 var prev = input.prevAll('input:first');
4213 if (prev.is(':visible'))
4216 prev.next('select').focus();
4221 var next = input.nextAll('input:first');
4222 if (next.is(':visible'))
4225 next.next('select').focus();
4232 _btnclick: function(ev)
4234 if (!this.getAttribute('disabled'))
4236 if (ev.target.src.indexOf('remove') > -1)
4238 var index = ev.data.index;
4239 ev.data.self._redraw(-index, -1, index, ev.data);
4243 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4250 widget: function(sid)
4252 this.options.optional = true;
4254 var v = this.ucivalue(sid);
4257 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4259 var d = $('<div />')
4260 .attr('id', this.id(sid))
4261 .addClass('cbi-input-dynlist');
4263 this._redraw(NaN, -1, -1, {
4273 ucivalue: function(sid)
4275 var v = this.callSuper('ucivalue', sid);
4278 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4283 formvalue: function(sid)
4286 var fields = $('#' + this.id(sid) + ' > input');
4288 for (var i = 0; i < fields.length; i++)
4289 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4290 rv.push(fields[i].value);
4296 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4297 widget: function(sid)
4300 .addClass('cbi-value-dummy')
4301 .attr('id', this.id(sid))
4302 .html(this.ucivalue(sid));
4305 formvalue: function(sid)
4307 return this.ucivalue(sid);
4311 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4316 if (!self.interfaces)
4318 self.interfaces = [ ];
4319 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4320 self.interfaces = ifaces;
4328 _device_icon: function(dev)
4330 var type = 'ethernet';
4331 var desc = _luci2.tr('Ethernet device');
4333 if (dev.type == 'IP tunnel')
4336 desc = _luci2.tr('Tunnel interface');
4338 else if (dev['bridge-members'])
4341 desc = _luci2.tr('Bridge');
4343 else if (dev.wireless)
4346 desc = _luci2.tr('Wireless Network');
4348 else if (dev.device.indexOf('.') > 0)
4351 desc = _luci2.tr('VLAN interface');
4355 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4356 .attr('title', '%s (%s)'.format(desc, dev.device));
4359 widget: function(sid)
4361 var id = this.id(sid);
4362 var ul = $('<ul />')
4364 .addClass('cbi-input-networks');
4366 var itype = this.options.multiple ? 'checkbox' : 'radio';
4367 var value = this.ucivalue(sid);
4370 if (!this.options.multiple)
4371 check[value] = true;
4373 for (var i = 0; i < value.length; i++)
4374 check[value[i]] = true;
4376 if (this.interfaces)
4378 for (var i = 0; i < this.interfaces.length; i++)
4380 var iface = this.interfaces[i];
4381 var badge = $('<span />')
4382 .addClass('ifacebadge')
4383 .text('%s: '.format(iface['interface']));
4385 if (iface.device && iface.device.subdevices)
4386 for (var j = 0; j < iface.device.subdevices.length; j++)
4387 badge.append(this._device_icon(iface.device.subdevices[j]));
4388 else if (iface.device)
4389 badge.append(this._device_icon(iface.device));
4391 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4394 .append($('<label />')
4395 .append($('<input />')
4396 .attr('name', itype + id)
4397 .attr('type', itype)
4398 .attr('value', iface['interface'])
4399 .prop('checked', !!check[iface['interface']])
4400 .addClass('cbi-input-' + itype))
4406 if (!this.options.multiple)
4409 .append($('<label />')
4410 .append($('<input />')
4411 .attr('name', itype + id)
4412 .attr('type', itype)
4414 .prop('checked', !value)
4415 .addClass('cbi-input-' + itype))
4416 .append(_luci2.tr('unspecified')))
4423 ucivalue: function(sid)
4425 var v = this.callSuper('ucivalue', sid);
4427 if (!this.options.multiple)
4433 else if (typeof(v) == 'string')
4436 return v ? v[0] : undefined;
4443 if (typeof(v) == 'string')
4444 v = v.match(/\S+/g);
4450 formvalue: function(sid)
4452 var inputs = $('#' + this.id(sid) + ' input');
4454 if (!this.options.multiple)
4456 for (var i = 0; i < inputs.length; i++)
4457 if (inputs[i].checked && inputs[i].value !== '')
4458 return inputs[i].value;
4465 for (var i = 0; i < inputs.length; i++)
4466 if (inputs[i].checked)
4467 rv.push(inputs[i].value);
4469 return rv.length ? rv : undefined;
4474 this.cbi.AbstractSection = AbstractWidget.extend({
4477 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4479 for (var i = 1; i < arguments.length; i++)
4480 s.push(arguments[i].replace(/\./g, '_'));
4485 option: function(widget, name, options)
4487 if (this.tabs.length == 0)
4488 this.tab({ id: '__default__', selected: true });
4490 return this.taboption('__default__', widget, name, options);
4493 tab: function(options)
4495 if (options.selected)
4496 this.tabs.selected = this.tabs.length;
4500 caption: options.caption,
4501 description: options.description,
4507 taboption: function(tabid, widget, name, options)
4510 for (var i = 0; i < this.tabs.length; i++)
4512 if (this.tabs[i].id == tabid)
4520 throw 'Cannot append to unknown tab ' + tabid;
4522 var w = widget ? new widget(name, options) : null;
4524 if (!(w instanceof _luci2.cbi.AbstractValue))
4525 throw 'Widget must be an instance of AbstractValue';
4530 this.fields[name] = w;
4536 ucipackages: function(pkg)
4538 for (var i = 0; i < this.tabs.length; i++)
4539 for (var j = 0; j < this.tabs[i].fields.length; j++)
4540 if (this.tabs[i].fields[j].options.uci_package)
4541 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4544 formvalue: function()
4548 this.sections(function(s) {
4549 var sid = s['.name'];
4550 var sv = rv[sid] || (rv[sid] = { });
4552 for (var i = 0; i < this.tabs.length; i++)
4553 for (var j = 0; j < this.tabs[i].fields.length; j++)
4555 var val = this.tabs[i].fields[j].formvalue(sid);
4556 sv[this.tabs[i].fields[j].name] = val;
4563 validate: function(sid)
4569 var as = this.sections();
4570 for (var i = 0; i < as.length; i++)
4571 if (!this.validate(as[i]['.name']))
4576 var inst = this.instance[sid];
4577 var sv = rv[sid] || (rv[sid] = { });
4580 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4582 legend.children('span').detach();
4584 for (var i = 0; i < this.tabs.length; i++)
4587 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4589 tab.children('span').detach();
4591 for (var j = 0; j < this.tabs[i].fields.length; j++)
4592 if (!this.tabs[i].fields[j].validate(sid))
4599 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4612 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4620 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
4621 init: function(uci_type, options)
4623 this.uci_type = uci_type;
4624 this.options = options;
4627 this.active_panel = 0;
4628 this.active_tab = { };
4631 filter: function(section)
4636 sections: function(cb)
4638 var s1 = this.map.ucisections(this.map.uci_package);
4641 for (var i = 0; i < s1.length; i++)
4642 if (s1[i]['.type'] == this.uci_type)
4643 if (this.filter(s1[i]))
4646 if (typeof(cb) == 'function')
4647 for (var i = 0; i < s2.length; i++)
4648 cb.apply(this, [ s2[i] ]);
4655 this.map.add(this.map.uci_package, this.uci_type, name);
4658 remove: function(sid)
4660 this.map.remove(this.map.uci_package, sid);
4666 var name = undefined;
4667 var self = ev.data.self;
4669 if (addb.prev().prop('nodeName') == 'INPUT')
4670 name = addb.prev().val();
4672 if (addb.prop('disabled') || name === '')
4675 _luci2.ui.saveScrollTop();
4677 self.active_panel = -1;
4682 _luci2.ui.restoreScrollTop();
4685 _remove: function(ev)
4687 var self = ev.data.self;
4688 var sid = ev.data.sid;
4690 if (ev.data.index == (self.sections().length - 1))
4691 self.active_panel = -1;
4693 _luci2.ui.saveScrollTop();
4699 _luci2.ui.restoreScrollTop();
4701 ev.stopPropagation();
4706 var self = ev.data.self;
4708 var addb = text.next();
4709 var errt = addb.next();
4710 var name = text.val();
4713 if (!/^[a-zA-Z0-9_]*$/.test(name))
4715 errt.text(_luci2.tr('Invalid section name')).show();
4716 text.addClass('error');
4717 addb.prop('disabled', true);
4721 for (var sid in self.map.uci.values[self.map.uci_package])
4728 for (var sid in self.map.uci.creates[self.map.uci_package])
4737 errt.text(_luci2.tr('Name already used')).show();
4738 text.addClass('error');
4739 addb.prop('disabled', true);
4743 errt.text('').hide();
4744 text.removeClass('error');
4745 addb.prop('disabled', false);
4749 teaser: function(sid)
4751 var tf = this.teaser_fields;
4755 tf = this.teaser_fields = [ ];
4757 if ($.isArray(this.options.teasers))
4759 for (var i = 0; i < this.options.teasers.length; i++)
4761 var f = this.options.teasers[i];
4762 if (f instanceof _luci2.cbi.AbstractValue)
4764 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
4765 tf.push(this.fields[f]);
4770 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4771 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4772 tf.push(this.tabs[i].fields[j]);
4778 for (var i = 0; i < tf.length; i++)
4780 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4783 var n = tf[i].options.caption || tf[i].name;
4784 var v = tf[i].textvalue(sid);
4786 if (typeof(v) == 'undefined')
4789 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4795 _render_add: function()
4797 var text = _luci2.tr('Add section');
4798 var ttip = _luci2.tr('Create new section...');
4800 if ($.isArray(this.options.add_caption))
4801 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4802 else if (typeof(this.options.add_caption) == 'string')
4803 text = this.options.add_caption, ttip = '';
4805 var add = $('<div />').addClass('cbi-section-add');
4807 if (this.options.anonymous === false)
4810 .addClass('cbi-input-text')
4811 .attr('type', 'text')
4812 .attr('placeholder', ttip)
4813 .blur({ self: this }, this._sid)
4814 .keyup({ self: this }, this._sid)
4818 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4819 .attr('title', text)
4820 .addClass('cbi-button')
4821 .click({ self: this }, this._add)
4825 .addClass('cbi-value-error')
4832 .attr('type', 'button')
4833 .addClass('cbi-button')
4834 .addClass('cbi-button-add')
4835 .val(text).attr('title', ttip)
4836 .click({ self: this }, this._add)
4843 _render_remove: function(sid, index)
4845 var text = _luci2.tr('Remove');
4846 var ttip = _luci2.tr('Remove this section');
4848 if ($.isArray(this.options.remove_caption))
4849 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4850 else if (typeof(this.options.remove_caption) == 'string')
4851 text = this.options.remove_caption, ttip = '';
4853 return $('<input />')
4854 .attr('type', 'button')
4855 .addClass('cbi-button')
4856 .addClass('cbi-button-remove')
4857 .val(text).attr('title', ttip)
4858 .click({ self: this, sid: sid, index: index }, this._remove);
4861 _render_caption: function(sid)
4863 if (typeof(this.options.caption) == 'string')
4865 return $('<legend />')
4866 .text(this.options.caption.format(sid));
4868 else if (typeof(this.options.caption) == 'function')
4870 return $('<legend />')
4871 .text(this.options.caption.call(this, sid));
4879 var allsections = $();
4880 var panel_index = 0;
4882 this.instance = { };
4884 var s = this.sections();
4888 var fieldset = $('<fieldset />')
4889 .addClass('cbi-section');
4891 var head = $('<div />')
4892 .addClass('cbi-section-head')
4893 .appendTo(fieldset);
4895 head.append(this._render_caption(undefined));
4897 if (typeof(this.options.description) == 'string')
4900 .addClass('cbi-section-descr')
4901 .text(this.options.description)
4905 allsections = allsections.add(fieldset);
4908 for (var i = 0; i < s.length; i++)
4910 var sid = s[i]['.name'];
4911 var inst = this.instance[sid] = { tabs: [ ] };
4913 var fieldset = $('<fieldset />')
4914 .attr('id', this.id('sort', sid))
4915 .addClass('cbi-section');
4917 var head = $('<div />')
4918 .addClass('cbi-section-head')
4919 .attr('cbi-section-num', this.index)
4920 .attr('cbi-section-id', sid);
4922 head.append(this._render_caption(sid));
4924 if (typeof(this.options.description) == 'string')
4927 .addClass('cbi-section-descr')
4928 .text(this.options.description)
4933 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4934 teaser = $('<div />')
4935 .addClass('cbi-section-teaser')
4938 if (this.options.addremove)
4940 .addClass('cbi-section-remove')
4942 .append(this._render_remove(sid, panel_index))
4945 var body = $('<div />')
4946 .attr('index', panel_index++);
4948 var fields = $('<fieldset />')
4949 .addClass('cbi-section-node');
4951 if (this.tabs.length > 1)
4953 var menu = $('<ul />')
4954 .addClass('cbi-tabmenu');
4956 for (var j = 0; j < this.tabs.length; j++)
4958 var tabid = this.id('tab', sid, this.tabs[j].id);
4959 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4961 var tabc = $('<div />')
4962 .addClass('cbi-tabcontainer')
4966 if (typeof(this.tabs[j].description) == 'string')
4969 .addClass('cbi-tab-descr')
4970 .text(this.tabs[j].description)
4974 for (var k = 0; k < this.tabs[j].fields.length; k++)
4975 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4977 tabc.appendTo(fields);
4980 $('<li />').attr('id', theadid).append(
4982 .text(this.tabs[j].caption.format(this.tabs[j].id))
4983 .attr('href', '#' + tabid)
4987 menu.appendTo(body);
4990 fields.appendTo(body);
4993 var t = body.tabs({ active: this.active_tab[sid] });
4995 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4998 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
5003 for (var j = 0; j < this.tabs[0].fields.length; j++)
5004 this.tabs[0].fields[j].render(sid).appendTo(fields);
5006 fields.appendTo(body);
5010 head.appendTo(fieldset);
5013 body.appendTo(fieldset);
5016 allsections = allsections.add(fieldset);
5019 //this.validate(sid);
5022 // teaser.append(this.teaser(sid));
5025 if (this.options.collabsible && s.length > 1)
5027 var a = $('<div />').append(allsections).accordion({
5028 header: '> fieldset > div.cbi-section-head',
5029 heightStyle: 'content',
5030 active: this.active_panel
5033 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
5034 var h = ui.oldHeader;
5035 var s = ev.data.self;
5036 var i = h.attr('cbi-section-id');
5038 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
5042 a.on('accordionactivate', { self: this }, function(ev, ui) {
5043 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
5046 if (this.options.sortable)
5048 var s = a.sortable({
5050 handle: 'div.cbi-section-head'
5053 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
5055 for (var i = 0; i < ev.data.ids.length; i++)
5056 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
5057 _luci2.uci.order(ev.data.self.map.uci_package, sections);
5060 s.on('sortstop', function(ev, ui) {
5061 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
5065 if (this.options.addremove)
5066 this._render_add().appendTo(a);
5071 if (this.options.addremove)
5072 allsections = allsections.add(this._render_add());
5079 var s = this.sections();
5081 for (var i = 0; i < s.length; i++)
5083 var sid = s[i]['.name'];
5087 $('#' + this.id('sort', sid))
5088 .children('.cbi-section-head')
5089 .children('.cbi-section-teaser')
5090 .append(this.teaser(sid));
5095 this.cbi.TableSection = this.cbi.TypedSection.extend({
5098 var allsections = $();
5099 var panel_index = 0;
5101 this.instance = { };
5103 var s = this.sections();
5105 var fieldset = $('<fieldset />')
5106 .addClass('cbi-section');
5108 fieldset.append(this._render_caption(sid));
5110 if (typeof(this.options.description) == 'string')
5113 .addClass('cbi-section-descr')
5114 .text(this.options.description)
5115 .appendTo(fieldset);
5118 var fields = $('<div />')
5119 .addClass('cbi-section-node')
5120 .appendTo(fieldset);
5122 var table = $('<table />')
5123 .addClass('cbi-section-table')
5126 var thead = $('<thead />')
5127 .append($('<tr />').addClass('cbi-section-table-titles'))
5130 for (var j = 0; j < this.tabs[0].fields.length; j++)
5132 .addClass('cbi-section-table-cell')
5133 .css('width', this.tabs[0].fields[j].options.width || '')
5134 .append(this.tabs[0].fields[j].options.caption)
5135 .appendTo(thead.children());
5137 if (this.options.sortable)
5138 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
5140 if (this.options.addremove !== false)
5141 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
5143 var tbody = $('<tbody />')
5149 .addClass('cbi-section-table-row')
5152 .addClass('cbi-section-table-cell')
5153 .addClass('cbi-section-table-placeholder')
5154 .attr('colspan', thead.children().children().length)
5155 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
5159 for (var i = 0; i < s.length; i++)
5161 var sid = s[i]['.name'];
5162 var inst = this.instance[sid] = { tabs: [ ] };
5164 var row = $('<tr />')
5165 .addClass('cbi-section-table-row')
5168 for (var j = 0; j < this.tabs[0].fields.length; j++)
5171 .addClass('cbi-section-table-cell')
5172 .css('width', this.tabs[0].fields[j].options.width || '')
5173 .append(this.tabs[0].fields[j].render(sid, true))
5177 if (this.options.sortable)
5180 .addClass('cbi-section-table-cell')
5181 .addClass('cbi-section-table-sort')
5182 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
5183 .append($('<br />'))
5184 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
5188 if (this.options.addremove !== false)
5191 .addClass('cbi-section-table-cell')
5192 .append(this._render_remove(sid))
5201 if (this.options.sortable)
5203 var s = tbody.sortable({
5204 handle: 'td.cbi-section-table-sort'
5207 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
5209 for (var i = 0; i < ev.data.ids.length; i++)
5210 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
5211 _luci2.uci.order(ev.data.self.map.uci_package, sections);
5214 s.on('sortstop', function(ev, ui) {
5215 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
5219 if (this.options.addremove)
5220 this._render_add().appendTo(fieldset);
5222 fields = table = thead = tbody = null;
5228 this.cbi.NamedSection = this.cbi.TypedSection.extend({
5229 sections: function(cb)
5232 var pkg = this.map.uci.values[this.map.uci_package];
5235 if (pkg[s]['.name'] == this.uci_type)
5241 if (typeof(cb) == 'function' && sa.length > 0)
5242 cb.apply(this, [ sa[0] ]);
5248 this.cbi.DummySection = this.cbi.TypedSection.extend({
5249 sections: function(cb)
5251 if (typeof(cb) == 'function')
5252 cb.apply(this, [ { '.name': this.uci_type } ]);
5254 return [ { '.name': this.uci_type } ];
5258 this.cbi.Map = AbstractWidget.extend({
5259 init: function(uci_package, options)
5263 this.uci_package = uci_package;
5264 this.sections = [ ];
5265 this.options = _luci2.defaults(options, {
5266 save: function() { },
5267 prepare: function() {
5268 return _luci2.uci.writable(function(writable) {
5269 self.options.readonly = !writable;
5285 if (typeof(this.active_panel) == 'undefined')
5286 this.active_panel = 0;
5290 for (var i = 0; i < this.sections.length; i++)
5291 this.sections[i].ucipackages(packages);
5293 packages[this.uci_package] = true;
5295 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
5296 for (var i = 0; i < packages.length; i++)
5298 this.uci.values[packages[i]['.package']] = packages[i];
5299 delete packages[i]['.package'];
5302 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5304 for (var i = 0; i < this.sections.length; i++)
5306 for (var f in this.sections[i].fields)
5308 if (typeof(this.sections[i].fields[f].load) != 'function')
5311 var s = this.sections[i].sections();
5312 for (var j = 0; j < s.length; j++)
5314 var rv = this.sections[i].fields[f].load(s[j]['.name']);
5315 if (_luci2.isDeferred(rv))
5321 return $.when.apply($, deferreds);
5326 for (var pkg in packages)
5327 _luci2.uci.get_all(pkg);
5329 return _luci2.rpc.flush().then(load_cb);
5334 var map = $('<div />').addClass('cbi-map');
5336 if (typeof(this.options.caption) == 'string')
5337 $('<h2 />').text(this.options.caption).appendTo(map);
5339 if (typeof(this.options.description) == 'string')
5340 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
5342 var sections = $('<div />').appendTo(map);
5344 for (var i = 0; i < this.sections.length; i++)
5346 var s = this.sections[i].render();
5348 if (this.options.readonly || this.sections[i].options.readonly)
5349 s.find('input, select, button, img.cbi-button').attr('disabled', true);
5351 s.appendTo(sections);
5353 if (this.sections[i].options.active)
5354 this.active_panel = i;
5357 if (this.options.collabsible)
5359 var a = sections.accordion({
5360 header: '> fieldset > div.cbi-section-head',
5361 heightStyle: 'content',
5362 active: this.active_panel
5365 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
5366 var h = ui.oldHeader;
5367 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
5368 var i = h.attr('cbi-section-id');
5370 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
5372 for (var i = 0; i < ev.data.self.sections.length; i++)
5373 ev.data.self.sections[i].validate();
5376 a.on('accordionactivate', { self: this }, function(ev, ui) {
5377 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
5381 if (this.options.pageaction !== false)
5383 var a = $('<div />')
5384 .addClass('cbi-page-actions')
5388 .addClass('cbi-button').addClass('cbi-button-apply')
5389 .attr('type', 'button')
5390 .val(_luci2.tr('Save & Apply'))
5394 .addClass('cbi-button').addClass('cbi-button-save')
5395 .attr('type', 'button')
5396 .val(_luci2.tr('Save'))
5397 .click({ self: this }, function(ev) { ev.data.self.send(); })
5401 .addClass('cbi-button').addClass('cbi-button-reset')
5402 .attr('type', 'button')
5403 .val(_luci2.tr('Reset'))
5404 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
5410 var top = $('<form />').append(map);
5419 for (var i = 0; i < this.sections.length; i++)
5420 this.sections[i].finish();
5427 this.target.hide().empty().append(this.render());
5432 section: function(widget, uci_type, options)
5434 var w = widget ? new widget(uci_type, options) : null;
5436 if (!(w instanceof _luci2.cbi.AbstractSection))
5437 throw 'Widget must be an instance of AbstractSection';
5440 w.index = this.sections.length;
5442 this.sections.push(w);
5446 formvalue: function()
5450 for (var i = 0; i < this.sections.length; i++)
5452 var sids = this.sections[i].formvalue();
5453 for (var sid in sids)
5455 var s = rv[sid] || (rv[sid] = { });
5456 $.extend(s, sids[sid]);
5463 add: function(conf, type, name)
5465 var c = this.uci.creates;
5466 var s = '.new.%d'.format(this.uci.newid++);
5481 remove: function(conf, sid)
5483 var n = this.uci.creates;
5484 var c = this.uci.changes;
5485 var d = this.uci.deletes;
5487 /* requested deletion of a just created section */
5488 if (sid.indexOf('.new.') == 0)
5491 delete n[conf][sid];
5496 delete c[conf][sid];
5501 d[conf][sid] = true;
5505 ucisections: function(conf, cb)
5508 var pkg = this.uci.values[conf];
5509 var crt = this.uci.creates[conf];
5510 var del = this.uci.deletes[conf];
5516 if (!del || del[s] !== true)
5519 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5525 if (typeof(cb) == 'function')
5526 for (var i = 0; i < sa.length; i++)
5527 cb.apply(this, [ sa[i] ]);
5532 get: function(conf, sid, opt)
5534 var v = this.uci.values;
5535 var n = this.uci.creates;
5536 var c = this.uci.changes;
5537 var d = this.uci.deletes;
5539 /* requested option in a just created section */
5540 if (sid.indexOf('.new.') == 0)
5545 if (typeof(opt) == 'undefined')
5546 return (n[conf][sid] || { });
5548 return n[conf][sid][opt];
5551 /* requested an option value */
5552 if (typeof(opt) != 'undefined')
5554 /* check whether option was deleted */
5555 if (d[conf] && d[conf][sid])
5557 if (d[conf][sid] === true)
5560 for (var i = 0; i < d[conf][sid].length; i++)
5561 if (d[conf][sid][i] == opt)
5565 /* check whether option was changed */
5566 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5567 return c[conf][sid][opt];
5569 /* return base value */
5570 if (v[conf] && v[conf][sid])
5571 return v[conf][sid][opt];
5576 /* requested an entire section */
5578 return (v[conf][sid] || { });
5583 set: function(conf, sid, opt, val)
5585 var n = this.uci.creates;
5586 var c = this.uci.changes;
5587 var d = this.uci.deletes;
5589 if (sid.indexOf('.new.') == 0)
5591 if (n[conf] && n[conf][sid])
5593 if (typeof(val) != 'undefined')
5594 n[conf][sid][opt] = val;
5596 delete n[conf][sid][opt];
5599 else if (typeof(val) != 'undefined')
5607 c[conf][sid][opt] = val;
5617 d[conf][sid].push(opt);
5621 validate: function()
5625 for (var i = 0; i < this.sections.length; i++)
5626 if (!this.sections[i].validate())
5634 if (this.options.readonly)
5635 return _luci2.deferrable();
5637 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5639 for (var i = 0; i < this.sections.length; i++)
5641 if (this.sections[i].options.readonly)
5644 for (var f in this.sections[i].fields)
5646 if (typeof(this.sections[i].fields[f].save) != 'function')
5649 var s = this.sections[i].sections();
5650 for (var j = 0; j < s.length; j++)
5652 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5653 if (_luci2.isDeferred(rv))
5659 return $.when.apply($, deferreds);
5664 if (!this.validate())
5665 return _luci2.deferrable();
5667 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5670 if (this.uci.creates)
5671 for (var c in this.uci.creates)
5672 for (var s in this.uci.creates[c])
5679 for (var k in this.uci.creates[c][s])
5682 r.type = this.uci.creates[c][s][k];
5683 else if (k == '.create')
5684 r.name = this.uci.creates[c][s][k];
5685 else if (k.charAt(0) != '.')
5686 r.values[k] = this.uci.creates[c][s][k];
5689 _luci2.uci.add(r.config, r.type, r.name, r.values);
5692 if (this.uci.changes)
5693 for (var c in this.uci.changes)
5694 for (var s in this.uci.changes[c])
5695 _luci2.uci.set(c, s, this.uci.changes[c][s]);
5697 if (this.uci.deletes)
5698 for (var c in this.uci.deletes)
5699 for (var s in this.uci.deletes[c])
5701 var o = this.uci.deletes[c][s];
5702 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
5705 return _luci2.rpc.flush().then(function() {
5706 return _luci2.ui.updateChanges();
5712 _luci2.ui.saveScrollTop();
5713 _luci2.ui.loading(true);
5715 return this.save().then(send_cb).then(function() {
5717 }).then(function() {
5721 _luci2.ui.loading(false);
5722 _luci2.ui.restoreScrollTop();
5726 insertInto: function(id)
5729 self.target = $(id);
5731 _luci2.ui.loading(true);
5734 return self.load().then(function() {
5735 self.target.empty().append(self.render());
5739 _luci2.ui.loading(false);