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 } }
1020 listDeviceNames: _luci2.rpc.declare({
1023 expect: { 'devices': [ ] },
1024 filter: function(data) {
1030 getDeviceStatus: _luci2.rpc.declare({
1033 params: [ 'device' ],
1034 expect: { '': { } },
1035 filter: function(data, params) {
1036 if (!$.isEmptyObject(data))
1038 data['device'] = params['device'];
1045 getAssocList: _luci2.rpc.declare({
1047 method: 'assoclist',
1048 params: [ 'device' ],
1049 expect: { results: [ ] },
1050 filter: function(data, params) {
1051 for (var i = 0; i < data.length; i++)
1052 data[i]['device'] = params['device'];
1054 data.sort(function(a, b) {
1055 if (a.bssid < b.bssid)
1057 else if (a.bssid > b.bssid)
1067 getWirelessStatus: function() {
1068 return this.listDeviceNames().then(function(names) {
1071 for (var i = 0; i < names.length; i++)
1072 _luci2.wireless.getDeviceStatus(names[i]);
1074 return _luci2.rpc.flush();
1075 }).then(function(networks) {
1079 'country', 'channel', 'frequency', 'frequency_offset',
1080 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1084 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1085 'signal', 'noise', 'bitrate', 'encryption'
1088 for (var i = 0; i < networks.length; i++)
1090 var phy = rv[networks[i].phy] || (
1091 rv[networks[i].phy] = { networks: [ ] }
1095 device: networks[i].device
1098 for (var j = 0; j < phy_attrs.length; j++)
1099 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1101 for (var j = 0; j < net_attrs.length; j++)
1102 net[net_attrs[j]] = networks[i][net_attrs[j]];
1104 phy.networks.push(net);
1111 getAssocLists: function()
1113 return this.listDeviceNames().then(function(names) {
1116 for (var i = 0; i < names.length; i++)
1117 _luci2.wireless.getAssocList(names[i]);
1119 return _luci2.rpc.flush();
1120 }).then(function(assoclists) {
1123 for (var i = 0; i < assoclists.length; i++)
1124 for (var j = 0; j < assoclists[i].length; j++)
1125 rv.push(assoclists[i][j]);
1131 formatEncryption: function(enc)
1133 var format_list = function(l, s)
1136 for (var i = 0; i < l.length; i++)
1137 rv.push(l[i].toUpperCase());
1138 return rv.join(s ? s : ', ');
1141 if (!enc || !enc.enabled)
1142 return _luci2.tr('None');
1146 if (enc.wep.length == 2)
1147 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1148 else if (enc.wep[0] == 'shared')
1149 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1151 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1155 if (enc.wpa.length == 2)
1156 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1157 format_list(enc.authentication, '/'),
1158 format_list(enc.ciphers, ', ')
1160 else if (enc.wpa[0] == 2)
1161 return 'WPA2 %s (%s)'.format(
1162 format_list(enc.authentication, '/'),
1163 format_list(enc.ciphers, ', ')
1166 return 'WPA %s (%s)'.format(
1167 format_list(enc.authentication, '/'),
1168 format_list(enc.ciphers, ', ')
1172 return _luci2.tr('Unknown');
1177 getSystemInfo: _luci2.rpc.declare({
1183 getBoardInfo: _luci2.rpc.declare({
1189 getDiskInfo: _luci2.rpc.declare({
1190 object: 'luci2.system',
1195 getInfo: function(cb)
1199 this.getSystemInfo();
1200 this.getBoardInfo();
1203 return _luci2.rpc.flush().then(function(info) {
1206 $.extend(rv, info[0]);
1207 $.extend(rv, info[1]);
1208 $.extend(rv, info[2]);
1214 getProcessList: _luci2.rpc.declare({
1215 object: 'luci2.system',
1216 method: 'process_list',
1217 expect: { processes: [ ] },
1218 filter: function(data) {
1219 data.sort(function(a, b) { return a.pid - b.pid });
1224 getSystemLog: _luci2.rpc.declare({
1225 object: 'luci2.system',
1230 getKernelLog: _luci2.rpc.declare({
1231 object: 'luci2.system',
1236 getZoneInfo: function(cb)
1238 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1241 sendSignal: _luci2.rpc.declare({
1242 object: 'luci2.system',
1243 method: 'process_signal',
1244 params: [ 'pid', 'signal' ],
1245 filter: function(data) {
1250 initList: _luci2.rpc.declare({
1251 object: 'luci2.system',
1252 method: 'init_list',
1253 expect: { initscripts: [ ] },
1254 filter: function(data) {
1255 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1260 initEnabled: function(init, cb)
1262 return this.initList().then(function(list) {
1263 for (var i = 0; i < list.length; i++)
1264 if (list[i].name == init)
1265 return !!list[i].enabled;
1271 initRun: _luci2.rpc.declare({
1272 object: 'luci2.system',
1273 method: 'init_action',
1274 params: [ 'name', 'action' ],
1275 filter: function(data) {
1280 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1281 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1282 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1283 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1284 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1285 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1288 getRcLocal: _luci2.rpc.declare({
1289 object: 'luci2.system',
1290 method: 'rclocal_get',
1291 expect: { data: '' }
1294 setRcLocal: _luci2.rpc.declare({
1295 object: 'luci2.system',
1296 method: 'rclocal_set',
1301 getCrontab: _luci2.rpc.declare({
1302 object: 'luci2.system',
1303 method: 'crontab_get',
1304 expect: { data: '' }
1307 setCrontab: _luci2.rpc.declare({
1308 object: 'luci2.system',
1309 method: 'crontab_set',
1314 getSSHKeys: _luci2.rpc.declare({
1315 object: 'luci2.system',
1316 method: 'sshkeys_get',
1317 expect: { keys: [ ] }
1320 setSSHKeys: _luci2.rpc.declare({
1321 object: 'luci2.system',
1322 method: 'sshkeys_set',
1327 setPassword: _luci2.rpc.declare({
1328 object: 'luci2.system',
1329 method: 'password_set',
1330 params: [ 'user', 'password' ]
1334 listLEDs: _luci2.rpc.declare({
1335 object: 'luci2.system',
1337 expect: { leds: [ ] }
1340 listUSBDevices: _luci2.rpc.declare({
1341 object: 'luci2.system',
1343 expect: { devices: [ ] }
1347 testUpgrade: _luci2.rpc.declare({
1348 object: 'luci2.system',
1349 method: 'upgrade_test',
1353 startUpgrade: _luci2.rpc.declare({
1354 object: 'luci2.system',
1355 method: 'upgrade_start',
1359 cleanUpgrade: _luci2.rpc.declare({
1360 object: 'luci2.system',
1361 method: 'upgrade_clean'
1365 restoreBackup: _luci2.rpc.declare({
1366 object: 'luci2.system',
1367 method: 'backup_restore'
1370 cleanBackup: _luci2.rpc.declare({
1371 object: 'luci2.system',
1372 method: 'backup_clean'
1376 getBackupConfig: _luci2.rpc.declare({
1377 object: 'luci2.system',
1378 method: 'backup_config_get',
1379 expect: { config: '' }
1382 setBackupConfig: _luci2.rpc.declare({
1383 object: 'luci2.system',
1384 method: 'backup_config_set',
1389 listBackup: _luci2.rpc.declare({
1390 object: 'luci2.system',
1391 method: 'backup_list',
1392 expect: { files: [ ] }
1396 testReset: _luci2.rpc.declare({
1397 object: 'luci2.system',
1398 method: 'reset_test',
1399 expect: { supported: false }
1402 startReset: _luci2.rpc.declare({
1403 object: 'luci2.system',
1404 method: 'reset_start'
1408 performReboot: _luci2.rpc.declare({
1409 object: 'luci2.system',
1415 updateLists: _luci2.rpc.declare({
1416 object: 'luci2.opkg',
1421 _allPackages: _luci2.rpc.declare({
1422 object: 'luci2.opkg',
1424 params: [ 'offset', 'limit', 'pattern' ],
1428 _installedPackages: _luci2.rpc.declare({
1429 object: 'luci2.opkg',
1430 method: 'list_installed',
1431 params: [ 'offset', 'limit', 'pattern' ],
1435 _findPackages: _luci2.rpc.declare({
1436 object: 'luci2.opkg',
1438 params: [ 'offset', 'limit', 'pattern' ],
1442 _fetchPackages: function(action, offset, limit, pattern)
1446 return action(offset, limit, pattern).then(function(list) {
1447 if (!list.total || !list.packages)
1448 return { length: 0, total: 0 };
1450 packages.push.apply(packages, list.packages);
1451 packages.total = list.total;
1456 if (packages.length >= limit)
1461 for (var i = offset + packages.length; i < limit; i += 100)
1462 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1464 return _luci2.rpc.flush();
1465 }).then(function(lists) {
1466 for (var i = 0; i < lists.length; i++)
1468 if (!lists[i].total || !lists[i].packages)
1471 packages.push.apply(packages, lists[i].packages);
1472 packages.total = lists[i].total;
1479 listPackages: function(offset, limit, pattern)
1481 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1484 installedPackages: function(offset, limit, pattern)
1486 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1489 findPackages: function(offset, limit, pattern)
1491 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1494 installPackage: _luci2.rpc.declare({
1495 object: 'luci2.opkg',
1497 params: [ 'package' ],
1501 removePackage: _luci2.rpc.declare({
1502 object: 'luci2.opkg',
1504 params: [ 'package' ],
1508 getConfig: _luci2.rpc.declare({
1509 object: 'luci2.opkg',
1510 method: 'config_get',
1511 expect: { config: '' }
1514 setConfig: _luci2.rpc.declare({
1515 object: 'luci2.opkg',
1516 method: 'config_set',
1523 login: _luci2.rpc.declare({
1526 params: [ 'username', 'password' ],
1530 access: _luci2.rpc.declare({
1533 params: [ 'scope', 'object', 'function' ],
1534 expect: { access: false }
1539 return _luci2.session.access('ubus', 'session', 'access');
1542 startHeartbeat: function()
1544 this._hearbeatInterval = window.setInterval(function() {
1545 _luci2.session.isAlive().then(function(alive) {
1548 _luci2.session.stopHeartbeat();
1549 _luci2.ui.login(true);
1553 }, _luci2.globals.timeout * 2);
1556 stopHeartbeat: function()
1558 if (typeof(this._hearbeatInterval) != 'undefined')
1560 window.clearInterval(this._hearbeatInterval);
1561 delete this._hearbeatInterval;
1568 saveScrollTop: function()
1570 this._scroll_top = $(document).scrollTop();
1573 restoreScrollTop: function()
1575 if (typeof(this._scroll_top) == 'undefined')
1578 $(document).scrollTop(this._scroll_top);
1580 delete this._scroll_top;
1583 loading: function(enable)
1585 var win = $(window);
1586 var body = $('body');
1588 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1590 .addClass('cbi-modal-loader')
1591 .append($('<div />').text(_luci2.tr('Loading data...')))
1597 body.css('overflow', 'hidden');
1598 body.css('padding', 0);
1599 body.css('width', win.width());
1600 body.css('height', win.height());
1601 state.modal.css('width', win.width());
1602 state.modal.css('height', win.height());
1608 body.css('overflow', '');
1609 body.css('padding', '');
1610 body.css('width', '');
1611 body.css('height', '');
1615 dialog: function(title, content, options)
1617 var win = $(window);
1618 var body = $('body');
1620 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1621 dialog: $('<div />')
1622 .addClass('cbi-modal-dialog')
1623 .append($('<div />')
1624 .append($('<div />')
1625 .addClass('cbi-modal-dialog-header'))
1626 .append($('<div />')
1627 .addClass('cbi-modal-dialog-body'))
1628 .append($('<div />')
1629 .addClass('cbi-modal-dialog-footer')
1630 .append($('<button />')
1631 .addClass('cbi-button')
1632 .text(_luci2.tr('Close'))
1635 .css('overflow', '')
1640 $(this).parent().parent().parent().hide();
1645 if (typeof(options) != 'object')
1648 if (title === false)
1651 .css('overflow', '')
1656 state.dialog.hide();
1661 var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1662 var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1666 if (options.style == 'confirm')
1668 ftr.append($('<button />')
1669 .addClass('cbi-button')
1670 .text(_luci2.tr('Ok'))
1671 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1673 ftr.append($('<button />')
1674 .addClass('cbi-button')
1675 .text(_luci2.tr('Cancel'))
1676 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1678 else if (options.style == 'close')
1680 ftr.append($('<button />')
1681 .addClass('cbi-button')
1682 .text(_luci2.tr('Close'))
1683 .click(options.close || function() { _luci2.ui.dialog(false) }));
1685 else if (options.style == 'wait')
1687 ftr.append($('<button />')
1688 .addClass('cbi-button')
1689 .text(_luci2.tr('Close'))
1690 .attr('disabled', true));
1693 state.dialog.find('div.cbi-modal-dialog-header').text(title);
1694 state.dialog.show();
1697 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1701 state.dialog.children()
1702 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1704 body.css('overflow', 'hidden');
1705 body.css('padding', 0);
1706 body.css('width', win.width());
1707 body.css('height', win.height());
1708 state.dialog.css('width', win.width());
1709 state.dialog.css('height', win.height());
1712 upload: function(title, content, options)
1714 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1716 .attr('method', 'post')
1717 .attr('action', '/cgi-bin/luci-upload')
1718 .attr('enctype', 'multipart/form-data')
1719 .attr('target', 'cbi-fileupload-frame')
1721 .append($('<input />')
1722 .attr('type', 'hidden')
1723 .attr('name', 'sessionid'))
1724 .append($('<input />')
1725 .attr('type', 'hidden')
1726 .attr('name', 'filename'))
1727 .append($('<input />')
1728 .attr('type', 'file')
1729 .attr('name', 'filedata')
1730 .addClass('cbi-input-file'))
1731 .append($('<div />')
1732 .css('width', '100%')
1733 .addClass('progressbar')
1734 .addClass('intermediate')
1735 .append($('<div />')
1736 .css('width', '100%')))
1737 .append($('<iframe />')
1738 .attr('name', 'cbi-fileupload-frame')
1739 .css('width', '1px')
1740 .css('height', '1px')
1741 .css('visibility', 'hidden')),
1743 finish_cb: function(ev) {
1744 $(this).off('load');
1746 var body = (this.contentDocument || this.contentWindow.document).body;
1747 if (body.firstChild.tagName.toLowerCase() == 'pre')
1748 body = body.firstChild;
1752 json = $.parseJSON(body.innerHTML);
1755 message: _luci2.tr('Invalid server response received'),
1756 error: [ -1, _luci2.tr('Invalid data') ]
1762 L.ui.dialog(L.tr('File upload'), [
1763 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1764 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1765 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1766 ], { style: 'close' });
1768 else if (typeof(state.success_cb) == 'function')
1770 state.success_cb(json);
1774 confirm_cb: function() {
1775 var f = state.form.find('.cbi-input-file');
1776 var b = state.form.find('.progressbar');
1777 var p = state.form.find('p');
1782 state.form.find('iframe').on('load', state.finish_cb);
1783 state.form.submit();
1787 p.text(_luci2.tr('File upload in progress …'));
1789 state.form.parent().parent().find('button').prop('disabled', true);
1793 state.form.find('.progressbar').hide();
1794 state.form.find('.cbi-input-file').val('').show();
1795 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1797 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1798 state.form.find('[name=filename]').val(options.filename);
1800 state.success_cb = options.success;
1802 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1804 confirm: state.confirm_cb
1808 reconnect: function()
1810 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1811 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1812 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1814 var interval, timeout;
1817 _luci2.tr('Waiting for device'), [
1818 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1820 .css('width', '100%')
1821 .addClass('progressbar')
1822 .addClass('intermediate')
1823 .append($('<div />')
1824 .css('width', '100%'))
1825 ], { style: 'wait' }
1828 for (var i = 0; i < protocols.length; i++)
1829 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1831 //_luci2.network.getNetworkStatus(function(s) {
1832 // for (var i = 0; i < protocols.length; i++)
1834 // for (var j = 0; j < s.length; j++)
1836 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1837 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1839 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1840 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1843 //}).then(function() {
1844 images.on('load', function() {
1845 var url = this.getAttribute('url');
1846 _luci2.session.isAlive().then(function(access) {
1849 window.clearTimeout(timeout);
1850 window.clearInterval(interval);
1851 _luci2.ui.dialog(false);
1856 location.href = url;
1861 interval = window.setInterval(function() {
1862 images.each(function() {
1863 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1867 timeout = window.setTimeout(function() {
1868 window.clearInterval(interval);
1872 _luci2.tr('Device not responding'),
1873 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1880 login: function(invalid)
1882 var state = _luci2.ui._login || (_luci2.ui._login = {
1885 .attr('method', 'post')
1887 .addClass('alert-message')
1888 .text(_luci2.tr('Wrong username or password given!')))
1890 .append($('<label />')
1891 .text(_luci2.tr('Username'))
1892 .append($('<br />'))
1893 .append($('<input />')
1894 .attr('type', 'text')
1895 .attr('name', 'username')
1896 .attr('value', 'root')
1897 .addClass('cbi-input-text')
1898 .keypress(function(ev) {
1899 if (ev.which == 10 || ev.which == 13)
1903 .append($('<label />')
1904 .text(_luci2.tr('Password'))
1905 .append($('<br />'))
1906 .append($('<input />')
1907 .attr('type', 'password')
1908 .attr('name', 'password')
1909 .addClass('cbi-input-password')
1910 .keypress(function(ev) {
1911 if (ev.which == 10 || ev.which == 13)
1915 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1917 response_cb: function(response) {
1918 if (!response.ubus_rpc_session)
1920 _luci2.ui.login(true);
1924 _luci2.globals.sid = response.ubus_rpc_session;
1925 _luci2.setHash('id', _luci2.globals.sid);
1926 _luci2.session.startHeartbeat();
1927 _luci2.ui.dialog(false);
1928 state.deferred.resolve();
1932 confirm_cb: function() {
1933 var u = state.form.find('[name=username]').val();
1934 var p = state.form.find('[name=password]').val();
1940 _luci2.tr('Logging in'), [
1941 $('<p />').text(_luci2.tr('Log in in progress …')),
1943 .css('width', '100%')
1944 .addClass('progressbar')
1945 .addClass('intermediate')
1946 .append($('<div />')
1947 .css('width', '100%'))
1948 ], { style: 'wait' }
1951 _luci2.globals.sid = '00000000000000000000000000000000';
1952 _luci2.session.login(u, p).then(state.response_cb);
1956 if (!state.deferred || state.deferred.state() != 'pending')
1957 state.deferred = $.Deferred();
1959 /* try to find sid from hash */
1960 var sid = _luci2.getHash('id');
1961 if (sid && sid.match(/^[a-f0-9]{32}$/))
1963 _luci2.globals.sid = sid;
1964 _luci2.session.isAlive().then(function(access) {
1967 _luci2.session.startHeartbeat();
1968 state.deferred.resolve();
1972 _luci2.setHash('id', undefined);
1977 return state.deferred;
1981 state.form.find('.alert-message').show();
1983 state.form.find('.alert-message').hide();
1985 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
1987 confirm: state.confirm_cb
1990 state.form.find('[name=password]').focus();
1992 return state.deferred;
1995 cryptPassword: _luci2.rpc.declare({
1999 expect: { crypt: '' }
2003 _acl_merge_scope: function(acl_scope, scope)
2005 if ($.isArray(scope))
2007 for (var i = 0; i < scope.length; i++)
2008 acl_scope[scope[i]] = true;
2010 else if ($.isPlainObject(scope))
2012 for (var object_name in scope)
2014 if (!$.isArray(scope[object_name]))
2017 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2019 for (var i = 0; i < scope[object_name].length; i++)
2020 acl_object[scope[object_name][i]] = true;
2025 _acl_merge_permission: function(acl_perm, perm)
2027 if ($.isPlainObject(perm))
2029 for (var scope_name in perm)
2031 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2032 this._acl_merge_scope(acl_scope, perm[scope_name]);
2037 _acl_merge_group: function(acl_group, group)
2039 if ($.isPlainObject(group))
2041 if (!acl_group.description)
2042 acl_group.description = group.description;
2046 var acl_perm = acl_group.read || (acl_group.read = { });
2047 this._acl_merge_permission(acl_perm, group.read);
2052 var acl_perm = acl_group.write || (acl_group.write = { });
2053 this._acl_merge_permission(acl_perm, group.write);
2058 _acl_merge_tree: function(acl_tree, tree)
2060 if ($.isPlainObject(tree))
2062 for (var group_name in tree)
2064 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2065 this._acl_merge_group(acl_group, tree[group_name]);
2070 listAvailableACLs: _luci2.rpc.declare({
2073 expect: { acls: [ ] },
2074 filter: function(trees) {
2076 for (var i = 0; i < trees.length; i++)
2077 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2082 renderMainMenu: _luci2.rpc.declare({
2085 expect: { menu: { } },
2086 filter: function(entries) {
2087 _luci2.globals.mainMenu = new _luci2.ui.menu();
2088 _luci2.globals.mainMenu.entries(entries);
2092 .append(_luci2.globals.mainMenu.render(0, 1));
2096 renderViewMenu: function()
2100 .append(_luci2.globals.mainMenu.render(2, 900));
2103 renderView: function(node)
2105 var name = node.view.split(/\//).join('.');
2107 if (_luci2.globals.currentView)
2108 _luci2.globals.currentView.finish();
2110 _luci2.ui.renderViewMenu();
2113 _luci2._views = { };
2115 _luci2.setHash('view', node.view);
2117 if (_luci2._views[name] instanceof _luci2.ui.view)
2119 _luci2.globals.currentView = _luci2._views[name];
2120 return _luci2._views[name].render();
2123 var url = _luci2.globals.resource + '/view/' + name + '.js';
2125 return $.ajax(url, {
2129 }).then(function(data) {
2131 var viewConstructorSource = (
2132 '(function(L, $) { ' +
2134 '})(_luci2, $);\n\n' +
2136 ).format(data, url);
2138 var viewConstructor = eval(viewConstructorSource);
2140 _luci2._views[name] = new viewConstructor({
2142 acls: node.write || { }
2145 _luci2.globals.currentView = _luci2._views[name];
2146 return _luci2._views[name].render();
2149 alert('Unable to instantiate view "%s": %s'.format(url, e));
2152 return $.Deferred().resolve();
2156 updateHostname: function()
2158 return _luci2.system.getBoardInfo().then(function(info) {
2160 $('#hostname').text(info.hostname);
2164 updateChanges: function()
2166 return _luci2.uci.changes().then(function(changes) {
2170 for (var config in changes)
2174 for (var i = 0; i < changes[config].length; i++)
2176 var c = changes[config][i];
2185 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2187 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2192 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2194 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2198 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2202 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2206 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2211 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2213 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2218 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2219 n += changes[config].length;
2230 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2231 .click(function(ev) {
2232 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2233 ev.preventDefault();
2243 _luci2.ui.loading(true);
2246 _luci2.ui.updateHostname(),
2247 _luci2.ui.updateChanges(),
2248 _luci2.ui.renderMainMenu()
2250 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2251 _luci2.ui.loading(false);
2257 var AbstractWidget = Class.extend({
2258 i18n: function(text) {
2262 toString: function() {
2263 var x = document.createElement('div');
2264 x.appendChild(this.render());
2269 insertInto: function(id) {
2270 return $(id).empty().append(this.render());
2274 this.ui.view = AbstractWidget.extend({
2275 _fetch_template: function()
2277 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2281 success: function(data) {
2282 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2283 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2290 return _luci2.tr(p2);
2293 return _luci2.globals[p2] || '';
2296 return '(?' + match + ')';
2300 $('#maincontent').append(data);
2307 throw "Not implemented";
2312 var container = $('#maincontent');
2317 container.append($('<h2 />').append(this.title));
2319 if (this.description)
2320 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2323 return this._fetch_template().then(function() {
2324 return _luci2.deferrable(self.execute());
2328 repeat: function(func, interval)
2332 if (!self._timeouts)
2333 self._timeouts = [ ];
2335 var index = self._timeouts.length;
2337 if (typeof(interval) != 'number')
2340 var setTimer, runTimer;
2342 setTimer = function() {
2343 self._timeouts[index] = window.setTimeout(runTimer, interval);
2346 runTimer = function() {
2347 _luci2.deferrable(func.call(self)).then(setTimer);
2355 if ($.isArray(this._timeouts))
2357 for (var i = 0; i < this._timeouts.length; i++)
2358 window.clearTimeout(this._timeouts[i]);
2360 delete this._timeouts;
2365 this.ui.menu = AbstractWidget.extend({
2370 entries: function(entries)
2372 for (var entry in entries)
2374 var path = entry.split(/\//);
2375 var node = this._nodes;
2377 for (i = 0; i < path.length; i++)
2382 if (!node.childs[path[i]])
2383 node.childs[path[i]] = { };
2385 node = node.childs[path[i]];
2388 $.extend(node, entries[entry]);
2392 _indexcmp: function(a, b)
2394 var x = a.index || 0;
2395 var y = b.index || 0;
2399 firstChildView: function(node)
2405 for (var child in (node.childs || { }))
2406 nodes.push(node.childs[child]);
2408 nodes.sort(this._indexcmp);
2410 for (var i = 0; i < nodes.length; i++)
2412 var child = this.firstChildView(nodes[i]);
2415 for (var key in child)
2416 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2417 node[key] = child[key];
2426 _onclick: function(ev)
2428 _luci2.ui.loading(true);
2429 _luci2.ui.renderView(ev.data).then(function() {
2430 _luci2.ui.loading(false);
2433 ev.preventDefault();
2437 _render: function(childs, level, min, max)
2440 for (var node in childs)
2442 var child = this.firstChildView(childs[node]);
2444 nodes.push(childs[node]);
2447 nodes.sort(this._indexcmp);
2449 var list = $('<ul />');
2452 list.addClass('nav');
2453 else if (level == 1)
2454 list.addClass('dropdown-menu');
2456 for (var i = 0; i < nodes.length; i++)
2458 if (!_luci2.globals.defaultNode)
2460 var v = _luci2.getHash('view');
2461 if (!v || v == nodes[i].view)
2462 _luci2.globals.defaultNode = nodes[i];
2465 var item = $('<li />')
2468 .text(_luci2.tr(nodes[i].title))
2469 .click(nodes[i], this._onclick))
2472 if (nodes[i].childs && level < max)
2474 item.addClass('dropdown');
2475 item.find('a').addClass('menu');
2476 item.append(this._render(nodes[i].childs, level + 1));
2483 render: function(min, max)
2485 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2486 return this._render(top.childs, 0, min, max);
2489 getNode: function(path, max)
2491 var p = path.split(/\//);
2492 var n = this._nodes;
2494 if (typeof(max) == 'undefined')
2497 for (var i = 0; i < max; i++)
2499 if (!n.childs[p[i]])
2509 this.ui.table = AbstractWidget.extend({
2515 row: function(values)
2517 if ($.isArray(values))
2519 this._rows.push(values);
2521 else if ($.isPlainObject(values))
2524 for (var i = 0; i < this.options.columns.length; i++)
2526 var col = this.options.columns[i];
2528 if (typeof col.key == 'string')
2529 v.push(values[col.key]);
2537 rows: function(rows)
2539 for (var i = 0; i < rows.length; i++)
2543 render: function(id)
2545 var fieldset = document.createElement('fieldset');
2546 fieldset.className = 'cbi-section';
2548 if (this.options.caption)
2550 var legend = document.createElement('legend');
2551 $(legend).append(this.options.caption);
2552 fieldset.appendChild(legend);
2555 var table = document.createElement('table');
2556 table.className = 'cbi-section-table';
2558 var has_caption = false;
2559 var has_description = false;
2561 for (var i = 0; i < this.options.columns.length; i++)
2562 if (this.options.columns[i].caption)
2567 else if (this.options.columns[i].description)
2569 has_description = true;
2575 var tr = table.insertRow(-1);
2576 tr.className = 'cbi-section-table-titles';
2578 for (var i = 0; i < this.options.columns.length; i++)
2580 var col = this.options.columns[i];
2581 var th = document.createElement('th');
2582 th.className = 'cbi-section-table-cell';
2587 th.style.width = col.width;
2590 th.style.textAlign = col.align;
2593 $(th).append(col.caption);
2597 if (has_description)
2599 var tr = table.insertRow(-1);
2600 tr.className = 'cbi-section-table-descr';
2602 for (var i = 0; i < this.options.columns.length; i++)
2604 var col = this.options.columns[i];
2605 var th = document.createElement('th');
2606 th.className = 'cbi-section-table-cell';
2611 th.style.width = col.width;
2614 th.style.textAlign = col.align;
2616 if (col.description)
2617 $(th).append(col.description);
2621 if (this._rows.length == 0)
2623 if (this.options.placeholder)
2625 var tr = table.insertRow(-1);
2626 var td = tr.insertCell(-1);
2627 td.className = 'cbi-section-table-cell';
2629 td.colSpan = this.options.columns.length;
2630 $(td).append(this.options.placeholder);
2635 for (var i = 0; i < this._rows.length; i++)
2637 var tr = table.insertRow(-1);
2639 for (var j = 0; j < this.options.columns.length; j++)
2641 var col = this.options.columns[j];
2642 var td = tr.insertCell(-1);
2644 var val = this._rows[i][j];
2646 if (typeof(val) == 'undefined')
2647 val = col.placeholder;
2649 if (typeof(val) == 'undefined')
2653 td.style.width = col.width;
2656 td.style.textAlign = col.align;
2658 if (typeof col.format == 'string')
2659 $(td).append(col.format.format(val));
2660 else if (typeof col.format == 'function')
2661 $(td).append(col.format(val, i));
2669 fieldset.appendChild(table);
2675 this.ui.progress = AbstractWidget.extend({
2678 var vn = parseInt(this.options.value) || 0;
2679 var mn = parseInt(this.options.max) || 100;
2680 var pc = Math.floor((100 / mn) * vn);
2682 var bar = document.createElement('div');
2683 bar.className = 'progressbar';
2685 bar.appendChild(document.createElement('div'));
2686 bar.lastChild.appendChild(document.createElement('div'));
2687 bar.lastChild.style.width = pc + '%';
2689 if (typeof(this.options.format) == 'string')
2690 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2691 else if (typeof(this.options.format) == 'function')
2692 $(bar.lastChild.lastChild).append(this.options.format(pc));
2694 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2700 this.ui.devicebadge = AbstractWidget.extend({
2703 var l2dev = this.options.l2_device || this.options.device;
2704 var l3dev = this.options.l3_device;
2705 var dev = l3dev || l2dev || '?';
2707 var span = document.createElement('span');
2708 span.className = 'ifacebadge';
2710 if (typeof(this.options.signal) == 'number' ||
2711 typeof(this.options.noise) == 'number')
2714 if (typeof(this.options.signal) != 'undefined' &&
2715 typeof(this.options.noise) != 'undefined')
2717 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2730 span.appendChild(document.createElement('img'));
2731 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2734 span.title = _luci2.tr('No signal');
2736 span.title = '%s: %d %s / %s: %d %s'.format(
2737 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2738 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2743 var type = 'ethernet';
2744 var desc = _luci2.tr('Ethernet device');
2749 desc = _luci2.tr('Tunnel interface');
2751 else if (dev.indexOf('br-') == 0)
2754 desc = _luci2.tr('Bridge');
2756 else if (dev.indexOf('.') > 0)
2759 desc = _luci2.tr('VLAN interface');
2761 else if (dev.indexOf('wlan') == 0 ||
2762 dev.indexOf('ath') == 0 ||
2763 dev.indexOf('wl') == 0)
2766 desc = _luci2.tr('Wireless Network');
2769 span.appendChild(document.createElement('img'));
2770 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2774 $(span).append(' ');
2775 $(span).append(dev);
2781 var type = function(f, l)
2791 _luci2.cbi.validation.message = _luci2.tr(msg);
2794 compile: function(code)
2799 var types = _luci2.cbi.validation.types;
2804 for (var i = 0; i < code.length; i++)
2812 switch (code.charCodeAt(i))
2824 var label = code.substring(pos, i);
2825 label = label.replace(/\\(.)/g, '$1');
2826 label = label.replace(/^[ \t]+/g, '');
2827 label = label.replace(/[ \t]+$/g, '');
2829 if (label && !isNaN(label))
2831 stack.push(parseFloat(label));
2833 else if (label.match(/^(['"]).*\1$/))
2835 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2837 else if (typeof types[label] == 'function')
2839 stack.push(types[label]);
2844 throw "Syntax error, unhandled token '"+label+"'";
2849 depth += (code.charCodeAt(i) == 40);
2855 if (typeof stack[stack.length-2] != 'function')
2856 throw "Syntax error, argument list follows non-function";
2858 stack[stack.length-1] =
2859 arguments.callee(code.substring(pos, i));
2872 var validation = this.cbi.validation;
2874 validation.types = {
2875 'integer': function()
2877 if (this.match(/^-?[0-9]+$/) != null)
2880 validation.i18n('Must be a valid integer');
2884 'uinteger': function()
2886 if (validation.types['integer'].apply(this) && (this >= 0))
2889 validation.i18n('Must be a positive integer');
2895 if (!isNaN(parseFloat(this)))
2898 validation.i18n('Must be a valid number');
2902 'ufloat': function()
2904 if (validation.types['float'].apply(this) && (this >= 0))
2907 validation.i18n('Must be a positive number');
2911 'ipaddr': function()
2913 if (validation.types['ip4addr'].apply(this) ||
2914 validation.types['ip6addr'].apply(this))
2917 validation.i18n('Must be a valid IP address');
2921 'ip4addr': function()
2923 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2925 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2926 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2927 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2928 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2929 ((RegExp.$6.indexOf('.') < 0)
2930 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2931 : (validation.types['ip4addr'].apply(RegExp.$6))))
2935 validation.i18n('Must be a valid IPv4 address');
2939 'ip6addr': function()
2941 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2943 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2945 var addr = RegExp.$1;
2952 if (addr.indexOf('.') > 0)
2954 var off = addr.lastIndexOf(':');
2956 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2958 validation.i18n('Must be a valid IPv6 address');
2962 addr = addr.substr(0, off) + ':0:0';
2965 if (addr.indexOf('::') >= 0)
2970 for (var i = 1; i < (addr.length-1); i++)
2971 if (addr.charAt(i) == ':')
2976 validation.i18n('Must be a valid IPv6 address');
2980 for (var i = 0; i < (7 - colons); i++)
2983 if (addr.match(/^(.*?)::(.*?)$/))
2984 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2985 (RegExp.$2 ? ':' + RegExp.$2 : '');
2988 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2991 validation.i18n('Must be a valid IPv6 address');
2996 validation.i18n('Must be a valid IPv6 address');
3002 if (validation.types['integer'].apply(this) &&
3003 (this >= 0) && (this <= 65535))
3006 validation.i18n('Must be a valid port number');
3010 'portrange': function()
3012 if (this.match(/^(\d+)-(\d+)$/))
3017 if (validation.types['port'].apply(p1) &&
3018 validation.types['port'].apply(p2) &&
3019 (parseInt(p1) <= parseInt(p2)))
3022 else if (validation.types['port'].apply(this))
3027 validation.i18n('Must be a valid port range');
3031 'macaddr': function()
3033 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3036 validation.i18n('Must be a valid MAC address');
3042 if (validation.types['hostname'].apply(this) ||
3043 validation.types['ipaddr'].apply(this))
3046 validation.i18n('Must be a valid hostname or IP address');
3050 'hostname': function()
3052 if ((this.length <= 253) &&
3053 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3054 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3055 this.match(/[^0-9.]/)))))
3058 validation.i18n('Must be a valid host name');
3062 'network': function()
3064 if (validation.types['uciname'].apply(this) ||
3065 validation.types['host'].apply(this))
3068 validation.i18n('Must be a valid network name');
3072 'wpakey': function()
3076 if ((v.length == 64)
3077 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
3078 : ((v.length >= 8) && (v.length <= 63)))
3081 validation.i18n('Must be a valid WPA key');
3085 'wepkey': function()
3089 if (v.substr(0,2) == 's:')
3092 if (((v.length == 10) || (v.length == 26))
3093 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
3094 : ((v.length == 5) || (v.length == 13)))
3097 validation.i18n('Must be a valid WEP key');
3101 'uciname': function()
3103 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3106 validation.i18n('Must be a valid UCI identifier');
3110 'range': function(min, max)
3112 var val = parseFloat(this);
3114 if (validation.types['integer'].apply(this) &&
3115 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
3118 validation.i18n('Must be a number between %d and %d');
3122 'min': function(min)
3124 var val = parseFloat(this);
3126 if (validation.types['integer'].apply(this) &&
3127 !isNaN(min) && !isNaN(val) && (val >= min))
3130 validation.i18n('Must be a number greater or equal to %d');
3134 'max': function(max)
3136 var val = parseFloat(this);
3138 if (validation.types['integer'].apply(this) &&
3139 !isNaN(max) && !isNaN(val) && (val <= max))
3142 validation.i18n('Must be a number lower or equal to %d');
3146 'rangelength': function(min, max)
3148 var val = '' + this;
3150 if (!isNaN(min) && !isNaN(max) &&
3151 (val.length >= min) && (val.length <= max))
3154 validation.i18n('Must be between %d and %d characters');
3158 'minlength': function(min)
3160 var val = '' + this;
3162 if (!isNaN(min) && (val.length >= min))
3165 validation.i18n('Must be at least %d characters');
3169 'maxlength': function(max)
3171 var val = '' + this;
3173 if (!isNaN(max) && (val.length <= max))
3176 validation.i18n('Must be at most %d characters');
3184 for (var i = 0; i < arguments.length; i += 2)
3186 delete validation.message;
3188 if (typeof(arguments[i]) != 'function')
3190 if (arguments[i] == this)
3194 else if (arguments[i].apply(this, arguments[i+1]))
3199 if (validation.message)
3200 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3203 validation.message = msgs.join( _luci2.tr(' - or - '));
3211 for (var i = 0; i < arguments.length; i += 2)
3213 delete validation.message;
3215 if (typeof arguments[i] != 'function')
3217 if (arguments[i] != this)
3221 else if (!arguments[i].apply(this, arguments[i+1]))
3226 if (validation.message)
3227 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3230 validation.message = msgs.join(', ');
3236 return validation.types['or'].apply(
3237 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3240 'list': function(subvalidator, subargs)
3242 if (typeof subvalidator != 'function')
3245 var tokens = this.match(/[^ \t]+/g);
3246 for (var i = 0; i < tokens.length; i++)
3247 if (!subvalidator.apply(tokens[i], subargs))
3253 'phonedigit': function()
3255 if (this.match(/^[0-9\*#!\.]+$/) != null)
3258 validation.i18n('Must be a valid phone number digit');
3262 'string': function()
3269 this.cbi.AbstractValue = AbstractWidget.extend({
3270 init: function(name, options)
3273 this.instance = { };
3274 this.dependencies = [ ];
3275 this.rdependency = { };
3277 this.options = _luci2.defaults(options, {
3287 return this.section.id('field', sid || '__unknown__', this.name);
3290 render: function(sid)
3292 var i = this.instance[sid] = { };
3294 i.top = $('<div />').addClass('cbi-value');
3296 if (typeof(this.options.caption) == 'string')
3298 .addClass('cbi-value-title')
3299 .attr('for', this.id(sid))
3300 .text(this.options.caption)
3303 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
3304 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
3306 if (typeof(this.options.description) == 'string')
3308 .addClass('cbi-value-description')
3309 .text(this.options.description)
3315 ucipath: function(sid)
3318 config: (this.options.uci_package || this.map.uci_package),
3319 section: (this.options.uci_section || sid),
3320 option: (this.options.uci_option || this.name)
3324 ucivalue: function(sid)
3326 var uci = this.ucipath(sid);
3327 var val = this.map.get(uci.config, uci.section, uci.option);
3329 if (typeof(val) == 'undefined')
3330 return this.options.initial;
3335 formvalue: function(sid)
3337 var v = $('#' + this.id(sid)).val();
3338 return (v === '') ? undefined : v;
3341 textvalue: function(sid)
3343 var v = this.formvalue(sid);
3345 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3346 v = this.ucivalue(sid);
3348 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3349 v = this.options.placeholder;
3351 if (typeof(v) == 'undefined' || v === '')
3354 if (typeof(v) == 'string' && $.isArray(this.choices))
3356 for (var i = 0; i < this.choices.length; i++)
3357 if (v === this.choices[i][0])
3358 return this.choices[i][1];
3360 else if (v === true)
3361 return _luci2.tr('yes');
3362 else if (v === false)
3363 return _luci2.tr('no');
3364 else if ($.isArray(v))
3365 return v.join(', ');
3370 changed: function(sid)
3372 var a = this.ucivalue(sid);
3373 var b = this.formvalue(sid);
3375 if (typeof(a) != typeof(b))
3378 if (typeof(a) == 'object')
3380 if (a.length != b.length)
3383 for (var i = 0; i < a.length; i++)
3395 var uci = this.ucipath(sid);
3397 if (this.instance[sid].disabled)
3399 if (!this.options.keep)
3400 return this.map.set(uci.config, uci.section, uci.option, undefined);
3405 var chg = this.changed(sid);
3406 var val = this.formvalue(sid);
3409 this.map.set(uci.config, uci.section, uci.option, val);
3414 validator: function(sid, elem, multi)
3416 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3420 if (typeof(this.options.datatype) == 'string')
3423 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3426 else if (typeof(this.options.datatype) == 'function')
3428 var vfunc = this.options.datatype;
3429 vstack = [ function(elem) {
3430 var rv = vfunc(this, elem);
3432 validation.message = rv;
3433 return (rv === true);
3442 inst: this.instance[sid],
3443 opt: this.options.optional
3446 var validator = function(ev)
3450 var val = d.elem.val();
3452 if (vstack && typeof(vstack[0]) == 'function')
3454 delete validation.message;
3456 if ((val.length == 0 && !d.opt))
3458 d.elem.addClass('error');
3459 d.inst.top.addClass('error');
3460 d.inst.error.text(_luci2.tr('Field must not be empty'));
3463 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3465 d.elem.addClass('error');
3466 d.inst.top.addClass('error');
3467 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3472 d.elem.removeClass('error');
3474 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3480 d.inst.top.removeClass('error');
3481 d.inst.error.text('');
3488 for (var field in d.self.rdependency)
3489 d.self.rdependency[field].toggle(d.sid);
3495 if (elem.prop('tagName') == 'SELECT')
3497 elem.change(evdata, validator);
3499 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3501 elem.click(evdata, validator);
3502 elem.blur(evdata, validator);
3506 elem.keyup(evdata, validator);
3507 elem.blur(evdata, validator);
3510 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3515 validate: function(sid)
3517 var i = this.instance[sid];
3519 i.widget.find('[cbi-validate]').trigger('validate');
3521 return (i.disabled || i.error.text() == '');
3524 depends: function(d, v)
3531 for (var i = 0; i < d.length; i++)
3533 if (typeof(d[i]) == 'string')
3535 else if (d[i] instanceof _luci2.cbi.AbstractValue)
3536 dep[d[i].name] = true;
3539 else if (d instanceof _luci2.cbi.AbstractValue)
3542 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3544 else if (typeof(d) == 'object')
3548 else if (typeof(d) == 'string')
3551 dep[d] = (typeof(v) == 'undefined') ? true : v;
3554 if (!dep || $.isEmptyObject(dep))
3557 for (var field in dep)
3559 var f = this.section.fields[field];
3561 f.rdependency[this.name] = this;
3566 if ($.isEmptyObject(dep))
3569 this.dependencies.push(dep);
3574 toggle: function(sid)
3576 var d = this.dependencies;
3577 var i = this.instance[sid];
3582 for (var n = 0; n < d.length; n++)
3586 for (var field in d[n])
3588 var val = this.section.fields[field].formvalue(sid);
3589 var cmp = d[n][field];
3591 if (typeof(cmp) == 'boolean')
3593 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3599 else if (typeof(cmp) == 'string')
3607 else if (typeof(cmp) == 'function')
3615 else if (cmp instanceof RegExp)
3640 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3647 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
3648 widget: function(sid)
3650 var o = this.options;
3652 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3653 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3655 var i = $('<input />')
3656 .attr('id', this.id(sid))
3657 .attr('type', 'checkbox')
3658 .prop('checked', this.ucivalue(sid));
3660 return this.validator(sid, i);
3663 ucivalue: function(sid)
3665 var v = this.callSuper('ucivalue', sid);
3667 if (typeof(v) == 'boolean')
3670 return (v == this.options.enabled);
3673 formvalue: function(sid)
3675 var v = $('#' + this.id(sid)).prop('checked');
3677 if (typeof(v) == 'undefined')
3678 return !!this.options.initial;
3685 var uci = this.ucipath(sid);
3687 if (this.instance[sid].disabled)
3689 if (!this.options.keep)
3690 return this.map.set(uci.config, uci.section, uci.option, undefined);
3695 var chg = this.changed(sid);
3696 var val = this.formvalue(sid);
3700 if (this.options.optional && val == this.options.initial)
3701 this.map.set(uci.config, uci.section, uci.option, undefined);
3703 this.map.set(uci.config, uci.section, uci.option, val ? this.options.enabled : this.options.disabled);
3710 this.cbi.InputValue = this.cbi.AbstractValue.extend({
3711 widget: function(sid)
3713 var i = $('<input />')
3714 .attr('id', this.id(sid))
3715 .attr('type', 'text')
3716 .attr('placeholder', this.options.placeholder)
3717 .val(this.ucivalue(sid));
3719 return this.validator(sid, i);
3723 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
3724 widget: function(sid)
3726 var i = $('<input />')
3727 .attr('id', this.id(sid))
3728 .attr('type', 'password')
3729 .attr('placeholder', this.options.placeholder)
3730 .val(this.ucivalue(sid));
3732 var t = $('<img />')
3733 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3734 .attr('title', _luci2.tr('Reveal or hide password'))
3735 .addClass('cbi-button')
3736 .click(function(ev) {
3737 var i = $(this).prev();
3738 var t = i.attr('type');
3739 i.attr('type', (t == 'password') ? 'text' : 'password');
3743 this.validator(sid, i);
3746 .addClass('cbi-input-password')
3752 this.cbi.ListValue = this.cbi.AbstractValue.extend({
3753 widget: function(sid)
3755 var s = $('<select />');
3757 if (this.options.optional)
3760 .text(_luci2.tr('-- Please choose --'))
3764 for (var i = 0; i < this.choices.length; i++)
3766 .attr('value', this.choices[i][0])
3767 .text(this.choices[i][1])
3770 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3772 return this.validator(sid, s);
3775 value: function(k, v)
3780 this.choices.push([k, v || k]);
3785 this.cbi.MultiValue = this.cbi.ListValue.extend({
3786 widget: function(sid)
3788 var v = this.ucivalue(sid);
3789 var t = $('<div />').attr('id', this.id(sid));
3792 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3795 for (var i = 0; i < v.length; i++)
3799 for (var i = 0; i < this.choices.length; i++)
3802 .append($('<input />')
3803 .addClass('cbi-input-checkbox')
3804 .attr('type', 'checkbox')
3805 .attr('value', this.choices[i][0])
3806 .prop('checked', s[this.choices[i][0]]))
3807 .append(this.choices[i][1])
3817 formvalue: function(sid)
3820 var fields = $('#' + this.id(sid) + ' > label > input');
3822 for (var i = 0; i < fields.length; i++)
3823 if (fields[i].checked)
3824 rv.push(fields[i].getAttribute('value'));
3829 textvalue: function(sid)
3831 var v = this.formvalue(sid);
3835 for (var i = 0; i < this.choices.length; i++)
3836 c[this.choices[i][0]] = this.choices[i][1];
3840 for (var i = 0; i < v.length; i++)
3841 t.push(c[v[i]] || v[i]);
3843 return t.join(', ');
3847 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
3848 _change: function(ev)
3851 var self = ev.data.self;
3853 if (s.selectedIndex == (s.options.length - 1))
3855 ev.data.select.hide();
3856 ev.data.input.show().focus();
3858 var v = ev.data.input.val();
3859 ev.data.input.val(' ');
3860 ev.data.input.val(v);
3862 else if (self.options.optional && s.selectedIndex == 0)
3864 ev.data.input.val('');
3868 ev.data.input.val(ev.data.select.val());
3875 var val = this.value;
3876 var self = ev.data.self;
3878 ev.data.select.empty();
3880 if (self.options.optional)
3883 .text(_luci2.tr('-- please choose --'))
3884 .appendTo(ev.data.select);
3887 for (var i = 0; i < self.choices.length; i++)
3889 if (self.choices[i][0] == val)
3893 .attr('value', self.choices[i][0])
3894 .text(self.choices[i][1])
3895 .appendTo(ev.data.select);
3898 if (!seen && val != '')
3902 .appendTo(ev.data.select);
3906 .text(_luci2.tr('-- custom --'))
3907 .appendTo(ev.data.select);
3909 ev.data.input.hide();
3910 ev.data.select.val(val).show().focus();
3913 _enter: function(ev)
3918 ev.preventDefault();
3919 ev.data.self._blur(ev);
3923 widget: function(sid)
3925 var d = $('<div />')
3926 .attr('id', this.id(sid));
3928 var t = $('<input />')
3929 .attr('type', 'text')
3933 var s = $('<select />')
3938 input: this.validator(sid, t),
3939 select: this.validator(sid, s)
3942 s.change(evdata, this._change);
3943 t.blur(evdata, this._blur);
3944 t.keydown(evdata, this._enter);
3946 t.val(this.ucivalue(sid));
3952 value: function(k, v)
3957 this.choices.push([k, v || k]);
3961 formvalue: function(sid)
3963 var v = $('#' + this.id(sid)).children('input').val();
3964 return (v == '') ? undefined : v;
3968 this.cbi.DynamicList = this.cbi.ComboBox.extend({
3969 _redraw: function(focus, add, del, s)
3971 var v = s.values || [ ];
3974 $(s.parent).children('input').each(function(i) {
3976 v.push(this.value || '');
3979 $(s.parent).empty();
3984 v.splice(focus, 0, '');
3986 else if (v.length == 0)
3992 for (var i = 0; i < v.length; i++)
4003 var txt = $('<input />')
4004 .attr('type', 'text')
4006 .appendTo(s.parent);
4008 var sel = $('<select />')
4009 .appendTo(s.parent);
4011 evdata.input = this.validator(s.sid, txt, true);
4012 evdata.select = this.validator(s.sid, sel, true);
4014 sel.change(evdata, this._change);
4015 txt.blur(evdata, this._blur);
4016 txt.keydown(evdata, this._keydown);
4021 if (i == focus || -(i+1) == focus)
4028 var f = $('<input />')
4029 .attr('type', 'text')
4031 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
4032 .addClass('cbi-input-text')
4033 .keydown(evdata, this._keydown)
4034 .keypress(evdata, this._keypress)
4037 f.appendTo(s.parent);
4043 else if (-(i+1) == focus)
4047 /* force cursor to end */
4053 evdata.input = this.validator(s.sid, f, true);
4059 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
4060 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
4061 .addClass('cbi-button')
4062 .click(evdata, this._btnclick)
4063 .appendTo(s.parent);
4066 .appendTo(s.parent);
4074 _keypress: function(ev)
4078 /* backspace, delete */
4081 if (ev.data.input.val() == '')
4083 ev.preventDefault();
4089 /* enter, arrow up, arrow down */
4093 ev.preventDefault();
4100 _keydown: function(ev)
4102 var input = ev.data.input;
4106 /* backspace, delete */
4109 if (input.val().length == 0)
4111 ev.preventDefault();
4113 var index = ev.data.index;
4119 ev.data.self._redraw(focus, -1, index, ev.data);
4127 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4132 var prev = input.prevAll('input:first');
4133 if (prev.is(':visible'))
4136 prev.next('select').focus();
4141 var next = input.nextAll('input:first');
4142 if (next.is(':visible'))
4145 next.next('select').focus();
4152 _btnclick: function(ev)
4154 if (!this.getAttribute('disabled'))
4156 if (ev.target.src.indexOf('remove') > -1)
4158 var index = ev.data.index;
4159 ev.data.self._redraw(-index, -1, index, ev.data);
4163 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4170 widget: function(sid)
4172 this.options.optional = true;
4174 var v = this.ucivalue(sid);
4177 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4179 var d = $('<div />')
4180 .attr('id', this.id(sid))
4181 .addClass('cbi-input-dynlist');
4183 this._redraw(NaN, -1, -1, {
4193 ucivalue: function(sid)
4195 var v = this.callSuper('ucivalue', sid);
4198 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4203 formvalue: function(sid)
4206 var fields = $('#' + this.id(sid) + ' > input');
4208 for (var i = 0; i < fields.length; i++)
4209 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4210 rv.push(fields[i].value);
4216 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4217 widget: function(sid)
4220 .addClass('cbi-value-dummy')
4221 .attr('id', this.id(sid))
4222 .html(this.ucivalue(sid));
4225 formvalue: function(sid)
4227 return this.ucivalue(sid);
4231 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4236 if (!self.interfaces)
4238 self.interfaces = [ ];
4239 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4240 self.interfaces = ifaces;
4248 _device_icon: function(dev)
4250 var type = 'ethernet';
4251 var desc = _luci2.tr('Ethernet device');
4253 if (dev.type == 'IP tunnel')
4256 desc = _luci2.tr('Tunnel interface');
4258 else if (dev['bridge-members'])
4261 desc = _luci2.tr('Bridge');
4263 else if (dev.wireless)
4266 desc = _luci2.tr('Wireless Network');
4268 else if (dev.device.indexOf('.') > 0)
4271 desc = _luci2.tr('VLAN interface');
4275 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4276 .attr('title', '%s (%s)'.format(desc, dev.device));
4279 widget: function(sid)
4281 var id = this.id(sid);
4282 var ul = $('<ul />')
4284 .addClass('cbi-input-networks');
4286 var itype = this.options.multiple ? 'checkbox' : 'radio';
4287 var value = this.ucivalue(sid);
4290 if (!this.options.multiple)
4291 check[value] = true;
4293 for (var i = 0; i < value.length; i++)
4294 check[value[i]] = true;
4296 if (this.interfaces)
4298 for (var i = 0; i < this.interfaces.length; i++)
4300 var iface = this.interfaces[i];
4301 var badge = $('<span />')
4302 .addClass('ifacebadge')
4303 .text('%s: '.format(iface['interface']));
4305 if (iface.device && iface.device.subdevices)
4306 for (var j = 0; j < iface.device.subdevices.length; j++)
4307 badge.append(this._device_icon(iface.device.subdevices[j]));
4308 else if (iface.device)
4309 badge.append(this._device_icon(iface.device));
4311 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4314 .append($('<label />')
4315 .append($('<input />')
4316 .attr('name', itype + id)
4317 .attr('type', itype)
4318 .attr('value', iface['interface'])
4319 .prop('checked', !!check[iface['interface']])
4320 .addClass('cbi-input-' + itype))
4326 if (!this.options.multiple)
4329 .append($('<label />')
4330 .append($('<input />')
4331 .attr('name', itype + id)
4332 .attr('type', itype)
4334 .prop('checked', !value)
4335 .addClass('cbi-input-' + itype))
4336 .append(_luci2.tr('unspecified')))
4343 ucivalue: function(sid)
4345 var v = this.callSuper('ucivalue', sid);
4347 if (!this.options.multiple)
4353 else if (typeof(v) == 'string')
4356 return v ? v[0] : undefined;
4363 if (typeof(v) == 'string')
4364 v = v.match(/\S+/g);
4370 formvalue: function(sid)
4372 var inputs = $('#' + this.id(sid) + ' input');
4374 if (!this.options.multiple)
4376 for (var i = 0; i < inputs.length; i++)
4377 if (inputs[i].checked && inputs[i].value !== '')
4378 return inputs[i].value;
4385 for (var i = 0; i < inputs.length; i++)
4386 if (inputs[i].checked)
4387 rv.push(inputs[i].value);
4389 return rv.length ? rv : undefined;
4394 this.cbi.AbstractSection = AbstractWidget.extend({
4397 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4399 for (var i = 1; i < arguments.length; i++)
4400 s.push(arguments[i].replace(/\./g, '_'));
4405 option: function(widget, name, options)
4407 if (this.tabs.length == 0)
4408 this.tab({ id: '__default__', selected: true });
4410 return this.taboption('__default__', widget, name, options);
4413 tab: function(options)
4415 if (options.selected)
4416 this.tabs.selected = this.tabs.length;
4420 caption: options.caption,
4421 description: options.description,
4427 taboption: function(tabid, widget, name, options)
4430 for (var i = 0; i < this.tabs.length; i++)
4432 if (this.tabs[i].id == tabid)
4440 throw 'Cannot append to unknown tab ' + tabid;
4442 var w = widget ? new widget(name, options) : null;
4444 if (!(w instanceof _luci2.cbi.AbstractValue))
4445 throw 'Widget must be an instance of AbstractValue';
4450 this.fields[name] = w;
4456 ucipackages: function(pkg)
4458 for (var i = 0; i < this.tabs.length; i++)
4459 for (var j = 0; j < this.tabs[i].fields.length; j++)
4460 if (this.tabs[i].fields[j].options.uci_package)
4461 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4464 formvalue: function()
4468 this.sections(function(s) {
4469 var sid = s['.name'];
4470 var sv = rv[sid] || (rv[sid] = { });
4472 for (var i = 0; i < this.tabs.length; i++)
4473 for (var j = 0; j < this.tabs[i].fields.length; j++)
4475 var val = this.tabs[i].fields[j].formvalue(sid);
4476 sv[this.tabs[i].fields[j].name] = val;
4483 validate: function(sid)
4489 var as = this.sections();
4490 for (var i = 0; i < as.length; i++)
4491 if (!this.validate(as[i]['.name']))
4496 var inst = this.instance[sid];
4497 var sv = rv[sid] || (rv[sid] = { });
4500 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4502 legend.children('span').detach();
4504 for (var i = 0; i < this.tabs.length; i++)
4507 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4509 tab.children('span').detach();
4511 for (var j = 0; j < this.tabs[i].fields.length; j++)
4512 if (!this.tabs[i].fields[j].validate(sid))
4519 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4532 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4540 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
4541 init: function(uci_type, options)
4543 this.uci_type = uci_type;
4544 this.options = options;
4547 this.active_panel = 0;
4548 this.active_tab = { };
4551 filter: function(section)
4556 sections: function(cb)
4558 var s1 = this.map.ucisections(this.map.uci_package);
4561 for (var i = 0; i < s1.length; i++)
4562 if (s1[i]['.type'] == this.uci_type)
4563 if (this.filter(s1[i]))
4566 if (typeof(cb) == 'function')
4567 for (var i = 0; i < s2.length; i++)
4568 cb.apply(this, [ s2[i] ]);
4575 this.map.add(this.map.uci_package, this.uci_type, name);
4578 remove: function(sid)
4580 this.map.remove(this.map.uci_package, sid);
4586 var name = undefined;
4587 var self = ev.data.self;
4589 if (addb.prev().prop('nodeName') == 'INPUT')
4590 name = addb.prev().val();
4592 if (addb.prop('disabled') || name === '')
4595 _luci2.ui.saveScrollTop();
4597 self.active_panel = -1;
4602 _luci2.ui.restoreScrollTop();
4605 _remove: function(ev)
4607 var self = ev.data.self;
4608 var sid = ev.data.sid;
4610 if (ev.data.index == (self.sections().length - 1))
4611 self.active_panel = -1;
4613 _luci2.ui.saveScrollTop();
4619 _luci2.ui.restoreScrollTop();
4621 ev.stopPropagation();
4626 var self = ev.data.self;
4628 var addb = text.next();
4629 var errt = addb.next();
4630 var name = text.val();
4633 if (!/^[a-zA-Z0-9_]*$/.test(name))
4635 errt.text(_luci2.tr('Invalid section name')).show();
4636 text.addClass('error');
4637 addb.prop('disabled', true);
4641 for (var sid in self.map.uci.values[self.map.uci_package])
4648 for (var sid in self.map.uci.creates[self.map.uci_package])
4657 errt.text(_luci2.tr('Name already used')).show();
4658 text.addClass('error');
4659 addb.prop('disabled', true);
4663 errt.text('').hide();
4664 text.removeClass('error');
4665 addb.prop('disabled', false);
4669 teaser: function(sid)
4671 var tf = this.teaser_fields;
4675 tf = this.teaser_fields = [ ];
4677 if ($.isArray(this.options.teasers))
4679 for (var i = 0; i < this.options.teasers.length; i++)
4681 var f = this.options.teasers[i];
4682 if (f instanceof _luci2.cbi.AbstractValue)
4684 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
4685 tf.push(this.fields[f]);
4690 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4691 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4692 tf.push(this.tabs[i].fields[j]);
4698 for (var i = 0; i < tf.length; i++)
4700 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4703 var n = tf[i].options.caption || tf[i].name;
4704 var v = tf[i].textvalue(sid);
4706 if (typeof(v) == 'undefined')
4709 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4715 _render_add: function()
4717 var text = _luci2.tr('Add section');
4718 var ttip = _luci2.tr('Create new section...');
4720 if ($.isArray(this.options.add_caption))
4721 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4722 else if (typeof(this.options.add_caption) == 'string')
4723 text = this.options.add_caption, ttip = '';
4725 var add = $('<div />').addClass('cbi-section-add');
4727 if (this.options.anonymous === false)
4730 .addClass('cbi-input-text')
4731 .attr('type', 'text')
4732 .attr('placeholder', ttip)
4733 .blur({ self: this }, this._sid)
4734 .keyup({ self: this }, this._sid)
4738 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4739 .attr('title', text)
4740 .addClass('cbi-button')
4741 .click({ self: this }, this._add)
4745 .addClass('cbi-value-error')
4752 .attr('type', 'button')
4753 .addClass('cbi-button')
4754 .addClass('cbi-button-add')
4755 .val(text).attr('title', ttip)
4756 .click({ self: this }, this._add)
4763 _render_remove: function(sid, index)
4765 var text = _luci2.tr('Remove');
4766 var ttip = _luci2.tr('Remove this section');
4768 if ($.isArray(this.options.remove_caption))
4769 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4770 else if (typeof(this.options.remove_caption) == 'string')
4771 text = this.options.remove_caption, ttip = '';
4773 return $('<input />')
4774 .attr('type', 'button')
4775 .addClass('cbi-button')
4776 .addClass('cbi-button-remove')
4777 .val(text).attr('title', ttip)
4778 .click({ self: this, sid: sid, index: index }, this._remove);
4781 _render_caption: function(sid)
4783 if (typeof(this.options.caption) == 'string')
4785 return $('<legend />')
4786 .text(this.options.caption.format(sid));
4788 else if (typeof(this.options.caption) == 'function')
4790 return $('<legend />')
4791 .text(this.options.caption.call(this, sid));
4799 var allsections = $();
4800 var panel_index = 0;
4802 this.instance = { };
4804 var s = this.sections();
4808 var fieldset = $('<fieldset />')
4809 .addClass('cbi-section');
4811 var head = $('<div />')
4812 .addClass('cbi-section-head')
4813 .appendTo(fieldset);
4815 head.append(this._render_caption(undefined));
4817 if (typeof(this.options.description) == 'string')
4820 .addClass('cbi-section-descr')
4821 .text(this.options.description)
4825 allsections = allsections.add(fieldset);
4828 for (var i = 0; i < s.length; i++)
4830 var sid = s[i]['.name'];
4831 var inst = this.instance[sid] = { tabs: [ ] };
4833 var fieldset = $('<fieldset />')
4834 .attr('id', this.id('sort', sid))
4835 .addClass('cbi-section');
4837 var head = $('<div />')
4838 .addClass('cbi-section-head')
4839 .attr('cbi-section-num', this.index)
4840 .attr('cbi-section-id', sid);
4842 head.append(this._render_caption(sid));
4844 if (typeof(this.options.description) == 'string')
4847 .addClass('cbi-section-descr')
4848 .text(this.options.description)
4853 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4854 teaser = $('<div />')
4855 .addClass('cbi-section-teaser')
4858 if (this.options.addremove)
4860 .addClass('cbi-section-remove')
4862 .append(this._render_remove(sid, panel_index))
4865 var body = $('<div />')
4866 .attr('index', panel_index++);
4868 var fields = $('<fieldset />')
4869 .addClass('cbi-section-node');
4871 if (this.tabs.length > 1)
4873 var menu = $('<ul />')
4874 .addClass('cbi-tabmenu');
4876 for (var j = 0; j < this.tabs.length; j++)
4878 var tabid = this.id('tab', sid, this.tabs[j].id);
4879 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4881 var tabc = $('<div />')
4882 .addClass('cbi-tabcontainer')
4886 if (typeof(this.tabs[j].description) == 'string')
4889 .addClass('cbi-tab-descr')
4890 .text(this.tabs[j].description)
4894 for (var k = 0; k < this.tabs[j].fields.length; k++)
4895 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4897 tabc.appendTo(fields);
4900 $('<li />').attr('id', theadid).append(
4902 .text(this.tabs[j].caption.format(this.tabs[j].id))
4903 .attr('href', '#' + tabid)
4907 menu.appendTo(body);
4910 fields.appendTo(body);
4913 var t = body.tabs({ active: this.active_tab[sid] });
4915 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4918 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4923 for (var j = 0; j < this.tabs[0].fields.length; j++)
4924 this.tabs[0].fields[j].render(sid).appendTo(fields);
4926 fields.appendTo(body);
4930 head.appendTo(fieldset);
4933 body.appendTo(fieldset);
4936 allsections = allsections.add(fieldset);
4939 //this.validate(sid);
4942 // teaser.append(this.teaser(sid));
4945 if (this.options.collabsible && s.length > 1)
4947 var a = $('<div />').append(allsections).accordion({
4948 header: '> fieldset > div.cbi-section-head',
4949 heightStyle: 'content',
4950 active: this.active_panel
4953 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4954 var h = ui.oldHeader;
4955 var s = ev.data.self;
4956 var i = h.attr('cbi-section-id');
4958 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4962 a.on('accordionactivate', { self: this }, function(ev, ui) {
4963 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4966 if (this.options.sortable)
4968 var s = a.sortable({
4970 handle: 'div.cbi-section-head'
4973 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4975 for (var i = 0; i < ev.data.ids.length; i++)
4976 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4977 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4980 s.on('sortstop', function(ev, ui) {
4981 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4985 if (this.options.addremove)
4986 this._render_add().appendTo(a);
4991 if (this.options.addremove)
4992 allsections = allsections.add(this._render_add());
4999 var s = this.sections();
5001 for (var i = 0; i < s.length; i++)
5003 var sid = s[i]['.name'];
5007 $('#' + this.id('sort', sid))
5008 .children('.cbi-section-head')
5009 .children('.cbi-section-teaser')
5010 .append(this.teaser(sid));
5015 this.cbi.TableSection = this.cbi.TypedSection.extend({
5018 var allsections = $();
5019 var panel_index = 0;
5021 this.instance = { };
5023 var s = this.sections();
5025 var fieldset = $('<fieldset />')
5026 .addClass('cbi-section');
5028 fieldset.append(this._render_caption(sid));
5030 if (typeof(this.options.description) == 'string')
5033 .addClass('cbi-section-descr')
5034 .text(this.options.description)
5035 .appendTo(fieldset);
5038 var fields = $('<div />')
5039 .addClass('cbi-section-node')
5040 .appendTo(fieldset);
5042 var table = $('<table />')
5043 .addClass('cbi-section-table')
5046 var thead = $('<thead />')
5047 .append($('<tr />').addClass('cbi-section-table-titles'))
5050 for (var j = 0; j < this.tabs[0].fields.length; j++)
5052 .addClass('cbi-section-table-cell')
5053 .css('width', this.tabs[0].fields[j].options.width || '')
5054 .append(this.tabs[0].fields[j].options.caption)
5055 .appendTo(thead.children());
5057 if (this.options.sortable)
5058 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
5060 if (this.options.addremove !== false)
5061 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
5063 var tbody = $('<tbody />')
5069 .addClass('cbi-section-table-row')
5072 .addClass('cbi-section-table-cell')
5073 .addClass('cbi-section-table-placeholder')
5074 .attr('colspan', thead.children().children().length)
5075 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
5079 for (var i = 0; i < s.length; i++)
5081 var sid = s[i]['.name'];
5082 var inst = this.instance[sid] = { tabs: [ ] };
5084 var row = $('<tr />')
5085 .addClass('cbi-section-table-row')
5088 for (var j = 0; j < this.tabs[0].fields.length; j++)
5091 .addClass('cbi-section-table-cell')
5092 .css('width', this.tabs[0].fields[j].options.width || '')
5093 .append(this.tabs[0].fields[j].render(sid, true))
5097 if (this.options.sortable)
5100 .addClass('cbi-section-table-cell')
5101 .addClass('cbi-section-table-sort')
5102 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
5103 .append($('<br />'))
5104 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
5108 if (this.options.addremove !== false)
5111 .addClass('cbi-section-table-cell')
5112 .append(this._render_remove(sid))
5121 if (this.options.sortable)
5123 var s = tbody.sortable({
5124 handle: 'td.cbi-section-table-sort'
5127 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
5129 for (var i = 0; i < ev.data.ids.length; i++)
5130 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
5131 _luci2.uci.order(ev.data.self.map.uci_package, sections);
5134 s.on('sortstop', function(ev, ui) {
5135 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
5139 if (this.options.addremove)
5140 this._render_add().appendTo(fieldset);
5142 fields = table = thead = tbody = null;
5148 this.cbi.NamedSection = this.cbi.TypedSection.extend({
5149 sections: function(cb)
5152 var pkg = this.map.uci.values[this.map.uci_package];
5155 if (pkg[s]['.name'] == this.uci_type)
5161 if (typeof(cb) == 'function' && sa.length > 0)
5162 cb.apply(this, [ sa[0] ]);
5168 this.cbi.DummySection = this.cbi.TypedSection.extend({
5169 sections: function(cb)
5171 if (typeof(cb) == 'function')
5172 cb.apply(this, [ { '.name': this.uci_type } ]);
5174 return [ { '.name': this.uci_type } ];
5178 this.cbi.Map = AbstractWidget.extend({
5179 init: function(uci_package, options)
5183 this.uci_package = uci_package;
5184 this.sections = [ ];
5185 this.options = _luci2.defaults(options, {
5186 save: function() { },
5187 prepare: function() {
5188 return _luci2.uci.writable(function(writable) {
5189 self.options.readonly = !writable;
5205 if (typeof(this.active_panel) == 'undefined')
5206 this.active_panel = 0;
5210 for (var i = 0; i < this.sections.length; i++)
5211 this.sections[i].ucipackages(packages);
5213 packages[this.uci_package] = true;
5215 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
5216 for (var i = 0; i < packages.length; i++)
5218 this.uci.values[packages[i]['.package']] = packages[i];
5219 delete packages[i]['.package'];
5222 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5224 for (var i = 0; i < this.sections.length; i++)
5226 for (var f in this.sections[i].fields)
5228 if (typeof(this.sections[i].fields[f].load) != 'function')
5231 var s = this.sections[i].sections();
5232 for (var j = 0; j < s.length; j++)
5234 var rv = this.sections[i].fields[f].load(s[j]['.name']);
5235 if (_luci2.isDeferred(rv))
5241 return $.when.apply($, deferreds);
5246 for (var pkg in packages)
5247 _luci2.uci.get_all(pkg);
5249 return _luci2.rpc.flush().then(load_cb);
5254 var map = $('<div />').addClass('cbi-map');
5256 if (typeof(this.options.caption) == 'string')
5257 $('<h2 />').text(this.options.caption).appendTo(map);
5259 if (typeof(this.options.description) == 'string')
5260 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
5262 var sections = $('<div />').appendTo(map);
5264 for (var i = 0; i < this.sections.length; i++)
5266 var s = this.sections[i].render();
5268 if (this.options.readonly || this.sections[i].options.readonly)
5269 s.find('input, select, button, img.cbi-button').attr('disabled', true);
5271 s.appendTo(sections);
5273 if (this.sections[i].options.active)
5274 this.active_panel = i;
5277 if (this.options.collabsible)
5279 var a = sections.accordion({
5280 header: '> fieldset > div.cbi-section-head',
5281 heightStyle: 'content',
5282 active: this.active_panel
5285 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
5286 var h = ui.oldHeader;
5287 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
5288 var i = h.attr('cbi-section-id');
5290 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
5292 for (var i = 0; i < ev.data.self.sections.length; i++)
5293 ev.data.self.sections[i].validate();
5296 a.on('accordionactivate', { self: this }, function(ev, ui) {
5297 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
5301 if (this.options.pageaction !== false)
5303 var a = $('<div />')
5304 .addClass('cbi-page-actions')
5308 .addClass('cbi-button').addClass('cbi-button-apply')
5309 .attr('type', 'button')
5310 .val(_luci2.tr('Save & Apply'))
5314 .addClass('cbi-button').addClass('cbi-button-save')
5315 .attr('type', 'button')
5316 .val(_luci2.tr('Save'))
5317 .click({ self: this }, function(ev) { ev.data.self.send(); })
5321 .addClass('cbi-button').addClass('cbi-button-reset')
5322 .attr('type', 'button')
5323 .val(_luci2.tr('Reset'))
5324 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
5330 var top = $('<form />').append(map);
5339 for (var i = 0; i < this.sections.length; i++)
5340 this.sections[i].finish();
5347 this.target.hide().empty().append(this.render());
5352 section: function(widget, uci_type, options)
5354 var w = widget ? new widget(uci_type, options) : null;
5356 if (!(w instanceof _luci2.cbi.AbstractSection))
5357 throw 'Widget must be an instance of AbstractSection';
5360 w.index = this.sections.length;
5362 this.sections.push(w);
5366 formvalue: function()
5370 for (var i = 0; i < this.sections.length; i++)
5372 var sids = this.sections[i].formvalue();
5373 for (var sid in sids)
5375 var s = rv[sid] || (rv[sid] = { });
5376 $.extend(s, sids[sid]);
5383 add: function(conf, type, name)
5385 var c = this.uci.creates;
5386 var s = '.new.%d'.format(this.uci.newid++);
5401 remove: function(conf, sid)
5403 var n = this.uci.creates;
5404 var c = this.uci.changes;
5405 var d = this.uci.deletes;
5407 /* requested deletion of a just created section */
5408 if (sid.indexOf('.new.') == 0)
5411 delete n[conf][sid];
5416 delete c[conf][sid];
5421 d[conf][sid] = true;
5425 ucisections: function(conf, cb)
5428 var pkg = this.uci.values[conf];
5429 var crt = this.uci.creates[conf];
5430 var del = this.uci.deletes[conf];
5436 if (!del || del[s] !== true)
5439 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5445 if (typeof(cb) == 'function')
5446 for (var i = 0; i < sa.length; i++)
5447 cb.apply(this, [ sa[i] ]);
5452 get: function(conf, sid, opt)
5454 var v = this.uci.values;
5455 var n = this.uci.creates;
5456 var c = this.uci.changes;
5457 var d = this.uci.deletes;
5459 /* requested option in a just created section */
5460 if (sid.indexOf('.new.') == 0)
5465 if (typeof(opt) == 'undefined')
5466 return (n[conf][sid] || { });
5468 return n[conf][sid][opt];
5471 /* requested an option value */
5472 if (typeof(opt) != 'undefined')
5474 /* check whether option was deleted */
5475 if (d[conf] && d[conf][sid])
5477 if (d[conf][sid] === true)
5480 for (var i = 0; i < d[conf][sid].length; i++)
5481 if (d[conf][sid][i] == opt)
5485 /* check whether option was changed */
5486 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5487 return c[conf][sid][opt];
5489 /* return base value */
5490 if (v[conf] && v[conf][sid])
5491 return v[conf][sid][opt];
5496 /* requested an entire section */
5498 return (v[conf][sid] || { });
5503 set: function(conf, sid, opt, val)
5505 var n = this.uci.creates;
5506 var c = this.uci.changes;
5507 var d = this.uci.deletes;
5509 if (sid.indexOf('.new.') == 0)
5511 if (n[conf] && n[conf][sid])
5513 if (typeof(val) != 'undefined')
5514 n[conf][sid][opt] = val;
5516 delete n[conf][sid][opt];
5519 else if (typeof(val) != 'undefined')
5527 c[conf][sid][opt] = val;
5537 d[conf][sid].push(opt);
5541 validate: function()
5545 for (var i = 0; i < this.sections.length; i++)
5546 if (!this.sections[i].validate())
5554 if (this.options.readonly)
5555 return _luci2.deferrable();
5557 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5559 for (var i = 0; i < this.sections.length; i++)
5561 if (this.sections[i].options.readonly)
5564 for (var f in this.sections[i].fields)
5566 if (typeof(this.sections[i].fields[f].save) != 'function')
5569 var s = this.sections[i].sections();
5570 for (var j = 0; j < s.length; j++)
5572 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5573 if (_luci2.isDeferred(rv))
5579 return $.when.apply($, deferreds);
5584 if (!this.validate())
5585 return _luci2.deferrable();
5587 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5590 if (this.uci.creates)
5591 for (var c in this.uci.creates)
5592 for (var s in this.uci.creates[c])
5599 for (var k in this.uci.creates[c][s])
5602 r.type = this.uci.creates[c][s][k];
5603 else if (k == '.create')
5604 r.name = this.uci.creates[c][s][k];
5605 else if (k.charAt(0) != '.')
5606 r.values[k] = this.uci.creates[c][s][k];
5609 _luci2.uci.add(r.config, r.type, r.name, r.values);
5612 if (this.uci.changes)
5613 for (var c in this.uci.changes)
5614 for (var s in this.uci.changes[c])
5615 _luci2.uci.set(c, s, this.uci.changes[c][s]);
5617 if (this.uci.deletes)
5618 for (var c in this.uci.deletes)
5619 for (var s in this.uci.deletes[c])
5621 var o = this.uci.deletes[c][s];
5622 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
5625 return _luci2.rpc.flush().then(function() {
5626 return _luci2.ui.updateChanges();
5632 _luci2.ui.saveScrollTop();
5633 _luci2.ui.loading(true);
5635 return this.save().then(send_cb).then(function() {
5637 }).then(function() {
5641 _luci2.ui.loading(false);
5642 _luci2.ui.restoreScrollTop();
5646 dialog: function(id)
5648 var d = $('<div />');
5652 .attr('src', _luci2.globals.resource + '/icons/loading.gif')
5653 .css('vertical-align', 'middle')
5654 .css('padding-right', '10px')
5657 p.append(_luci2.tr('Loading data...'));
5668 $(this).parent().children('.ui-dialog-titlebar').hide();
5673 insertInto: function(id)
5676 self.target = $(id);
5678 _luci2.ui.loading(true);
5681 return self.load().then(function() {
5682 self.target.empty().append(self.render());
5686 _luci2.ui.loading(false);