2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String.prototype.format = function()
15 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27 var a = b = [], numSubstitutions = 0, numMatches = 0;
29 while ((a = re.exec(str)) != null)
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
43 if (numSubstitutions < arguments.length)
45 var param = arguments[numSubstitutions++];
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
59 minLength = parseInt(pMinLength);
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
70 subst = (parseInt(param) || 0).toString(2);
74 subst = String.fromCharCode(parseInt(param) || 0);
78 subst = (parseInt(param) || 0);
82 subst = Math.abs(parseInt(param) || 0);
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
92 subst = (parseInt(param) || 0).toString(8);
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
108 subst = esc(param, html_esc);
112 subst = esc(param, quot_esc);
116 subst = String.serialize(param);
123 var ts = (param || 0);
126 tm = Math.floor(ts / 60);
131 th = Math.floor(tm / 60);
136 td = Math.floor(th / 24);
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i = 0; (i < units.length) && (val > mf); i++)
157 subst = val.toFixed(pr) + ' ' + units[i];
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
169 out += leftpart + subst;
170 str = str.substr(m.length);
180 var Class = function() { };
182 Class.extend = function(properties)
184 Class.initializing = true;
186 var prototype = new this();
187 var superprot = this.prototype;
189 Class.initializing = false;
191 $.extend(prototype, properties, {
192 callSuper: function() {
194 var meth = arguments[0];
196 if (typeof(superprot[meth]) != 'function')
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
202 return superprot[meth].apply(this, args);
208 this.options = arguments[0] || { };
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
217 _class.extend = arguments.callee;
222 this.defaults = function(obj, def)
225 if (typeof(obj[key]) == 'undefined')
231 this.isDeferred = function(x)
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments[0]))
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
253 plural: function(n) { return 0 + (n != 1) },
256 if (_luci2.i18n.loaded)
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
270 var pe = _luci2.i18n.catalog[''];
273 delete _luci2.i18n.catalog[''];
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
282 _luci2.i18n.loaded = true;
287 this.tr = function(msgid)
291 var msgstr = _luci2.i18n.catalog[msgid];
293 if (typeof(msgstr) == 'undefined')
295 else if (typeof(msgstr) == 'string')
301 this.trp = function(msgid, msgid_plural, count)
305 var msgstr = _luci2.i18n.catalog[msgid];
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
312 return msgstr[_luci2.i18n.plural(count)];
315 this.trc = function(msgctx, msgid)
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
321 if (typeof(msgstr) == 'undefined')
323 else if (typeof(msgstr) == 'string')
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
340 return msgstr[_luci2.i18n.plural(count)];
343 this.setHash = function(key, value)
346 var data = this.getHash(undefined);
348 if (typeof(value) == 'undefined')
359 for (var i = 0; i < keys.length; i++)
364 h += keys[i] + ':' + data[keys[i]];
368 location.hash = '#' + h;
371 this.getHash = function(key)
374 var tuples = (location.hash || '#').substring(1).split(/,/);
376 for (var i = 0; i < tuples.length; i++)
378 var tuple = tuples[i].split(/:/);
379 if (tuple.length == 2)
380 data[tuple[0]] = tuple[1];
383 if (typeof(key) != 'undefined')
392 sid: '00000000000000000000000000000000'
401 _call: function(req, cb)
403 return $.ajax('/ubus', {
405 contentType: 'application/json',
406 data: JSON.stringify(req),
409 timeout: _luci2.globals.timeout
413 _list_cb: function(msg)
415 /* verify message frame */
416 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
417 throw 'Invalid JSON response';
422 _call_cb: function(msg)
425 var type = Object.prototype.toString;
430 for (var i = 0; i < msg.length; i++)
432 /* verify message frame */
433 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
434 throw 'Invalid JSON response';
436 /* fetch related request info */
437 var req = _luci2.rpc._requests[msg[i].id];
438 if (typeof(req) != 'object')
439 throw 'No related request for JSON response';
441 /* fetch response attribute and verify returned type */
444 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
445 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
449 for (var key in req.expect)
451 if (typeof(ret) != 'undefined' && key != '')
454 if (type.call(ret) != type.call(req.expect[key]))
455 ret = req.expect[key];
462 if (typeof(req.filter) == 'function')
465 req.priv[1] = req.params;
466 ret = req.filter.apply(_luci2.rpc, req.priv);
469 /* store response data */
470 if (typeof(req.index) == 'number')
471 data[req.index] = ret;
475 /* delete request object */
476 delete _luci2.rpc._requests[msg[i].id];
485 for (var i = 0; i < arguments.length; i++)
486 params[i] = arguments[i];
492 params: (params.length > 0) ? params : undefined
495 return this._call(msg, this._list_cb);
500 if (!$.isArray(this._batch))
506 if (!$.isArray(this._batch))
507 return _luci2.deferrable([ ]);
509 var req = this._batch;
513 return this._call(req, this._call_cb);
516 declare: function(options)
521 /* build parameter object */
524 if ($.isArray(options.params))
525 for (p_off = 0; p_off < options.params.length; p_off++)
526 params[options.params[p_off]] = arguments[p_off];
528 /* all remaining arguments are private args */
529 var priv = [ undefined, undefined ];
530 for (; p_off < arguments.length; p_off++)
531 priv.push(arguments[p_off]);
533 /* store request info */
534 var req = _rpc._requests[_rpc._id] = {
535 expect: options.expect,
536 filter: options.filter,
541 /* build message object */
554 /* when a batch is in progress then store index in request data
555 * and push message object onto the stack */
556 if ($.isArray(_rpc._batch))
558 req.index = _rpc._batch.push(msg) - 1;
559 return _luci2.deferrable(msg);
563 return _rpc._call(msg, _rpc._call_cb);
572 return _luci2.session.access('ubus', 'uci', 'commit');
575 add: _luci2.rpc.declare({
578 params: [ 'config', 'type', 'name', 'values' ],
579 expect: { section: '' }
587 configs: _luci2.rpc.declare({
590 expect: { configs: [ ] }
593 _changes: _luci2.rpc.declare({
596 params: [ 'config' ],
597 expect: { changes: [ ] }
600 changes: function(config)
602 if (typeof(config) == 'string')
603 return this._changes(config);
606 return this.configs().then(function(configs) {
608 configlist = configs;
610 for (var i = 0; i < configs.length; i++)
611 _luci2.uci._changes(configs[i]);
613 return _luci2.rpc.flush();
614 }).then(function(changes) {
617 for (var i = 0; i < configlist.length; i++)
618 if (changes[i].length)
619 rv[configlist[i]] = changes[i];
625 commit: _luci2.rpc.declare({
631 _delete_one: _luci2.rpc.declare({
634 params: [ 'config', 'section', 'option' ]
637 _delete_multiple: _luci2.rpc.declare({
640 params: [ 'config', 'section', 'options' ]
643 'delete': function(config, section, option)
645 if ($.isArray(option))
646 return this._delete_multiple(config, section, option);
648 return this._delete_one(config, section, option);
651 delete_all: _luci2.rpc.declare({
654 params: [ 'config', 'type', 'match' ]
657 _foreach: _luci2.rpc.declare({
660 params: [ 'config', 'type' ],
661 expect: { values: { } }
664 foreach: function(config, type, cb)
666 return this._foreach(config, type).then(function(sections) {
667 for (var s in sections)
672 get: _luci2.rpc.declare({
675 params: [ 'config', 'section', 'option' ],
677 filter: function(data, params) {
678 if (typeof(params.option) == 'undefined')
679 return data.values ? data.values['.type'] : undefined;
685 get_all: _luci2.rpc.declare({
688 params: [ 'config', 'section' ],
689 expect: { values: { } },
690 filter: function(data, params) {
691 if (typeof(params.section) == 'string')
692 data['.section'] = params.section;
693 else if (typeof(params.config) == 'string')
694 data['.package'] = params.config;
699 get_first: function(config, type, option)
701 return this._foreach(config, type).then(function(sections) {
702 for (var s in sections)
704 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
706 if (typeof(val) != 'undefined')
714 section: _luci2.rpc.declare({
717 params: [ 'config', 'type', 'name', 'values' ],
718 expect: { section: '' }
721 _set: _luci2.rpc.declare({
724 params: [ 'config', 'section', 'values' ]
727 set: function(config, section, option, value)
729 if (typeof(value) == 'undefined' && typeof(option) == 'string')
730 return this.section(config, section, option); /* option -> type */
731 else if ($.isPlainObject(option))
732 return this._set(config, section, option); /* option -> values */
735 values[option] = value;
737 return this._set(config, section, values);
740 order: _luci2.rpc.declare({
743 params: [ 'config', 'sections' ]
748 listNetworkNames: function() {
749 return _luci2.rpc.list('network.interface.*').then(function(list) {
751 for (var name in list)
752 if (name != 'network.interface.loopback')
753 names.push(name.substring(18));
759 listDeviceNames: _luci2.rpc.declare({
760 object: 'network.device',
763 filter: function(data) {
765 for (var name in data)
773 getNetworkStatus: function()
778 return this.listNetworkNames().then(function(names) {
781 for (var i = 0; i < names.length; i++)
782 _luci2.network.getInterfaceStatus(names[i]);
784 return _luci2.rpc.flush();
785 }).then(function(networks) {
786 for (var i = 0; i < networks.length; i++)
788 var net = nets[i] = networks[i];
789 var dev = net.l3_device || net.l2_device;
791 net.device = devs[dev] || (devs[dev] = { });
796 for (var dev in devs)
797 _luci2.network.getDeviceStatus(dev);
799 return _luci2.rpc.flush();
800 }).then(function(devices) {
803 for (var i = 0; i < devices.length; i++)
805 var brm = devices[i]['bridge-members'];
806 delete devices[i]['bridge-members'];
808 $.extend(devs[devices[i]['device']], devices[i]);
813 devs[devices[i]['device']].subdevices = [ ];
815 for (var j = 0; j < brm.length; j++)
820 _luci2.network.getDeviceStatus(brm[j]);
823 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
827 return _luci2.rpc.flush();
828 }).then(function(subdevices) {
829 for (var i = 0; i < subdevices.length; i++)
830 $.extend(devs[subdevices[i]['device']], subdevices[i]);
834 for (var dev in devs)
835 _luci2.wireless.getDeviceStatus(dev);
837 return _luci2.rpc.flush();
838 }).then(function(wifidevices) {
839 for (var i = 0; i < wifidevices.length; i++)
841 devs[wifidevices[i]['device']].wireless = wifidevices[i];
843 nets.sort(function(a, b) {
844 if (a['interface'] < b['interface'])
846 else if (a['interface'] > b['interface'])
856 findWanInterfaces: function(cb)
858 return this.listNetworkNames().then(function(names) {
861 for (var i = 0; i < names.length; i++)
862 _luci2.network.getInterfaceStatus(names[i]);
864 return _luci2.rpc.flush();
865 }).then(function(interfaces) {
866 var rv = [ undefined, undefined ];
868 for (var i = 0; i < interfaces.length; i++)
870 if (!interfaces[i].route)
873 for (var j = 0; j < interfaces[i].route.length; j++)
875 var rt = interfaces[i].route[j];
877 if (typeof(rt.table) != 'undefined')
880 if (rt.target == '0.0.0.0' && rt.mask == 0)
881 rv[0] = interfaces[i];
882 else if (rt.target == '::' && rt.mask == 0)
883 rv[1] = interfaces[i];
891 getDHCPLeases: _luci2.rpc.declare({
892 object: 'luci2.network',
893 method: 'dhcp_leases',
894 expect: { leases: [ ] }
897 getDHCPv6Leases: _luci2.rpc.declare({
898 object: 'luci2.network',
899 method: 'dhcp6_leases',
900 expect: { leases: [ ] }
903 getRoutes: _luci2.rpc.declare({
904 object: 'luci2.network',
906 expect: { routes: [ ] }
909 getIPv6Routes: _luci2.rpc.declare({
910 object: 'luci2.network',
912 expect: { routes: [ ] }
915 getARPTable: _luci2.rpc.declare({
916 object: 'luci2.network',
918 expect: { entries: [ ] }
921 getInterfaceStatus: _luci2.rpc.declare({
922 object: 'network.interface',
924 params: [ 'interface' ],
926 filter: function(data, params) {
927 data['interface'] = params['interface'];
928 data['l2_device'] = data['device'];
929 delete data['device'];
934 getDeviceStatus: _luci2.rpc.declare({
935 object: 'network.device',
939 filter: function(data, params) {
940 data['device'] = params['name'];
945 getConntrackCount: _luci2.rpc.declare({
946 object: 'luci2.network',
947 method: 'conntrack_count',
948 expect: { '': { count: 0, limit: 0 } }
951 listSwitchNames: _luci2.rpc.declare({
952 object: 'luci2.network',
953 method: 'switch_list',
954 expect: { switches: [ ] }
957 getSwitchInfo: _luci2.rpc.declare({
958 object: 'luci2.network',
959 method: 'switch_info',
960 params: [ 'switch' ],
961 expect: { info: { } },
962 filter: function(data, params) {
963 data['attrs'] = data['switch'];
964 data['vlan_attrs'] = data['vlan'];
965 data['port_attrs'] = data['port'];
966 data['switch'] = params['switch'];
975 getSwitchStatus: _luci2.rpc.declare({
976 object: 'luci2.network',
977 method: 'switch_status',
978 params: [ 'switch' ],
979 expect: { ports: [ ] }
983 runPing: _luci2.rpc.declare({
984 object: 'luci2.network',
987 expect: { '': { code: -1 } }
990 runPing6: _luci2.rpc.declare({
991 object: 'luci2.network',
994 expect: { '': { code: -1 } }
997 runTraceroute: _luci2.rpc.declare({
998 object: 'luci2.network',
999 method: 'traceroute',
1001 expect: { '': { code: -1 } }
1004 runTraceroute6: _luci2.rpc.declare({
1005 object: 'luci2.network',
1006 method: 'traceroute6',
1008 expect: { '': { code: -1 } }
1011 runNslookup: _luci2.rpc.declare({
1012 object: 'luci2.network',
1015 expect: { '': { code: -1 } }
1019 setUp: _luci2.rpc.declare({
1020 object: 'luci2.network',
1023 expect: { '': { code: -1 } }
1026 setDown: _luci2.rpc.declare({
1027 object: 'luci2.network',
1030 expect: { '': { code: -1 } }
1035 listDeviceNames: _luci2.rpc.declare({
1038 expect: { 'devices': [ ] },
1039 filter: function(data) {
1045 getDeviceStatus: _luci2.rpc.declare({
1048 params: [ 'device' ],
1049 expect: { '': { } },
1050 filter: function(data, params) {
1051 if (!$.isEmptyObject(data))
1053 data['device'] = params['device'];
1060 getAssocList: _luci2.rpc.declare({
1062 method: 'assoclist',
1063 params: [ 'device' ],
1064 expect: { results: [ ] },
1065 filter: function(data, params) {
1066 for (var i = 0; i < data.length; i++)
1067 data[i]['device'] = params['device'];
1069 data.sort(function(a, b) {
1070 if (a.bssid < b.bssid)
1072 else if (a.bssid > b.bssid)
1082 getWirelessStatus: function() {
1083 return this.listDeviceNames().then(function(names) {
1086 for (var i = 0; i < names.length; i++)
1087 _luci2.wireless.getDeviceStatus(names[i]);
1089 return _luci2.rpc.flush();
1090 }).then(function(networks) {
1094 'country', 'channel', 'frequency', 'frequency_offset',
1095 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1099 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1100 'signal', 'noise', 'bitrate', 'encryption'
1103 for (var i = 0; i < networks.length; i++)
1105 var phy = rv[networks[i].phy] || (
1106 rv[networks[i].phy] = { networks: [ ] }
1110 device: networks[i].device
1113 for (var j = 0; j < phy_attrs.length; j++)
1114 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1116 for (var j = 0; j < net_attrs.length; j++)
1117 net[net_attrs[j]] = networks[i][net_attrs[j]];
1119 phy.networks.push(net);
1126 getAssocLists: function()
1128 return this.listDeviceNames().then(function(names) {
1131 for (var i = 0; i < names.length; i++)
1132 _luci2.wireless.getAssocList(names[i]);
1134 return _luci2.rpc.flush();
1135 }).then(function(assoclists) {
1138 for (var i = 0; i < assoclists.length; i++)
1139 for (var j = 0; j < assoclists[i].length; j++)
1140 rv.push(assoclists[i][j]);
1146 formatEncryption: function(enc)
1148 var format_list = function(l, s)
1151 for (var i = 0; i < l.length; i++)
1152 rv.push(l[i].toUpperCase());
1153 return rv.join(s ? s : ', ');
1156 if (!enc || !enc.enabled)
1157 return _luci2.tr('None');
1161 if (enc.wep.length == 2)
1162 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1163 else if (enc.wep[0] == 'shared')
1164 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1166 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1170 if (enc.wpa.length == 2)
1171 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1172 format_list(enc.authentication, '/'),
1173 format_list(enc.ciphers, ', ')
1175 else if (enc.wpa[0] == 2)
1176 return 'WPA2 %s (%s)'.format(
1177 format_list(enc.authentication, '/'),
1178 format_list(enc.ciphers, ', ')
1181 return 'WPA %s (%s)'.format(
1182 format_list(enc.authentication, '/'),
1183 format_list(enc.ciphers, ', ')
1187 return _luci2.tr('Unknown');
1192 getSystemInfo: _luci2.rpc.declare({
1198 getBoardInfo: _luci2.rpc.declare({
1204 getDiskInfo: _luci2.rpc.declare({
1205 object: 'luci2.system',
1210 getInfo: function(cb)
1214 this.getSystemInfo();
1215 this.getBoardInfo();
1218 return _luci2.rpc.flush().then(function(info) {
1221 $.extend(rv, info[0]);
1222 $.extend(rv, info[1]);
1223 $.extend(rv, info[2]);
1229 getProcessList: _luci2.rpc.declare({
1230 object: 'luci2.system',
1231 method: 'process_list',
1232 expect: { processes: [ ] },
1233 filter: function(data) {
1234 data.sort(function(a, b) { return a.pid - b.pid });
1239 getSystemLog: _luci2.rpc.declare({
1240 object: 'luci2.system',
1245 getKernelLog: _luci2.rpc.declare({
1246 object: 'luci2.system',
1251 getZoneInfo: function(cb)
1253 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1256 sendSignal: _luci2.rpc.declare({
1257 object: 'luci2.system',
1258 method: 'process_signal',
1259 params: [ 'pid', 'signal' ],
1260 filter: function(data) {
1265 initList: _luci2.rpc.declare({
1266 object: 'luci2.system',
1267 method: 'init_list',
1268 expect: { initscripts: [ ] },
1269 filter: function(data) {
1270 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1275 initEnabled: function(init, cb)
1277 return this.initList().then(function(list) {
1278 for (var i = 0; i < list.length; i++)
1279 if (list[i].name == init)
1280 return !!list[i].enabled;
1286 initRun: _luci2.rpc.declare({
1287 object: 'luci2.system',
1288 method: 'init_action',
1289 params: [ 'name', 'action' ],
1290 filter: function(data) {
1295 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1296 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1297 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1298 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1299 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1300 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1303 getRcLocal: _luci2.rpc.declare({
1304 object: 'luci2.system',
1305 method: 'rclocal_get',
1306 expect: { data: '' }
1309 setRcLocal: _luci2.rpc.declare({
1310 object: 'luci2.system',
1311 method: 'rclocal_set',
1316 getCrontab: _luci2.rpc.declare({
1317 object: 'luci2.system',
1318 method: 'crontab_get',
1319 expect: { data: '' }
1322 setCrontab: _luci2.rpc.declare({
1323 object: 'luci2.system',
1324 method: 'crontab_set',
1329 getSSHKeys: _luci2.rpc.declare({
1330 object: 'luci2.system',
1331 method: 'sshkeys_get',
1332 expect: { keys: [ ] }
1335 setSSHKeys: _luci2.rpc.declare({
1336 object: 'luci2.system',
1337 method: 'sshkeys_set',
1342 setPassword: _luci2.rpc.declare({
1343 object: 'luci2.system',
1344 method: 'password_set',
1345 params: [ 'user', 'password' ]
1349 listLEDs: _luci2.rpc.declare({
1350 object: 'luci2.system',
1352 expect: { leds: [ ] }
1355 listUSBDevices: _luci2.rpc.declare({
1356 object: 'luci2.system',
1358 expect: { devices: [ ] }
1362 testUpgrade: _luci2.rpc.declare({
1363 object: 'luci2.system',
1364 method: 'upgrade_test',
1368 startUpgrade: _luci2.rpc.declare({
1369 object: 'luci2.system',
1370 method: 'upgrade_start',
1374 cleanUpgrade: _luci2.rpc.declare({
1375 object: 'luci2.system',
1376 method: 'upgrade_clean'
1380 restoreBackup: _luci2.rpc.declare({
1381 object: 'luci2.system',
1382 method: 'backup_restore'
1385 cleanBackup: _luci2.rpc.declare({
1386 object: 'luci2.system',
1387 method: 'backup_clean'
1391 getBackupConfig: _luci2.rpc.declare({
1392 object: 'luci2.system',
1393 method: 'backup_config_get',
1394 expect: { config: '' }
1397 setBackupConfig: _luci2.rpc.declare({
1398 object: 'luci2.system',
1399 method: 'backup_config_set',
1404 listBackup: _luci2.rpc.declare({
1405 object: 'luci2.system',
1406 method: 'backup_list',
1407 expect: { files: [ ] }
1411 testReset: _luci2.rpc.declare({
1412 object: 'luci2.system',
1413 method: 'reset_test',
1414 expect: { supported: false }
1417 startReset: _luci2.rpc.declare({
1418 object: 'luci2.system',
1419 method: 'reset_start'
1423 performReboot: _luci2.rpc.declare({
1424 object: 'luci2.system',
1430 updateLists: _luci2.rpc.declare({
1431 object: 'luci2.opkg',
1436 _allPackages: _luci2.rpc.declare({
1437 object: 'luci2.opkg',
1439 params: [ 'offset', 'limit', 'pattern' ],
1443 _installedPackages: _luci2.rpc.declare({
1444 object: 'luci2.opkg',
1445 method: 'list_installed',
1446 params: [ 'offset', 'limit', 'pattern' ],
1450 _findPackages: _luci2.rpc.declare({
1451 object: 'luci2.opkg',
1453 params: [ 'offset', 'limit', 'pattern' ],
1457 _fetchPackages: function(action, offset, limit, pattern)
1461 return action(offset, limit, pattern).then(function(list) {
1462 if (!list.total || !list.packages)
1463 return { length: 0, total: 0 };
1465 packages.push.apply(packages, list.packages);
1466 packages.total = list.total;
1471 if (packages.length >= limit)
1476 for (var i = offset + packages.length; i < limit; i += 100)
1477 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1479 return _luci2.rpc.flush();
1480 }).then(function(lists) {
1481 for (var i = 0; i < lists.length; i++)
1483 if (!lists[i].total || !lists[i].packages)
1486 packages.push.apply(packages, lists[i].packages);
1487 packages.total = lists[i].total;
1494 listPackages: function(offset, limit, pattern)
1496 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1499 installedPackages: function(offset, limit, pattern)
1501 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1504 findPackages: function(offset, limit, pattern)
1506 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1509 installPackage: _luci2.rpc.declare({
1510 object: 'luci2.opkg',
1512 params: [ 'package' ],
1516 removePackage: _luci2.rpc.declare({
1517 object: 'luci2.opkg',
1519 params: [ 'package' ],
1523 getConfig: _luci2.rpc.declare({
1524 object: 'luci2.opkg',
1525 method: 'config_get',
1526 expect: { config: '' }
1529 setConfig: _luci2.rpc.declare({
1530 object: 'luci2.opkg',
1531 method: 'config_set',
1538 login: _luci2.rpc.declare({
1541 params: [ 'username', 'password' ],
1545 access: _luci2.rpc.declare({
1548 params: [ 'scope', 'object', 'function' ],
1549 expect: { access: false }
1554 return _luci2.session.access('ubus', 'session', 'access');
1557 startHeartbeat: function()
1559 this._hearbeatInterval = window.setInterval(function() {
1560 _luci2.session.isAlive().then(function(alive) {
1563 _luci2.session.stopHeartbeat();
1564 _luci2.ui.login(true);
1568 }, _luci2.globals.timeout * 2);
1571 stopHeartbeat: function()
1573 if (typeof(this._hearbeatInterval) != 'undefined')
1575 window.clearInterval(this._hearbeatInterval);
1576 delete this._hearbeatInterval;
1583 saveScrollTop: function()
1585 this._scroll_top = $(document).scrollTop();
1588 restoreScrollTop: function()
1590 if (typeof(this._scroll_top) == 'undefined')
1593 $(document).scrollTop(this._scroll_top);
1595 delete this._scroll_top;
1598 loading: function(enable)
1600 var win = $(window);
1601 var body = $('body');
1603 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1605 .addClass('cbi-modal-loader')
1606 .append($('<div />').text(_luci2.tr('Loading data...')))
1612 body.css('overflow', 'hidden');
1613 body.css('padding', 0);
1614 body.css('width', win.width());
1615 body.css('height', win.height());
1616 state.modal.css('width', win.width());
1617 state.modal.css('height', win.height());
1623 body.css('overflow', '');
1624 body.css('padding', '');
1625 body.css('width', '');
1626 body.css('height', '');
1630 dialog: function(title, content, options)
1632 var win = $(window);
1633 var body = $('body');
1635 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1636 dialog: $('<div />')
1637 .addClass('cbi-modal-dialog')
1638 .append($('<div />')
1639 .append($('<div />')
1640 .addClass('cbi-modal-dialog-header'))
1641 .append($('<div />')
1642 .addClass('cbi-modal-dialog-body'))
1643 .append($('<div />')
1644 .addClass('cbi-modal-dialog-footer')
1645 .append($('<button />')
1646 .addClass('cbi-button')
1647 .text(_luci2.tr('Close'))
1650 .css('overflow', '')
1655 $(this).parent().parent().parent().hide();
1660 if (typeof(options) != 'object')
1663 if (title === false)
1666 .css('overflow', '')
1671 state.dialog.hide();
1676 var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1677 var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1681 if (options.style == 'confirm')
1683 ftr.append($('<button />')
1684 .addClass('cbi-button')
1685 .text(_luci2.tr('Ok'))
1686 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1688 ftr.append($('<button />')
1689 .addClass('cbi-button')
1690 .text(_luci2.tr('Cancel'))
1691 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1693 else if (options.style == 'close')
1695 ftr.append($('<button />')
1696 .addClass('cbi-button')
1697 .text(_luci2.tr('Close'))
1698 .click(options.close || function() { _luci2.ui.dialog(false) }));
1700 else if (options.style == 'wait')
1702 ftr.append($('<button />')
1703 .addClass('cbi-button')
1704 .text(_luci2.tr('Close'))
1705 .attr('disabled', true));
1708 state.dialog.find('div.cbi-modal-dialog-header').text(title);
1709 state.dialog.show();
1712 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1716 state.dialog.children()
1717 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1719 body.css('overflow', 'hidden');
1720 body.css('padding', 0);
1721 body.css('width', win.width());
1722 body.css('height', win.height());
1723 state.dialog.css('width', win.width());
1724 state.dialog.css('height', win.height());
1727 upload: function(title, content, options)
1729 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1731 .attr('method', 'post')
1732 .attr('action', '/cgi-bin/luci-upload')
1733 .attr('enctype', 'multipart/form-data')
1734 .attr('target', 'cbi-fileupload-frame')
1736 .append($('<input />')
1737 .attr('type', 'hidden')
1738 .attr('name', 'sessionid'))
1739 .append($('<input />')
1740 .attr('type', 'hidden')
1741 .attr('name', 'filename'))
1742 .append($('<input />')
1743 .attr('type', 'file')
1744 .attr('name', 'filedata')
1745 .addClass('cbi-input-file'))
1746 .append($('<div />')
1747 .css('width', '100%')
1748 .addClass('progressbar')
1749 .addClass('intermediate')
1750 .append($('<div />')
1751 .css('width', '100%')))
1752 .append($('<iframe />')
1753 .attr('name', 'cbi-fileupload-frame')
1754 .css('width', '1px')
1755 .css('height', '1px')
1756 .css('visibility', 'hidden')),
1758 finish_cb: function(ev) {
1759 $(this).off('load');
1761 var body = (this.contentDocument || this.contentWindow.document).body;
1762 if (body.firstChild.tagName.toLowerCase() == 'pre')
1763 body = body.firstChild;
1767 json = $.parseJSON(body.innerHTML);
1770 message: _luci2.tr('Invalid server response received'),
1771 error: [ -1, _luci2.tr('Invalid data') ]
1777 L.ui.dialog(L.tr('File upload'), [
1778 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1779 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1780 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1781 ], { style: 'close' });
1783 else if (typeof(state.success_cb) == 'function')
1785 state.success_cb(json);
1789 confirm_cb: function() {
1790 var f = state.form.find('.cbi-input-file');
1791 var b = state.form.find('.progressbar');
1792 var p = state.form.find('p');
1797 state.form.find('iframe').on('load', state.finish_cb);
1798 state.form.submit();
1802 p.text(_luci2.tr('File upload in progress …'));
1804 state.form.parent().parent().find('button').prop('disabled', true);
1808 state.form.find('.progressbar').hide();
1809 state.form.find('.cbi-input-file').val('').show();
1810 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1812 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1813 state.form.find('[name=filename]').val(options.filename);
1815 state.success_cb = options.success;
1817 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1819 confirm: state.confirm_cb
1823 reconnect: function()
1825 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1826 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1827 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1829 var interval, timeout;
1832 _luci2.tr('Waiting for device'), [
1833 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1835 .css('width', '100%')
1836 .addClass('progressbar')
1837 .addClass('intermediate')
1838 .append($('<div />')
1839 .css('width', '100%'))
1840 ], { style: 'wait' }
1843 for (var i = 0; i < protocols.length; i++)
1844 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1846 //_luci2.network.getNetworkStatus(function(s) {
1847 // for (var i = 0; i < protocols.length; i++)
1849 // for (var j = 0; j < s.length; j++)
1851 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1852 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1854 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1855 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1858 //}).then(function() {
1859 images.on('load', function() {
1860 var url = this.getAttribute('url');
1861 _luci2.session.isAlive().then(function(access) {
1864 window.clearTimeout(timeout);
1865 window.clearInterval(interval);
1866 _luci2.ui.dialog(false);
1871 location.href = url;
1876 interval = window.setInterval(function() {
1877 images.each(function() {
1878 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1882 timeout = window.setTimeout(function() {
1883 window.clearInterval(interval);
1887 _luci2.tr('Device not responding'),
1888 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1895 login: function(invalid)
1897 var state = _luci2.ui._login || (_luci2.ui._login = {
1900 .attr('method', 'post')
1902 .addClass('alert-message')
1903 .text(_luci2.tr('Wrong username or password given!')))
1905 .append($('<label />')
1906 .text(_luci2.tr('Username'))
1907 .append($('<br />'))
1908 .append($('<input />')
1909 .attr('type', 'text')
1910 .attr('name', 'username')
1911 .attr('value', 'root')
1912 .addClass('cbi-input-text')
1913 .keypress(function(ev) {
1914 if (ev.which == 10 || ev.which == 13)
1918 .append($('<label />')
1919 .text(_luci2.tr('Password'))
1920 .append($('<br />'))
1921 .append($('<input />')
1922 .attr('type', 'password')
1923 .attr('name', 'password')
1924 .addClass('cbi-input-password')
1925 .keypress(function(ev) {
1926 if (ev.which == 10 || ev.which == 13)
1930 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1932 response_cb: function(response) {
1933 if (!response.ubus_rpc_session)
1935 _luci2.ui.login(true);
1939 _luci2.globals.sid = response.ubus_rpc_session;
1940 _luci2.setHash('id', _luci2.globals.sid);
1941 _luci2.session.startHeartbeat();
1942 _luci2.ui.dialog(false);
1943 state.deferred.resolve();
1947 confirm_cb: function() {
1948 var u = state.form.find('[name=username]').val();
1949 var p = state.form.find('[name=password]').val();
1955 _luci2.tr('Logging in'), [
1956 $('<p />').text(_luci2.tr('Log in in progress …')),
1958 .css('width', '100%')
1959 .addClass('progressbar')
1960 .addClass('intermediate')
1961 .append($('<div />')
1962 .css('width', '100%'))
1963 ], { style: 'wait' }
1966 _luci2.globals.sid = '00000000000000000000000000000000';
1967 _luci2.session.login(u, p).then(state.response_cb);
1971 if (!state.deferred || state.deferred.state() != 'pending')
1972 state.deferred = $.Deferred();
1974 /* try to find sid from hash */
1975 var sid = _luci2.getHash('id');
1976 if (sid && sid.match(/^[a-f0-9]{32}$/))
1978 _luci2.globals.sid = sid;
1979 _luci2.session.isAlive().then(function(access) {
1982 _luci2.session.startHeartbeat();
1983 state.deferred.resolve();
1987 _luci2.setHash('id', undefined);
1992 return state.deferred;
1996 state.form.find('.alert-message').show();
1998 state.form.find('.alert-message').hide();
2000 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2002 confirm: state.confirm_cb
2005 state.form.find('[name=password]').focus();
2007 return state.deferred;
2010 cryptPassword: _luci2.rpc.declare({
2014 expect: { crypt: '' }
2018 _acl_merge_scope: function(acl_scope, scope)
2020 if ($.isArray(scope))
2022 for (var i = 0; i < scope.length; i++)
2023 acl_scope[scope[i]] = true;
2025 else if ($.isPlainObject(scope))
2027 for (var object_name in scope)
2029 if (!$.isArray(scope[object_name]))
2032 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2034 for (var i = 0; i < scope[object_name].length; i++)
2035 acl_object[scope[object_name][i]] = true;
2040 _acl_merge_permission: function(acl_perm, perm)
2042 if ($.isPlainObject(perm))
2044 for (var scope_name in perm)
2046 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2047 this._acl_merge_scope(acl_scope, perm[scope_name]);
2052 _acl_merge_group: function(acl_group, group)
2054 if ($.isPlainObject(group))
2056 if (!acl_group.description)
2057 acl_group.description = group.description;
2061 var acl_perm = acl_group.read || (acl_group.read = { });
2062 this._acl_merge_permission(acl_perm, group.read);
2067 var acl_perm = acl_group.write || (acl_group.write = { });
2068 this._acl_merge_permission(acl_perm, group.write);
2073 _acl_merge_tree: function(acl_tree, tree)
2075 if ($.isPlainObject(tree))
2077 for (var group_name in tree)
2079 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2080 this._acl_merge_group(acl_group, tree[group_name]);
2085 listAvailableACLs: _luci2.rpc.declare({
2088 expect: { acls: [ ] },
2089 filter: function(trees) {
2091 for (var i = 0; i < trees.length; i++)
2092 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2097 renderMainMenu: _luci2.rpc.declare({
2100 expect: { menu: { } },
2101 filter: function(entries) {
2102 _luci2.globals.mainMenu = new _luci2.ui.menu();
2103 _luci2.globals.mainMenu.entries(entries);
2107 .append(_luci2.globals.mainMenu.render(0, 1));
2111 renderViewMenu: function()
2115 .append(_luci2.globals.mainMenu.render(2, 900));
2118 renderView: function(node)
2120 var name = node.view.split(/\//).join('.');
2122 if (_luci2.globals.currentView)
2123 _luci2.globals.currentView.finish();
2125 _luci2.ui.renderViewMenu();
2128 _luci2._views = { };
2130 _luci2.setHash('view', node.view);
2132 if (_luci2._views[name] instanceof _luci2.ui.view)
2134 _luci2.globals.currentView = _luci2._views[name];
2135 return _luci2._views[name].render();
2138 var url = _luci2.globals.resource + '/view/' + name + '.js';
2140 return $.ajax(url, {
2144 }).then(function(data) {
2146 var viewConstructorSource = (
2147 '(function(L, $) { ' +
2149 '})(_luci2, $);\n\n' +
2151 ).format(data, url);
2153 var viewConstructor = eval(viewConstructorSource);
2155 _luci2._views[name] = new viewConstructor({
2157 acls: node.write || { }
2160 _luci2.globals.currentView = _luci2._views[name];
2161 return _luci2._views[name].render();
2164 alert('Unable to instantiate view "%s": %s'.format(url, e));
2167 return $.Deferred().resolve();
2171 updateHostname: function()
2173 return _luci2.system.getBoardInfo().then(function(info) {
2175 $('#hostname').text(info.hostname);
2179 updateChanges: function()
2181 return _luci2.uci.changes().then(function(changes) {
2185 for (var config in changes)
2189 for (var i = 0; i < changes[config].length; i++)
2191 var c = changes[config][i];
2200 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2202 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2207 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2209 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2213 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2217 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2221 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2226 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2228 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2233 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2234 n += changes[config].length;
2245 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2246 .click(function(ev) {
2247 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2248 ev.preventDefault();
2258 _luci2.ui.loading(true);
2261 _luci2.ui.updateHostname(),
2262 _luci2.ui.updateChanges(),
2263 _luci2.ui.renderMainMenu()
2265 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2266 _luci2.ui.loading(false);
2272 var AbstractWidget = Class.extend({
2273 i18n: function(text) {
2277 toString: function() {
2278 var x = document.createElement('div');
2279 x.appendChild(this.render());
2284 insertInto: function(id) {
2285 return $(id).empty().append(this.render());
2289 this.ui.view = AbstractWidget.extend({
2290 _fetch_template: function()
2292 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2296 success: function(data) {
2297 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2298 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2305 return _luci2.tr(p2);
2308 return _luci2.globals[p2] || '';
2311 return '(?' + match + ')';
2315 $('#maincontent').append(data);
2322 throw "Not implemented";
2327 var container = $('#maincontent');
2332 container.append($('<h2 />').append(this.title));
2334 if (this.description)
2335 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2338 return this._fetch_template().then(function() {
2339 return _luci2.deferrable(self.execute());
2343 repeat: function(func, interval)
2347 if (!self._timeouts)
2348 self._timeouts = [ ];
2350 var index = self._timeouts.length;
2352 if (typeof(interval) != 'number')
2355 var setTimer, runTimer;
2357 setTimer = function() {
2358 self._timeouts[index] = window.setTimeout(runTimer, interval);
2361 runTimer = function() {
2362 _luci2.deferrable(func.call(self)).then(setTimer);
2370 if ($.isArray(this._timeouts))
2372 for (var i = 0; i < this._timeouts.length; i++)
2373 window.clearTimeout(this._timeouts[i]);
2375 delete this._timeouts;
2380 this.ui.menu = AbstractWidget.extend({
2385 entries: function(entries)
2387 for (var entry in entries)
2389 var path = entry.split(/\//);
2390 var node = this._nodes;
2392 for (i = 0; i < path.length; i++)
2397 if (!node.childs[path[i]])
2398 node.childs[path[i]] = { };
2400 node = node.childs[path[i]];
2403 $.extend(node, entries[entry]);
2407 _indexcmp: function(a, b)
2409 var x = a.index || 0;
2410 var y = b.index || 0;
2414 firstChildView: function(node)
2420 for (var child in (node.childs || { }))
2421 nodes.push(node.childs[child]);
2423 nodes.sort(this._indexcmp);
2425 for (var i = 0; i < nodes.length; i++)
2427 var child = this.firstChildView(nodes[i]);
2430 for (var key in child)
2431 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2432 node[key] = child[key];
2441 _onclick: function(ev)
2443 _luci2.ui.loading(true);
2444 _luci2.ui.renderView(ev.data).then(function() {
2445 _luci2.ui.loading(false);
2448 ev.preventDefault();
2452 _render: function(childs, level, min, max)
2455 for (var node in childs)
2457 var child = this.firstChildView(childs[node]);
2459 nodes.push(childs[node]);
2462 nodes.sort(this._indexcmp);
2464 var list = $('<ul />');
2467 list.addClass('nav');
2468 else if (level == 1)
2469 list.addClass('dropdown-menu');
2471 for (var i = 0; i < nodes.length; i++)
2473 if (!_luci2.globals.defaultNode)
2475 var v = _luci2.getHash('view');
2476 if (!v || v == nodes[i].view)
2477 _luci2.globals.defaultNode = nodes[i];
2480 var item = $('<li />')
2483 .text(_luci2.tr(nodes[i].title))
2484 .click(nodes[i], this._onclick))
2487 if (nodes[i].childs && level < max)
2489 item.addClass('dropdown');
2490 item.find('a').addClass('menu');
2491 item.append(this._render(nodes[i].childs, level + 1));
2498 render: function(min, max)
2500 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2501 return this._render(top.childs, 0, min, max);
2504 getNode: function(path, max)
2506 var p = path.split(/\//);
2507 var n = this._nodes;
2509 if (typeof(max) == 'undefined')
2512 for (var i = 0; i < max; i++)
2514 if (!n.childs[p[i]])
2524 this.ui.table = AbstractWidget.extend({
2530 row: function(values)
2532 if ($.isArray(values))
2534 this._rows.push(values);
2536 else if ($.isPlainObject(values))
2539 for (var i = 0; i < this.options.columns.length; i++)
2541 var col = this.options.columns[i];
2543 if (typeof col.key == 'string')
2544 v.push(values[col.key]);
2552 rows: function(rows)
2554 for (var i = 0; i < rows.length; i++)
2558 render: function(id)
2560 var fieldset = document.createElement('fieldset');
2561 fieldset.className = 'cbi-section';
2563 if (this.options.caption)
2565 var legend = document.createElement('legend');
2566 $(legend).append(this.options.caption);
2567 fieldset.appendChild(legend);
2570 var table = document.createElement('table');
2571 table.className = 'cbi-section-table';
2573 var has_caption = false;
2574 var has_description = false;
2576 for (var i = 0; i < this.options.columns.length; i++)
2577 if (this.options.columns[i].caption)
2582 else if (this.options.columns[i].description)
2584 has_description = true;
2590 var tr = table.insertRow(-1);
2591 tr.className = 'cbi-section-table-titles';
2593 for (var i = 0; i < this.options.columns.length; i++)
2595 var col = this.options.columns[i];
2596 var th = document.createElement('th');
2597 th.className = 'cbi-section-table-cell';
2602 th.style.width = col.width;
2605 th.style.textAlign = col.align;
2608 $(th).append(col.caption);
2612 if (has_description)
2614 var tr = table.insertRow(-1);
2615 tr.className = 'cbi-section-table-descr';
2617 for (var i = 0; i < this.options.columns.length; i++)
2619 var col = this.options.columns[i];
2620 var th = document.createElement('th');
2621 th.className = 'cbi-section-table-cell';
2626 th.style.width = col.width;
2629 th.style.textAlign = col.align;
2631 if (col.description)
2632 $(th).append(col.description);
2636 if (this._rows.length == 0)
2638 if (this.options.placeholder)
2640 var tr = table.insertRow(-1);
2641 var td = tr.insertCell(-1);
2642 td.className = 'cbi-section-table-cell';
2644 td.colSpan = this.options.columns.length;
2645 $(td).append(this.options.placeholder);
2650 for (var i = 0; i < this._rows.length; i++)
2652 var tr = table.insertRow(-1);
2654 for (var j = 0; j < this.options.columns.length; j++)
2656 var col = this.options.columns[j];
2657 var td = tr.insertCell(-1);
2659 var val = this._rows[i][j];
2661 if (typeof(val) == 'undefined')
2662 val = col.placeholder;
2664 if (typeof(val) == 'undefined')
2668 td.style.width = col.width;
2671 td.style.textAlign = col.align;
2673 if (typeof col.format == 'string')
2674 $(td).append(col.format.format(val));
2675 else if (typeof col.format == 'function')
2676 $(td).append(col.format(val, i));
2684 fieldset.appendChild(table);
2690 this.ui.progress = AbstractWidget.extend({
2693 var vn = parseInt(this.options.value) || 0;
2694 var mn = parseInt(this.options.max) || 100;
2695 var pc = Math.floor((100 / mn) * vn);
2697 var bar = document.createElement('div');
2698 bar.className = 'progressbar';
2700 bar.appendChild(document.createElement('div'));
2701 bar.lastChild.appendChild(document.createElement('div'));
2702 bar.lastChild.style.width = pc + '%';
2704 if (typeof(this.options.format) == 'string')
2705 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2706 else if (typeof(this.options.format) == 'function')
2707 $(bar.lastChild.lastChild).append(this.options.format(pc));
2709 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2715 this.ui.devicebadge = AbstractWidget.extend({
2718 var l2dev = this.options.l2_device || this.options.device;
2719 var l3dev = this.options.l3_device;
2720 var dev = l3dev || l2dev || '?';
2722 var span = document.createElement('span');
2723 span.className = 'ifacebadge';
2725 if (typeof(this.options.signal) == 'number' ||
2726 typeof(this.options.noise) == 'number')
2729 if (typeof(this.options.signal) != 'undefined' &&
2730 typeof(this.options.noise) != 'undefined')
2732 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2745 span.appendChild(document.createElement('img'));
2746 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2749 span.title = _luci2.tr('No signal');
2751 span.title = '%s: %d %s / %s: %d %s'.format(
2752 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2753 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2758 var type = 'ethernet';
2759 var desc = _luci2.tr('Ethernet device');
2764 desc = _luci2.tr('Tunnel interface');
2766 else if (dev.indexOf('br-') == 0)
2769 desc = _luci2.tr('Bridge');
2771 else if (dev.indexOf('.') > 0)
2774 desc = _luci2.tr('VLAN interface');
2776 else if (dev.indexOf('wlan') == 0 ||
2777 dev.indexOf('ath') == 0 ||
2778 dev.indexOf('wl') == 0)
2781 desc = _luci2.tr('Wireless Network');
2784 span.appendChild(document.createElement('img'));
2785 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2789 $(span).append(' ');
2790 $(span).append(dev);
2796 var type = function(f, l)
2806 _luci2.cbi.validation.message = _luci2.tr(msg);
2809 compile: function(code)
2814 var types = _luci2.cbi.validation.types;
2819 for (var i = 0; i < code.length; i++)
2827 switch (code.charCodeAt(i))
2839 var label = code.substring(pos, i);
2840 label = label.replace(/\\(.)/g, '$1');
2841 label = label.replace(/^[ \t]+/g, '');
2842 label = label.replace(/[ \t]+$/g, '');
2844 if (label && !isNaN(label))
2846 stack.push(parseFloat(label));
2848 else if (label.match(/^(['"]).*\1$/))
2850 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2852 else if (typeof types[label] == 'function')
2854 stack.push(types[label]);
2859 throw "Syntax error, unhandled token '"+label+"'";
2864 depth += (code.charCodeAt(i) == 40);
2870 if (typeof stack[stack.length-2] != 'function')
2871 throw "Syntax error, argument list follows non-function";
2873 stack[stack.length-1] =
2874 arguments.callee(code.substring(pos, i));
2887 var validation = this.cbi.validation;
2889 validation.types = {
2890 'integer': function()
2892 if (this.match(/^-?[0-9]+$/) != null)
2895 validation.i18n('Must be a valid integer');
2899 'uinteger': function()
2901 if (validation.types['integer'].apply(this) && (this >= 0))
2904 validation.i18n('Must be a positive integer');
2910 if (!isNaN(parseFloat(this)))
2913 validation.i18n('Must be a valid number');
2917 'ufloat': function()
2919 if (validation.types['float'].apply(this) && (this >= 0))
2922 validation.i18n('Must be a positive number');
2926 'ipaddr': function()
2928 if (validation.types['ip4addr'].apply(this) ||
2929 validation.types['ip6addr'].apply(this))
2932 validation.i18n('Must be a valid IP address');
2936 'ip4addr': function()
2938 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2940 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2941 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2942 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2943 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2944 ((RegExp.$6.indexOf('.') < 0)
2945 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2946 : (validation.types['ip4addr'].apply(RegExp.$6))))
2950 validation.i18n('Must be a valid IPv4 address');
2954 'ip6addr': function()
2956 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2958 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2960 var addr = RegExp.$1;
2967 if (addr.indexOf('.') > 0)
2969 var off = addr.lastIndexOf(':');
2971 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2973 validation.i18n('Must be a valid IPv6 address');
2977 addr = addr.substr(0, off) + ':0:0';
2980 if (addr.indexOf('::') >= 0)
2985 for (var i = 1; i < (addr.length-1); i++)
2986 if (addr.charAt(i) == ':')
2991 validation.i18n('Must be a valid IPv6 address');
2995 for (var i = 0; i < (7 - colons); i++)
2998 if (addr.match(/^(.*?)::(.*?)$/))
2999 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
3000 (RegExp.$2 ? ':' + RegExp.$2 : '');
3003 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3006 validation.i18n('Must be a valid IPv6 address');
3011 validation.i18n('Must be a valid IPv6 address');
3017 if (validation.types['integer'].apply(this) &&
3018 (this >= 0) && (this <= 65535))
3021 validation.i18n('Must be a valid port number');
3025 'portrange': function()
3027 if (this.match(/^(\d+)-(\d+)$/))
3032 if (validation.types['port'].apply(p1) &&
3033 validation.types['port'].apply(p2) &&
3034 (parseInt(p1) <= parseInt(p2)))
3037 else if (validation.types['port'].apply(this))
3042 validation.i18n('Must be a valid port range');
3046 'macaddr': function()
3048 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3051 validation.i18n('Must be a valid MAC address');
3057 if (validation.types['hostname'].apply(this) ||
3058 validation.types['ipaddr'].apply(this))
3061 validation.i18n('Must be a valid hostname or IP address');
3065 'hostname': function()
3067 if ((this.length <= 253) &&
3068 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3069 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3070 this.match(/[^0-9.]/)))))
3073 validation.i18n('Must be a valid host name');
3077 'network': function()
3079 if (validation.types['uciname'].apply(this) ||
3080 validation.types['host'].apply(this))
3083 validation.i18n('Must be a valid network name');
3087 'wpakey': function()
3091 if ((v.length == 64)
3092 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
3093 : ((v.length >= 8) && (v.length <= 63)))
3096 validation.i18n('Must be a valid WPA key');
3100 'wepkey': function()
3104 if (v.substr(0,2) == 's:')
3107 if (((v.length == 10) || (v.length == 26))
3108 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
3109 : ((v.length == 5) || (v.length == 13)))
3112 validation.i18n('Must be a valid WEP key');
3116 'uciname': function()
3118 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3121 validation.i18n('Must be a valid UCI identifier');
3125 'range': function(min, max)
3127 var val = parseFloat(this);
3129 if (validation.types['integer'].apply(this) &&
3130 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
3133 validation.i18n('Must be a number between %d and %d');
3137 'min': function(min)
3139 var val = parseFloat(this);
3141 if (validation.types['integer'].apply(this) &&
3142 !isNaN(min) && !isNaN(val) && (val >= min))
3145 validation.i18n('Must be a number greater or equal to %d');
3149 'max': function(max)
3151 var val = parseFloat(this);
3153 if (validation.types['integer'].apply(this) &&
3154 !isNaN(max) && !isNaN(val) && (val <= max))
3157 validation.i18n('Must be a number lower or equal to %d');
3161 'rangelength': function(min, max)
3163 var val = '' + this;
3165 if (!isNaN(min) && !isNaN(max) &&
3166 (val.length >= min) && (val.length <= max))
3169 validation.i18n('Must be between %d and %d characters');
3173 'minlength': function(min)
3175 var val = '' + this;
3177 if (!isNaN(min) && (val.length >= min))
3180 validation.i18n('Must be at least %d characters');
3184 'maxlength': function(max)
3186 var val = '' + this;
3188 if (!isNaN(max) && (val.length <= max))
3191 validation.i18n('Must be at most %d characters');
3199 for (var i = 0; i < arguments.length; i += 2)
3201 delete validation.message;
3203 if (typeof(arguments[i]) != 'function')
3205 if (arguments[i] == this)
3209 else if (arguments[i].apply(this, arguments[i+1]))
3214 if (validation.message)
3215 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3218 validation.message = msgs.join( _luci2.tr(' - or - '));
3226 for (var i = 0; i < arguments.length; i += 2)
3228 delete validation.message;
3230 if (typeof arguments[i] != 'function')
3232 if (arguments[i] != this)
3236 else if (!arguments[i].apply(this, arguments[i+1]))
3241 if (validation.message)
3242 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3245 validation.message = msgs.join(', ');
3251 return validation.types['or'].apply(
3252 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3255 'list': function(subvalidator, subargs)
3257 if (typeof subvalidator != 'function')
3260 var tokens = this.match(/[^ \t]+/g);
3261 for (var i = 0; i < tokens.length; i++)
3262 if (!subvalidator.apply(tokens[i], subargs))
3268 'phonedigit': function()
3270 if (this.match(/^[0-9\*#!\.]+$/) != null)
3273 validation.i18n('Must be a valid phone number digit');
3277 'string': function()
3284 this.cbi.AbstractValue = AbstractWidget.extend({
3285 init: function(name, options)
3288 this.instance = { };
3289 this.dependencies = [ ];
3290 this.rdependency = { };
3292 this.options = _luci2.defaults(options, {
3302 return this.section.id('field', sid || '__unknown__', this.name);
3305 render: function(sid)
3307 var i = this.instance[sid] = { };
3309 i.top = $('<div />').addClass('cbi-value');
3311 if (typeof(this.options.caption) == 'string')
3313 .addClass('cbi-value-title')
3314 .attr('for', this.id(sid))
3315 .text(this.options.caption)
3318 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
3319 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
3321 if (typeof(this.options.description) == 'string')
3323 .addClass('cbi-value-description')
3324 .text(this.options.description)
3330 ucipath: function(sid)
3333 config: (this.options.uci_package || this.map.uci_package),
3334 section: (this.options.uci_section || sid),
3335 option: (this.options.uci_option || this.name)
3339 ucivalue: function(sid)
3341 var uci = this.ucipath(sid);
3342 var val = this.map.get(uci.config, uci.section, uci.option);
3344 if (typeof(val) == 'undefined')
3345 return this.options.initial;
3350 formvalue: function(sid)
3352 var v = $('#' + this.id(sid)).val();
3353 return (v === '') ? undefined : v;
3356 textvalue: function(sid)
3358 var v = this.formvalue(sid);
3360 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3361 v = this.ucivalue(sid);
3363 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3364 v = this.options.placeholder;
3366 if (typeof(v) == 'undefined' || v === '')
3369 if (typeof(v) == 'string' && $.isArray(this.choices))
3371 for (var i = 0; i < this.choices.length; i++)
3372 if (v === this.choices[i][0])
3373 return this.choices[i][1];
3375 else if (v === true)
3376 return _luci2.tr('yes');
3377 else if (v === false)
3378 return _luci2.tr('no');
3379 else if ($.isArray(v))
3380 return v.join(', ');
3385 changed: function(sid)
3387 var a = this.ucivalue(sid);
3388 var b = this.formvalue(sid);
3390 if (typeof(a) != typeof(b))
3393 if (typeof(a) == 'object')
3395 if (a.length != b.length)
3398 for (var i = 0; i < a.length; i++)
3410 var uci = this.ucipath(sid);
3412 if (this.instance[sid].disabled)
3414 if (!this.options.keep)
3415 return this.map.set(uci.config, uci.section, uci.option, undefined);
3420 var chg = this.changed(sid);
3421 var val = this.formvalue(sid);
3424 this.map.set(uci.config, uci.section, uci.option, val);
3429 validator: function(sid, elem, multi)
3431 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3435 if (typeof(this.options.datatype) == 'string')
3438 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3441 else if (typeof(this.options.datatype) == 'function')
3443 var vfunc = this.options.datatype;
3444 vstack = [ function(elem) {
3445 var rv = vfunc(this, elem);
3447 validation.message = rv;
3448 return (rv === true);
3457 inst: this.instance[sid],
3458 opt: this.options.optional
3461 var validator = function(ev)
3465 var val = d.elem.val();
3467 if (vstack && typeof(vstack[0]) == 'function')
3469 delete validation.message;
3471 if ((val.length == 0 && !d.opt))
3473 d.elem.addClass('error');
3474 d.inst.top.addClass('error');
3475 d.inst.error.text(_luci2.tr('Field must not be empty'));
3478 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3480 d.elem.addClass('error');
3481 d.inst.top.addClass('error');
3482 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3487 d.elem.removeClass('error');
3489 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3495 d.inst.top.removeClass('error');
3496 d.inst.error.text('');
3503 for (var field in d.self.rdependency)
3504 d.self.rdependency[field].toggle(d.sid);
3510 if (elem.prop('tagName') == 'SELECT')
3512 elem.change(evdata, validator);
3514 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3516 elem.click(evdata, validator);
3517 elem.blur(evdata, validator);
3521 elem.keyup(evdata, validator);
3522 elem.blur(evdata, validator);
3525 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3530 validate: function(sid)
3532 var i = this.instance[sid];
3534 i.widget.find('[cbi-validate]').trigger('validate');
3536 return (i.disabled || i.error.text() == '');
3539 depends: function(d, v)
3546 for (var i = 0; i < d.length; i++)
3548 if (typeof(d[i]) == 'string')
3550 else if (d[i] instanceof _luci2.cbi.AbstractValue)
3551 dep[d[i].name] = true;
3554 else if (d instanceof _luci2.cbi.AbstractValue)
3557 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3559 else if (typeof(d) == 'object')
3563 else if (typeof(d) == 'string')
3566 dep[d] = (typeof(v) == 'undefined') ? true : v;
3569 if (!dep || $.isEmptyObject(dep))
3572 for (var field in dep)
3574 var f = this.section.fields[field];
3576 f.rdependency[this.name] = this;
3581 if ($.isEmptyObject(dep))
3584 this.dependencies.push(dep);
3589 toggle: function(sid)
3591 var d = this.dependencies;
3592 var i = this.instance[sid];
3597 for (var n = 0; n < d.length; n++)
3601 for (var field in d[n])
3603 var val = this.section.fields[field].formvalue(sid);
3604 var cmp = d[n][field];
3606 if (typeof(cmp) == 'boolean')
3608 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3614 else if (typeof(cmp) == 'string')
3622 else if (typeof(cmp) == 'function')
3630 else if (cmp instanceof RegExp)
3655 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3662 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
3663 widget: function(sid)
3665 var o = this.options;
3667 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3668 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3670 var i = $('<input />')
3671 .attr('id', this.id(sid))
3672 .attr('type', 'checkbox')
3673 .prop('checked', this.ucivalue(sid));
3675 return this.validator(sid, i);
3678 ucivalue: function(sid)
3680 var v = this.callSuper('ucivalue', sid);
3682 if (typeof(v) == 'boolean')
3685 return (v == this.options.enabled);
3688 formvalue: function(sid)
3690 var v = $('#' + this.id(sid)).prop('checked');
3692 if (typeof(v) == 'undefined')
3693 return !!this.options.initial;
3700 var uci = this.ucipath(sid);
3702 if (this.instance[sid].disabled)
3704 if (!this.options.keep)
3705 return this.map.set(uci.config, uci.section, uci.option, undefined);
3710 var chg = this.changed(sid);
3711 var val = this.formvalue(sid);
3715 if (this.options.optional && val == this.options.initial)
3716 this.map.set(uci.config, uci.section, uci.option, undefined);
3718 this.map.set(uci.config, uci.section, uci.option, val ? this.options.enabled : this.options.disabled);
3725 this.cbi.InputValue = this.cbi.AbstractValue.extend({
3726 widget: function(sid)
3728 var i = $('<input />')
3729 .attr('id', this.id(sid))
3730 .attr('type', 'text')
3731 .attr('placeholder', this.options.placeholder)
3732 .val(this.ucivalue(sid));
3734 return this.validator(sid, i);
3738 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
3739 widget: function(sid)
3741 var i = $('<input />')
3742 .attr('id', this.id(sid))
3743 .attr('type', 'password')
3744 .attr('placeholder', this.options.placeholder)
3745 .val(this.ucivalue(sid));
3747 var t = $('<img />')
3748 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3749 .attr('title', _luci2.tr('Reveal or hide password'))
3750 .addClass('cbi-button')
3751 .click(function(ev) {
3752 var i = $(this).prev();
3753 var t = i.attr('type');
3754 i.attr('type', (t == 'password') ? 'text' : 'password');
3758 this.validator(sid, i);
3761 .addClass('cbi-input-password')
3767 this.cbi.ListValue = this.cbi.AbstractValue.extend({
3768 widget: function(sid)
3770 var s = $('<select />');
3772 if (this.options.optional)
3775 .text(_luci2.tr('-- Please choose --'))
3779 for (var i = 0; i < this.choices.length; i++)
3781 .attr('value', this.choices[i][0])
3782 .text(this.choices[i][1])
3785 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3787 return this.validator(sid, s);
3790 value: function(k, v)
3795 this.choices.push([k, v || k]);
3800 this.cbi.MultiValue = this.cbi.ListValue.extend({
3801 widget: function(sid)
3803 var v = this.ucivalue(sid);
3804 var t = $('<div />').attr('id', this.id(sid));
3807 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3810 for (var i = 0; i < v.length; i++)
3814 for (var i = 0; i < this.choices.length; i++)
3817 .append($('<input />')
3818 .addClass('cbi-input-checkbox')
3819 .attr('type', 'checkbox')
3820 .attr('value', this.choices[i][0])
3821 .prop('checked', s[this.choices[i][0]]))
3822 .append(this.choices[i][1])
3832 formvalue: function(sid)
3835 var fields = $('#' + this.id(sid) + ' > label > input');
3837 for (var i = 0; i < fields.length; i++)
3838 if (fields[i].checked)
3839 rv.push(fields[i].getAttribute('value'));
3844 textvalue: function(sid)
3846 var v = this.formvalue(sid);
3850 for (var i = 0; i < this.choices.length; i++)
3851 c[this.choices[i][0]] = this.choices[i][1];
3855 for (var i = 0; i < v.length; i++)
3856 t.push(c[v[i]] || v[i]);
3858 return t.join(', ');
3862 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
3863 _change: function(ev)
3866 var self = ev.data.self;
3868 if (s.selectedIndex == (s.options.length - 1))
3870 ev.data.select.hide();
3871 ev.data.input.show().focus();
3873 var v = ev.data.input.val();
3874 ev.data.input.val(' ');
3875 ev.data.input.val(v);
3877 else if (self.options.optional && s.selectedIndex == 0)
3879 ev.data.input.val('');
3883 ev.data.input.val(ev.data.select.val());
3890 var val = this.value;
3891 var self = ev.data.self;
3893 ev.data.select.empty();
3895 if (self.options.optional)
3898 .text(_luci2.tr('-- please choose --'))
3899 .appendTo(ev.data.select);
3902 for (var i = 0; i < self.choices.length; i++)
3904 if (self.choices[i][0] == val)
3908 .attr('value', self.choices[i][0])
3909 .text(self.choices[i][1])
3910 .appendTo(ev.data.select);
3913 if (!seen && val != '')
3917 .appendTo(ev.data.select);
3921 .text(_luci2.tr('-- custom --'))
3922 .appendTo(ev.data.select);
3924 ev.data.input.hide();
3925 ev.data.select.val(val).show().focus();
3928 _enter: function(ev)
3933 ev.preventDefault();
3934 ev.data.self._blur(ev);
3938 widget: function(sid)
3940 var d = $('<div />')
3941 .attr('id', this.id(sid));
3943 var t = $('<input />')
3944 .attr('type', 'text')
3948 var s = $('<select />')
3953 input: this.validator(sid, t),
3954 select: this.validator(sid, s)
3957 s.change(evdata, this._change);
3958 t.blur(evdata, this._blur);
3959 t.keydown(evdata, this._enter);
3961 t.val(this.ucivalue(sid));
3967 value: function(k, v)
3972 this.choices.push([k, v || k]);
3976 formvalue: function(sid)
3978 var v = $('#' + this.id(sid)).children('input').val();
3979 return (v == '') ? undefined : v;
3983 this.cbi.DynamicList = this.cbi.ComboBox.extend({
3984 _redraw: function(focus, add, del, s)
3986 var v = s.values || [ ];
3989 $(s.parent).children('input').each(function(i) {
3991 v.push(this.value || '');
3994 $(s.parent).empty();
3999 v.splice(focus, 0, '');
4001 else if (v.length == 0)
4007 for (var i = 0; i < v.length; i++)
4018 var txt = $('<input />')
4019 .attr('type', 'text')
4021 .appendTo(s.parent);
4023 var sel = $('<select />')
4024 .appendTo(s.parent);
4026 evdata.input = this.validator(s.sid, txt, true);
4027 evdata.select = this.validator(s.sid, sel, true);
4029 sel.change(evdata, this._change);
4030 txt.blur(evdata, this._blur);
4031 txt.keydown(evdata, this._keydown);
4036 if (i == focus || -(i+1) == focus)
4043 var f = $('<input />')
4044 .attr('type', 'text')
4046 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
4047 .addClass('cbi-input-text')
4048 .keydown(evdata, this._keydown)
4049 .keypress(evdata, this._keypress)
4052 f.appendTo(s.parent);
4058 else if (-(i+1) == focus)
4062 /* force cursor to end */
4068 evdata.input = this.validator(s.sid, f, true);
4074 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
4075 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
4076 .addClass('cbi-button')
4077 .click(evdata, this._btnclick)
4078 .appendTo(s.parent);
4081 .appendTo(s.parent);
4089 _keypress: function(ev)
4093 /* backspace, delete */
4096 if (ev.data.input.val() == '')
4098 ev.preventDefault();
4104 /* enter, arrow up, arrow down */
4108 ev.preventDefault();
4115 _keydown: function(ev)
4117 var input = ev.data.input;
4121 /* backspace, delete */
4124 if (input.val().length == 0)
4126 ev.preventDefault();
4128 var index = ev.data.index;
4134 ev.data.self._redraw(focus, -1, index, ev.data);
4142 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4147 var prev = input.prevAll('input:first');
4148 if (prev.is(':visible'))
4151 prev.next('select').focus();
4156 var next = input.nextAll('input:first');
4157 if (next.is(':visible'))
4160 next.next('select').focus();
4167 _btnclick: function(ev)
4169 if (!this.getAttribute('disabled'))
4171 if (ev.target.src.indexOf('remove') > -1)
4173 var index = ev.data.index;
4174 ev.data.self._redraw(-index, -1, index, ev.data);
4178 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4185 widget: function(sid)
4187 this.options.optional = true;
4189 var v = this.ucivalue(sid);
4192 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4194 var d = $('<div />')
4195 .attr('id', this.id(sid))
4196 .addClass('cbi-input-dynlist');
4198 this._redraw(NaN, -1, -1, {
4208 ucivalue: function(sid)
4210 var v = this.callSuper('ucivalue', sid);
4213 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4218 formvalue: function(sid)
4221 var fields = $('#' + this.id(sid) + ' > input');
4223 for (var i = 0; i < fields.length; i++)
4224 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4225 rv.push(fields[i].value);
4231 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4232 widget: function(sid)
4235 .addClass('cbi-value-dummy')
4236 .attr('id', this.id(sid))
4237 .html(this.ucivalue(sid));
4240 formvalue: function(sid)
4242 return this.ucivalue(sid);
4246 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4251 if (!self.interfaces)
4253 self.interfaces = [ ];
4254 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4255 self.interfaces = ifaces;
4263 _device_icon: function(dev)
4265 var type = 'ethernet';
4266 var desc = _luci2.tr('Ethernet device');
4268 if (dev.type == 'IP tunnel')
4271 desc = _luci2.tr('Tunnel interface');
4273 else if (dev['bridge-members'])
4276 desc = _luci2.tr('Bridge');
4278 else if (dev.wireless)
4281 desc = _luci2.tr('Wireless Network');
4283 else if (dev.device.indexOf('.') > 0)
4286 desc = _luci2.tr('VLAN interface');
4290 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4291 .attr('title', '%s (%s)'.format(desc, dev.device));
4294 widget: function(sid)
4296 var id = this.id(sid);
4297 var ul = $('<ul />')
4299 .addClass('cbi-input-networks');
4301 var itype = this.options.multiple ? 'checkbox' : 'radio';
4302 var value = this.ucivalue(sid);
4305 if (!this.options.multiple)
4306 check[value] = true;
4308 for (var i = 0; i < value.length; i++)
4309 check[value[i]] = true;
4311 if (this.interfaces)
4313 for (var i = 0; i < this.interfaces.length; i++)
4315 var iface = this.interfaces[i];
4316 var badge = $('<span />')
4317 .addClass('ifacebadge')
4318 .text('%s: '.format(iface['interface']));
4320 if (iface.device && iface.device.subdevices)
4321 for (var j = 0; j < iface.device.subdevices.length; j++)
4322 badge.append(this._device_icon(iface.device.subdevices[j]));
4323 else if (iface.device)
4324 badge.append(this._device_icon(iface.device));
4326 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4329 .append($('<label />')
4330 .append($('<input />')
4331 .attr('name', itype + id)
4332 .attr('type', itype)
4333 .attr('value', iface['interface'])
4334 .prop('checked', !!check[iface['interface']])
4335 .addClass('cbi-input-' + itype))
4341 if (!this.options.multiple)
4344 .append($('<label />')
4345 .append($('<input />')
4346 .attr('name', itype + id)
4347 .attr('type', itype)
4349 .prop('checked', !value)
4350 .addClass('cbi-input-' + itype))
4351 .append(_luci2.tr('unspecified')))
4358 ucivalue: function(sid)
4360 var v = this.callSuper('ucivalue', sid);
4362 if (!this.options.multiple)
4368 else if (typeof(v) == 'string')
4371 return v ? v[0] : undefined;
4378 if (typeof(v) == 'string')
4379 v = v.match(/\S+/g);
4385 formvalue: function(sid)
4387 var inputs = $('#' + this.id(sid) + ' input');
4389 if (!this.options.multiple)
4391 for (var i = 0; i < inputs.length; i++)
4392 if (inputs[i].checked && inputs[i].value !== '')
4393 return inputs[i].value;
4400 for (var i = 0; i < inputs.length; i++)
4401 if (inputs[i].checked)
4402 rv.push(inputs[i].value);
4404 return rv.length ? rv : undefined;
4409 this.cbi.AbstractSection = AbstractWidget.extend({
4412 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4414 for (var i = 1; i < arguments.length; i++)
4415 s.push(arguments[i].replace(/\./g, '_'));
4420 option: function(widget, name, options)
4422 if (this.tabs.length == 0)
4423 this.tab({ id: '__default__', selected: true });
4425 return this.taboption('__default__', widget, name, options);
4428 tab: function(options)
4430 if (options.selected)
4431 this.tabs.selected = this.tabs.length;
4435 caption: options.caption,
4436 description: options.description,
4442 taboption: function(tabid, widget, name, options)
4445 for (var i = 0; i < this.tabs.length; i++)
4447 if (this.tabs[i].id == tabid)
4455 throw 'Cannot append to unknown tab ' + tabid;
4457 var w = widget ? new widget(name, options) : null;
4459 if (!(w instanceof _luci2.cbi.AbstractValue))
4460 throw 'Widget must be an instance of AbstractValue';
4465 this.fields[name] = w;
4471 ucipackages: function(pkg)
4473 for (var i = 0; i < this.tabs.length; i++)
4474 for (var j = 0; j < this.tabs[i].fields.length; j++)
4475 if (this.tabs[i].fields[j].options.uci_package)
4476 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4479 formvalue: function()
4483 this.sections(function(s) {
4484 var sid = s['.name'];
4485 var sv = rv[sid] || (rv[sid] = { });
4487 for (var i = 0; i < this.tabs.length; i++)
4488 for (var j = 0; j < this.tabs[i].fields.length; j++)
4490 var val = this.tabs[i].fields[j].formvalue(sid);
4491 sv[this.tabs[i].fields[j].name] = val;
4498 validate: function(sid)
4504 var as = this.sections();
4505 for (var i = 0; i < as.length; i++)
4506 if (!this.validate(as[i]['.name']))
4511 var inst = this.instance[sid];
4512 var sv = rv[sid] || (rv[sid] = { });
4515 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4517 legend.children('span').detach();
4519 for (var i = 0; i < this.tabs.length; i++)
4522 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4524 tab.children('span').detach();
4526 for (var j = 0; j < this.tabs[i].fields.length; j++)
4527 if (!this.tabs[i].fields[j].validate(sid))
4534 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4547 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4555 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
4556 init: function(uci_type, options)
4558 this.uci_type = uci_type;
4559 this.options = options;
4562 this.active_panel = 0;
4563 this.active_tab = { };
4566 filter: function(section)
4571 sections: function(cb)
4573 var s1 = this.map.ucisections(this.map.uci_package);
4576 for (var i = 0; i < s1.length; i++)
4577 if (s1[i]['.type'] == this.uci_type)
4578 if (this.filter(s1[i]))
4581 if (typeof(cb) == 'function')
4582 for (var i = 0; i < s2.length; i++)
4583 cb.apply(this, [ s2[i] ]);
4590 this.map.add(this.map.uci_package, this.uci_type, name);
4593 remove: function(sid)
4595 this.map.remove(this.map.uci_package, sid);
4601 var name = undefined;
4602 var self = ev.data.self;
4604 if (addb.prev().prop('nodeName') == 'INPUT')
4605 name = addb.prev().val();
4607 if (addb.prop('disabled') || name === '')
4610 _luci2.ui.saveScrollTop();
4612 self.active_panel = -1;
4617 _luci2.ui.restoreScrollTop();
4620 _remove: function(ev)
4622 var self = ev.data.self;
4623 var sid = ev.data.sid;
4625 if (ev.data.index == (self.sections().length - 1))
4626 self.active_panel = -1;
4628 _luci2.ui.saveScrollTop();
4634 _luci2.ui.restoreScrollTop();
4636 ev.stopPropagation();
4641 var self = ev.data.self;
4643 var addb = text.next();
4644 var errt = addb.next();
4645 var name = text.val();
4648 if (!/^[a-zA-Z0-9_]*$/.test(name))
4650 errt.text(_luci2.tr('Invalid section name')).show();
4651 text.addClass('error');
4652 addb.prop('disabled', true);
4656 for (var sid in self.map.uci.values[self.map.uci_package])
4663 for (var sid in self.map.uci.creates[self.map.uci_package])
4672 errt.text(_luci2.tr('Name already used')).show();
4673 text.addClass('error');
4674 addb.prop('disabled', true);
4678 errt.text('').hide();
4679 text.removeClass('error');
4680 addb.prop('disabled', false);
4684 teaser: function(sid)
4686 var tf = this.teaser_fields;
4690 tf = this.teaser_fields = [ ];
4692 if ($.isArray(this.options.teasers))
4694 for (var i = 0; i < this.options.teasers.length; i++)
4696 var f = this.options.teasers[i];
4697 if (f instanceof _luci2.cbi.AbstractValue)
4699 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
4700 tf.push(this.fields[f]);
4705 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4706 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4707 tf.push(this.tabs[i].fields[j]);
4713 for (var i = 0; i < tf.length; i++)
4715 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4718 var n = tf[i].options.caption || tf[i].name;
4719 var v = tf[i].textvalue(sid);
4721 if (typeof(v) == 'undefined')
4724 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4730 _render_add: function()
4732 var text = _luci2.tr('Add section');
4733 var ttip = _luci2.tr('Create new section...');
4735 if ($.isArray(this.options.add_caption))
4736 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4737 else if (typeof(this.options.add_caption) == 'string')
4738 text = this.options.add_caption, ttip = '';
4740 var add = $('<div />').addClass('cbi-section-add');
4742 if (this.options.anonymous === false)
4745 .addClass('cbi-input-text')
4746 .attr('type', 'text')
4747 .attr('placeholder', ttip)
4748 .blur({ self: this }, this._sid)
4749 .keyup({ self: this }, this._sid)
4753 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4754 .attr('title', text)
4755 .addClass('cbi-button')
4756 .click({ self: this }, this._add)
4760 .addClass('cbi-value-error')
4767 .attr('type', 'button')
4768 .addClass('cbi-button')
4769 .addClass('cbi-button-add')
4770 .val(text).attr('title', ttip)
4771 .click({ self: this }, this._add)
4778 _render_remove: function(sid, index)
4780 var text = _luci2.tr('Remove');
4781 var ttip = _luci2.tr('Remove this section');
4783 if ($.isArray(this.options.remove_caption))
4784 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4785 else if (typeof(this.options.remove_caption) == 'string')
4786 text = this.options.remove_caption, ttip = '';
4788 return $('<input />')
4789 .attr('type', 'button')
4790 .addClass('cbi-button')
4791 .addClass('cbi-button-remove')
4792 .val(text).attr('title', ttip)
4793 .click({ self: this, sid: sid, index: index }, this._remove);
4796 _render_caption: function(sid)
4798 if (typeof(this.options.caption) == 'string')
4800 return $('<legend />')
4801 .text(this.options.caption.format(sid));
4803 else if (typeof(this.options.caption) == 'function')
4805 return $('<legend />')
4806 .text(this.options.caption.call(this, sid));
4814 var allsections = $();
4815 var panel_index = 0;
4817 this.instance = { };
4819 var s = this.sections();
4823 var fieldset = $('<fieldset />')
4824 .addClass('cbi-section');
4826 var head = $('<div />')
4827 .addClass('cbi-section-head')
4828 .appendTo(fieldset);
4830 head.append(this._render_caption(undefined));
4832 if (typeof(this.options.description) == 'string')
4835 .addClass('cbi-section-descr')
4836 .text(this.options.description)
4840 allsections = allsections.add(fieldset);
4843 for (var i = 0; i < s.length; i++)
4845 var sid = s[i]['.name'];
4846 var inst = this.instance[sid] = { tabs: [ ] };
4848 var fieldset = $('<fieldset />')
4849 .attr('id', this.id('sort', sid))
4850 .addClass('cbi-section');
4852 var head = $('<div />')
4853 .addClass('cbi-section-head')
4854 .attr('cbi-section-num', this.index)
4855 .attr('cbi-section-id', sid);
4857 head.append(this._render_caption(sid));
4859 if (typeof(this.options.description) == 'string')
4862 .addClass('cbi-section-descr')
4863 .text(this.options.description)
4868 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4869 teaser = $('<div />')
4870 .addClass('cbi-section-teaser')
4873 if (this.options.addremove)
4875 .addClass('cbi-section-remove')
4877 .append(this._render_remove(sid, panel_index))
4880 var body = $('<div />')
4881 .attr('index', panel_index++);
4883 var fields = $('<fieldset />')
4884 .addClass('cbi-section-node');
4886 if (this.tabs.length > 1)
4888 var menu = $('<ul />')
4889 .addClass('cbi-tabmenu');
4891 for (var j = 0; j < this.tabs.length; j++)
4893 var tabid = this.id('tab', sid, this.tabs[j].id);
4894 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4896 var tabc = $('<div />')
4897 .addClass('cbi-tabcontainer')
4901 if (typeof(this.tabs[j].description) == 'string')
4904 .addClass('cbi-tab-descr')
4905 .text(this.tabs[j].description)
4909 for (var k = 0; k < this.tabs[j].fields.length; k++)
4910 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4912 tabc.appendTo(fields);
4915 $('<li />').attr('id', theadid).append(
4917 .text(this.tabs[j].caption.format(this.tabs[j].id))
4918 .attr('href', '#' + tabid)
4922 menu.appendTo(body);
4925 fields.appendTo(body);
4928 var t = body.tabs({ active: this.active_tab[sid] });
4930 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4933 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4938 for (var j = 0; j < this.tabs[0].fields.length; j++)
4939 this.tabs[0].fields[j].render(sid).appendTo(fields);
4941 fields.appendTo(body);
4945 head.appendTo(fieldset);
4948 body.appendTo(fieldset);
4951 allsections = allsections.add(fieldset);
4954 //this.validate(sid);
4957 // teaser.append(this.teaser(sid));
4960 if (this.options.collabsible && s.length > 1)
4962 var a = $('<div />').append(allsections).accordion({
4963 header: '> fieldset > div.cbi-section-head',
4964 heightStyle: 'content',
4965 active: this.active_panel
4968 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4969 var h = ui.oldHeader;
4970 var s = ev.data.self;
4971 var i = h.attr('cbi-section-id');
4973 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4977 a.on('accordionactivate', { self: this }, function(ev, ui) {
4978 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4981 if (this.options.sortable)
4983 var s = a.sortable({
4985 handle: 'div.cbi-section-head'
4988 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4990 for (var i = 0; i < ev.data.ids.length; i++)
4991 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4992 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4995 s.on('sortstop', function(ev, ui) {
4996 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
5000 if (this.options.addremove)
5001 this._render_add().appendTo(a);
5006 if (this.options.addremove)
5007 allsections = allsections.add(this._render_add());
5014 var s = this.sections();
5016 for (var i = 0; i < s.length; i++)
5018 var sid = s[i]['.name'];
5022 $('#' + this.id('sort', sid))
5023 .children('.cbi-section-head')
5024 .children('.cbi-section-teaser')
5025 .append(this.teaser(sid));
5030 this.cbi.TableSection = this.cbi.TypedSection.extend({
5033 var allsections = $();
5034 var panel_index = 0;
5036 this.instance = { };
5038 var s = this.sections();
5040 var fieldset = $('<fieldset />')
5041 .addClass('cbi-section');
5043 fieldset.append(this._render_caption(sid));
5045 if (typeof(this.options.description) == 'string')
5048 .addClass('cbi-section-descr')
5049 .text(this.options.description)
5050 .appendTo(fieldset);
5053 var fields = $('<div />')
5054 .addClass('cbi-section-node')
5055 .appendTo(fieldset);
5057 var table = $('<table />')
5058 .addClass('cbi-section-table')
5061 var thead = $('<thead />')
5062 .append($('<tr />').addClass('cbi-section-table-titles'))
5065 for (var j = 0; j < this.tabs[0].fields.length; j++)
5067 .addClass('cbi-section-table-cell')
5068 .css('width', this.tabs[0].fields[j].options.width || '')
5069 .append(this.tabs[0].fields[j].options.caption)
5070 .appendTo(thead.children());
5072 if (this.options.sortable)
5073 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
5075 if (this.options.addremove !== false)
5076 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
5078 var tbody = $('<tbody />')
5084 .addClass('cbi-section-table-row')
5087 .addClass('cbi-section-table-cell')
5088 .addClass('cbi-section-table-placeholder')
5089 .attr('colspan', thead.children().children().length)
5090 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
5094 for (var i = 0; i < s.length; i++)
5096 var sid = s[i]['.name'];
5097 var inst = this.instance[sid] = { tabs: [ ] };
5099 var row = $('<tr />')
5100 .addClass('cbi-section-table-row')
5103 for (var j = 0; j < this.tabs[0].fields.length; j++)
5106 .addClass('cbi-section-table-cell')
5107 .css('width', this.tabs[0].fields[j].options.width || '')
5108 .append(this.tabs[0].fields[j].render(sid, true))
5112 if (this.options.sortable)
5115 .addClass('cbi-section-table-cell')
5116 .addClass('cbi-section-table-sort')
5117 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
5118 .append($('<br />'))
5119 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
5123 if (this.options.addremove !== false)
5126 .addClass('cbi-section-table-cell')
5127 .append(this._render_remove(sid))
5136 if (this.options.sortable)
5138 var s = tbody.sortable({
5139 handle: 'td.cbi-section-table-sort'
5142 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
5144 for (var i = 0; i < ev.data.ids.length; i++)
5145 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
5146 _luci2.uci.order(ev.data.self.map.uci_package, sections);
5149 s.on('sortstop', function(ev, ui) {
5150 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
5154 if (this.options.addremove)
5155 this._render_add().appendTo(fieldset);
5157 fields = table = thead = tbody = null;
5163 this.cbi.NamedSection = this.cbi.TypedSection.extend({
5164 sections: function(cb)
5167 var pkg = this.map.uci.values[this.map.uci_package];
5170 if (pkg[s]['.name'] == this.uci_type)
5176 if (typeof(cb) == 'function' && sa.length > 0)
5177 cb.apply(this, [ sa[0] ]);
5183 this.cbi.DummySection = this.cbi.TypedSection.extend({
5184 sections: function(cb)
5186 if (typeof(cb) == 'function')
5187 cb.apply(this, [ { '.name': this.uci_type } ]);
5189 return [ { '.name': this.uci_type } ];
5193 this.cbi.Map = AbstractWidget.extend({
5194 init: function(uci_package, options)
5198 this.uci_package = uci_package;
5199 this.sections = [ ];
5200 this.options = _luci2.defaults(options, {
5201 save: function() { },
5202 prepare: function() {
5203 return _luci2.uci.writable(function(writable) {
5204 self.options.readonly = !writable;
5220 if (typeof(this.active_panel) == 'undefined')
5221 this.active_panel = 0;
5225 for (var i = 0; i < this.sections.length; i++)
5226 this.sections[i].ucipackages(packages);
5228 packages[this.uci_package] = true;
5230 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
5231 for (var i = 0; i < packages.length; i++)
5233 this.uci.values[packages[i]['.package']] = packages[i];
5234 delete packages[i]['.package'];
5237 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5239 for (var i = 0; i < this.sections.length; i++)
5241 for (var f in this.sections[i].fields)
5243 if (typeof(this.sections[i].fields[f].load) != 'function')
5246 var s = this.sections[i].sections();
5247 for (var j = 0; j < s.length; j++)
5249 var rv = this.sections[i].fields[f].load(s[j]['.name']);
5250 if (_luci2.isDeferred(rv))
5256 return $.when.apply($, deferreds);
5261 for (var pkg in packages)
5262 _luci2.uci.get_all(pkg);
5264 return _luci2.rpc.flush().then(load_cb);
5269 var map = $('<div />').addClass('cbi-map');
5271 if (typeof(this.options.caption) == 'string')
5272 $('<h2 />').text(this.options.caption).appendTo(map);
5274 if (typeof(this.options.description) == 'string')
5275 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
5277 var sections = $('<div />').appendTo(map);
5279 for (var i = 0; i < this.sections.length; i++)
5281 var s = this.sections[i].render();
5283 if (this.options.readonly || this.sections[i].options.readonly)
5284 s.find('input, select, button, img.cbi-button').attr('disabled', true);
5286 s.appendTo(sections);
5288 if (this.sections[i].options.active)
5289 this.active_panel = i;
5292 if (this.options.collabsible)
5294 var a = sections.accordion({
5295 header: '> fieldset > div.cbi-section-head',
5296 heightStyle: 'content',
5297 active: this.active_panel
5300 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
5301 var h = ui.oldHeader;
5302 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
5303 var i = h.attr('cbi-section-id');
5305 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
5307 for (var i = 0; i < ev.data.self.sections.length; i++)
5308 ev.data.self.sections[i].validate();
5311 a.on('accordionactivate', { self: this }, function(ev, ui) {
5312 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
5316 if (this.options.pageaction !== false)
5318 var a = $('<div />')
5319 .addClass('cbi-page-actions')
5323 .addClass('cbi-button').addClass('cbi-button-apply')
5324 .attr('type', 'button')
5325 .val(_luci2.tr('Save & Apply'))
5329 .addClass('cbi-button').addClass('cbi-button-save')
5330 .attr('type', 'button')
5331 .val(_luci2.tr('Save'))
5332 .click({ self: this }, function(ev) { ev.data.self.send(); })
5336 .addClass('cbi-button').addClass('cbi-button-reset')
5337 .attr('type', 'button')
5338 .val(_luci2.tr('Reset'))
5339 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
5345 var top = $('<form />').append(map);
5354 for (var i = 0; i < this.sections.length; i++)
5355 this.sections[i].finish();
5362 this.target.hide().empty().append(this.render());
5367 section: function(widget, uci_type, options)
5369 var w = widget ? new widget(uci_type, options) : null;
5371 if (!(w instanceof _luci2.cbi.AbstractSection))
5372 throw 'Widget must be an instance of AbstractSection';
5375 w.index = this.sections.length;
5377 this.sections.push(w);
5381 formvalue: function()
5385 for (var i = 0; i < this.sections.length; i++)
5387 var sids = this.sections[i].formvalue();
5388 for (var sid in sids)
5390 var s = rv[sid] || (rv[sid] = { });
5391 $.extend(s, sids[sid]);
5398 add: function(conf, type, name)
5400 var c = this.uci.creates;
5401 var s = '.new.%d'.format(this.uci.newid++);
5416 remove: function(conf, sid)
5418 var n = this.uci.creates;
5419 var c = this.uci.changes;
5420 var d = this.uci.deletes;
5422 /* requested deletion of a just created section */
5423 if (sid.indexOf('.new.') == 0)
5426 delete n[conf][sid];
5431 delete c[conf][sid];
5436 d[conf][sid] = true;
5440 ucisections: function(conf, cb)
5443 var pkg = this.uci.values[conf];
5444 var crt = this.uci.creates[conf];
5445 var del = this.uci.deletes[conf];
5451 if (!del || del[s] !== true)
5454 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5460 if (typeof(cb) == 'function')
5461 for (var i = 0; i < sa.length; i++)
5462 cb.apply(this, [ sa[i] ]);
5467 get: function(conf, sid, opt)
5469 var v = this.uci.values;
5470 var n = this.uci.creates;
5471 var c = this.uci.changes;
5472 var d = this.uci.deletes;
5474 /* requested option in a just created section */
5475 if (sid.indexOf('.new.') == 0)
5480 if (typeof(opt) == 'undefined')
5481 return (n[conf][sid] || { });
5483 return n[conf][sid][opt];
5486 /* requested an option value */
5487 if (typeof(opt) != 'undefined')
5489 /* check whether option was deleted */
5490 if (d[conf] && d[conf][sid])
5492 if (d[conf][sid] === true)
5495 for (var i = 0; i < d[conf][sid].length; i++)
5496 if (d[conf][sid][i] == opt)
5500 /* check whether option was changed */
5501 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5502 return c[conf][sid][opt];
5504 /* return base value */
5505 if (v[conf] && v[conf][sid])
5506 return v[conf][sid][opt];
5511 /* requested an entire section */
5513 return (v[conf][sid] || { });
5518 set: function(conf, sid, opt, val)
5520 var n = this.uci.creates;
5521 var c = this.uci.changes;
5522 var d = this.uci.deletes;
5524 if (sid.indexOf('.new.') == 0)
5526 if (n[conf] && n[conf][sid])
5528 if (typeof(val) != 'undefined')
5529 n[conf][sid][opt] = val;
5531 delete n[conf][sid][opt];
5534 else if (typeof(val) != 'undefined')
5542 c[conf][sid][opt] = val;
5552 d[conf][sid].push(opt);
5556 validate: function()
5560 for (var i = 0; i < this.sections.length; i++)
5561 if (!this.sections[i].validate())
5569 if (this.options.readonly)
5570 return _luci2.deferrable();
5572 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5574 for (var i = 0; i < this.sections.length; i++)
5576 if (this.sections[i].options.readonly)
5579 for (var f in this.sections[i].fields)
5581 if (typeof(this.sections[i].fields[f].save) != 'function')
5584 var s = this.sections[i].sections();
5585 for (var j = 0; j < s.length; j++)
5587 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5588 if (_luci2.isDeferred(rv))
5594 return $.when.apply($, deferreds);
5599 if (!this.validate())
5600 return _luci2.deferrable();
5602 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5605 if (this.uci.creates)
5606 for (var c in this.uci.creates)
5607 for (var s in this.uci.creates[c])
5614 for (var k in this.uci.creates[c][s])
5617 r.type = this.uci.creates[c][s][k];
5618 else if (k == '.create')
5619 r.name = this.uci.creates[c][s][k];
5620 else if (k.charAt(0) != '.')
5621 r.values[k] = this.uci.creates[c][s][k];
5624 _luci2.uci.add(r.config, r.type, r.name, r.values);
5627 if (this.uci.changes)
5628 for (var c in this.uci.changes)
5629 for (var s in this.uci.changes[c])
5630 _luci2.uci.set(c, s, this.uci.changes[c][s]);
5632 if (this.uci.deletes)
5633 for (var c in this.uci.deletes)
5634 for (var s in this.uci.deletes[c])
5636 var o = this.uci.deletes[c][s];
5637 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
5640 return _luci2.rpc.flush().then(function() {
5641 return _luci2.ui.updateChanges();
5647 _luci2.ui.saveScrollTop();
5648 _luci2.ui.loading(true);
5650 return this.save().then(send_cb).then(function() {
5652 }).then(function() {
5656 _luci2.ui.loading(false);
5657 _luci2.ui.restoreScrollTop();
5661 insertInto: function(id)
5664 self.target = $(id);
5666 _luci2.ui.loading(true);
5669 return self.load().then(function() {
5670 self.target.empty().append(self.render());
5674 _luci2.ui.loading(false);