2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String.prototype.format = function()
15 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27 var a = b = [], numSubstitutions = 0, numMatches = 0;
29 while ((a = re.exec(str)) != null)
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
43 if (numSubstitutions < arguments.length)
45 var param = arguments[numSubstitutions++];
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
59 minLength = parseInt(pMinLength);
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
70 subst = (parseInt(param) || 0).toString(2);
74 subst = String.fromCharCode(parseInt(param) || 0);
78 subst = (parseInt(param) || 0);
82 subst = Math.abs(parseInt(param) || 0);
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
92 subst = (parseInt(param) || 0).toString(8);
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
108 subst = esc(param, html_esc);
112 subst = esc(param, quot_esc);
116 subst = String.serialize(param);
123 var ts = (param || 0);
126 tm = Math.floor(ts / 60);
131 th = Math.floor(tm / 60);
136 td = Math.floor(th / 24);
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i = 0; (i < units.length) && (val > mf); i++)
157 subst = val.toFixed(pr) + ' ' + units[i];
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
169 out += leftpart + subst;
170 str = str.substr(m.length);
180 var Class = function() { };
182 Class.extend = function(properties)
184 Class.initializing = true;
186 var prototype = new this();
187 var superprot = this.prototype;
189 Class.initializing = false;
191 $.extend(prototype, properties, {
192 callSuper: function() {
194 var meth = arguments[0];
196 if (typeof(superprot[meth]) != 'function')
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
202 return superprot[meth].apply(this, args);
208 this.options = arguments[0] || { };
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
217 _class.extend = arguments.callee;
222 this.defaults = function(obj, def)
225 if (typeof(obj[key]) == 'undefined')
231 this.isDeferred = function(x)
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments[0]))
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
253 plural: function(n) { return 0 + (n != 1) },
256 if (_luci2.i18n.loaded)
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
270 var pe = _luci2.i18n.catalog[''];
273 delete _luci2.i18n.catalog[''];
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
282 _luci2.i18n.loaded = true;
287 this.tr = function(msgid)
291 var msgstr = _luci2.i18n.catalog[msgid];
293 if (typeof(msgstr) == 'undefined')
295 else if (typeof(msgstr) == 'string')
301 this.trp = function(msgid, msgid_plural, count)
305 var msgstr = _luci2.i18n.catalog[msgid];
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
312 return msgstr[_luci2.i18n.plural(count)];
315 this.trc = function(msgctx, msgid)
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
321 if (typeof(msgstr) == 'undefined')
323 else if (typeof(msgstr) == 'string')
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
340 return msgstr[_luci2.i18n.plural(count)];
343 this.setHash = function(key, value)
346 var data = this.getHash(undefined);
348 if (typeof(value) == 'undefined')
359 for (var i = 0; i < keys.length; i++)
364 h += keys[i] + ':' + data[keys[i]];
368 location.hash = '#' + h;
371 this.getHash = function(key)
374 var tuples = (location.hash || '#').substring(1).split(/,/);
376 for (var i = 0; i < tuples.length; i++)
378 var tuple = tuples[i].split(/:/);
379 if (tuple.length == 2)
380 data[tuple[0]] = tuple[1];
383 if (typeof(key) != 'undefined')
392 sid: '00000000000000000000000000000000'
401 _call: function(req, cb)
403 return $.ajax('/ubus', {
405 contentType: 'application/json',
406 data: JSON.stringify(req),
409 timeout: _luci2.globals.timeout
413 _list_cb: function(msg)
415 /* verify message frame */
416 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
417 throw 'Invalid JSON response';
422 _call_cb: function(msg)
425 var type = Object.prototype.toString;
430 for (var i = 0; i < msg.length; i++)
432 /* verify message frame */
433 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
434 throw 'Invalid JSON response';
436 /* fetch related request info */
437 var req = _luci2.rpc._requests[msg[i].id];
438 if (typeof(req) != 'object')
439 throw 'No related request for JSON response';
441 /* fetch response attribute and verify returned type */
444 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
445 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
449 for (var key in req.expect)
451 if (typeof(ret) != 'undefined' && key != '')
454 if (type.call(ret) != type.call(req.expect[key]))
455 ret = req.expect[key];
462 if (typeof(req.filter) == 'function')
465 req.priv[1] = req.params;
466 ret = req.filter.apply(_luci2.rpc, req.priv);
469 /* store response data */
470 if (typeof(req.index) == 'number')
471 data[req.index] = ret;
475 /* delete request object */
476 delete _luci2.rpc._requests[msg[i].id];
485 for (var i = 0; i < arguments.length; i++)
486 params[i] = arguments[i];
492 params: (params.length > 0) ? params : undefined
495 return this._call(msg, this._list_cb);
500 if (!$.isArray(this._batch))
506 if (!$.isArray(this._batch))
507 return _luci2.deferrable([ ]);
509 var req = this._batch;
513 return this._call(req, this._call_cb);
516 declare: function(options)
521 /* build parameter object */
524 if ($.isArray(options.params))
525 for (p_off = 0; p_off < options.params.length; p_off++)
526 params[options.params[p_off]] = arguments[p_off];
528 /* all remaining arguments are private args */
529 var priv = [ undefined, undefined ];
530 for (; p_off < arguments.length; p_off++)
531 priv.push(arguments[p_off]);
533 /* store request info */
534 var req = _rpc._requests[_rpc._id] = {
535 expect: options.expect,
536 filter: options.filter,
541 /* build message object */
554 /* when a batch is in progress then store index in request data
555 * and push message object onto the stack */
556 if ($.isArray(_rpc._batch))
558 req.index = _rpc._batch.push(msg) - 1;
559 return _luci2.deferrable(msg);
563 return _rpc._call(msg, _rpc._call_cb);
572 return _luci2.session.access('ubus', 'uci', 'commit');
575 add: _luci2.rpc.declare({
578 params: [ 'config', 'type', 'name', 'values' ],
579 expect: { section: '' }
587 configs: _luci2.rpc.declare({
590 expect: { configs: [ ] }
593 _changes: _luci2.rpc.declare({
596 params: [ 'config' ],
597 expect: { changes: [ ] }
600 changes: function(config)
602 if (typeof(config) == 'string')
603 return this._changes(config);
606 return this.configs().then(function(configs) {
608 configlist = configs;
610 for (var i = 0; i < configs.length; i++)
611 _luci2.uci._changes(configs[i]);
613 return _luci2.rpc.flush();
614 }).then(function(changes) {
617 for (var i = 0; i < configlist.length; i++)
618 if (changes[i].length)
619 rv[configlist[i]] = changes[i];
625 commit: _luci2.rpc.declare({
631 _delete_one: _luci2.rpc.declare({
634 params: [ 'config', 'section', 'option' ]
637 _delete_multiple: _luci2.rpc.declare({
640 params: [ 'config', 'section', 'options' ]
643 'delete': function(config, section, option)
645 if ($.isArray(option))
646 return this._delete_multiple(config, section, option);
648 return this._delete_one(config, section, option);
651 delete_all: _luci2.rpc.declare({
654 params: [ 'config', 'type', 'match' ]
657 _foreach: _luci2.rpc.declare({
660 params: [ 'config', 'type' ],
661 expect: { values: { } }
664 foreach: function(config, type, cb)
666 return this._foreach(config, type).then(function(sections) {
667 for (var s in sections)
672 get: _luci2.rpc.declare({
675 params: [ 'config', 'section', 'option' ],
677 filter: function(data, params) {
678 if (typeof(params.option) == 'undefined')
679 return data.values ? data.values['.type'] : undefined;
685 get_all: _luci2.rpc.declare({
688 params: [ 'config', 'section' ],
689 expect: { values: { } },
690 filter: function(data, params) {
691 if (typeof(params.section) == 'string')
692 data['.section'] = params.section;
693 else if (typeof(params.config) == 'string')
694 data['.package'] = params.config;
699 get_first: function(config, type, option)
701 return this._foreach(config, type).then(function(sections) {
702 for (var s in sections)
704 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
706 if (typeof(val) != 'undefined')
714 section: _luci2.rpc.declare({
717 params: [ 'config', 'type', 'name', 'values' ],
718 expect: { section: '' }
721 _set: _luci2.rpc.declare({
724 params: [ 'config', 'section', 'values' ]
727 set: function(config, section, option, value)
729 if (typeof(value) == 'undefined' && typeof(option) == 'string')
730 return this.section(config, section, option); /* option -> type */
731 else if ($.isPlainObject(option))
732 return this._set(config, section, option); /* option -> values */
735 values[option] = value;
737 return this._set(config, section, values);
740 order: _luci2.rpc.declare({
743 params: [ 'config', 'sections' ]
748 listNetworkNames: function() {
749 return _luci2.rpc.list('network.interface.*').then(function(list) {
751 for (var name in list)
752 if (name != 'network.interface.loopback')
753 names.push(name.substring(18));
759 listDeviceNames: _luci2.rpc.declare({
760 object: 'network.device',
763 filter: function(data) {
765 for (var name in data)
773 getNetworkStatus: function()
778 return this.listNetworkNames().then(function(names) {
781 for (var i = 0; i < names.length; i++)
782 _luci2.network.getInterfaceStatus(names[i]);
784 return _luci2.rpc.flush();
785 }).then(function(networks) {
786 for (var i = 0; i < networks.length; i++)
788 var net = nets[i] = networks[i];
789 var dev = net.l3_device || net.l2_device;
791 net.device = devs[dev] || (devs[dev] = { });
796 for (var dev in devs)
797 _luci2.network.getDeviceStatus(dev);
799 return _luci2.rpc.flush();
800 }).then(function(devices) {
803 for (var i = 0; i < devices.length; i++)
805 var brm = devices[i]['bridge-members'];
806 delete devices[i]['bridge-members'];
808 $.extend(devs[devices[i]['device']], devices[i]);
813 devs[devices[i]['device']].subdevices = [ ];
815 for (var j = 0; j < brm.length; j++)
820 _luci2.network.getDeviceStatus(brm[j]);
823 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
827 return _luci2.rpc.flush();
828 }).then(function(subdevices) {
829 for (var i = 0; i < subdevices.length; i++)
830 $.extend(devs[subdevices[i]['device']], subdevices[i]);
834 for (var dev in devs)
835 _luci2.wireless.getDeviceStatus(dev);
837 return _luci2.rpc.flush();
838 }).then(function(wifidevices) {
839 for (var i = 0; i < wifidevices.length; i++)
841 devs[wifidevices[i]['device']].wireless = wifidevices[i];
843 nets.sort(function(a, b) {
844 if (a['interface'] < b['interface'])
846 else if (a['interface'] > b['interface'])
856 findWanInterfaces: function(cb)
858 return this.listNetworkNames().then(function(names) {
861 for (var i = 0; i < names.length; i++)
862 _luci2.network.getInterfaceStatus(names[i]);
864 return _luci2.rpc.flush();
865 }).then(function(interfaces) {
866 var rv = [ undefined, undefined ];
868 for (var i = 0; i < interfaces.length; i++)
870 if (!interfaces[i].route)
873 for (var j = 0; j < interfaces[i].route.length; j++)
875 var rt = interfaces[i].route[j];
877 if (typeof(rt.table) != 'undefined')
880 if (rt.target == '0.0.0.0' && rt.mask == 0)
881 rv[0] = interfaces[i];
882 else if (rt.target == '::' && rt.mask == 0)
883 rv[1] = interfaces[i];
891 getDHCPLeases: _luci2.rpc.declare({
892 object: 'luci2.network',
893 method: 'dhcp_leases',
894 expect: { leases: [ ] }
897 getDHCPv6Leases: _luci2.rpc.declare({
898 object: 'luci2.network',
899 method: 'dhcp6_leases',
900 expect: { leases: [ ] }
903 getRoutes: _luci2.rpc.declare({
904 object: 'luci2.network',
906 expect: { routes: [ ] }
909 getIPv6Routes: _luci2.rpc.declare({
910 object: 'luci2.network',
912 expect: { routes: [ ] }
915 getARPTable: _luci2.rpc.declare({
916 object: 'luci2.network',
918 expect: { entries: [ ] }
921 getInterfaceStatus: _luci2.rpc.declare({
922 object: 'network.interface',
924 params: [ 'interface' ],
926 filter: function(data, params) {
927 data['interface'] = params['interface'];
928 data['l2_device'] = data['device'];
929 delete data['device'];
934 getDeviceStatus: _luci2.rpc.declare({
935 object: 'network.device',
939 filter: function(data, params) {
940 data['device'] = params['name'];
945 getConntrackCount: _luci2.rpc.declare({
946 object: 'luci2.network',
947 method: 'conntrack_count',
948 expect: { '': { count: 0, limit: 0 } }
951 listSwitchNames: _luci2.rpc.declare({
952 object: 'luci2.network',
953 method: 'switch_list',
954 expect: { switches: [ ] }
957 getSwitchInfo: _luci2.rpc.declare({
958 object: 'luci2.network',
959 method: 'switch_info',
960 params: [ 'switch' ],
961 expect: { info: { } },
962 filter: function(data, params) {
963 data['attrs'] = data['switch'];
964 data['vlan_attrs'] = data['vlan'];
965 data['port_attrs'] = data['port'];
966 data['switch'] = params['switch'];
975 getSwitchStatus: _luci2.rpc.declare({
976 object: 'luci2.network',
977 method: 'switch_status',
978 params: [ 'switch' ],
979 expect: { ports: [ ] }
984 listDeviceNames: _luci2.rpc.declare({
987 expect: { 'devices': [ ] },
988 filter: function(data) {
994 getDeviceStatus: _luci2.rpc.declare({
997 params: [ 'device' ],
999 filter: function(data, params) {
1000 if (!$.isEmptyObject(data))
1002 data['device'] = params['device'];
1009 getAssocList: _luci2.rpc.declare({
1011 method: 'assoclist',
1012 params: [ 'device' ],
1013 expect: { results: [ ] },
1014 filter: function(data, params) {
1015 for (var i = 0; i < data.length; i++)
1016 data[i]['device'] = params['device'];
1018 data.sort(function(a, b) {
1019 if (a.bssid < b.bssid)
1021 else if (a.bssid > b.bssid)
1031 getWirelessStatus: function() {
1032 return this.listDeviceNames().then(function(names) {
1035 for (var i = 0; i < names.length; i++)
1036 _luci2.wireless.getDeviceStatus(names[i]);
1038 return _luci2.rpc.flush();
1039 }).then(function(networks) {
1043 'country', 'channel', 'frequency', 'frequency_offset',
1044 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1048 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1049 'signal', 'noise', 'bitrate', 'encryption'
1052 for (var i = 0; i < networks.length; i++)
1054 var phy = rv[networks[i].phy] || (
1055 rv[networks[i].phy] = { networks: [ ] }
1059 device: networks[i].device
1062 for (var j = 0; j < phy_attrs.length; j++)
1063 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1065 for (var j = 0; j < net_attrs.length; j++)
1066 net[net_attrs[j]] = networks[i][net_attrs[j]];
1068 phy.networks.push(net);
1075 getAssocLists: function()
1077 return this.listDeviceNames().then(function(names) {
1080 for (var i = 0; i < names.length; i++)
1081 _luci2.wireless.getAssocList(names[i]);
1083 return _luci2.rpc.flush();
1084 }).then(function(assoclists) {
1087 for (var i = 0; i < assoclists.length; i++)
1088 for (var j = 0; j < assoclists[i].length; j++)
1089 rv.push(assoclists[i][j]);
1095 formatEncryption: function(enc)
1097 var format_list = function(l, s)
1100 for (var i = 0; i < l.length; i++)
1101 rv.push(l[i].toUpperCase());
1102 return rv.join(s ? s : ', ');
1105 if (!enc || !enc.enabled)
1106 return _luci2.tr('None');
1110 if (enc.wep.length == 2)
1111 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1112 else if (enc.wep[0] == 'shared')
1113 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1115 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1119 if (enc.wpa.length == 2)
1120 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1121 format_list(enc.authentication, '/'),
1122 format_list(enc.ciphers, ', ')
1124 else if (enc.wpa[0] == 2)
1125 return 'WPA2 %s (%s)'.format(
1126 format_list(enc.authentication, '/'),
1127 format_list(enc.ciphers, ', ')
1130 return 'WPA %s (%s)'.format(
1131 format_list(enc.authentication, '/'),
1132 format_list(enc.ciphers, ', ')
1136 return _luci2.tr('Unknown');
1141 getSystemInfo: _luci2.rpc.declare({
1147 getBoardInfo: _luci2.rpc.declare({
1153 getDiskInfo: _luci2.rpc.declare({
1154 object: 'luci2.system',
1159 getInfo: function(cb)
1163 this.getSystemInfo();
1164 this.getBoardInfo();
1167 return _luci2.rpc.flush().then(function(info) {
1170 $.extend(rv, info[0]);
1171 $.extend(rv, info[1]);
1172 $.extend(rv, info[2]);
1178 getProcessList: _luci2.rpc.declare({
1179 object: 'luci2.system',
1180 method: 'process_list',
1181 expect: { processes: [ ] },
1182 filter: function(data) {
1183 data.sort(function(a, b) { return a.pid - b.pid });
1188 getSystemLog: _luci2.rpc.declare({
1189 object: 'luci2.system',
1194 getKernelLog: _luci2.rpc.declare({
1195 object: 'luci2.system',
1200 getZoneInfo: function(cb)
1202 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1205 sendSignal: _luci2.rpc.declare({
1206 object: 'luci2.system',
1207 method: 'process_signal',
1208 params: [ 'pid', 'signal' ],
1209 filter: function(data) {
1214 initList: _luci2.rpc.declare({
1215 object: 'luci2.system',
1216 method: 'init_list',
1217 expect: { initscripts: [ ] },
1218 filter: function(data) {
1219 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1224 initEnabled: function(init, cb)
1226 return this.initList().then(function(list) {
1227 for (var i = 0; i < list.length; i++)
1228 if (list[i].name == init)
1229 return !!list[i].enabled;
1235 initRun: _luci2.rpc.declare({
1236 object: 'luci2.system',
1237 method: 'init_action',
1238 params: [ 'name', 'action' ],
1239 filter: function(data) {
1244 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1245 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1246 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1247 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1248 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1249 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1252 getRcLocal: _luci2.rpc.declare({
1253 object: 'luci2.system',
1254 method: 'rclocal_get',
1255 expect: { data: '' }
1258 setRcLocal: _luci2.rpc.declare({
1259 object: 'luci2.system',
1260 method: 'rclocal_set',
1265 getCrontab: _luci2.rpc.declare({
1266 object: 'luci2.system',
1267 method: 'crontab_get',
1268 expect: { data: '' }
1271 setCrontab: _luci2.rpc.declare({
1272 object: 'luci2.system',
1273 method: 'crontab_set',
1278 getSSHKeys: _luci2.rpc.declare({
1279 object: 'luci2.system',
1280 method: 'sshkeys_get',
1281 expect: { keys: [ ] }
1284 setSSHKeys: _luci2.rpc.declare({
1285 object: 'luci2.system',
1286 method: 'sshkeys_set',
1291 setPassword: _luci2.rpc.declare({
1292 object: 'luci2.system',
1293 method: 'password_set',
1294 params: [ 'user', 'password' ]
1298 listLEDs: _luci2.rpc.declare({
1299 object: 'luci2.system',
1301 expect: { leds: [ ] }
1304 listUSBDevices: _luci2.rpc.declare({
1305 object: 'luci2.system',
1307 expect: { devices: [ ] }
1311 testUpgrade: _luci2.rpc.declare({
1312 object: 'luci2.system',
1313 method: 'upgrade_test',
1317 startUpgrade: _luci2.rpc.declare({
1318 object: 'luci2.system',
1319 method: 'upgrade_start',
1323 cleanUpgrade: _luci2.rpc.declare({
1324 object: 'luci2.system',
1325 method: 'upgrade_clean'
1329 restoreBackup: _luci2.rpc.declare({
1330 object: 'luci2.system',
1331 method: 'backup_restore'
1334 cleanBackup: _luci2.rpc.declare({
1335 object: 'luci2.system',
1336 method: 'backup_clean'
1340 getBackupConfig: _luci2.rpc.declare({
1341 object: 'luci2.system',
1342 method: 'backup_config_get',
1343 expect: { config: '' }
1346 setBackupConfig: _luci2.rpc.declare({
1347 object: 'luci2.system',
1348 method: 'backup_config_set',
1353 listBackup: _luci2.rpc.declare({
1354 object: 'luci2.system',
1355 method: 'backup_list',
1356 expect: { files: [ ] }
1360 testReset: _luci2.rpc.declare({
1361 object: 'luci2.system',
1362 method: 'reset_test',
1363 expect: { supported: false }
1366 startReset: _luci2.rpc.declare({
1367 object: 'luci2.system',
1368 method: 'reset_start'
1372 performReboot: _luci2.rpc.declare({
1373 object: 'luci2.system',
1379 updateLists: _luci2.rpc.declare({
1380 object: 'luci2.opkg',
1385 _allPackages: _luci2.rpc.declare({
1386 object: 'luci2.opkg',
1388 params: [ 'offset', 'limit', 'pattern' ],
1392 _installedPackages: _luci2.rpc.declare({
1393 object: 'luci2.opkg',
1394 method: 'list_installed',
1395 params: [ 'offset', 'limit', 'pattern' ],
1399 _findPackages: _luci2.rpc.declare({
1400 object: 'luci2.opkg',
1402 params: [ 'offset', 'limit', 'pattern' ],
1406 _fetchPackages: function(action, offset, limit, pattern)
1410 return action(offset, limit, pattern).then(function(list) {
1411 if (!list.total || !list.packages)
1412 return { length: 0, total: 0 };
1414 packages.push.apply(packages, list.packages);
1415 packages.total = list.total;
1420 if (packages.length >= limit)
1425 for (var i = offset + packages.length; i < limit; i += 100)
1426 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1428 return _luci2.rpc.flush();
1429 }).then(function(lists) {
1430 for (var i = 0; i < lists.length; i++)
1432 if (!lists[i].total || !lists[i].packages)
1435 packages.push.apply(packages, lists[i].packages);
1436 packages.total = lists[i].total;
1443 listPackages: function(offset, limit, pattern)
1445 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1448 installedPackages: function(offset, limit, pattern)
1450 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1453 findPackages: function(offset, limit, pattern)
1455 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1458 installPackage: _luci2.rpc.declare({
1459 object: 'luci2.opkg',
1461 params: [ 'package' ],
1465 removePackage: _luci2.rpc.declare({
1466 object: 'luci2.opkg',
1468 params: [ 'package' ],
1472 getConfig: _luci2.rpc.declare({
1473 object: 'luci2.opkg',
1474 method: 'config_get',
1475 expect: { config: '' }
1478 setConfig: _luci2.rpc.declare({
1479 object: 'luci2.opkg',
1480 method: 'config_set',
1487 login: _luci2.rpc.declare({
1490 params: [ 'username', 'password' ],
1494 access: _luci2.rpc.declare({
1497 params: [ 'scope', 'object', 'function' ],
1498 expect: { access: false }
1503 return _luci2.session.access('ubus', 'session', 'access');
1506 startHeartbeat: function()
1508 this._hearbeatInterval = window.setInterval(function() {
1509 _luci2.session.isAlive().then(function(alive) {
1512 _luci2.session.stopHeartbeat();
1513 _luci2.ui.login(true);
1517 }, _luci2.globals.timeout * 2);
1520 stopHeartbeat: function()
1522 if (typeof(this._hearbeatInterval) != 'undefined')
1524 window.clearInterval(this._hearbeatInterval);
1525 delete this._hearbeatInterval;
1532 saveScrollTop: function()
1534 this._scroll_top = $(document).scrollTop();
1537 restoreScrollTop: function()
1539 if (typeof(this._scroll_top) == 'undefined')
1542 $(document).scrollTop(this._scroll_top);
1544 delete this._scroll_top;
1547 loading: function(enable)
1549 var win = $(window);
1550 var body = $('body');
1552 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1554 .addClass('cbi-modal-loader')
1555 .append($('<div />').text(_luci2.tr('Loading data...')))
1561 body.css('overflow', 'hidden');
1562 body.css('padding', 0);
1563 body.css('width', win.width());
1564 body.css('height', win.height());
1565 state.modal.css('width', win.width());
1566 state.modal.css('height', win.height());
1572 body.css('overflow', '');
1573 body.css('padding', '');
1574 body.css('width', '');
1575 body.css('height', '');
1579 dialog: function(title, content, options)
1581 var win = $(window);
1582 var body = $('body');
1584 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1585 dialog: $('<div />')
1586 .addClass('cbi-modal-dialog')
1587 .append($('<div />')
1588 .append($('<div />')
1589 .addClass('cbi-modal-dialog-header'))
1590 .append($('<div />')
1591 .addClass('cbi-modal-dialog-body'))
1592 .append($('<div />')
1593 .addClass('cbi-modal-dialog-footer')
1594 .append($('<button />')
1595 .addClass('cbi-button')
1596 .text(_luci2.tr('Close'))
1599 .css('overflow', '')
1604 $(this).parent().parent().parent().hide();
1609 if (typeof(options) != 'object')
1612 if (title === false)
1615 .css('overflow', '')
1620 state.dialog.hide();
1625 var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1626 var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1630 if (options.style == 'confirm')
1632 ftr.append($('<button />')
1633 .addClass('cbi-button')
1634 .text(_luci2.tr('Ok'))
1635 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1637 ftr.append($('<button />')
1638 .addClass('cbi-button')
1639 .text(_luci2.tr('Cancel'))
1640 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1642 else if (options.style == 'close')
1644 ftr.append($('<button />')
1645 .addClass('cbi-button')
1646 .text(_luci2.tr('Close'))
1647 .click(options.close || function() { _luci2.ui.dialog(false) }));
1649 else if (options.style == 'wait')
1651 ftr.append($('<button />')
1652 .addClass('cbi-button')
1653 .text(_luci2.tr('Close'))
1654 .attr('disabled', true));
1657 state.dialog.find('div.cbi-modal-dialog-header').text(title);
1658 state.dialog.show();
1661 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1665 state.dialog.children()
1666 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1668 body.css('overflow', 'hidden');
1669 body.css('padding', 0);
1670 body.css('width', win.width());
1671 body.css('height', win.height());
1672 state.dialog.css('width', win.width());
1673 state.dialog.css('height', win.height());
1676 upload: function(title, content, options)
1678 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1680 .attr('method', 'post')
1681 .attr('action', '/cgi-bin/luci-upload')
1682 .attr('enctype', 'multipart/form-data')
1683 .attr('target', 'cbi-fileupload-frame')
1685 .append($('<input />')
1686 .attr('type', 'hidden')
1687 .attr('name', 'sessionid'))
1688 .append($('<input />')
1689 .attr('type', 'hidden')
1690 .attr('name', 'filename'))
1691 .append($('<input />')
1692 .attr('type', 'file')
1693 .attr('name', 'filedata')
1694 .addClass('cbi-input-file'))
1695 .append($('<div />')
1696 .css('width', '100%')
1697 .addClass('progressbar')
1698 .addClass('intermediate')
1699 .append($('<div />')
1700 .css('width', '100%')))
1701 .append($('<iframe />')
1702 .attr('name', 'cbi-fileupload-frame')
1703 .css('width', '1px')
1704 .css('height', '1px')
1705 .css('visibility', 'hidden')),
1707 finish_cb: function(ev) {
1708 $(this).off('load');
1710 var body = (this.contentDocument || this.contentWindow.document).body;
1711 if (body.firstChild.tagName.toLowerCase() == 'pre')
1712 body = body.firstChild;
1716 json = $.parseJSON(body.innerHTML);
1719 message: _luci2.tr('Invalid server response received'),
1720 error: [ -1, _luci2.tr('Invalid data') ]
1726 L.ui.dialog(L.tr('File upload'), [
1727 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1728 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1729 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1730 ], { style: 'close' });
1732 else if (typeof(state.success_cb) == 'function')
1734 state.success_cb(json);
1738 confirm_cb: function() {
1739 var f = state.form.find('.cbi-input-file');
1740 var b = state.form.find('.progressbar');
1741 var p = state.form.find('p');
1746 state.form.find('iframe').on('load', state.finish_cb);
1747 state.form.submit();
1751 p.text(_luci2.tr('File upload in progress …'));
1753 state.form.parent().parent().find('button').prop('disabled', true);
1757 state.form.find('.progressbar').hide();
1758 state.form.find('.cbi-input-file').val('').show();
1759 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1761 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1762 state.form.find('[name=filename]').val(options.filename);
1764 state.success_cb = options.success;
1766 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1768 confirm: state.confirm_cb
1772 reconnect: function()
1774 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1775 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1776 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1778 var interval, timeout;
1781 _luci2.tr('Waiting for device'), [
1782 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1784 .css('width', '100%')
1785 .addClass('progressbar')
1786 .addClass('intermediate')
1787 .append($('<div />')
1788 .css('width', '100%'))
1789 ], { style: 'wait' }
1792 for (var i = 0; i < protocols.length; i++)
1793 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1795 //_luci2.network.getNetworkStatus(function(s) {
1796 // for (var i = 0; i < protocols.length; i++)
1798 // for (var j = 0; j < s.length; j++)
1800 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1801 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1803 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1804 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1807 //}).then(function() {
1808 images.on('load', function() {
1809 var url = this.getAttribute('url');
1810 _luci2.session.isAlive().then(function(access) {
1813 window.clearTimeout(timeout);
1814 window.clearInterval(interval);
1815 _luci2.ui.dialog(false);
1820 location.href = url;
1825 interval = window.setInterval(function() {
1826 images.each(function() {
1827 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1831 timeout = window.setTimeout(function() {
1832 window.clearInterval(interval);
1836 _luci2.tr('Device not responding'),
1837 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1844 login: function(invalid)
1846 var state = _luci2.ui._login || (_luci2.ui._login = {
1849 .attr('method', 'post')
1851 .addClass('alert-message')
1852 .text(_luci2.tr('Wrong username or password given!')))
1854 .append($('<label />')
1855 .text(_luci2.tr('Username'))
1856 .append($('<br />'))
1857 .append($('<input />')
1858 .attr('type', 'text')
1859 .attr('name', 'username')
1860 .attr('value', 'root')
1861 .addClass('cbi-input-text')
1862 .keypress(function(ev) {
1863 if (ev.which == 10 || ev.which == 13)
1867 .append($('<label />')
1868 .text(_luci2.tr('Password'))
1869 .append($('<br />'))
1870 .append($('<input />')
1871 .attr('type', 'password')
1872 .attr('name', 'password')
1873 .addClass('cbi-input-password')
1874 .keypress(function(ev) {
1875 if (ev.which == 10 || ev.which == 13)
1879 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1881 response_cb: function(response) {
1882 if (!response.ubus_rpc_session)
1884 _luci2.ui.login(true);
1888 _luci2.globals.sid = response.ubus_rpc_session;
1889 _luci2.setHash('id', _luci2.globals.sid);
1890 _luci2.session.startHeartbeat();
1891 _luci2.ui.dialog(false);
1892 state.deferred.resolve();
1896 confirm_cb: function() {
1897 var u = state.form.find('[name=username]').val();
1898 var p = state.form.find('[name=password]').val();
1904 _luci2.tr('Logging in'), [
1905 $('<p />').text(_luci2.tr('Log in in progress …')),
1907 .css('width', '100%')
1908 .addClass('progressbar')
1909 .addClass('intermediate')
1910 .append($('<div />')
1911 .css('width', '100%'))
1912 ], { style: 'wait' }
1915 _luci2.globals.sid = '00000000000000000000000000000000';
1916 _luci2.session.login(u, p).then(state.response_cb);
1920 if (!state.deferred || state.deferred.state() != 'pending')
1921 state.deferred = $.Deferred();
1923 /* try to find sid from hash */
1924 var sid = _luci2.getHash('id');
1925 if (sid && sid.match(/^[a-f0-9]{32}$/))
1927 _luci2.globals.sid = sid;
1928 _luci2.session.isAlive().then(function(access) {
1931 _luci2.session.startHeartbeat();
1932 state.deferred.resolve();
1936 _luci2.setHash('id', undefined);
1941 return state.deferred;
1945 state.form.find('.alert-message').show();
1947 state.form.find('.alert-message').hide();
1949 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
1951 confirm: state.confirm_cb
1954 state.form.find('[name=password]').focus();
1956 return state.deferred;
1959 cryptPassword: _luci2.rpc.declare({
1963 expect: { crypt: '' }
1967 _acl_merge_scope: function(acl_scope, scope)
1969 if ($.isArray(scope))
1971 for (var i = 0; i < scope.length; i++)
1972 acl_scope[scope[i]] = true;
1974 else if ($.isPlainObject(scope))
1976 for (var object_name in scope)
1978 if (!$.isArray(scope[object_name]))
1981 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
1983 for (var i = 0; i < scope[object_name].length; i++)
1984 acl_object[scope[object_name][i]] = true;
1989 _acl_merge_permission: function(acl_perm, perm)
1991 if ($.isPlainObject(perm))
1993 for (var scope_name in perm)
1995 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
1996 this._acl_merge_scope(acl_scope, perm[scope_name]);
2001 _acl_merge_group: function(acl_group, group)
2003 if ($.isPlainObject(group))
2005 if (!acl_group.description)
2006 acl_group.description = group.description;
2010 var acl_perm = acl_group.read || (acl_group.read = { });
2011 this._acl_merge_permission(acl_perm, group.read);
2016 var acl_perm = acl_group.write || (acl_group.write = { });
2017 this._acl_merge_permission(acl_perm, group.write);
2022 _acl_merge_tree: function(acl_tree, tree)
2024 if ($.isPlainObject(tree))
2026 for (var group_name in tree)
2028 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2029 this._acl_merge_group(acl_group, tree[group_name]);
2034 listAvailableACLs: _luci2.rpc.declare({
2037 expect: { acls: [ ] },
2038 filter: function(trees) {
2040 for (var i = 0; i < trees.length; i++)
2041 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2046 renderMainMenu: _luci2.rpc.declare({
2049 expect: { menu: { } },
2050 filter: function(entries) {
2051 _luci2.globals.mainMenu = new _luci2.ui.menu();
2052 _luci2.globals.mainMenu.entries(entries);
2056 .append(_luci2.globals.mainMenu.render(0, 1));
2060 renderViewMenu: function()
2064 .append(_luci2.globals.mainMenu.render(2, 900));
2067 renderView: function(node)
2069 var name = node.view.split(/\//).join('.');
2071 if (_luci2.globals.currentView)
2072 _luci2.globals.currentView.finish();
2074 _luci2.ui.renderViewMenu();
2077 _luci2._views = { };
2079 _luci2.setHash('view', node.view);
2081 if (_luci2._views[name] instanceof _luci2.ui.view)
2083 _luci2.globals.currentView = _luci2._views[name];
2084 return _luci2._views[name].render();
2087 var url = _luci2.globals.resource + '/view/' + name + '.js';
2089 return $.ajax(url, {
2093 }).then(function(data) {
2095 var viewConstructorSource = (
2096 '(function(L, $) { ' +
2098 '})(_luci2, $);\n\n' +
2100 ).format(data, url);
2102 var viewConstructor = eval(viewConstructorSource);
2104 _luci2._views[name] = new viewConstructor({
2106 acls: node.write || { }
2109 _luci2.globals.currentView = _luci2._views[name];
2110 return _luci2._views[name].render();
2113 alert('Unable to instantiate view "%s": %s'.format(url, e));
2116 return $.Deferred().resolve();
2120 updateHostname: function()
2122 return _luci2.system.getBoardInfo().then(function(info) {
2124 $('#hostname').text(info.hostname);
2128 updateChanges: function()
2130 return _luci2.uci.changes().then(function(changes) {
2134 for (var config in changes)
2138 for (var i = 0; i < changes[config].length; i++)
2140 var c = changes[config][i];
2149 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2151 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2156 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2158 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2162 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2166 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2170 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2175 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2177 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2182 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2183 n += changes[config].length;
2194 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2195 .click(function(ev) {
2196 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2197 ev.preventDefault();
2207 _luci2.ui.loading(true);
2210 _luci2.ui.updateHostname(),
2211 _luci2.ui.updateChanges(),
2212 _luci2.ui.renderMainMenu()
2214 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2215 _luci2.ui.loading(false);
2221 var AbstractWidget = Class.extend({
2222 i18n: function(text) {
2226 toString: function() {
2227 var x = document.createElement('div');
2228 x.appendChild(this.render());
2233 insertInto: function(id) {
2234 return $(id).empty().append(this.render());
2238 this.ui.view = AbstractWidget.extend({
2239 _fetch_template: function()
2241 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2245 success: function(data) {
2246 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2247 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2254 return _luci2.tr(p2);
2257 return _luci2.globals[p2] || '';
2260 return '(?' + match + ')';
2264 $('#maincontent').append(data);
2271 throw "Not implemented";
2276 var container = $('#maincontent');
2281 container.append($('<h2 />').append(this.title));
2283 if (this.description)
2284 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2287 return this._fetch_template().then(function() {
2288 return _luci2.deferrable(self.execute());
2292 repeat: function(func, interval)
2296 if (!self._timeouts)
2297 self._timeouts = [ ];
2299 var index = self._timeouts.length;
2301 if (typeof(interval) != 'number')
2304 var setTimer, runTimer;
2306 setTimer = function() {
2307 self._timeouts[index] = window.setTimeout(runTimer, interval);
2310 runTimer = function() {
2311 _luci2.deferrable(func.call(self)).then(setTimer);
2319 if ($.isArray(this._timeouts))
2321 for (var i = 0; i < this._timeouts.length; i++)
2322 window.clearTimeout(this._timeouts[i]);
2324 delete this._timeouts;
2329 this.ui.menu = AbstractWidget.extend({
2334 entries: function(entries)
2336 for (var entry in entries)
2338 var path = entry.split(/\//);
2339 var node = this._nodes;
2341 for (i = 0; i < path.length; i++)
2346 if (!node.childs[path[i]])
2347 node.childs[path[i]] = { };
2349 node = node.childs[path[i]];
2352 $.extend(node, entries[entry]);
2356 _indexcmp: function(a, b)
2358 var x = a.index || 0;
2359 var y = b.index || 0;
2363 firstChildView: function(node)
2369 for (var child in (node.childs || { }))
2370 nodes.push(node.childs[child]);
2372 nodes.sort(this._indexcmp);
2374 for (var i = 0; i < nodes.length; i++)
2376 var child = this.firstChildView(nodes[i]);
2379 for (var key in child)
2380 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2381 node[key] = child[key];
2390 _onclick: function(ev)
2392 _luci2.ui.loading(true);
2393 _luci2.ui.renderView(ev.data).then(function() {
2394 _luci2.ui.loading(false);
2397 ev.preventDefault();
2401 _render: function(childs, level, min, max)
2404 for (var node in childs)
2406 var child = this.firstChildView(childs[node]);
2408 nodes.push(childs[node]);
2411 nodes.sort(this._indexcmp);
2413 var list = $('<ul />');
2416 list.addClass('nav');
2417 else if (level == 1)
2418 list.addClass('dropdown-menu');
2420 for (var i = 0; i < nodes.length; i++)
2422 if (!_luci2.globals.defaultNode)
2424 var v = _luci2.getHash('view');
2425 if (!v || v == nodes[i].view)
2426 _luci2.globals.defaultNode = nodes[i];
2429 var item = $('<li />')
2432 .text(_luci2.tr(nodes[i].title))
2433 .click(nodes[i], this._onclick))
2436 if (nodes[i].childs && level < max)
2438 item.addClass('dropdown');
2439 item.find('a').addClass('menu');
2440 item.append(this._render(nodes[i].childs, level + 1));
2447 render: function(min, max)
2449 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2450 return this._render(top.childs, 0, min, max);
2453 getNode: function(path, max)
2455 var p = path.split(/\//);
2456 var n = this._nodes;
2458 if (typeof(max) == 'undefined')
2461 for (var i = 0; i < max; i++)
2463 if (!n.childs[p[i]])
2473 this.ui.table = AbstractWidget.extend({
2479 row: function(values)
2481 if ($.isArray(values))
2483 this._rows.push(values);
2485 else if ($.isPlainObject(values))
2488 for (var i = 0; i < this.options.columns.length; i++)
2490 var col = this.options.columns[i];
2492 if (typeof col.key == 'string')
2493 v.push(values[col.key]);
2501 rows: function(rows)
2503 for (var i = 0; i < rows.length; i++)
2507 render: function(id)
2509 var fieldset = document.createElement('fieldset');
2510 fieldset.className = 'cbi-section';
2512 if (this.options.caption)
2514 var legend = document.createElement('legend');
2515 $(legend).append(this.options.caption);
2516 fieldset.appendChild(legend);
2519 var table = document.createElement('table');
2520 table.className = 'cbi-section-table';
2522 var has_caption = false;
2523 var has_description = false;
2525 for (var i = 0; i < this.options.columns.length; i++)
2526 if (this.options.columns[i].caption)
2531 else if (this.options.columns[i].description)
2533 has_description = true;
2539 var tr = table.insertRow(-1);
2540 tr.className = 'cbi-section-table-titles';
2542 for (var i = 0; i < this.options.columns.length; i++)
2544 var col = this.options.columns[i];
2545 var th = document.createElement('th');
2546 th.className = 'cbi-section-table-cell';
2551 th.style.width = col.width;
2554 th.style.textAlign = col.align;
2557 $(th).append(col.caption);
2561 if (has_description)
2563 var tr = table.insertRow(-1);
2564 tr.className = 'cbi-section-table-descr';
2566 for (var i = 0; i < this.options.columns.length; i++)
2568 var col = this.options.columns[i];
2569 var th = document.createElement('th');
2570 th.className = 'cbi-section-table-cell';
2575 th.style.width = col.width;
2578 th.style.textAlign = col.align;
2580 if (col.description)
2581 $(th).append(col.description);
2585 if (this._rows.length == 0)
2587 if (this.options.placeholder)
2589 var tr = table.insertRow(-1);
2590 var td = tr.insertCell(-1);
2591 td.className = 'cbi-section-table-cell';
2593 td.colSpan = this.options.columns.length;
2594 $(td).append(this.options.placeholder);
2599 for (var i = 0; i < this._rows.length; i++)
2601 var tr = table.insertRow(-1);
2603 for (var j = 0; j < this.options.columns.length; j++)
2605 var col = this.options.columns[j];
2606 var td = tr.insertCell(-1);
2608 var val = this._rows[i][j];
2610 if (typeof(val) == 'undefined')
2611 val = col.placeholder;
2613 if (typeof(val) == 'undefined')
2617 td.style.width = col.width;
2620 td.style.textAlign = col.align;
2622 if (typeof col.format == 'string')
2623 $(td).append(col.format.format(val));
2624 else if (typeof col.format == 'function')
2625 $(td).append(col.format(val, i));
2633 fieldset.appendChild(table);
2639 this.ui.progress = AbstractWidget.extend({
2642 var vn = parseInt(this.options.value) || 0;
2643 var mn = parseInt(this.options.max) || 100;
2644 var pc = Math.floor((100 / mn) * vn);
2646 var bar = document.createElement('div');
2647 bar.className = 'progressbar';
2649 bar.appendChild(document.createElement('div'));
2650 bar.lastChild.appendChild(document.createElement('div'));
2651 bar.lastChild.style.width = pc + '%';
2653 if (typeof(this.options.format) == 'string')
2654 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2655 else if (typeof(this.options.format) == 'function')
2656 $(bar.lastChild.lastChild).append(this.options.format(pc));
2658 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2664 this.ui.devicebadge = AbstractWidget.extend({
2667 var dev = this.options.l3_device || this.options.device || '?';
2669 var span = document.createElement('span');
2670 span.className = 'ifacebadge';
2672 if (typeof(this.options.signal) == 'number' ||
2673 typeof(this.options.noise) == 'number')
2676 if (typeof(this.options.signal) != 'undefined' &&
2677 typeof(this.options.noise) != 'undefined')
2679 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2692 span.appendChild(document.createElement('img'));
2693 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2696 span.title = _luci2.tr('No signal');
2698 span.title = '%s: %d %s / %s: %d %s'.format(
2699 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2700 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2705 var type = 'ethernet';
2706 var desc = _luci2.tr('Ethernet device');
2708 if (this.options.l3_device != this.options.device)
2711 desc = _luci2.tr('Tunnel interface');
2713 else if (dev.indexOf('br-') == 0)
2716 desc = _luci2.tr('Bridge');
2718 else if (dev.indexOf('.') > 0)
2721 desc = _luci2.tr('VLAN interface');
2723 else if (dev.indexOf('wlan') == 0 ||
2724 dev.indexOf('ath') == 0 ||
2725 dev.indexOf('wl') == 0)
2728 desc = _luci2.tr('Wireless Network');
2731 span.appendChild(document.createElement('img'));
2732 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2736 $(span).append(' ');
2737 $(span).append(dev);
2743 var type = function(f, l)
2753 _luci2.cbi.validation.message = _luci2.tr(msg);
2756 compile: function(code)
2761 var types = _luci2.cbi.validation.types;
2766 for (var i = 0; i < code.length; i++)
2774 switch (code.charCodeAt(i))
2786 var label = code.substring(pos, i);
2787 label = label.replace(/\\(.)/g, '$1');
2788 label = label.replace(/^[ \t]+/g, '');
2789 label = label.replace(/[ \t]+$/g, '');
2791 if (label && !isNaN(label))
2793 stack.push(parseFloat(label));
2795 else if (label.match(/^(['"]).*\1$/))
2797 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2799 else if (typeof types[label] == 'function')
2801 stack.push(types[label]);
2806 throw "Syntax error, unhandled token '"+label+"'";
2811 depth += (code.charCodeAt(i) == 40);
2817 if (typeof stack[stack.length-2] != 'function')
2818 throw "Syntax error, argument list follows non-function";
2820 stack[stack.length-1] =
2821 arguments.callee(code.substring(pos, i));
2834 var validation = this.cbi.validation;
2836 validation.types = {
2837 'integer': function()
2839 if (this.match(/^-?[0-9]+$/) != null)
2842 validation.i18n('Must be a valid integer');
2846 'uinteger': function()
2848 if (validation.types['integer'].apply(this) && (this >= 0))
2851 validation.i18n('Must be a positive integer');
2857 if (!isNaN(parseFloat(this)))
2860 validation.i18n('Must be a valid number');
2864 'ufloat': function()
2866 if (validation.types['float'].apply(this) && (this >= 0))
2869 validation.i18n('Must be a positive number');
2873 'ipaddr': function()
2875 if (validation.types['ip4addr'].apply(this) ||
2876 validation.types['ip6addr'].apply(this))
2879 validation.i18n('Must be a valid IP address');
2883 'ip4addr': function()
2885 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2887 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2888 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2889 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2890 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2891 ((RegExp.$6.indexOf('.') < 0)
2892 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2893 : (validation.types['ip4addr'].apply(RegExp.$6))))
2897 validation.i18n('Must be a valid IPv4 address');
2901 'ip6addr': function()
2903 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2905 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2907 var addr = RegExp.$1;
2914 if (addr.indexOf('.') > 0)
2916 var off = addr.lastIndexOf(':');
2918 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2920 validation.i18n('Must be a valid IPv6 address');
2924 addr = addr.substr(0, off) + ':0:0';
2927 if (addr.indexOf('::') >= 0)
2932 for (var i = 1; i < (addr.length-1); i++)
2933 if (addr.charAt(i) == ':')
2938 validation.i18n('Must be a valid IPv6 address');
2942 for (var i = 0; i < (7 - colons); i++)
2945 if (addr.match(/^(.*?)::(.*?)$/))
2946 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2947 (RegExp.$2 ? ':' + RegExp.$2 : '');
2950 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2953 validation.i18n('Must be a valid IPv6 address');
2963 if (validation.types['integer'].apply(this) &&
2964 (this >= 0) && (this <= 65535))
2967 validation.i18n('Must be a valid port number');
2971 'portrange': function()
2973 if (this.match(/^(\d+)-(\d+)$/))
2978 if (validation.types['port'].apply(p1) &&
2979 validation.types['port'].apply(p2) &&
2980 (parseInt(p1) <= parseInt(p2)))
2983 else if (validation.types['port'].apply(this))
2988 validation.i18n('Must be a valid port range');
2992 'macaddr': function()
2994 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2997 validation.i18n('Must be a valid MAC address');
3003 if (validation.types['hostname'].apply(this) ||
3004 validation.types['ipaddr'].apply(this))
3007 validation.i18n('Must be a valid hostname or IP address');
3011 'hostname': function()
3013 if ((this.length <= 253) &&
3014 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3015 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3016 this.match(/[^0-9.]/)))))
3019 validation.i18n('Must be a valid host name');
3023 'network': function()
3025 if (validation.types['uciname'].apply(this) ||
3026 validation.types['host'].apply(this))
3029 validation.i18n('Must be a valid network name');
3033 'wpakey': function()
3037 if ((v.length == 64)
3038 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
3039 : ((v.length >= 8) && (v.length <= 63)))
3042 validation.i18n('Must be a valid WPA key');
3046 'wepkey': function()
3050 if (v.substr(0,2) == 's:')
3053 if (((v.length == 10) || (v.length == 26))
3054 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
3055 : ((v.length == 5) || (v.length == 13)))
3058 validation.i18n('Must be a valid WEP key');
3062 'uciname': function()
3064 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3067 validation.i18n('Must be a valid UCI identifier');
3071 'range': function(min, max)
3073 var val = parseFloat(this);
3075 if (validation.types['integer'].apply(this) &&
3076 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
3079 validation.i18n('Must be a number between %d and %d');
3083 'min': function(min)
3085 var val = parseFloat(this);
3087 if (validation.types['integer'].apply(this) &&
3088 !isNaN(min) && !isNaN(val) && (val >= min))
3091 validation.i18n('Must be a number greater or equal to %d');
3095 'max': function(max)
3097 var val = parseFloat(this);
3099 if (validation.types['integer'].apply(this) &&
3100 !isNaN(max) && !isNaN(val) && (val <= max))
3103 validation.i18n('Must be a number lower or equal to %d');
3107 'rangelength': function(min, max)
3109 var val = '' + this;
3111 if (!isNaN(min) && !isNaN(max) &&
3112 (val.length >= min) && (val.length <= max))
3115 validation.i18n('Must be between %d and %d characters');
3119 'minlength': function(min)
3121 var val = '' + this;
3123 if (!isNaN(min) && (val.length >= min))
3126 validation.i18n('Must be at least %d characters');
3130 'maxlength': function(max)
3132 var val = '' + this;
3134 if (!isNaN(max) && (val.length <= max))
3137 validation.i18n('Must be at most %d characters');
3145 for (var i = 0; i < arguments.length; i += 2)
3147 delete validation.message;
3149 if (typeof(arguments[i]) != 'function')
3151 if (arguments[i] == this)
3155 else if (arguments[i].apply(this, arguments[i+1]))
3160 if (validation.message)
3161 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3164 validation.message = msgs.join( _luci2.tr(' - or - '));
3172 for (var i = 0; i < arguments.length; i += 2)
3174 delete validation.message;
3176 if (typeof arguments[i] != 'function')
3178 if (arguments[i] != this)
3182 else if (!arguments[i].apply(this, arguments[i+1]))
3187 if (validation.message)
3188 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3191 validation.message = msgs.join(', ');
3197 return validation.types['or'].apply(
3198 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3201 'list': function(subvalidator, subargs)
3203 if (typeof subvalidator != 'function')
3206 var tokens = this.match(/[^ \t]+/g);
3207 for (var i = 0; i < tokens.length; i++)
3208 if (!subvalidator.apply(tokens[i], subargs))
3214 'phonedigit': function()
3216 if (this.match(/^[0-9\*#!\.]+$/) != null)
3219 validation.i18n('Must be a valid phone number digit');
3223 'string': function()
3230 this.cbi.AbstractValue = AbstractWidget.extend({
3231 init: function(name, options)
3234 this.instance = { };
3235 this.dependencies = [ ];
3236 this.rdependency = { };
3238 this.options = _luci2.defaults(options, {
3248 return this.section.id('field', sid || '__unknown__', this.name);
3251 render: function(sid)
3253 var i = this.instance[sid] = { };
3255 i.top = $('<div />').addClass('cbi-value');
3257 if (typeof(this.options.caption) == 'string')
3259 .addClass('cbi-value-title')
3260 .attr('for', this.id(sid))
3261 .text(this.options.caption)
3264 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
3265 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
3267 if (typeof(this.options.description) == 'string')
3269 .addClass('cbi-value-description')
3270 .text(this.options.description)
3276 ucipath: function(sid)
3279 config: (this.options.uci_package || this.map.uci_package),
3280 section: (this.options.uci_section || sid),
3281 option: (this.options.uci_option || this.name)
3285 ucivalue: function(sid)
3287 var uci = this.ucipath(sid);
3288 var val = this.map.get(uci.config, uci.section, uci.option);
3290 if (typeof(val) == 'undefined')
3291 return this.options.initial;
3296 formvalue: function(sid)
3298 var v = $('#' + this.id(sid)).val();
3299 return (v === '') ? undefined : v;
3302 textvalue: function(sid)
3304 var v = this.formvalue(sid);
3306 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3307 v = this.ucivalue(sid);
3309 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3310 v = this.options.placeholder;
3312 if (typeof(v) == 'undefined' || v === '')
3315 if (typeof(v) == 'string' && $.isArray(this.choices))
3317 for (var i = 0; i < this.choices.length; i++)
3318 if (v === this.choices[i][0])
3319 return this.choices[i][1];
3321 else if (v === true)
3322 return _luci2.tr('yes');
3323 else if (v === false)
3324 return _luci2.tr('no');
3325 else if ($.isArray(v))
3326 return v.join(', ');
3331 changed: function(sid)
3333 var a = this.ucivalue(sid);
3334 var b = this.formvalue(sid);
3336 if (typeof(a) != typeof(b))
3339 if (typeof(a) == 'object')
3341 if (a.length != b.length)
3344 for (var i = 0; i < a.length; i++)
3356 var uci = this.ucipath(sid);
3358 if (this.instance[sid].disabled)
3360 if (!this.options.keep)
3361 return this.map.set(uci.config, uci.section, uci.option, undefined);
3366 var chg = this.changed(sid);
3367 var val = this.formvalue(sid);
3370 this.map.set(uci.config, uci.section, uci.option, val);
3375 validator: function(sid, elem, multi)
3377 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3381 if (typeof(this.options.datatype) == 'string')
3384 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3387 else if (typeof(this.options.datatype) == 'function')
3389 var vfunc = this.options.datatype;
3390 vstack = [ function(elem) {
3391 var rv = vfunc(this, elem);
3393 validation.message = rv;
3394 return (rv === true);
3403 inst: this.instance[sid],
3404 opt: this.options.optional
3407 var validator = function(ev)
3411 var val = d.elem.val();
3413 if (vstack && typeof(vstack[0]) == 'function')
3415 delete validation.message;
3417 if ((val.length == 0 && !d.opt))
3419 d.elem.addClass('error');
3420 d.inst.top.addClass('error');
3421 d.inst.error.text(_luci2.tr('Field must not be empty'));
3424 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3426 d.elem.addClass('error');
3427 d.inst.top.addClass('error');
3428 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3433 d.elem.removeClass('error');
3435 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3441 d.inst.top.removeClass('error');
3442 d.inst.error.text('');
3449 for (var field in d.self.rdependency)
3450 d.self.rdependency[field].toggle(d.sid);
3456 if (elem.prop('tagName') == 'SELECT')
3458 elem.change(evdata, validator);
3460 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3462 elem.click(evdata, validator);
3463 elem.blur(evdata, validator);
3467 elem.keyup(evdata, validator);
3468 elem.blur(evdata, validator);
3471 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3476 validate: function(sid)
3478 var i = this.instance[sid];
3480 i.widget.find('[cbi-validate]').trigger('validate');
3482 return (i.disabled || i.error.text() == '');
3485 depends: function(d, v)
3492 for (var i = 0; i < d.length; i++)
3494 if (typeof(d[i]) == 'string')
3496 else if (d[i] instanceof _luci2.cbi.AbstractValue)
3497 dep[d[i].name] = true;
3500 else if (d instanceof _luci2.cbi.AbstractValue)
3503 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3505 else if (typeof(d) == 'object')
3509 else if (typeof(d) == 'string')
3512 dep[d] = (typeof(v) == 'undefined') ? true : v;
3515 if (!dep || $.isEmptyObject(dep))
3518 for (var field in dep)
3520 var f = this.section.fields[field];
3522 f.rdependency[this.name] = this;
3527 if ($.isEmptyObject(dep))
3530 this.dependencies.push(dep);
3535 toggle: function(sid)
3537 var d = this.dependencies;
3538 var i = this.instance[sid];
3543 for (var n = 0; n < d.length; n++)
3547 for (var field in d[n])
3549 var val = this.section.fields[field].formvalue(sid);
3550 var cmp = d[n][field];
3552 if (typeof(cmp) == 'boolean')
3554 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3560 else if (typeof(cmp) == 'string')
3568 else if (typeof(cmp) == 'function')
3576 else if (cmp instanceof RegExp)
3601 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3608 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
3609 widget: function(sid)
3611 var o = this.options;
3613 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3614 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3616 var i = $('<input />')
3617 .attr('id', this.id(sid))
3618 .attr('type', 'checkbox')
3619 .prop('checked', this.ucivalue(sid));
3621 return this.validator(sid, i);
3624 ucivalue: function(sid)
3626 var v = this.callSuper('ucivalue', sid);
3628 if (typeof(v) == 'boolean')
3631 return (v == this.options.enabled);
3634 formvalue: function(sid)
3636 var v = $('#' + this.id(sid)).prop('checked');
3638 if (typeof(v) == 'undefined')
3639 return !!this.options.initial;
3646 var uci = this.ucipath(sid);
3648 if (this.instance[sid].disabled)
3650 if (!this.options.keep)
3651 return this.map.set(uci.config, uci.section, uci.option, undefined);
3656 var chg = this.changed(sid);
3657 var val = this.formvalue(sid);
3661 if (this.options.optional && val == this.options.initial)
3662 this.map.set(uci.config, uci.section, uci.option, undefined);
3664 this.map.set(uci.config, uci.section, uci.option, val ? this.options.enabled : this.options.disabled);
3671 this.cbi.InputValue = this.cbi.AbstractValue.extend({
3672 widget: function(sid)
3674 var i = $('<input />')
3675 .attr('id', this.id(sid))
3676 .attr('type', 'text')
3677 .attr('placeholder', this.options.placeholder)
3678 .val(this.ucivalue(sid));
3680 return this.validator(sid, i);
3684 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
3685 widget: function(sid)
3687 var i = $('<input />')
3688 .attr('id', this.id(sid))
3689 .attr('type', 'password')
3690 .attr('placeholder', this.options.placeholder)
3691 .val(this.ucivalue(sid));
3693 var t = $('<img />')
3694 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3695 .attr('title', _luci2.tr('Reveal or hide password'))
3696 .addClass('cbi-button')
3697 .click(function(ev) {
3698 var i = $(this).prev();
3699 var t = i.attr('type');
3700 i.attr('type', (t == 'password') ? 'text' : 'password');
3704 this.validator(sid, i);
3707 .addClass('cbi-input-password')
3713 this.cbi.ListValue = this.cbi.AbstractValue.extend({
3714 widget: function(sid)
3716 var s = $('<select />');
3718 if (this.options.optional)
3721 .text(_luci2.tr('-- Please choose --'))
3725 for (var i = 0; i < this.choices.length; i++)
3727 .attr('value', this.choices[i][0])
3728 .text(this.choices[i][1])
3731 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3733 return this.validator(sid, s);
3736 value: function(k, v)
3741 this.choices.push([k, v || k]);
3746 this.cbi.MultiValue = this.cbi.ListValue.extend({
3747 widget: function(sid)
3749 var v = this.ucivalue(sid);
3750 var t = $('<div />').attr('id', this.id(sid));
3753 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3756 for (var i = 0; i < v.length; i++)
3760 for (var i = 0; i < this.choices.length; i++)
3763 .append($('<input />')
3764 .addClass('cbi-input-checkbox')
3765 .attr('type', 'checkbox')
3766 .attr('value', this.choices[i][0])
3767 .prop('checked', s[this.choices[i][0]]))
3768 .append(this.choices[i][1])
3778 formvalue: function(sid)
3781 var fields = $('#' + this.id(sid) + ' > label > input');
3783 for (var i = 0; i < fields.length; i++)
3784 if (fields[i].checked)
3785 rv.push(fields[i].getAttribute('value'));
3790 textvalue: function(sid)
3792 var v = this.formvalue(sid);
3796 for (var i = 0; i < this.choices.length; i++)
3797 c[this.choices[i][0]] = this.choices[i][1];
3801 for (var i = 0; i < v.length; i++)
3802 t.push(c[v[i]] || v[i]);
3804 return t.join(', ');
3808 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
3809 _change: function(ev)
3812 var self = ev.data.self;
3814 if (s.selectedIndex == (s.options.length - 1))
3816 ev.data.select.hide();
3817 ev.data.input.show().focus();
3819 var v = ev.data.input.val();
3820 ev.data.input.val(' ');
3821 ev.data.input.val(v);
3823 else if (self.options.optional && s.selectedIndex == 0)
3825 ev.data.input.val('');
3829 ev.data.input.val(ev.data.select.val());
3836 var val = this.value;
3837 var self = ev.data.self;
3839 ev.data.select.empty();
3841 if (self.options.optional)
3844 .text(_luci2.tr('-- please choose --'))
3845 .appendTo(ev.data.select);
3848 for (var i = 0; i < self.choices.length; i++)
3850 if (self.choices[i][0] == val)
3854 .attr('value', self.choices[i][0])
3855 .text(self.choices[i][1])
3856 .appendTo(ev.data.select);
3859 if (!seen && val != '')
3863 .appendTo(ev.data.select);
3867 .text(_luci2.tr('-- custom --'))
3868 .appendTo(ev.data.select);
3870 ev.data.input.hide();
3871 ev.data.select.val(val).show().focus();
3874 _enter: function(ev)
3879 ev.preventDefault();
3880 ev.data.self._blur(ev);
3884 widget: function(sid)
3886 var d = $('<div />')
3887 .attr('id', this.id(sid));
3889 var t = $('<input />')
3890 .attr('type', 'text')
3894 var s = $('<select />')
3899 input: this.validator(sid, t),
3900 select: this.validator(sid, s)
3903 s.change(evdata, this._change);
3904 t.blur(evdata, this._blur);
3905 t.keydown(evdata, this._enter);
3907 t.val(this.ucivalue(sid));
3913 value: function(k, v)
3918 this.choices.push([k, v || k]);
3922 formvalue: function(sid)
3924 var v = $('#' + this.id(sid)).children('input').val();
3925 return (v == '') ? undefined : v;
3929 this.cbi.DynamicList = this.cbi.ComboBox.extend({
3930 _redraw: function(focus, add, del, s)
3932 var v = s.values || [ ];
3935 $(s.parent).children('input').each(function(i) {
3937 v.push(this.value || '');
3940 $(s.parent).empty();
3945 v.splice(focus, 0, '');
3947 else if (v.length == 0)
3953 for (var i = 0; i < v.length; i++)
3964 var txt = $('<input />')
3965 .attr('type', 'text')
3967 .appendTo(s.parent);
3969 var sel = $('<select />')
3970 .appendTo(s.parent);
3972 evdata.input = this.validator(s.sid, txt, true);
3973 evdata.select = this.validator(s.sid, sel, true);
3975 sel.change(evdata, this._change);
3976 txt.blur(evdata, this._blur);
3977 txt.keydown(evdata, this._keydown);
3982 if (i == focus || -(i+1) == focus)
3989 var f = $('<input />')
3990 .attr('type', 'text')
3992 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
3993 .addClass('cbi-input-text')
3994 .keydown(evdata, this._keydown)
3995 .keypress(evdata, this._keypress)
3998 f.appendTo(s.parent);
4004 else if (-(i+1) == focus)
4008 /* force cursor to end */
4014 evdata.input = this.validator(s.sid, f, true);
4020 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
4021 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
4022 .addClass('cbi-button')
4023 .click(evdata, this._btnclick)
4024 .appendTo(s.parent);
4027 .appendTo(s.parent);
4035 _keypress: function(ev)
4039 /* backspace, delete */
4042 if (ev.data.input.val() == '')
4044 ev.preventDefault();
4050 /* enter, arrow up, arrow down */
4054 ev.preventDefault();
4061 _keydown: function(ev)
4063 var input = ev.data.input;
4067 /* backspace, delete */
4070 if (input.val().length == 0)
4072 ev.preventDefault();
4074 var index = ev.data.index;
4080 ev.data.self._redraw(focus, -1, index, ev.data);
4088 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4093 var prev = input.prevAll('input:first');
4094 if (prev.is(':visible'))
4097 prev.next('select').focus();
4102 var next = input.nextAll('input:first');
4103 if (next.is(':visible'))
4106 next.next('select').focus();
4113 _btnclick: function(ev)
4115 if (!this.getAttribute('disabled'))
4117 if (ev.target.src.indexOf('remove') > -1)
4119 var index = ev.data.index;
4120 ev.data.self._redraw(-index, -1, index, ev.data);
4124 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4131 widget: function(sid)
4133 this.options.optional = true;
4135 var v = this.ucivalue(sid);
4138 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4140 var d = $('<div />')
4141 .attr('id', this.id(sid))
4142 .addClass('cbi-input-dynlist');
4144 this._redraw(NaN, -1, -1, {
4154 ucivalue: function(sid)
4156 var v = this.callSuper('ucivalue', sid);
4159 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4164 formvalue: function(sid)
4167 var fields = $('#' + this.id(sid) + ' > input');
4169 for (var i = 0; i < fields.length; i++)
4170 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4171 rv.push(fields[i].value);
4177 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4178 widget: function(sid)
4181 .addClass('cbi-value-dummy')
4182 .attr('id', this.id(sid))
4183 .html(this.ucivalue(sid));
4186 formvalue: function(sid)
4188 return this.ucivalue(sid);
4192 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4197 if (!self.interfaces)
4199 self.interfaces = [ ];
4200 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4201 self.interfaces = ifaces;
4209 _device_icon: function(dev)
4211 var type = 'ethernet';
4212 var desc = _luci2.tr('Ethernet device');
4214 if (dev.type == 'IP tunnel')
4217 desc = _luci2.tr('Tunnel interface');
4219 else if (dev['bridge-members'])
4222 desc = _luci2.tr('Bridge');
4224 else if (dev.wireless)
4227 desc = _luci2.tr('Wireless Network');
4229 else if (dev.device.indexOf('.') > 0)
4232 desc = _luci2.tr('VLAN interface');
4236 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4237 .attr('title', '%s (%s)'.format(desc, dev.device));
4240 widget: function(sid)
4242 var id = this.id(sid);
4243 var ul = $('<ul />')
4245 .addClass('cbi-input-networks');
4247 var itype = this.options.multiple ? 'checkbox' : 'radio';
4248 var value = this.ucivalue(sid);
4251 if (!this.options.multiple)
4252 check[value] = true;
4254 for (var i = 0; i < value.length; i++)
4255 check[value[i]] = true;
4257 if (this.interfaces)
4259 for (var i = 0; i < this.interfaces.length; i++)
4261 var iface = this.interfaces[i];
4262 var badge = $('<span />')
4263 .addClass('ifacebadge')
4264 .text('%s: '.format(iface['interface']));
4266 if (iface.device && iface.device.subdevices)
4267 for (var j = 0; j < iface.device.subdevices.length; j++)
4268 badge.append(this._device_icon(iface.device.subdevices[j]));
4269 else if (iface.device)
4270 badge.append(this._device_icon(iface.device));
4272 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4275 .append($('<label />')
4276 .append($('<input />')
4277 .attr('name', itype + id)
4278 .attr('type', itype)
4279 .attr('value', iface['interface'])
4280 .prop('checked', !!check[iface['interface']])
4281 .addClass('cbi-input-' + itype))
4287 if (!this.options.multiple)
4290 .append($('<label />')
4291 .append($('<input />')
4292 .attr('name', itype + id)
4293 .attr('type', itype)
4295 .prop('checked', !value)
4296 .addClass('cbi-input-' + itype))
4297 .append(_luci2.tr('unspecified')))
4304 ucivalue: function(sid)
4306 var v = this.callSuper('ucivalue', sid);
4308 if (!this.options.multiple)
4314 else if (typeof(v) == 'string')
4317 return v ? v[0] : undefined;
4324 if (typeof(v) == 'string')
4325 v = v.match(/\S+/g);
4331 formvalue: function(sid)
4333 var inputs = $('#' + this.id(sid) + ' input');
4335 if (!this.options.multiple)
4337 for (var i = 0; i < inputs.length; i++)
4338 if (inputs[i].checked && inputs[i].value !== '')
4339 return inputs[i].value;
4346 for (var i = 0; i < inputs.length; i++)
4347 if (inputs[i].checked)
4348 rv.push(inputs[i].value);
4350 return rv.length ? rv : undefined;
4355 this.cbi.AbstractSection = AbstractWidget.extend({
4358 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4360 for (var i = 1; i < arguments.length; i++)
4361 s.push(arguments[i].replace(/\./g, '_'));
4366 option: function(widget, name, options)
4368 if (this.tabs.length == 0)
4369 this.tab({ id: '__default__', selected: true });
4371 return this.taboption('__default__', widget, name, options);
4374 tab: function(options)
4376 if (options.selected)
4377 this.tabs.selected = this.tabs.length;
4381 caption: options.caption,
4382 description: options.description,
4388 taboption: function(tabid, widget, name, options)
4391 for (var i = 0; i < this.tabs.length; i++)
4393 if (this.tabs[i].id == tabid)
4401 throw 'Cannot append to unknown tab ' + tabid;
4403 var w = widget ? new widget(name, options) : null;
4405 if (!(w instanceof _luci2.cbi.AbstractValue))
4406 throw 'Widget must be an instance of AbstractValue';
4411 this.fields[name] = w;
4417 ucipackages: function(pkg)
4419 for (var i = 0; i < this.tabs.length; i++)
4420 for (var j = 0; j < this.tabs[i].fields.length; j++)
4421 if (this.tabs[i].fields[j].options.uci_package)
4422 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4425 formvalue: function()
4429 this.sections(function(s) {
4430 var sid = s['.name'];
4431 var sv = rv[sid] || (rv[sid] = { });
4433 for (var i = 0; i < this.tabs.length; i++)
4434 for (var j = 0; j < this.tabs[i].fields.length; j++)
4436 var val = this.tabs[i].fields[j].formvalue(sid);
4437 sv[this.tabs[i].fields[j].name] = val;
4444 validate: function(sid)
4450 var as = this.sections();
4451 for (var i = 0; i < as.length; i++)
4452 if (!this.validate(as[i]['.name']))
4457 var inst = this.instance[sid];
4458 var sv = rv[sid] || (rv[sid] = { });
4461 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4463 legend.children('span').detach();
4465 for (var i = 0; i < this.tabs.length; i++)
4468 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4470 tab.children('span').detach();
4472 for (var j = 0; j < this.tabs[i].fields.length; j++)
4473 if (!this.tabs[i].fields[j].validate(sid))
4480 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4493 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4501 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
4502 init: function(uci_type, options)
4504 this.uci_type = uci_type;
4505 this.options = options;
4508 this.active_panel = 0;
4509 this.active_tab = { };
4512 filter: function(section)
4517 sections: function(cb)
4519 var s1 = this.map.ucisections(this.map.uci_package);
4522 for (var i = 0; i < s1.length; i++)
4523 if (s1[i]['.type'] == this.uci_type)
4524 if (this.filter(s1[i]))
4527 if (typeof(cb) == 'function')
4528 for (var i = 0; i < s2.length; i++)
4529 cb.apply(this, [ s2[i] ]);
4536 this.map.add(this.map.uci_package, this.uci_type, name);
4539 remove: function(sid)
4541 this.map.remove(this.map.uci_package, sid);
4547 var name = undefined;
4548 var self = ev.data.self;
4550 if (addb.prev().prop('nodeName') == 'INPUT')
4551 name = addb.prev().val();
4553 if (addb.prop('disabled') || name === '')
4556 _luci2.ui.saveScrollTop();
4558 self.active_panel = -1;
4563 _luci2.ui.restoreScrollTop();
4566 _remove: function(ev)
4568 var self = ev.data.self;
4569 var sid = ev.data.sid;
4571 if (ev.data.index == (self.sections().length - 1))
4572 self.active_panel = -1;
4574 _luci2.ui.saveScrollTop();
4580 _luci2.ui.restoreScrollTop();
4582 ev.stopPropagation();
4587 var self = ev.data.self;
4589 var addb = text.next();
4590 var errt = addb.next();
4591 var name = text.val();
4594 if (!/^[a-zA-Z0-9_]*$/.test(name))
4596 errt.text(_luci2.tr('Invalid section name')).show();
4597 text.addClass('error');
4598 addb.prop('disabled', true);
4602 for (var sid in self.map.uci.values[self.map.uci_package])
4609 for (var sid in self.map.uci.creates[self.map.uci_package])
4618 errt.text(_luci2.tr('Name already used')).show();
4619 text.addClass('error');
4620 addb.prop('disabled', true);
4624 errt.text('').hide();
4625 text.removeClass('error');
4626 addb.prop('disabled', false);
4630 teaser: function(sid)
4632 var tf = this.teaser_fields;
4636 tf = this.teaser_fields = [ ];
4638 if ($.isArray(this.options.teasers))
4640 for (var i = 0; i < this.options.teasers.length; i++)
4642 var f = this.options.teasers[i];
4643 if (f instanceof _luci2.cbi.AbstractValue)
4645 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
4646 tf.push(this.fields[f]);
4651 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4652 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4653 tf.push(this.tabs[i].fields[j]);
4659 for (var i = 0; i < tf.length; i++)
4661 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4664 var n = tf[i].options.caption || tf[i].name;
4665 var v = tf[i].textvalue(sid);
4667 if (typeof(v) == 'undefined')
4670 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4676 _render_add: function()
4678 var text = _luci2.tr('Add section');
4679 var ttip = _luci2.tr('Create new section...');
4681 if ($.isArray(this.options.add_caption))
4682 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4683 else if (typeof(this.options.add_caption) == 'string')
4684 text = this.options.add_caption, ttip = '';
4686 var add = $('<div />').addClass('cbi-section-add');
4688 if (this.options.anonymous === false)
4691 .addClass('cbi-input-text')
4692 .attr('type', 'text')
4693 .attr('placeholder', ttip)
4694 .blur({ self: this }, this._sid)
4695 .keyup({ self: this }, this._sid)
4699 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4700 .attr('title', text)
4701 .addClass('cbi-button')
4702 .click({ self: this }, this._add)
4706 .addClass('cbi-value-error')
4713 .attr('type', 'button')
4714 .addClass('cbi-button')
4715 .addClass('cbi-button-add')
4716 .val(text).attr('title', ttip)
4717 .click({ self: this }, this._add)
4724 _render_remove: function(sid, index)
4726 var text = _luci2.tr('Remove');
4727 var ttip = _luci2.tr('Remove this section');
4729 if ($.isArray(this.options.remove_caption))
4730 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4731 else if (typeof(this.options.remove_caption) == 'string')
4732 text = this.options.remove_caption, ttip = '';
4734 return $('<input />')
4735 .attr('type', 'button')
4736 .addClass('cbi-button')
4737 .addClass('cbi-button-remove')
4738 .val(text).attr('title', ttip)
4739 .click({ self: this, sid: sid, index: index }, this._remove);
4742 _render_caption: function(sid)
4744 if (typeof(this.options.caption) == 'string')
4746 return $('<legend />')
4747 .text(this.options.caption.format(sid));
4749 else if (typeof(this.options.caption) == 'function')
4751 return $('<legend />')
4752 .text(this.options.caption.call(this, sid));
4760 var allsections = $();
4761 var panel_index = 0;
4763 this.instance = { };
4765 var s = this.sections();
4769 var fieldset = $('<fieldset />')
4770 .addClass('cbi-section');
4772 var head = $('<div />')
4773 .addClass('cbi-section-head')
4774 .appendTo(fieldset);
4776 head.append(this._render_caption(undefined));
4778 if (typeof(this.options.description) == 'string')
4781 .addClass('cbi-section-descr')
4782 .text(this.options.description)
4786 allsections = allsections.add(fieldset);
4789 for (var i = 0; i < s.length; i++)
4791 var sid = s[i]['.name'];
4792 var inst = this.instance[sid] = { tabs: [ ] };
4794 var fieldset = $('<fieldset />')
4795 .attr('id', this.id('sort', sid))
4796 .addClass('cbi-section');
4798 var head = $('<div />')
4799 .addClass('cbi-section-head')
4800 .attr('cbi-section-num', this.index)
4801 .attr('cbi-section-id', sid);
4803 head.append(this._render_caption(sid));
4805 if (typeof(this.options.description) == 'string')
4808 .addClass('cbi-section-descr')
4809 .text(this.options.description)
4814 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4815 teaser = $('<div />')
4816 .addClass('cbi-section-teaser')
4819 if (this.options.addremove)
4821 .addClass('cbi-section-remove')
4823 .append(this._render_remove(sid, panel_index))
4826 var body = $('<div />')
4827 .attr('index', panel_index++);
4829 var fields = $('<fieldset />')
4830 .addClass('cbi-section-node');
4832 if (this.tabs.length > 1)
4834 var menu = $('<ul />')
4835 .addClass('cbi-tabmenu');
4837 for (var j = 0; j < this.tabs.length; j++)
4839 var tabid = this.id('tab', sid, this.tabs[j].id);
4840 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4842 var tabc = $('<div />')
4843 .addClass('cbi-tabcontainer')
4847 if (typeof(this.tabs[j].description) == 'string')
4850 .addClass('cbi-tab-descr')
4851 .text(this.tabs[j].description)
4855 for (var k = 0; k < this.tabs[j].fields.length; k++)
4856 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4858 tabc.appendTo(fields);
4861 $('<li />').attr('id', theadid).append(
4863 .text(this.tabs[j].caption.format(this.tabs[j].id))
4864 .attr('href', '#' + tabid)
4868 menu.appendTo(body);
4871 fields.appendTo(body);
4874 var t = body.tabs({ active: this.active_tab[sid] });
4876 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4879 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4884 for (var j = 0; j < this.tabs[0].fields.length; j++)
4885 this.tabs[0].fields[j].render(sid).appendTo(fields);
4887 fields.appendTo(body);
4891 head.appendTo(fieldset);
4894 body.appendTo(fieldset);
4897 allsections = allsections.add(fieldset);
4900 //this.validate(sid);
4903 // teaser.append(this.teaser(sid));
4906 if (this.options.collabsible && s.length > 1)
4908 var a = $('<div />').append(allsections).accordion({
4909 header: '> fieldset > div.cbi-section-head',
4910 heightStyle: 'content',
4911 active: this.active_panel
4914 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4915 var h = ui.oldHeader;
4916 var s = ev.data.self;
4917 var i = h.attr('cbi-section-id');
4919 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4923 a.on('accordionactivate', { self: this }, function(ev, ui) {
4924 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4927 if (this.options.sortable)
4929 var s = a.sortable({
4931 handle: 'div.cbi-section-head'
4934 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4936 for (var i = 0; i < ev.data.ids.length; i++)
4937 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4938 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4941 s.on('sortstop', function(ev, ui) {
4942 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4946 if (this.options.addremove)
4947 this._render_add().appendTo(a);
4952 if (this.options.addremove)
4953 allsections = allsections.add(this._render_add());
4960 var s = this.sections();
4962 for (var i = 0; i < s.length; i++)
4964 var sid = s[i]['.name'];
4968 $('#' + this.id('sort', sid))
4969 .children('.cbi-section-head')
4970 .children('.cbi-section-teaser')
4971 .append(this.teaser(sid));
4976 this.cbi.TableSection = this.cbi.TypedSection.extend({
4979 var allsections = $();
4980 var panel_index = 0;
4982 this.instance = { };
4984 var s = this.sections();
4986 var fieldset = $('<fieldset />')
4987 .addClass('cbi-section');
4989 fieldset.append(this._render_caption(sid));
4991 if (typeof(this.options.description) == 'string')
4994 .addClass('cbi-section-descr')
4995 .text(this.options.description)
4996 .appendTo(fieldset);
4999 var fields = $('<div />')
5000 .addClass('cbi-section-node')
5001 .appendTo(fieldset);
5003 var table = $('<table />')
5004 .addClass('cbi-section-table')
5007 var thead = $('<thead />')
5008 .append($('<tr />').addClass('cbi-section-table-titles'))
5011 for (var j = 0; j < this.tabs[0].fields.length; j++)
5013 .addClass('cbi-section-table-cell')
5014 .css('width', this.tabs[0].fields[j].options.width || '')
5015 .append(this.tabs[0].fields[j].options.caption)
5016 .appendTo(thead.children());
5018 if (this.options.sortable)
5019 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
5021 if (this.options.addremove !== false)
5022 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
5024 var tbody = $('<tbody />')
5030 .addClass('cbi-section-table-row')
5033 .addClass('cbi-section-table-cell')
5034 .addClass('cbi-section-table-placeholder')
5035 .attr('colspan', thead.children().children().length)
5036 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
5040 for (var i = 0; i < s.length; i++)
5042 var sid = s[i]['.name'];
5043 var inst = this.instance[sid] = { tabs: [ ] };
5045 var row = $('<tr />')
5046 .addClass('cbi-section-table-row')
5049 for (var j = 0; j < this.tabs[0].fields.length; j++)
5052 .addClass('cbi-section-table-cell')
5053 .css('width', this.tabs[0].fields[j].options.width || '')
5054 .append(this.tabs[0].fields[j].render(sid, true))
5058 if (this.options.sortable)
5061 .addClass('cbi-section-table-cell')
5062 .addClass('cbi-section-table-sort')
5063 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
5064 .append($('<br />'))
5065 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
5069 if (this.options.addremove !== false)
5072 .addClass('cbi-section-table-cell')
5073 .append(this._render_remove(sid))
5082 if (this.options.sortable)
5084 var s = tbody.sortable({
5085 handle: 'td.cbi-section-table-sort'
5088 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
5090 for (var i = 0; i < ev.data.ids.length; i++)
5091 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
5092 _luci2.uci.order(ev.data.self.map.uci_package, sections);
5095 s.on('sortstop', function(ev, ui) {
5096 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
5100 if (this.options.addremove)
5101 this._render_add().appendTo(fieldset);
5103 fields = table = thead = tbody = null;
5109 this.cbi.NamedSection = this.cbi.TypedSection.extend({
5110 sections: function(cb)
5113 var pkg = this.map.uci.values[this.map.uci_package];
5116 if (pkg[s]['.name'] == this.uci_type)
5122 if (typeof(cb) == 'function' && sa.length > 0)
5123 cb.apply(this, [ sa[0] ]);
5129 this.cbi.DummySection = this.cbi.TypedSection.extend({
5130 sections: function(cb)
5132 if (typeof(cb) == 'function')
5133 cb.apply(this, [ { '.name': this.uci_type } ]);
5135 return [ { '.name': this.uci_type } ];
5139 this.cbi.Map = AbstractWidget.extend({
5140 init: function(uci_package, options)
5144 this.uci_package = uci_package;
5145 this.sections = [ ];
5146 this.options = _luci2.defaults(options, {
5147 save: function() { },
5148 prepare: function() {
5149 return _luci2.uci.writable(function(writable) {
5150 self.options.readonly = !writable;
5166 if (typeof(this.active_panel) == 'undefined')
5167 this.active_panel = 0;
5171 for (var i = 0; i < this.sections.length; i++)
5172 this.sections[i].ucipackages(packages);
5174 packages[this.uci_package] = true;
5176 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
5177 for (var i = 0; i < packages.length; i++)
5179 this.uci.values[packages[i]['.package']] = packages[i];
5180 delete packages[i]['.package'];
5183 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5185 for (var i = 0; i < this.sections.length; i++)
5187 for (var f in this.sections[i].fields)
5189 if (typeof(this.sections[i].fields[f].load) != 'function')
5192 var s = this.sections[i].sections();
5193 for (var j = 0; j < s.length; j++)
5195 var rv = this.sections[i].fields[f].load(s[j]['.name']);
5196 if (_luci2.isDeferred(rv))
5202 return $.when.apply($, deferreds);
5207 for (var pkg in packages)
5208 _luci2.uci.get_all(pkg);
5210 return _luci2.rpc.flush().then(load_cb);
5215 var map = $('<div />').addClass('cbi-map');
5217 if (typeof(this.options.caption) == 'string')
5218 $('<h2 />').text(this.options.caption).appendTo(map);
5220 if (typeof(this.options.description) == 'string')
5221 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
5223 var sections = $('<div />').appendTo(map);
5225 for (var i = 0; i < this.sections.length; i++)
5227 var s = this.sections[i].render();
5229 if (this.options.readonly || this.sections[i].options.readonly)
5230 s.find('input, select, button, img.cbi-button').attr('disabled', true);
5232 s.appendTo(sections);
5234 if (this.sections[i].options.active)
5235 this.active_panel = i;
5238 if (this.options.collabsible)
5240 var a = sections.accordion({
5241 header: '> fieldset > div.cbi-section-head',
5242 heightStyle: 'content',
5243 active: this.active_panel
5246 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
5247 var h = ui.oldHeader;
5248 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
5249 var i = h.attr('cbi-section-id');
5251 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
5253 for (var i = 0; i < ev.data.self.sections.length; i++)
5254 ev.data.self.sections[i].validate();
5257 a.on('accordionactivate', { self: this }, function(ev, ui) {
5258 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
5262 if (this.options.pageaction !== false)
5264 var a = $('<div />')
5265 .addClass('cbi-page-actions')
5269 .addClass('cbi-button').addClass('cbi-button-apply')
5270 .attr('type', 'button')
5271 .val(_luci2.tr('Save & Apply'))
5275 .addClass('cbi-button').addClass('cbi-button-save')
5276 .attr('type', 'button')
5277 .val(_luci2.tr('Save'))
5278 .click({ self: this }, function(ev) { ev.data.self.send(); })
5282 .addClass('cbi-button').addClass('cbi-button-reset')
5283 .attr('type', 'button')
5284 .val(_luci2.tr('Reset'))
5285 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
5291 var top = $('<form />').append(map);
5300 for (var i = 0; i < this.sections.length; i++)
5301 this.sections[i].finish();
5308 this.target.hide().empty().append(this.render());
5313 section: function(widget, uci_type, options)
5315 var w = widget ? new widget(uci_type, options) : null;
5317 if (!(w instanceof _luci2.cbi.AbstractSection))
5318 throw 'Widget must be an instance of AbstractSection';
5321 w.index = this.sections.length;
5323 this.sections.push(w);
5327 formvalue: function()
5331 for (var i = 0; i < this.sections.length; i++)
5333 var sids = this.sections[i].formvalue();
5334 for (var sid in sids)
5336 var s = rv[sid] || (rv[sid] = { });
5337 $.extend(s, sids[sid]);
5344 add: function(conf, type, name)
5346 var c = this.uci.creates;
5347 var s = '.new.%d'.format(this.uci.newid++);
5362 remove: function(conf, sid)
5364 var n = this.uci.creates;
5365 var c = this.uci.changes;
5366 var d = this.uci.deletes;
5368 /* requested deletion of a just created section */
5369 if (sid.indexOf('.new.') == 0)
5372 delete n[conf][sid];
5377 delete c[conf][sid];
5382 d[conf][sid] = true;
5386 ucisections: function(conf, cb)
5389 var pkg = this.uci.values[conf];
5390 var crt = this.uci.creates[conf];
5391 var del = this.uci.deletes[conf];
5397 if (!del || del[s] !== true)
5400 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5406 if (typeof(cb) == 'function')
5407 for (var i = 0; i < sa.length; i++)
5408 cb.apply(this, [ sa[i] ]);
5413 get: function(conf, sid, opt)
5415 var v = this.uci.values;
5416 var n = this.uci.creates;
5417 var c = this.uci.changes;
5418 var d = this.uci.deletes;
5420 /* requested option in a just created section */
5421 if (sid.indexOf('.new.') == 0)
5426 if (typeof(opt) == 'undefined')
5427 return (n[conf][sid] || { });
5429 return n[conf][sid][opt];
5432 /* requested an option value */
5433 if (typeof(opt) != 'undefined')
5435 /* check whether option was deleted */
5436 if (d[conf] && d[conf][sid])
5438 if (d[conf][sid] === true)
5441 for (var i = 0; i < d[conf][sid].length; i++)
5442 if (d[conf][sid][i] == opt)
5446 /* check whether option was changed */
5447 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5448 return c[conf][sid][opt];
5450 /* return base value */
5451 if (v[conf] && v[conf][sid])
5452 return v[conf][sid][opt];
5457 /* requested an entire section */
5459 return (v[conf][sid] || { });
5464 set: function(conf, sid, opt, val)
5466 var n = this.uci.creates;
5467 var c = this.uci.changes;
5468 var d = this.uci.deletes;
5470 if (sid.indexOf('.new.') == 0)
5472 if (n[conf] && n[conf][sid])
5474 if (typeof(val) != 'undefined')
5475 n[conf][sid][opt] = val;
5477 delete n[conf][sid][opt];
5480 else if (typeof(val) != 'undefined')
5488 c[conf][sid][opt] = val;
5498 d[conf][sid].push(opt);
5502 validate: function()
5506 for (var i = 0; i < this.sections.length; i++)
5507 if (!this.sections[i].validate())
5515 if (this.options.readonly)
5516 return _luci2.deferrable();
5518 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5520 for (var i = 0; i < this.sections.length; i++)
5522 if (this.sections[i].options.readonly)
5525 for (var f in this.sections[i].fields)
5527 if (typeof(this.sections[i].fields[f].save) != 'function')
5530 var s = this.sections[i].sections();
5531 for (var j = 0; j < s.length; j++)
5533 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5534 if (_luci2.isDeferred(rv))
5540 return $.when.apply($, deferreds);
5545 if (!this.validate())
5546 return _luci2.deferrable();
5548 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5551 if (this.uci.creates)
5552 for (var c in this.uci.creates)
5553 for (var s in this.uci.creates[c])
5560 for (var k in this.uci.creates[c][s])
5563 r.type = this.uci.creates[c][s][k];
5564 else if (k == '.create')
5565 r.name = this.uci.creates[c][s][k];
5566 else if (k.charAt(0) != '.')
5567 r.values[k] = this.uci.creates[c][s][k];
5570 _luci2.uci.add(r.config, r.type, r.name, r.values);
5573 if (this.uci.changes)
5574 for (var c in this.uci.changes)
5575 for (var s in this.uci.changes[c])
5576 _luci2.uci.set(c, s, this.uci.changes[c][s]);
5578 if (this.uci.deletes)
5579 for (var c in this.uci.deletes)
5580 for (var s in this.uci.deletes[c])
5582 var o = this.uci.deletes[c][s];
5583 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
5586 return _luci2.rpc.flush().then(function() {
5587 return _luci2.ui.updateChanges();
5593 _luci2.ui.saveScrollTop();
5594 _luci2.ui.loading(true);
5596 return this.save().then(send_cb).then(function() {
5598 }).then(function() {
5602 _luci2.ui.loading(false);
5603 _luci2.ui.restoreScrollTop();
5607 dialog: function(id)
5609 var d = $('<div />');
5613 .attr('src', _luci2.globals.resource + '/icons/loading.gif')
5614 .css('vertical-align', 'middle')
5615 .css('padding-right', '10px')
5618 p.append(_luci2.tr('Loading data...'));
5629 $(this).parent().children('.ui-dialog-titlebar').hide();
5634 insertInto: function(id)
5637 self.target = $(id);
5639 _luci2.ui.loading(true);
5642 return self.load().then(function() {
5643 self.target.empty().append(self.render());
5647 _luci2.ui.loading(false);