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 } }
953 listDeviceNames: _luci2.rpc.declare({
956 expect: { 'devices': [ ] },
957 filter: function(data) {
963 getDeviceStatus: _luci2.rpc.declare({
966 params: [ 'device' ],
968 filter: function(data, params) {
969 if (!$.isEmptyObject(data))
971 data['device'] = params['device'];
978 getAssocList: _luci2.rpc.declare({
981 params: [ 'device' ],
982 expect: { results: [ ] },
983 filter: function(data, params) {
984 for (var i = 0; i < data.length; i++)
985 data[i]['device'] = params['device'];
987 data.sort(function(a, b) {
988 if (a.bssid < b.bssid)
990 else if (a.bssid > b.bssid)
1000 getWirelessStatus: function() {
1001 return this.listDeviceNames().then(function(names) {
1004 for (var i = 0; i < names.length; i++)
1005 _luci2.wireless.getDeviceStatus(names[i]);
1007 return _luci2.rpc.flush();
1008 }).then(function(networks) {
1012 'country', 'channel', 'frequency', 'frequency_offset',
1013 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1017 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1018 'signal', 'noise', 'bitrate', 'encryption'
1021 for (var i = 0; i < networks.length; i++)
1023 var phy = rv[networks[i].phy] || (
1024 rv[networks[i].phy] = { networks: [ ] }
1028 device: networks[i].device
1031 for (var j = 0; j < phy_attrs.length; j++)
1032 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1034 for (var j = 0; j < net_attrs.length; j++)
1035 net[net_attrs[j]] = networks[i][net_attrs[j]];
1037 phy.networks.push(net);
1044 getAssocLists: function()
1046 return this.listDeviceNames().then(function(names) {
1049 for (var i = 0; i < names.length; i++)
1050 _luci2.wireless.getAssocList(names[i]);
1052 return _luci2.rpc.flush();
1053 }).then(function(assoclists) {
1056 for (var i = 0; i < assoclists.length; i++)
1057 for (var j = 0; j < assoclists[i].length; j++)
1058 rv.push(assoclists[i][j]);
1064 formatEncryption: function(enc)
1066 var format_list = function(l, s)
1069 for (var i = 0; i < l.length; i++)
1070 rv.push(l[i].toUpperCase());
1071 return rv.join(s ? s : ', ');
1074 if (!enc || !enc.enabled)
1075 return _luci2.tr('None');
1079 if (enc.wep.length == 2)
1080 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1081 else if (enc.wep[0] == 'shared')
1082 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1084 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1088 if (enc.wpa.length == 2)
1089 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1090 format_list(enc.authentication, '/'),
1091 format_list(enc.ciphers, ', ')
1093 else if (enc.wpa[0] == 2)
1094 return 'WPA2 %s (%s)'.format(
1095 format_list(enc.authentication, '/'),
1096 format_list(enc.ciphers, ', ')
1099 return 'WPA %s (%s)'.format(
1100 format_list(enc.authentication, '/'),
1101 format_list(enc.ciphers, ', ')
1105 return _luci2.tr('Unknown');
1110 getSystemInfo: _luci2.rpc.declare({
1116 getBoardInfo: _luci2.rpc.declare({
1122 getDiskInfo: _luci2.rpc.declare({
1123 object: 'luci2.system',
1128 getInfo: function(cb)
1132 this.getSystemInfo();
1133 this.getBoardInfo();
1136 return _luci2.rpc.flush().then(function(info) {
1139 $.extend(rv, info[0]);
1140 $.extend(rv, info[1]);
1141 $.extend(rv, info[2]);
1147 getProcessList: _luci2.rpc.declare({
1148 object: 'luci2.system',
1149 method: 'process_list',
1150 expect: { processes: [ ] },
1151 filter: function(data) {
1152 data.sort(function(a, b) { return a.pid - b.pid });
1157 getSystemLog: _luci2.rpc.declare({
1158 object: 'luci2.system',
1163 getKernelLog: _luci2.rpc.declare({
1164 object: 'luci2.system',
1169 getZoneInfo: function(cb)
1171 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1174 sendSignal: _luci2.rpc.declare({
1175 object: 'luci2.system',
1176 method: 'process_signal',
1177 params: [ 'pid', 'signal' ],
1178 filter: function(data) {
1183 initList: _luci2.rpc.declare({
1184 object: 'luci2.system',
1185 method: 'init_list',
1186 expect: { initscripts: [ ] },
1187 filter: function(data) {
1188 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1193 initEnabled: function(init, cb)
1195 return this.initList().then(function(list) {
1196 for (var i = 0; i < list.length; i++)
1197 if (list[i].name == init)
1198 return !!list[i].enabled;
1204 initRun: _luci2.rpc.declare({
1205 object: 'luci2.system',
1206 method: 'init_action',
1207 params: [ 'name', 'action' ],
1208 filter: function(data) {
1213 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1214 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1215 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1216 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1217 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1218 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1221 getRcLocal: _luci2.rpc.declare({
1222 object: 'luci2.system',
1223 method: 'rclocal_get',
1224 expect: { data: '' }
1227 setRcLocal: _luci2.rpc.declare({
1228 object: 'luci2.system',
1229 method: 'rclocal_set',
1234 getCrontab: _luci2.rpc.declare({
1235 object: 'luci2.system',
1236 method: 'crontab_get',
1237 expect: { data: '' }
1240 setCrontab: _luci2.rpc.declare({
1241 object: 'luci2.system',
1242 method: 'crontab_set',
1247 getSSHKeys: _luci2.rpc.declare({
1248 object: 'luci2.system',
1249 method: 'sshkeys_get',
1250 expect: { keys: [ ] }
1253 setSSHKeys: _luci2.rpc.declare({
1254 object: 'luci2.system',
1255 method: 'sshkeys_set',
1260 setPassword: _luci2.rpc.declare({
1261 object: 'luci2.system',
1262 method: 'password_set',
1263 params: [ 'user', 'password' ]
1267 listLEDs: _luci2.rpc.declare({
1268 object: 'luci2.system',
1270 expect: { leds: [ ] }
1273 listUSBDevices: _luci2.rpc.declare({
1274 object: 'luci2.system',
1276 expect: { devices: [ ] }
1280 testUpgrade: _luci2.rpc.declare({
1281 object: 'luci2.system',
1282 method: 'upgrade_test',
1286 startUpgrade: _luci2.rpc.declare({
1287 object: 'luci2.system',
1288 method: 'upgrade_start',
1292 cleanUpgrade: _luci2.rpc.declare({
1293 object: 'luci2.system',
1294 method: 'upgrade_clean'
1298 restoreBackup: _luci2.rpc.declare({
1299 object: 'luci2.system',
1300 method: 'backup_restore'
1303 cleanBackup: _luci2.rpc.declare({
1304 object: 'luci2.system',
1305 method: 'backup_clean'
1309 getBackupConfig: _luci2.rpc.declare({
1310 object: 'luci2.system',
1311 method: 'backup_config_get',
1312 expect: { config: '' }
1315 setBackupConfig: _luci2.rpc.declare({
1316 object: 'luci2.system',
1317 method: 'backup_config_set',
1322 listBackup: _luci2.rpc.declare({
1323 object: 'luci2.system',
1324 method: 'backup_list',
1325 expect: { files: [ ] }
1329 testReset: _luci2.rpc.declare({
1330 object: 'luci2.system',
1331 method: 'reset_test',
1332 expect: { supported: false }
1335 startReset: _luci2.rpc.declare({
1336 object: 'luci2.system',
1337 method: 'reset_start'
1341 performReboot: _luci2.rpc.declare({
1342 object: 'luci2.system',
1348 updateLists: _luci2.rpc.declare({
1349 object: 'luci2.opkg',
1354 _allPackages: _luci2.rpc.declare({
1355 object: 'luci2.opkg',
1357 params: [ 'offset', 'limit', 'pattern' ],
1361 _installedPackages: _luci2.rpc.declare({
1362 object: 'luci2.opkg',
1363 method: 'list_installed',
1364 params: [ 'offset', 'limit', 'pattern' ],
1368 _findPackages: _luci2.rpc.declare({
1369 object: 'luci2.opkg',
1371 params: [ 'offset', 'limit', 'pattern' ],
1375 _fetchPackages: function(action, offset, limit, pattern)
1379 return action(offset, limit, pattern).then(function(list) {
1380 if (!list.total || !list.packages)
1381 return { length: 0, total: 0 };
1383 packages.push.apply(packages, list.packages);
1384 packages.total = list.total;
1389 if (packages.length >= limit)
1394 for (var i = offset + packages.length; i < limit; i += 100)
1395 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1397 return _luci2.rpc.flush();
1398 }).then(function(lists) {
1399 for (var i = 0; i < lists.length; i++)
1401 if (!lists[i].total || !lists[i].packages)
1404 packages.push.apply(packages, lists[i].packages);
1405 packages.total = lists[i].total;
1412 listPackages: function(offset, limit, pattern)
1414 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1417 installedPackages: function(offset, limit, pattern)
1419 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1422 findPackages: function(offset, limit, pattern)
1424 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1427 installPackage: _luci2.rpc.declare({
1428 object: 'luci2.opkg',
1430 params: [ 'package' ],
1434 removePackage: _luci2.rpc.declare({
1435 object: 'luci2.opkg',
1437 params: [ 'package' ],
1441 getConfig: _luci2.rpc.declare({
1442 object: 'luci2.opkg',
1443 method: 'config_get',
1444 expect: { config: '' }
1447 setConfig: _luci2.rpc.declare({
1448 object: 'luci2.opkg',
1449 method: 'config_set',
1456 login: _luci2.rpc.declare({
1459 params: [ 'username', 'password' ],
1463 access: _luci2.rpc.declare({
1466 params: [ 'scope', 'object', 'function' ],
1467 expect: { access: false }
1472 return _luci2.session.access('ubus', 'session', 'access');
1475 startHeartbeat: function()
1477 this._hearbeatInterval = window.setInterval(function() {
1478 _luci2.session.isAlive().then(function(alive) {
1481 _luci2.session.stopHeartbeat();
1482 _luci2.ui.login(true);
1486 }, _luci2.globals.timeout * 2);
1489 stopHeartbeat: function()
1491 if (typeof(this._hearbeatInterval) != 'undefined')
1493 window.clearInterval(this._hearbeatInterval);
1494 delete this._hearbeatInterval;
1501 saveScrollTop: function()
1503 this._scroll_top = $(document).scrollTop();
1506 restoreScrollTop: function()
1508 if (typeof(this._scroll_top) == 'undefined')
1511 $(document).scrollTop(this._scroll_top);
1513 delete this._scroll_top;
1516 loading: function(enable)
1518 var win = $(window);
1519 var body = $('body');
1521 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1523 .addClass('cbi-modal-loader')
1524 .append($('<div />').text(_luci2.tr('Loading data...')))
1530 body.css('overflow', 'hidden');
1531 body.css('padding', 0);
1532 body.css('width', win.width());
1533 body.css('height', win.height());
1534 state.modal.css('width', win.width());
1535 state.modal.css('height', win.height());
1541 body.css('overflow', '');
1542 body.css('padding', '');
1543 body.css('width', '');
1544 body.css('height', '');
1548 dialog: function(title, content, options)
1550 var win = $(window);
1551 var body = $('body');
1553 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1554 dialog: $('<div />')
1555 .addClass('cbi-modal-dialog')
1556 .append($('<div />')
1557 .append($('<div />')
1558 .addClass('cbi-modal-dialog-header'))
1559 .append($('<div />')
1560 .addClass('cbi-modal-dialog-body'))
1561 .append($('<div />')
1562 .addClass('cbi-modal-dialog-footer')
1563 .append($('<button />')
1564 .addClass('cbi-button')
1565 .text(_luci2.tr('Close'))
1568 .css('overflow', '')
1573 $(this).parent().parent().parent().hide();
1578 if (typeof(options) != 'object')
1581 if (title === false)
1584 .css('overflow', '')
1589 state.dialog.hide();
1594 var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1595 var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1599 if (options.style == 'confirm')
1601 ftr.append($('<button />')
1602 .addClass('cbi-button')
1603 .text(_luci2.tr('Ok'))
1604 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1606 ftr.append($('<button />')
1607 .addClass('cbi-button')
1608 .text(_luci2.tr('Cancel'))
1609 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1611 else if (options.style == 'close')
1613 ftr.append($('<button />')
1614 .addClass('cbi-button')
1615 .text(_luci2.tr('Close'))
1616 .click(options.close || function() { _luci2.ui.dialog(false) }));
1618 else if (options.style == 'wait')
1620 ftr.append($('<button />')
1621 .addClass('cbi-button')
1622 .text(_luci2.tr('Close'))
1623 .attr('disabled', true));
1626 state.dialog.find('div.cbi-modal-dialog-header').text(title);
1627 state.dialog.show();
1630 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1634 state.dialog.children()
1635 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1637 body.css('overflow', 'hidden');
1638 body.css('padding', 0);
1639 body.css('width', win.width());
1640 body.css('height', win.height());
1641 state.dialog.css('width', win.width());
1642 state.dialog.css('height', win.height());
1645 upload: function(title, content, options)
1647 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1649 .attr('method', 'post')
1650 .attr('action', '/cgi-bin/luci-upload')
1651 .attr('enctype', 'multipart/form-data')
1652 .attr('target', 'cbi-fileupload-frame')
1654 .append($('<input />')
1655 .attr('type', 'hidden')
1656 .attr('name', 'sessionid'))
1657 .append($('<input />')
1658 .attr('type', 'hidden')
1659 .attr('name', 'filename'))
1660 .append($('<input />')
1661 .attr('type', 'file')
1662 .attr('name', 'filedata')
1663 .addClass('cbi-input-file'))
1664 .append($('<div />')
1665 .css('width', '100%')
1666 .addClass('progressbar')
1667 .addClass('intermediate')
1668 .append($('<div />')
1669 .css('width', '100%')))
1670 .append($('<iframe />')
1671 .attr('name', 'cbi-fileupload-frame')
1672 .css('width', '1px')
1673 .css('height', '1px')
1674 .css('visibility', 'hidden')),
1676 finish_cb: function(ev) {
1677 $(this).off('load');
1679 var body = (this.contentDocument || this.contentWindow.document).body;
1680 if (body.firstChild.tagName.toLowerCase() == 'pre')
1681 body = body.firstChild;
1685 json = $.parseJSON(body.innerHTML);
1688 message: _luci2.tr('Invalid server response received'),
1689 error: [ -1, _luci2.tr('Invalid data') ]
1695 L.ui.dialog(L.tr('File upload'), [
1696 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1697 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1698 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1699 ], { style: 'close' });
1701 else if (typeof(state.success_cb) == 'function')
1703 state.success_cb(json);
1707 confirm_cb: function() {
1708 var f = state.form.find('.cbi-input-file');
1709 var b = state.form.find('.progressbar');
1710 var p = state.form.find('p');
1715 state.form.find('iframe').on('load', state.finish_cb);
1716 state.form.submit();
1720 p.text(_luci2.tr('File upload in progress …'));
1722 state.form.parent().parent().find('button').prop('disabled', true);
1726 state.form.find('.progressbar').hide();
1727 state.form.find('.cbi-input-file').val('').show();
1728 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1730 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1731 state.form.find('[name=filename]').val(options.filename);
1733 state.success_cb = options.success;
1735 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1737 confirm: state.confirm_cb
1741 reconnect: function()
1743 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1744 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1745 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1747 var interval, timeout;
1750 _luci2.tr('Waiting for device'), [
1751 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1753 .css('width', '100%')
1754 .addClass('progressbar')
1755 .addClass('intermediate')
1756 .append($('<div />')
1757 .css('width', '100%'))
1758 ], { style: 'wait' }
1761 for (var i = 0; i < protocols.length; i++)
1762 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1764 //_luci2.network.getNetworkStatus(function(s) {
1765 // for (var i = 0; i < protocols.length; i++)
1767 // for (var j = 0; j < s.length; j++)
1769 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1770 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1772 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1773 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1776 //}).then(function() {
1777 images.on('load', function() {
1778 var url = this.getAttribute('url');
1779 _luci2.session.isAlive().then(function(access) {
1782 window.clearTimeout(timeout);
1783 window.clearInterval(interval);
1784 _luci2.ui.dialog(false);
1789 location.href = url;
1794 interval = window.setInterval(function() {
1795 images.each(function() {
1796 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1800 timeout = window.setTimeout(function() {
1801 window.clearInterval(interval);
1805 _luci2.tr('Device not responding'),
1806 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1813 login: function(invalid)
1815 var state = _luci2.ui._login || (_luci2.ui._login = {
1818 .attr('method', 'post')
1820 .addClass('alert-message')
1821 .text(_luci2.tr('Wrong username or password given!')))
1823 .append($('<label />')
1824 .text(_luci2.tr('Username'))
1825 .append($('<br />'))
1826 .append($('<input />')
1827 .attr('type', 'text')
1828 .attr('name', 'username')
1829 .attr('value', 'root')
1830 .addClass('cbi-input-text')
1831 .keypress(function(ev) {
1832 if (ev.which == 10 || ev.which == 13)
1836 .append($('<label />')
1837 .text(_luci2.tr('Password'))
1838 .append($('<br />'))
1839 .append($('<input />')
1840 .attr('type', 'password')
1841 .attr('name', 'password')
1842 .addClass('cbi-input-password')
1843 .keypress(function(ev) {
1844 if (ev.which == 10 || ev.which == 13)
1848 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1850 response_cb: function(response) {
1851 if (!response.ubus_rpc_session)
1853 _luci2.ui.login(true);
1857 _luci2.globals.sid = response.ubus_rpc_session;
1858 _luci2.setHash('id', _luci2.globals.sid);
1859 _luci2.session.startHeartbeat();
1860 _luci2.ui.dialog(false);
1861 state.deferred.resolve();
1865 confirm_cb: function() {
1866 var u = state.form.find('[name=username]').val();
1867 var p = state.form.find('[name=password]').val();
1873 _luci2.tr('Logging in'), [
1874 $('<p />').text(_luci2.tr('Log in in progress …')),
1876 .css('width', '100%')
1877 .addClass('progressbar')
1878 .addClass('intermediate')
1879 .append($('<div />')
1880 .css('width', '100%'))
1881 ], { style: 'wait' }
1884 _luci2.globals.sid = '00000000000000000000000000000000';
1885 _luci2.session.login(u, p).then(state.response_cb);
1889 if (!state.deferred || state.deferred.state() != 'pending')
1890 state.deferred = $.Deferred();
1892 /* try to find sid from hash */
1893 var sid = _luci2.getHash('id');
1894 if (sid && sid.match(/^[a-f0-9]{32}$/))
1896 _luci2.globals.sid = sid;
1897 _luci2.session.isAlive().then(function(access) {
1900 _luci2.session.startHeartbeat();
1901 state.deferred.resolve();
1905 _luci2.setHash('id', undefined);
1910 return state.deferred;
1914 state.form.find('.alert-message').show();
1916 state.form.find('.alert-message').hide();
1918 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
1920 confirm: state.confirm_cb
1923 state.form.find('[name=password]').focus();
1925 return state.deferred;
1928 cryptPassword: _luci2.rpc.declare({
1932 expect: { crypt: '' }
1936 _acl_merge_scope: function(acl_scope, scope)
1938 if ($.isArray(scope))
1940 for (var i = 0; i < scope.length; i++)
1941 acl_scope[scope[i]] = true;
1943 else if ($.isPlainObject(scope))
1945 for (var object_name in scope)
1947 if (!$.isArray(scope[object_name]))
1950 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
1952 for (var i = 0; i < scope[object_name].length; i++)
1953 acl_object[scope[object_name][i]] = true;
1958 _acl_merge_permission: function(acl_perm, perm)
1960 if ($.isPlainObject(perm))
1962 for (var scope_name in perm)
1964 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
1965 this._acl_merge_scope(acl_scope, perm[scope_name]);
1970 _acl_merge_group: function(acl_group, group)
1972 if ($.isPlainObject(group))
1974 if (!acl_group.description)
1975 acl_group.description = group.description;
1979 var acl_perm = acl_group.read || (acl_group.read = { });
1980 this._acl_merge_permission(acl_perm, group.read);
1985 var acl_perm = acl_group.write || (acl_group.write = { });
1986 this._acl_merge_permission(acl_perm, group.write);
1991 _acl_merge_tree: function(acl_tree, tree)
1993 if ($.isPlainObject(tree))
1995 for (var group_name in tree)
1997 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
1998 this._acl_merge_group(acl_group, tree[group_name]);
2003 listAvailableACLs: _luci2.rpc.declare({
2006 expect: { acls: [ ] },
2007 filter: function(trees) {
2009 for (var i = 0; i < trees.length; i++)
2010 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2015 renderMainMenu: _luci2.rpc.declare({
2018 expect: { menu: { } },
2019 filter: function(entries) {
2020 _luci2.globals.mainMenu = new _luci2.ui.menu();
2021 _luci2.globals.mainMenu.entries(entries);
2025 .append(_luci2.globals.mainMenu.render(0, 1));
2029 renderViewMenu: function()
2033 .append(_luci2.globals.mainMenu.render(2, 900));
2036 renderView: function(node)
2038 var name = node.view.split(/\//).join('.');
2040 _luci2.ui.renderViewMenu();
2043 _luci2._views = { };
2045 _luci2.setHash('view', node.view);
2047 if (_luci2._views[name] instanceof _luci2.ui.view)
2048 return _luci2._views[name].render();
2050 var url = _luci2.globals.resource + '/view/' + name + '.js';
2052 return $.ajax(url, {
2056 }).then(function(data) {
2058 var viewConstructorSource = (
2059 '(function(L, $) { ' +
2061 '})(_luci2, $);\n\n' +
2063 ).format(data, url);
2065 var viewConstructor = eval(viewConstructorSource);
2067 _luci2._views[name] = new viewConstructor({
2069 acls: node.write || { }
2072 return _luci2._views[name].render();
2075 alert('Unable to instantiate view "%s": %s'.format(url, e));
2078 return $.Deferred().resolve();
2082 updateHostname: function()
2084 return _luci2.system.getBoardInfo().then(function(info) {
2086 $('#hostname').text(info.hostname);
2090 updateChanges: function()
2092 return _luci2.uci.changes().then(function(changes) {
2096 for (var config in changes)
2100 for (var i = 0; i < changes[config].length; i++)
2102 var c = changes[config][i];
2111 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2113 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2118 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2120 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2124 log.push('uci add %s (= <ins><strong>%s</strong></ins>)'.format(config, c[1]));
2128 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2132 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2137 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2139 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2144 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2145 n += changes[config].length;
2156 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2157 .click(function(ev) {
2158 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2159 ev.preventDefault();
2169 _luci2.ui.loading(true);
2172 _luci2.ui.updateHostname(),
2173 _luci2.ui.updateChanges(),
2174 _luci2.ui.renderMainMenu()
2176 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2177 _luci2.ui.loading(false);
2183 var AbstractWidget = Class.extend({
2184 i18n: function(text) {
2188 toString: function() {
2189 var x = document.createElement('div');
2190 x.appendChild(this.render());
2195 insertInto: function(id) {
2196 return $(id).empty().append(this.render());
2200 this.ui.view = AbstractWidget.extend({
2201 _fetch_template: function()
2203 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2207 success: function(data) {
2208 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2209 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2216 return _luci2.tr(p2);
2219 return _luci2.globals[p2] || '';
2222 return '(?' + match + ')';
2226 $('#maincontent').append(data);
2233 throw "Not implemented";
2238 var container = $('#maincontent');
2243 container.append($('<h2 />').append(this.title));
2245 if (this.description)
2246 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2249 return this._fetch_template().then(function() {
2250 return _luci2.deferrable(self.execute());
2255 this.ui.menu = AbstractWidget.extend({
2260 entries: function(entries)
2262 for (var entry in entries)
2264 var path = entry.split(/\//);
2265 var node = this._nodes;
2267 for (i = 0; i < path.length; i++)
2272 if (!node.childs[path[i]])
2273 node.childs[path[i]] = { };
2275 node = node.childs[path[i]];
2278 $.extend(node, entries[entry]);
2282 _indexcmp: function(a, b)
2284 var x = a.index || 0;
2285 var y = b.index || 0;
2289 firstChildView: function(node)
2295 for (var child in (node.childs || { }))
2296 nodes.push(node.childs[child]);
2298 nodes.sort(this._indexcmp);
2300 for (var i = 0; i < nodes.length; i++)
2302 var child = this.firstChildView(nodes[i]);
2305 $.extend(node, child);
2313 _onclick: function(ev)
2315 _luci2.ui.loading(true);
2316 _luci2.ui.renderView(ev.data).then(function() {
2317 _luci2.ui.loading(false);
2320 ev.preventDefault();
2324 _render: function(childs, level, min, max)
2327 for (var node in childs)
2329 var child = this.firstChildView(childs[node]);
2331 nodes.push(childs[node]);
2334 nodes.sort(this._indexcmp);
2336 var list = $('<ul />');
2339 list.addClass('nav');
2340 else if (level == 1)
2341 list.addClass('dropdown-menu');
2343 for (var i = 0; i < nodes.length; i++)
2345 if (!_luci2.globals.defaultNode)
2347 var v = _luci2.getHash('view');
2348 if (!v || v == nodes[i].view)
2349 _luci2.globals.defaultNode = nodes[i];
2352 var item = $('<li />')
2355 .text(_luci2.tr(nodes[i].title))
2356 .click(nodes[i], this._onclick))
2359 if (nodes[i].childs && level < max)
2361 item.addClass('dropdown');
2362 item.find('a').addClass('menu');
2363 item.append(this._render(nodes[i].childs, level + 1));
2370 render: function(min, max)
2372 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2373 return this._render(top.childs, 0, min, max);
2376 getNode: function(path, max)
2378 var p = path.split(/\//);
2379 var n = this._nodes;
2381 if (typeof(max) == 'undefined')
2384 for (var i = 0; i < max; i++)
2386 if (!n.childs[p[i]])
2396 this.ui.table = AbstractWidget.extend({
2402 row: function(values)
2404 if ($.isArray(values))
2406 this._rows.push(values);
2408 else if ($.isPlainObject(values))
2411 for (var i = 0; i < this.options.columns.length; i++)
2413 var col = this.options.columns[i];
2415 if (typeof col.key == 'string')
2416 v.push(values[col.key]);
2424 rows: function(rows)
2426 for (var i = 0; i < rows.length; i++)
2430 render: function(id)
2432 var fieldset = document.createElement('fieldset');
2433 fieldset.className = 'cbi-section';
2435 if (this.options.caption)
2437 var legend = document.createElement('legend');
2438 $(legend).append(this.options.caption);
2439 fieldset.appendChild(legend);
2442 var table = document.createElement('table');
2443 table.className = 'cbi-section-table';
2445 var has_caption = false;
2446 var has_description = false;
2448 for (var i = 0; i < this.options.columns.length; i++)
2449 if (this.options.columns[i].caption)
2454 else if (this.options.columns[i].description)
2456 has_description = true;
2462 var tr = table.insertRow(-1);
2463 tr.className = 'cbi-section-table-titles';
2465 for (var i = 0; i < this.options.columns.length; i++)
2467 var col = this.options.columns[i];
2468 var th = document.createElement('th');
2469 th.className = 'cbi-section-table-cell';
2474 th.style.width = col.width;
2477 th.style.textAlign = col.align;
2480 $(th).append(col.caption);
2484 if (has_description)
2486 var tr = table.insertRow(-1);
2487 tr.className = 'cbi-section-table-descr';
2489 for (var i = 0; i < this.options.columns.length; i++)
2491 var col = this.options.columns[i];
2492 var th = document.createElement('th');
2493 th.className = 'cbi-section-table-cell';
2498 th.style.width = col.width;
2501 th.style.textAlign = col.align;
2503 if (col.description)
2504 $(th).append(col.description);
2508 if (this._rows.length == 0)
2510 if (this.options.placeholder)
2512 var tr = table.insertRow(-1);
2513 var td = tr.insertCell(-1);
2514 td.className = 'cbi-section-table-cell';
2516 td.colSpan = this.options.columns.length;
2517 $(td).append(this.options.placeholder);
2522 for (var i = 0; i < this._rows.length; i++)
2524 var tr = table.insertRow(-1);
2526 for (var j = 0; j < this.options.columns.length; j++)
2528 var col = this.options.columns[j];
2529 var td = tr.insertCell(-1);
2531 var val = this._rows[i][j];
2533 if (typeof(val) == 'undefined')
2534 val = col.placeholder;
2536 if (typeof(val) == 'undefined')
2540 td.style.width = col.width;
2543 td.style.textAlign = col.align;
2545 if (typeof col.format == 'string')
2546 $(td).append(col.format.format(val));
2547 else if (typeof col.format == 'function')
2548 $(td).append(col.format(val, i));
2556 fieldset.appendChild(table);
2562 this.ui.progress = AbstractWidget.extend({
2565 var vn = parseInt(this.options.value) || 0;
2566 var mn = parseInt(this.options.max) || 100;
2567 var pc = Math.floor((100 / mn) * vn);
2569 var bar = document.createElement('div');
2570 bar.className = 'progressbar';
2572 bar.appendChild(document.createElement('div'));
2573 bar.lastChild.appendChild(document.createElement('div'));
2574 bar.lastChild.style.width = pc + '%';
2576 if (typeof(this.options.format) == 'string')
2577 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2578 else if (typeof(this.options.format) == 'function')
2579 $(bar.lastChild.lastChild).append(this.options.format(pc));
2581 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2587 this.ui.devicebadge = AbstractWidget.extend({
2590 var dev = this.options.l3_device || this.options.device || '?';
2592 var span = document.createElement('span');
2593 span.className = 'ifacebadge';
2595 if (typeof(this.options.signal) == 'number' ||
2596 typeof(this.options.noise) == 'number')
2599 if (typeof(this.options.signal) != 'undefined' &&
2600 typeof(this.options.noise) != 'undefined')
2602 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2615 span.appendChild(document.createElement('img'));
2616 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2619 span.title = _luci2.tr('No signal');
2621 span.title = '%s: %d %s / %s: %d %s'.format(
2622 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2623 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2628 var type = 'ethernet';
2629 var desc = _luci2.tr('Ethernet device');
2631 if (this.options.l3_device != this.options.device)
2634 desc = _luci2.tr('Tunnel interface');
2636 else if (dev.indexOf('br-') == 0)
2639 desc = _luci2.tr('Bridge');
2641 else if (dev.indexOf('.') > 0)
2644 desc = _luci2.tr('VLAN interface');
2646 else if (dev.indexOf('wlan') == 0 ||
2647 dev.indexOf('ath') == 0 ||
2648 dev.indexOf('wl') == 0)
2651 desc = _luci2.tr('Wireless Network');
2654 span.appendChild(document.createElement('img'));
2655 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2659 $(span).append(' ');
2660 $(span).append(dev);
2666 var type = function(f, l)
2676 _luci2.cbi.validation.message = _luci2.tr(msg);
2679 compile: function(code)
2684 var types = _luci2.cbi.validation.types;
2689 for (var i = 0; i < code.length; i++)
2697 switch (code.charCodeAt(i))
2709 var label = code.substring(pos, i);
2710 label = label.replace(/\\(.)/g, '$1');
2711 label = label.replace(/^[ \t]+/g, '');
2712 label = label.replace(/[ \t]+$/g, '');
2714 if (label && !isNaN(label))
2716 stack.push(parseFloat(label));
2718 else if (label.match(/^(['"]).*\1$/))
2720 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2722 else if (typeof types[label] == 'function')
2724 stack.push(types[label]);
2729 throw "Syntax error, unhandled token '"+label+"'";
2734 depth += (code.charCodeAt(i) == 40);
2740 if (typeof stack[stack.length-2] != 'function')
2741 throw "Syntax error, argument list follows non-function";
2743 stack[stack.length-1] =
2744 arguments.callee(code.substring(pos, i));
2757 var validation = this.cbi.validation;
2759 validation.types = {
2760 'integer': function()
2762 if (this.match(/^-?[0-9]+$/) != null)
2765 validation.i18n('Must be a valid integer');
2769 'uinteger': function()
2771 if (validation.types['integer'].apply(this) && (this >= 0))
2774 validation.i18n('Must be a positive integer');
2780 if (!isNaN(parseFloat(this)))
2783 validation.i18n('Must be a valid number');
2787 'ufloat': function()
2789 if (validation.types['float'].apply(this) && (this >= 0))
2792 validation.i18n('Must be a positive number');
2796 'ipaddr': function()
2798 if (validation.types['ip4addr'].apply(this) ||
2799 validation.types['ip6addr'].apply(this))
2802 validation.i18n('Must be a valid IP address');
2806 'ip4addr': function()
2808 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2810 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2811 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2812 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2813 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2814 ((RegExp.$6.indexOf('.') < 0)
2815 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2816 : (validation.types['ip4addr'].apply(RegExp.$6))))
2820 validation.i18n('Must be a valid IPv4 address');
2824 'ip6addr': function()
2826 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2828 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2830 var addr = RegExp.$1;
2837 if (addr.indexOf('.') > 0)
2839 var off = addr.lastIndexOf(':');
2841 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2843 validation.i18n('Must be a valid IPv6 address');
2847 addr = addr.substr(0, off) + ':0:0';
2850 if (addr.indexOf('::') >= 0)
2855 for (var i = 1; i < (addr.length-1); i++)
2856 if (addr.charAt(i) == ':')
2861 validation.i18n('Must be a valid IPv6 address');
2865 for (var i = 0; i < (7 - colons); i++)
2868 if (addr.match(/^(.*?)::(.*?)$/))
2869 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2870 (RegExp.$2 ? ':' + RegExp.$2 : '');
2873 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2876 validation.i18n('Must be a valid IPv6 address');
2886 if (validation.types['integer'].apply(this) &&
2887 (this >= 0) && (this <= 65535))
2890 validation.i18n('Must be a valid port number');
2894 'portrange': function()
2896 if (this.match(/^(\d+)-(\d+)$/))
2901 if (validation.types['port'].apply(p1) &&
2902 validation.types['port'].apply(p2) &&
2903 (parseInt(p1) <= parseInt(p2)))
2906 else if (validation.types['port'].apply(this))
2911 validation.i18n('Must be a valid port range');
2915 'macaddr': function()
2917 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2920 validation.i18n('Must be a valid MAC address');
2926 if (validation.types['hostname'].apply(this) ||
2927 validation.types['ipaddr'].apply(this))
2930 validation.i18n('Must be a valid hostname or IP address');
2934 'hostname': function()
2936 if ((this.length <= 253) &&
2937 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2938 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2939 this.match(/[^0-9.]/)))))
2942 validation.i18n('Must be a valid host name');
2946 'network': function()
2948 if (validation.types['uciname'].apply(this) ||
2949 validation.types['host'].apply(this))
2952 validation.i18n('Must be a valid network name');
2956 'wpakey': function()
2960 if ((v.length == 64)
2961 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2962 : ((v.length >= 8) && (v.length <= 63)))
2965 validation.i18n('Must be a valid WPA key');
2969 'wepkey': function()
2973 if (v.substr(0,2) == 's:')
2976 if (((v.length == 10) || (v.length == 26))
2977 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2978 : ((v.length == 5) || (v.length == 13)))
2981 validation.i18n('Must be a valid WEP key');
2985 'uciname': function()
2987 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2990 validation.i18n('Must be a valid UCI identifier');
2994 'range': function(min, max)
2996 var val = parseFloat(this);
2998 if (validation.types['integer'].apply(this) &&
2999 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
3002 validation.i18n('Must be a number between %d and %d');
3006 'min': function(min)
3008 var val = parseFloat(this);
3010 if (validation.types['integer'].apply(this) &&
3011 !isNaN(min) && !isNaN(val) && (val >= min))
3014 validation.i18n('Must be a number greater or equal to %d');
3018 'max': function(max)
3020 var val = parseFloat(this);
3022 if (validation.types['integer'].apply(this) &&
3023 !isNaN(max) && !isNaN(val) && (val <= max))
3026 validation.i18n('Must be a number lower or equal to %d');
3030 'rangelength': function(min, max)
3032 var val = '' + this;
3034 if (!isNaN(min) && !isNaN(max) &&
3035 (val.length >= min) && (val.length <= max))
3038 validation.i18n('Must be between %d and %d characters');
3042 'minlength': function(min)
3044 var val = '' + this;
3046 if (!isNaN(min) && (val.length >= min))
3049 validation.i18n('Must be at least %d characters');
3053 'maxlength': function(max)
3055 var val = '' + this;
3057 if (!isNaN(max) && (val.length <= max))
3060 validation.i18n('Must be at most %d characters');
3068 for (var i = 0; i < arguments.length; i += 2)
3070 delete validation.message;
3072 if (typeof(arguments[i]) != 'function')
3074 if (arguments[i] == this)
3078 else if (arguments[i].apply(this, arguments[i+1]))
3083 if (validation.message)
3084 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3087 validation.message = msgs.join( _luci2.tr(' - or - '));
3095 for (var i = 0; i < arguments.length; i += 2)
3097 delete validation.message;
3099 if (typeof arguments[i] != 'function')
3101 if (arguments[i] != this)
3105 else if (!arguments[i].apply(this, arguments[i+1]))
3110 if (validation.message)
3111 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3114 validation.message = msgs.join(', ');
3120 return validation.types['or'].apply(
3121 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3124 'list': function(subvalidator, subargs)
3126 if (typeof subvalidator != 'function')
3129 var tokens = this.match(/[^ \t]+/g);
3130 for (var i = 0; i < tokens.length; i++)
3131 if (!subvalidator.apply(tokens[i], subargs))
3137 'phonedigit': function()
3139 if (this.match(/^[0-9\*#!\.]+$/) != null)
3142 validation.i18n('Must be a valid phone number digit');
3146 'string': function()
3153 this.cbi.AbstractValue = AbstractWidget.extend({
3154 init: function(name, options)
3157 this.instance = { };
3158 this.dependencies = [ ];
3159 this.rdependency = { };
3161 this.options = _luci2.defaults(options, {
3171 return this.section.id('field', sid || '__unknown__', this.name);
3174 render: function(sid)
3176 var i = this.instance[sid] = { };
3178 i.top = $('<div />').addClass('cbi-value');
3180 if (typeof(this.options.caption) == 'string')
3182 .addClass('cbi-value-title')
3183 .attr('for', this.id(sid))
3184 .text(this.options.caption)
3187 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
3188 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
3190 if (typeof(this.options.description) == 'string')
3192 .addClass('cbi-value-description')
3193 .text(this.options.description)
3199 ucipath: function(sid)
3202 config: (this.options.uci_package || this.map.uci_package),
3203 section: (this.options.uci_section || sid),
3204 option: (this.options.uci_option || this.name)
3208 ucivalue: function(sid)
3210 var uci = this.ucipath(sid);
3211 var val = this.map.get(uci.config, uci.section, uci.option);
3213 if (typeof(val) == 'undefined')
3214 return this.options.initial;
3219 formvalue: function(sid)
3221 var v = $('#' + this.id(sid)).val();
3222 return (v === '') ? undefined : v;
3225 textvalue: function(sid)
3227 var v = this.formvalue(sid);
3229 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3230 v = this.ucivalue(sid);
3232 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3233 v = this.options.placeholder;
3235 if (typeof(v) == 'undefined' || v === '')
3238 if (typeof(v) == 'string' && $.isArray(this.choices))
3240 for (var i = 0; i < this.choices.length; i++)
3241 if (v === this.choices[i][0])
3242 return this.choices[i][1];
3244 else if (v === true)
3245 return _luci2.tr('yes');
3246 else if (v === false)
3247 return _luci2.tr('no');
3248 else if ($.isArray(v))
3249 return v.join(', ');
3254 changed: function(sid)
3256 var a = this.ucivalue(sid);
3257 var b = this.formvalue(sid);
3259 if (typeof(a) != typeof(b))
3262 if (typeof(a) == 'object')
3264 if (a.length != b.length)
3267 for (var i = 0; i < a.length; i++)
3279 var uci = this.ucipath(sid);
3281 if (this.instance[sid].disabled)
3283 if (!this.options.keep)
3284 return this.map.set(uci.config, uci.section, uci.option, undefined);
3289 var chg = this.changed(sid);
3290 var val = this.formvalue(sid);
3293 this.map.set(uci.config, uci.section, uci.option, val);
3298 validator: function(sid, elem, multi)
3300 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3304 if (typeof(this.options.datatype) == 'string')
3307 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3310 else if (typeof(this.options.datatype) == 'function')
3312 var vfunc = this.options.datatype;
3313 vstack = [ function(elem) {
3314 var rv = vfunc(this, elem);
3316 validation.message = rv;
3317 return (rv === true);
3326 inst: this.instance[sid],
3327 opt: this.options.optional
3330 var validator = function(ev)
3334 var val = d.elem.val();
3336 if (vstack && typeof(vstack[0]) == 'function')
3338 delete validation.message;
3340 if ((val.length == 0 && !d.opt))
3342 d.elem.addClass('error');
3343 d.inst.top.addClass('error');
3344 d.inst.error.text(_luci2.tr('Field must not be empty'));
3347 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3349 d.elem.addClass('error');
3350 d.inst.top.addClass('error');
3351 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3356 d.elem.removeClass('error');
3358 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3364 d.inst.top.removeClass('error');
3365 d.inst.error.text('');
3372 for (var field in d.self.rdependency)
3373 d.self.rdependency[field].toggle(d.sid);
3379 if (elem.prop('tagName') == 'SELECT')
3381 elem.change(evdata, validator);
3383 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3385 elem.click(evdata, validator);
3386 elem.blur(evdata, validator);
3390 elem.keyup(evdata, validator);
3391 elem.blur(evdata, validator);
3394 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3399 validate: function(sid)
3401 var i = this.instance[sid];
3403 i.widget.find('[cbi-validate]').trigger('validate');
3405 return (i.disabled || i.error.text() == '');
3408 depends: function(d, v)
3415 for (var i = 0; i < d.length; i++)
3417 if (typeof(d[i]) == 'string')
3419 else if (d[i] instanceof _luci2.cbi.AbstractValue)
3420 dep[d[i].name] = true;
3423 else if (d instanceof _luci2.cbi.AbstractValue)
3426 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3428 else if (typeof(d) == 'object')
3432 else if (typeof(d) == 'string')
3435 dep[d] = (typeof(v) == 'undefined') ? true : v;
3438 if (!dep || $.isEmptyObject(dep))
3441 for (var field in dep)
3443 var f = this.section.fields[field];
3445 f.rdependency[this.name] = this;
3450 if ($.isEmptyObject(dep))
3453 this.dependencies.push(dep);
3458 toggle: function(sid)
3460 var d = this.dependencies;
3461 var i = this.instance[sid];
3466 for (var n = 0; n < d.length; n++)
3470 for (var field in d[n])
3472 var val = this.section.fields[field].formvalue(sid);
3473 var cmp = d[n][field];
3475 if (typeof(cmp) == 'boolean')
3477 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3483 else if (typeof(cmp) == 'string')
3491 else if (typeof(cmp) == 'function')
3499 else if (cmp instanceof RegExp)
3524 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3531 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
3532 widget: function(sid)
3534 var o = this.options;
3536 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3537 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3539 var i = $('<input />')
3540 .attr('id', this.id(sid))
3541 .attr('type', 'checkbox')
3542 .prop('checked', this.ucivalue(sid));
3544 return this.validator(sid, i);
3547 ucivalue: function(sid)
3549 var v = this.callSuper('ucivalue', sid);
3551 if (typeof(v) == 'boolean')
3554 return (v == this.options.enabled);
3557 formvalue: function(sid)
3559 var v = $('#' + this.id(sid)).prop('checked');
3561 if (typeof(v) == 'undefined')
3562 return !!this.options.initial;
3569 var uci = this.ucipath(sid);
3571 if (this.instance[sid].disabled)
3573 if (!this.options.keep)
3574 return this.map.set(uci.config, uci.section, uci.option, undefined);
3579 var chg = this.changed(sid);
3580 var val = this.formvalue(sid);
3584 val = val ? this.options.enabled : this.options.disabled;
3586 if (this.options.optional && val == this.options.initial)
3587 this.map.set(uci.config, uci.section, uci.option, undefined);
3589 this.map.set(uci.config, uci.section, uci.option, val);
3596 this.cbi.InputValue = this.cbi.AbstractValue.extend({
3597 widget: function(sid)
3599 var i = $('<input />')
3600 .attr('id', this.id(sid))
3601 .attr('type', 'text')
3602 .attr('placeholder', this.options.placeholder)
3603 .val(this.ucivalue(sid));
3605 return this.validator(sid, i);
3609 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
3610 widget: function(sid)
3612 var i = $('<input />')
3613 .attr('id', this.id(sid))
3614 .attr('type', 'password')
3615 .attr('placeholder', this.options.placeholder)
3616 .val(this.ucivalue(sid));
3618 var t = $('<img />')
3619 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3620 .attr('title', _luci2.tr('Reveal or hide password'))
3621 .addClass('cbi-button')
3622 .click(function(ev) {
3623 var i = $(this).prev();
3624 var t = i.attr('type');
3625 i.attr('type', (t == 'password') ? 'text' : 'password');
3629 this.validator(sid, i);
3632 .addClass('cbi-input-password')
3638 this.cbi.ListValue = this.cbi.AbstractValue.extend({
3639 widget: function(sid)
3641 var s = $('<select />');
3643 if (this.options.optional)
3646 .text(_luci2.tr('-- Please choose --'))
3650 for (var i = 0; i < this.choices.length; i++)
3652 .attr('value', this.choices[i][0])
3653 .text(this.choices[i][1])
3656 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3658 return this.validator(sid, s);
3661 value: function(k, v)
3666 this.choices.push([k, v || k]);
3671 this.cbi.MultiValue = this.cbi.ListValue.extend({
3672 widget: function(sid)
3674 var v = this.ucivalue(sid);
3675 var t = $('<div />').attr('id', this.id(sid));
3678 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3681 for (var i = 0; i < v.length; i++)
3685 for (var i = 0; i < this.choices.length; i++)
3688 .append($('<input />')
3689 .addClass('cbi-input-checkbox')
3690 .attr('type', 'checkbox')
3691 .attr('value', this.choices[i][0])
3692 .prop('checked', s[this.choices[i][0]]))
3693 .append(this.choices[i][1])
3703 formvalue: function(sid)
3706 var fields = $('#' + this.id(sid) + ' > label > input');
3708 for (var i = 0; i < fields.length; i++)
3709 if (fields[i].checked)
3710 rv.push(fields[i].getAttribute('value'));
3715 textvalue: function(sid)
3717 var v = this.formvalue(sid);
3721 for (var i = 0; i < this.choices.length; i++)
3722 c[this.choices[i][0]] = this.choices[i][1];
3726 for (var i = 0; i < v.length; i++)
3727 t.push(c[v[i]] || v[i]);
3729 return t.join(', ');
3733 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
3734 _change: function(ev)
3737 var self = ev.data.self;
3739 if (s.selectedIndex == (s.options.length - 1))
3741 ev.data.select.hide();
3742 ev.data.input.show().focus();
3744 var v = ev.data.input.val();
3745 ev.data.input.val(' ');
3746 ev.data.input.val(v);
3748 else if (self.options.optional && s.selectedIndex == 0)
3750 ev.data.input.val('');
3754 ev.data.input.val(ev.data.select.val());
3761 var val = this.value;
3762 var self = ev.data.self;
3764 ev.data.select.empty();
3766 if (self.options.optional)
3769 .text(_luci2.tr('-- please choose --'))
3770 .appendTo(ev.data.select);
3773 for (var i = 0; i < self.choices.length; i++)
3775 if (self.choices[i][0] == val)
3779 .attr('value', self.choices[i][0])
3780 .text(self.choices[i][1])
3781 .appendTo(ev.data.select);
3784 if (!seen && val != '')
3788 .appendTo(ev.data.select);
3792 .text(_luci2.tr('-- custom --'))
3793 .appendTo(ev.data.select);
3795 ev.data.input.hide();
3796 ev.data.select.val(val).show().focus();
3799 _enter: function(ev)
3804 ev.preventDefault();
3805 ev.data.self._blur(ev);
3809 widget: function(sid)
3811 var d = $('<div />')
3812 .attr('id', this.id(sid));
3814 var t = $('<input />')
3815 .attr('type', 'text')
3819 var s = $('<select />')
3824 input: this.validator(sid, t),
3825 select: this.validator(sid, s)
3828 s.change(evdata, this._change);
3829 t.blur(evdata, this._blur);
3830 t.keydown(evdata, this._enter);
3832 t.val(this.ucivalue(sid));
3838 value: function(k, v)
3843 this.choices.push([k, v || k]);
3847 formvalue: function(sid)
3849 var v = $('#' + this.id(sid)).children('input').val();
3850 return (v == '') ? undefined : v;
3854 this.cbi.DynamicList = this.cbi.ComboBox.extend({
3855 _redraw: function(focus, add, del, s)
3857 var v = s.values || [ ];
3860 $(s.parent).children('input').each(function(i) {
3862 v.push(this.value || '');
3865 $(s.parent).empty();
3870 v.splice(focus, 0, '');
3872 else if (v.length == 0)
3878 for (var i = 0; i < v.length; i++)
3889 var txt = $('<input />')
3890 .attr('type', 'text')
3892 .appendTo(s.parent);
3894 var sel = $('<select />')
3895 .appendTo(s.parent);
3897 evdata.input = this.validator(s.sid, txt, true);
3898 evdata.select = this.validator(s.sid, sel, true);
3900 sel.change(evdata, this._change);
3901 txt.blur(evdata, this._blur);
3902 txt.keydown(evdata, this._keydown);
3907 if (i == focus || -(i+1) == focus)
3914 var f = $('<input />')
3915 .attr('type', 'text')
3917 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
3918 .addClass('cbi-input-text')
3919 .keydown(evdata, this._keydown)
3920 .keypress(evdata, this._keypress)
3923 f.appendTo(s.parent);
3929 else if (-(i+1) == focus)
3933 /* force cursor to end */
3939 evdata.input = this.validator(s.sid, f, true);
3945 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
3946 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
3947 .addClass('cbi-button')
3948 .click(evdata, this._btnclick)
3949 .appendTo(s.parent);
3952 .appendTo(s.parent);
3960 _keypress: function(ev)
3964 /* backspace, delete */
3967 if (ev.data.input.val() == '')
3969 ev.preventDefault();
3975 /* enter, arrow up, arrow down */
3979 ev.preventDefault();
3986 _keydown: function(ev)
3988 var input = ev.data.input;
3992 /* backspace, delete */
3995 if (input.val().length == 0)
3997 ev.preventDefault();
3999 var index = ev.data.index;
4005 ev.data.self._redraw(focus, -1, index, ev.data);
4013 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4018 var prev = input.prevAll('input:first');
4019 if (prev.is(':visible'))
4022 prev.next('select').focus();
4027 var next = input.nextAll('input:first');
4028 if (next.is(':visible'))
4031 next.next('select').focus();
4038 _btnclick: function(ev)
4040 if (!this.getAttribute('disabled'))
4042 if (ev.target.src.indexOf('remove') > -1)
4044 var index = ev.data.index;
4045 ev.data.self._redraw(-index, -1, index, ev.data);
4049 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4056 widget: function(sid)
4058 this.options.optional = true;
4060 var v = this.ucivalue(sid);
4063 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4065 var d = $('<div />')
4066 .attr('id', this.id(sid))
4067 .addClass('cbi-input-dynlist');
4069 this._redraw(NaN, -1, -1, {
4079 ucivalue: function(sid)
4081 var v = this.callSuper('ucivalue', sid);
4084 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4089 formvalue: function(sid)
4092 var fields = $('#' + this.id(sid) + ' > input');
4094 for (var i = 0; i < fields.length; i++)
4095 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4096 rv.push(fields[i].value);
4102 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4103 widget: function(sid)
4106 .addClass('cbi-value-dummy')
4107 .attr('id', this.id(sid))
4108 .html(this.ucivalue(sid));
4111 formvalue: function(sid)
4113 return this.ucivalue(sid);
4117 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4122 if (!self.interfaces)
4124 self.interfaces = [ ];
4125 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4126 self.interfaces = ifaces;
4134 _device_icon: function(dev)
4136 var type = 'ethernet';
4137 var desc = _luci2.tr('Ethernet device');
4139 if (dev.type == 'IP tunnel')
4142 desc = _luci2.tr('Tunnel interface');
4144 else if (dev['bridge-members'])
4147 desc = _luci2.tr('Bridge');
4149 else if (dev.wireless)
4152 desc = _luci2.tr('Wireless Network');
4154 else if (dev.device.indexOf('.') > 0)
4157 desc = _luci2.tr('VLAN interface');
4161 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4162 .attr('title', '%s (%s)'.format(desc, dev.device));
4165 widget: function(sid)
4167 var id = this.id(sid);
4168 var ul = $('<ul />')
4170 .addClass('cbi-input-networks');
4172 var itype = this.options.multiple ? 'checkbox' : 'radio';
4173 var value = this.ucivalue(sid);
4176 if (!this.options.multiple)
4177 check[value] = true;
4179 for (var i = 0; i < value.length; i++)
4180 check[value[i]] = true;
4182 if (this.interfaces)
4184 for (var i = 0; i < this.interfaces.length; i++)
4186 var iface = this.interfaces[i];
4187 var badge = $('<span />')
4188 .addClass('ifacebadge')
4189 .text('%s: '.format(iface['interface']));
4191 if (iface.device && iface.device.subdevices)
4192 for (var j = 0; j < iface.device.subdevices.length; j++)
4193 badge.append(this._device_icon(iface.device.subdevices[j]));
4194 else if (iface.device)
4195 badge.append(this._device_icon(iface.device));
4197 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4200 .append($('<label />')
4201 .append($('<input />')
4202 .attr('name', itype + id)
4203 .attr('type', itype)
4204 .attr('value', iface['interface'])
4205 .prop('checked', !!check[iface['interface']])
4206 .addClass('cbi-input-' + itype))
4212 if (!this.options.multiple)
4215 .append($('<label />')
4216 .append($('<input />')
4217 .attr('name', itype + id)
4218 .attr('type', itype)
4220 .prop('checked', !value)
4221 .addClass('cbi-input-' + itype))
4222 .append(_luci2.tr('unspecified')))
4229 ucivalue: function(sid)
4231 var v = this.callSuper('ucivalue', sid);
4233 if (!this.options.multiple)
4239 else if (typeof(v) == 'string')
4242 return v ? v[0] : undefined;
4249 if (typeof(v) == 'string')
4250 v = v.match(/\S+/g);
4256 formvalue: function(sid)
4258 var inputs = $('#' + this.id(sid) + ' input');
4260 if (!this.options.multiple)
4262 for (var i = 0; i < inputs.length; i++)
4263 if (inputs[i].checked && inputs[i].value !== '')
4264 return inputs[i].value;
4271 for (var i = 0; i < inputs.length; i++)
4272 if (inputs[i].checked)
4273 rv.push(inputs[i].value);
4275 return rv.length ? rv : undefined;
4280 this.cbi.AbstractSection = AbstractWidget.extend({
4283 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4285 for (var i = 1; i < arguments.length; i++)
4286 s.push(arguments[i].replace(/\./g, '_'));
4291 option: function(widget, name, options)
4293 if (this.tabs.length == 0)
4294 this.tab({ id: '__default__', selected: true });
4296 return this.taboption('__default__', widget, name, options);
4299 tab: function(options)
4301 if (options.selected)
4302 this.tabs.selected = this.tabs.length;
4306 caption: options.caption,
4307 description: options.description,
4313 taboption: function(tabid, widget, name, options)
4316 for (var i = 0; i < this.tabs.length; i++)
4318 if (this.tabs[i].id == tabid)
4326 throw 'Cannot append to unknown tab ' + tabid;
4328 var w = widget ? new widget(name, options) : null;
4330 if (!(w instanceof _luci2.cbi.AbstractValue))
4331 throw 'Widget must be an instance of AbstractValue';
4336 this.fields[name] = w;
4342 ucipackages: function(pkg)
4344 for (var i = 0; i < this.tabs.length; i++)
4345 for (var j = 0; j < this.tabs[i].fields.length; j++)
4346 if (this.tabs[i].fields[j].options.uci_package)
4347 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4350 formvalue: function()
4354 this.sections(function(s) {
4355 var sid = s['.name'];
4356 var sv = rv[sid] || (rv[sid] = { });
4358 for (var i = 0; i < this.tabs.length; i++)
4359 for (var j = 0; j < this.tabs[i].fields.length; j++)
4361 var val = this.tabs[i].fields[j].formvalue(sid);
4362 sv[this.tabs[i].fields[j].name] = val;
4369 validate: function(sid)
4375 var as = this.sections();
4376 for (var i = 0; i < as.length; i++)
4377 if (!this.validate(as[i]['.name']))
4382 var inst = this.instance[sid];
4383 var sv = rv[sid] || (rv[sid] = { });
4386 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4388 legend.children('span').detach();
4390 for (var i = 0; i < this.tabs.length; i++)
4393 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4395 tab.children('span').detach();
4397 for (var j = 0; j < this.tabs[i].fields.length; j++)
4398 if (!this.tabs[i].fields[j].validate(sid))
4405 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4418 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4426 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
4427 init: function(uci_type, options)
4429 this.uci_type = uci_type;
4430 this.options = options;
4433 this.active_panel = 0;
4434 this.active_tab = { };
4437 filter: function(section)
4442 sections: function(cb)
4444 var s1 = this.map.ucisections(this.map.uci_package);
4447 for (var i = 0; i < s1.length; i++)
4448 if (s1[i]['.type'] == this.uci_type)
4449 if (this.filter(s1[i]))
4452 if (typeof(cb) == 'function')
4453 for (var i = 0; i < s2.length; i++)
4454 cb.apply(this, [ s2[i] ]);
4461 this.map.add(this.map.uci_package, this.uci_type, name);
4464 remove: function(sid)
4466 this.map.remove(this.map.uci_package, sid);
4472 var name = undefined;
4473 var self = ev.data.self;
4475 if (addb.prev().prop('nodeName') == 'INPUT')
4476 name = addb.prev().val();
4478 if (addb.prop('disabled') || name === '')
4481 _luci2.ui.saveScrollTop();
4483 self.active_panel = -1;
4488 _luci2.ui.restoreScrollTop();
4491 _remove: function(ev)
4493 var self = ev.data.self;
4494 var sid = ev.data.sid;
4496 if (ev.data.index == (self.sections().length - 1))
4497 self.active_panel = -1;
4499 _luci2.ui.saveScrollTop();
4505 _luci2.ui.restoreScrollTop();
4507 ev.stopPropagation();
4512 var self = ev.data.self;
4514 var addb = text.next();
4515 var errt = addb.next();
4516 var name = text.val();
4519 if (!/^[a-zA-Z0-9_]*$/.test(name))
4521 errt.text(_luci2.tr('Invalid section name')).show();
4522 text.addClass('error');
4523 addb.prop('disabled', true);
4527 for (var sid in self.map.uci.values[self.map.uci_package])
4534 for (var sid in self.map.uci.creates[self.map.uci_package])
4543 errt.text(_luci2.tr('Name already used')).show();
4544 text.addClass('error');
4545 addb.prop('disabled', true);
4549 errt.text('').hide();
4550 text.removeClass('error');
4551 addb.prop('disabled', false);
4555 teaser: function(sid)
4557 var tf = this.teaser_fields;
4561 tf = this.teaser_fields = [ ];
4563 if ($.isArray(this.options.teasers))
4565 for (var i = 0; i < this.options.teasers.length; i++)
4567 var f = this.options.teasers[i];
4568 if (f instanceof _luci2.cbi.AbstractValue)
4570 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
4571 tf.push(this.fields[f]);
4576 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4577 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4578 tf.push(this.tabs[i].fields[j]);
4584 for (var i = 0; i < tf.length; i++)
4586 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4589 var n = tf[i].options.caption || tf[i].name;
4590 var v = tf[i].textvalue(sid);
4592 if (typeof(v) == 'undefined')
4595 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4601 _render_add: function()
4603 var text = _luci2.tr('Add section');
4604 var ttip = _luci2.tr('Create new section...');
4606 if ($.isArray(this.options.add_caption))
4607 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4608 else if (typeof(this.options.add_caption) == 'string')
4609 text = this.options.add_caption, ttip = '';
4611 var add = $('<div />').addClass('cbi-section-add');
4613 if (this.options.anonymous === false)
4616 .addClass('cbi-input-text')
4617 .attr('type', 'text')
4618 .attr('placeholder', ttip)
4619 .blur({ self: this }, this._sid)
4620 .keyup({ self: this }, this._sid)
4624 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4625 .attr('title', text)
4626 .addClass('cbi-button')
4627 .click({ self: this }, this._add)
4631 .addClass('cbi-value-error')
4638 .attr('type', 'button')
4639 .addClass('cbi-button')
4640 .addClass('cbi-button-add')
4641 .val(text).attr('title', ttip)
4642 .click({ self: this }, this._add)
4649 _render_remove: function(sid, index)
4651 var text = _luci2.tr('Remove');
4652 var ttip = _luci2.tr('Remove this section');
4654 if ($.isArray(this.options.remove_caption))
4655 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4656 else if (typeof(this.options.remove_caption) == 'string')
4657 text = this.options.remove_caption, ttip = '';
4659 return $('<input />')
4660 .attr('type', 'button')
4661 .addClass('cbi-button')
4662 .addClass('cbi-button-remove')
4663 .val(text).attr('title', ttip)
4664 .click({ self: this, sid: sid, index: index }, this._remove);
4667 _render_caption: function(sid)
4669 if (typeof(this.options.caption) == 'string')
4671 return $('<legend />')
4672 .text(this.options.caption.format(sid));
4674 else if (typeof(this.options.caption) == 'function')
4676 return $('<legend />')
4677 .text(this.options.caption.call(this, sid));
4685 var allsections = $();
4686 var panel_index = 0;
4688 this.instance = { };
4690 var s = this.sections();
4694 var fieldset = $('<fieldset />')
4695 .addClass('cbi-section');
4697 var head = $('<div />')
4698 .addClass('cbi-section-head')
4699 .appendTo(fieldset);
4701 head.append(this._render_caption(undefined));
4703 if (typeof(this.options.description) == 'string')
4706 .addClass('cbi-section-descr')
4707 .text(this.options.description)
4711 allsections = allsections.add(fieldset);
4714 for (var i = 0; i < s.length; i++)
4716 var sid = s[i]['.name'];
4717 var inst = this.instance[sid] = { tabs: [ ] };
4719 var fieldset = $('<fieldset />')
4720 .attr('id', this.id('sort', sid))
4721 .addClass('cbi-section');
4723 var head = $('<div />')
4724 .addClass('cbi-section-head')
4725 .attr('cbi-section-num', this.index)
4726 .attr('cbi-section-id', sid);
4728 head.append(this._render_caption(sid));
4730 if (typeof(this.options.description) == 'string')
4733 .addClass('cbi-section-descr')
4734 .text(this.options.description)
4739 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4740 teaser = $('<div />')
4741 .addClass('cbi-section-teaser')
4744 if (this.options.addremove)
4746 .addClass('cbi-section-remove')
4748 .append(this._render_remove(sid, panel_index))
4751 var body = $('<div />')
4752 .attr('index', panel_index++);
4754 var fields = $('<fieldset />')
4755 .addClass('cbi-section-node');
4757 if (this.tabs.length > 1)
4759 var menu = $('<ul />')
4760 .addClass('cbi-tabmenu');
4762 for (var j = 0; j < this.tabs.length; j++)
4764 var tabid = this.id('tab', sid, this.tabs[j].id);
4765 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4767 var tabc = $('<div />')
4768 .addClass('cbi-tabcontainer')
4772 if (typeof(this.tabs[j].description) == 'string')
4775 .addClass('cbi-tab-descr')
4776 .text(this.tabs[j].description)
4780 for (var k = 0; k < this.tabs[j].fields.length; k++)
4781 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4783 tabc.appendTo(fields);
4786 $('<li />').attr('id', theadid).append(
4788 .text(this.tabs[j].caption.format(this.tabs[j].id))
4789 .attr('href', '#' + tabid)
4793 menu.appendTo(body);
4796 fields.appendTo(body);
4799 var t = body.tabs({ active: this.active_tab[sid] });
4801 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4804 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4809 for (var j = 0; j < this.tabs[0].fields.length; j++)
4810 this.tabs[0].fields[j].render(sid).appendTo(fields);
4812 fields.appendTo(body);
4816 head.appendTo(fieldset);
4819 body.appendTo(fieldset);
4822 allsections = allsections.add(fieldset);
4825 //this.validate(sid);
4828 // teaser.append(this.teaser(sid));
4831 if (this.options.collabsible && s.length > 1)
4833 var a = $('<div />').append(allsections).accordion({
4834 header: '> fieldset > div.cbi-section-head',
4835 heightStyle: 'content',
4836 active: this.active_panel
4839 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4840 var h = ui.oldHeader;
4841 var s = ev.data.self;
4842 var i = h.attr('cbi-section-id');
4844 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4848 a.on('accordionactivate', { self: this }, function(ev, ui) {
4849 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4852 if (this.options.sortable)
4854 var s = a.sortable({
4856 handle: 'div.cbi-section-head'
4859 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4861 for (var i = 0; i < ev.data.ids.length; i++)
4862 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4863 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4866 s.on('sortstop', function(ev, ui) {
4867 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4871 if (this.options.addremove)
4872 this._render_add().appendTo(a);
4877 if (this.options.addremove)
4878 allsections = allsections.add(this._render_add());
4885 var s = this.sections();
4887 for (var i = 0; i < s.length; i++)
4889 var sid = s[i]['.name'];
4893 $('#' + this.id('sort', sid))
4894 .children('.cbi-section-head')
4895 .children('.cbi-section-teaser')
4896 .append(this.teaser(sid));
4901 this.cbi.TableSection = this.cbi.TypedSection.extend({
4904 var allsections = $();
4905 var panel_index = 0;
4907 this.instance = { };
4909 var s = this.sections();
4911 var fieldset = $('<fieldset />')
4912 .addClass('cbi-section');
4914 fieldset.append(this._render_caption(sid));
4916 if (typeof(this.options.description) == 'string')
4919 .addClass('cbi-section-descr')
4920 .text(this.options.description)
4921 .appendTo(fieldset);
4924 var fields = $('<div />')
4925 .addClass('cbi-section-node')
4926 .appendTo(fieldset);
4928 var table = $('<table />')
4929 .addClass('cbi-section-table')
4932 var thead = $('<thead />')
4933 .append($('<tr />').addClass('cbi-section-table-titles'))
4936 for (var j = 0; j < this.tabs[0].fields.length; j++)
4938 .addClass('cbi-section-table-cell')
4939 .css('width', this.tabs[0].fields[j].options.width || '')
4940 .append(this.tabs[0].fields[j].options.caption)
4941 .appendTo(thead.children());
4943 if (this.options.sortable)
4944 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4946 if (this.options.addremove !== false)
4947 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4949 var tbody = $('<tbody />')
4955 .addClass('cbi-section-table-row')
4958 .addClass('cbi-section-table-cell')
4959 .addClass('cbi-section-table-placeholder')
4960 .attr('colspan', thead.children().children().length)
4961 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
4965 for (var i = 0; i < s.length; i++)
4967 var sid = s[i]['.name'];
4968 var inst = this.instance[sid] = { tabs: [ ] };
4970 var row = $('<tr />')
4971 .addClass('cbi-section-table-row')
4974 for (var j = 0; j < this.tabs[0].fields.length; j++)
4977 .addClass('cbi-section-table-cell')
4978 .css('width', this.tabs[0].fields[j].options.width || '')
4979 .append(this.tabs[0].fields[j].render(sid, true))
4983 if (this.options.sortable)
4986 .addClass('cbi-section-table-cell')
4987 .addClass('cbi-section-table-sort')
4988 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
4989 .append($('<br />'))
4990 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
4994 if (this.options.addremove !== false)
4997 .addClass('cbi-section-table-cell')
4998 .append(this._render_remove(sid))
5007 if (this.options.sortable)
5009 var s = tbody.sortable({
5010 handle: 'td.cbi-section-table-sort'
5013 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
5015 for (var i = 0; i < ev.data.ids.length; i++)
5016 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
5017 _luci2.uci.order(ev.data.self.map.uci_package, sections);
5020 s.on('sortstop', function(ev, ui) {
5021 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
5025 if (this.options.addremove)
5026 this._render_add().appendTo(fieldset);
5028 fields = table = thead = tbody = null;
5034 this.cbi.NamedSection = this.cbi.TypedSection.extend({
5035 sections: function(cb)
5038 var pkg = this.map.uci.values[this.map.uci_package];
5041 if (pkg[s]['.name'] == this.uci_type)
5047 if (typeof(cb) == 'function' && sa.length > 0)
5048 cb.apply(this, [ sa[0] ]);
5054 this.cbi.DummySection = this.cbi.TypedSection.extend({
5055 sections: function(cb)
5057 if (typeof(cb) == 'function')
5058 cb.apply(this, [ { '.name': this.uci_type } ]);
5060 return [ { '.name': this.uci_type } ];
5064 this.cbi.Map = AbstractWidget.extend({
5065 init: function(uci_package, options)
5069 this.uci_package = uci_package;
5070 this.sections = [ ];
5071 this.options = _luci2.defaults(options, {
5072 save: function() { },
5073 prepare: function() {
5074 return _luci2.uci.writable(function(writable) {
5075 self.options.readonly = !writable;
5091 if (typeof(this.active_panel) == 'undefined')
5092 this.active_panel = 0;
5096 for (var i = 0; i < this.sections.length; i++)
5097 this.sections[i].ucipackages(packages);
5099 packages[this.uci_package] = true;
5101 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
5102 for (var i = 0; i < packages.length; i++)
5104 this.uci.values[packages[i]['.package']] = packages[i];
5105 delete packages[i]['.package'];
5108 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5110 for (var i = 0; i < this.sections.length; i++)
5112 for (var f in this.sections[i].fields)
5114 if (typeof(this.sections[i].fields[f].load) != 'function')
5117 var s = this.sections[i].sections();
5118 for (var j = 0; j < s.length; j++)
5120 var rv = this.sections[i].fields[f].load(s[j]['.name']);
5121 if (_luci2.isDeferred(rv))
5127 return $.when.apply($, deferreds);
5132 for (var pkg in packages)
5133 _luci2.uci.get_all(pkg);
5135 return _luci2.rpc.flush().then(load_cb);
5140 var map = $('<div />').addClass('cbi-map');
5142 if (typeof(this.options.caption) == 'string')
5143 $('<h2 />').text(this.options.caption).appendTo(map);
5145 if (typeof(this.options.description) == 'string')
5146 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
5148 var sections = $('<div />').appendTo(map);
5150 for (var i = 0; i < this.sections.length; i++)
5152 var s = this.sections[i].render();
5154 if (this.options.readonly || this.sections[i].options.readonly)
5155 s.find('input, select, button, img.cbi-button').attr('disabled', true);
5157 s.appendTo(sections);
5159 if (this.sections[i].options.active)
5160 this.active_panel = i;
5163 if (this.options.collabsible)
5165 var a = sections.accordion({
5166 header: '> fieldset > div.cbi-section-head',
5167 heightStyle: 'content',
5168 active: this.active_panel
5171 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
5172 var h = ui.oldHeader;
5173 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
5174 var i = h.attr('cbi-section-id');
5176 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
5178 for (var i = 0; i < ev.data.self.sections.length; i++)
5179 ev.data.self.sections[i].validate();
5182 a.on('accordionactivate', { self: this }, function(ev, ui) {
5183 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
5187 if (this.options.pageaction !== false)
5189 var a = $('<div />')
5190 .addClass('cbi-page-actions')
5194 .addClass('cbi-button').addClass('cbi-button-apply')
5195 .attr('type', 'button')
5196 .val(_luci2.tr('Save & Apply'))
5200 .addClass('cbi-button').addClass('cbi-button-save')
5201 .attr('type', 'button')
5202 .val(_luci2.tr('Save'))
5203 .click({ self: this }, function(ev) { ev.data.self.send(); })
5207 .addClass('cbi-button').addClass('cbi-button-reset')
5208 .attr('type', 'button')
5209 .val(_luci2.tr('Reset'))
5210 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
5216 var top = $('<form />').append(map);
5225 for (var i = 0; i < this.sections.length; i++)
5226 this.sections[i].finish();
5233 this.target.hide().empty().append(this.render());
5238 section: function(widget, uci_type, options)
5240 var w = widget ? new widget(uci_type, options) : null;
5242 if (!(w instanceof _luci2.cbi.AbstractSection))
5243 throw 'Widget must be an instance of AbstractSection';
5246 w.index = this.sections.length;
5248 this.sections.push(w);
5252 formvalue: function()
5256 for (var i = 0; i < this.sections.length; i++)
5258 var sids = this.sections[i].formvalue();
5259 for (var sid in sids)
5261 var s = rv[sid] || (rv[sid] = { });
5262 $.extend(s, sids[sid]);
5269 add: function(conf, type, name)
5271 var c = this.uci.creates;
5272 var s = '.new.%d'.format(this.uci.newid++);
5287 remove: function(conf, sid)
5289 var n = this.uci.creates;
5290 var c = this.uci.changes;
5291 var d = this.uci.deletes;
5293 /* requested deletion of a just created section */
5294 if (sid.indexOf('.new.') == 0)
5297 delete n[conf][sid];
5302 delete c[conf][sid];
5307 d[conf][sid] = true;
5311 ucisections: function(conf, cb)
5314 var pkg = this.uci.values[conf];
5315 var crt = this.uci.creates[conf];
5316 var del = this.uci.deletes[conf];
5322 if (!del || del[s] !== true)
5325 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5331 if (typeof(cb) == 'function')
5332 for (var i = 0; i < sa.length; i++)
5333 cb.apply(this, [ sa[i] ]);
5338 get: function(conf, sid, opt)
5340 var v = this.uci.values;
5341 var n = this.uci.creates;
5342 var c = this.uci.changes;
5343 var d = this.uci.deletes;
5345 /* requested option in a just created section */
5346 if (sid.indexOf('.new.') == 0)
5351 if (typeof(opt) == 'undefined')
5352 return (n[conf][sid] || { });
5354 return n[conf][sid][opt];
5357 /* requested an option value */
5358 if (typeof(opt) != 'undefined')
5360 /* check whether option was deleted */
5361 if (d[conf] && d[conf][sid])
5363 if (d[conf][sid] === true)
5366 for (var i = 0; i < d[conf][sid].length; i++)
5367 if (d[conf][sid][i] == opt)
5371 /* check whether option was changed */
5372 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5373 return c[conf][sid][opt];
5375 /* return base value */
5376 if (v[conf] && v[conf][sid])
5377 return v[conf][sid][opt];
5382 /* requested an entire section */
5384 return (v[conf][sid] || { });
5389 set: function(conf, sid, opt, val)
5391 var n = this.uci.creates;
5392 var c = this.uci.changes;
5393 var d = this.uci.deletes;
5395 if (sid.indexOf('.new.') == 0)
5397 if (n[conf] && n[conf][sid])
5399 if (typeof(val) != 'undefined')
5400 n[conf][sid][opt] = val;
5402 delete n[conf][sid][opt];
5405 else if (typeof(val) != 'undefined')
5413 c[conf][sid][opt] = val;
5423 d[conf][sid].push(opt);
5427 validate: function()
5431 for (var i = 0; i < this.sections.length; i++)
5432 if (!this.sections[i].validate())
5440 if (this.options.readonly)
5441 return _luci2.deferrable();
5443 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5445 for (var i = 0; i < this.sections.length; i++)
5447 if (this.sections[i].options.readonly)
5450 for (var f in this.sections[i].fields)
5452 if (typeof(this.sections[i].fields[f].save) != 'function')
5455 var s = this.sections[i].sections();
5456 for (var j = 0; j < s.length; j++)
5458 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5459 if (_luci2.isDeferred(rv))
5465 return $.when.apply($, deferreds);
5470 if (!this.validate())
5471 return _luci2.deferrable();
5473 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5476 if (this.uci.creates)
5477 for (var c in this.uci.creates)
5478 for (var s in this.uci.creates[c])
5485 for (var k in this.uci.creates[c][s])
5488 r.type = this.uci.creates[c][s][k];
5489 else if (k == '.create')
5490 r.name = this.uci.creates[c][s][k];
5491 else if (k.charAt(0) != '.')
5492 r.values[k] = this.uci.creates[c][s][k];
5495 _luci2.uci.add(r.config, r.type, r.name, r.values);
5498 if (this.uci.changes)
5499 for (var c in this.uci.changes)
5500 for (var s in this.uci.changes[c])
5501 _luci2.uci.set(c, s, this.uci.changes[c][s]);
5503 if (this.uci.deletes)
5504 for (var c in this.uci.deletes)
5505 for (var s in this.uci.deletes[c])
5507 var o = this.uci.deletes[c][s];
5508 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
5511 return _luci2.rpc.flush().then(function() {
5512 return _luci2.ui.updateChanges();
5518 _luci2.ui.saveScrollTop();
5519 _luci2.ui.loading(true);
5521 return this.save().then(send_cb).then(function() {
5523 }).then(function() {
5527 _luci2.ui.loading(false);
5528 _luci2.ui.restoreScrollTop();
5532 dialog: function(id)
5534 var d = $('<div />');
5538 .attr('src', _luci2.globals.resource + '/icons/loading.gif')
5539 .css('vertical-align', 'middle')
5540 .css('padding-right', '10px')
5543 p.append(_luci2.tr('Loading data...'));
5554 $(this).parent().children('.ui-dialog-titlebar').hide();
5559 insertInto: function(id)
5562 self.target = $(id);
5564 _luci2.ui.loading(true);
5567 return self.load().then(function() {
5568 self.target.empty().append(self.render());
5572 _luci2.ui.loading(false);