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] = { };
796 for (var dev in devs)
797 _luci2.network.listDeviceNamestatus(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.listDeviceNamestatus(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 for (var j = 0; j < interfaces[i].route.length; j++)
872 var rt = interfaces[i].route[j];
874 if (typeof(rt.table) != 'undefined')
877 if (rt.target == '0.0.0.0' && rt.mask == 0)
878 rv[0] = interfaces[i];
879 else if (rt.target == '::' && rt.mask == 0)
880 rv[1] = interfaces[i];
888 getDHCPLeases: _luci2.rpc.declare({
889 object: 'luci2.network',
890 method: 'dhcp_leases',
891 expect: { leases: [ ] }
894 getDHCPv6Leases: _luci2.rpc.declare({
895 object: 'luci2.network',
896 method: 'dhcp6_leases',
897 expect: { leases: [ ] }
900 getRoutes: _luci2.rpc.declare({
901 object: 'luci2.network',
903 expect: { routes: [ ] }
906 getIPv6Routes: _luci2.rpc.declare({
907 object: 'luci2.network',
909 expect: { routes: [ ] }
912 getARPTable: _luci2.rpc.declare({
913 object: 'luci2.network',
915 expect: { entries: [ ] }
918 getInterfaceStatus: _luci2.rpc.declare({
919 object: 'network.interface',
921 params: [ 'interface' ],
923 filter: function(data, params) {
924 data['interface'] = params['interface'];
925 data['l2_device'] = data['device'];
926 delete data['device'];
931 listDeviceNamestatus: _luci2.rpc.declare({
932 object: 'network.device',
936 filter: function(data, params) {
937 data['device'] = params['name'];
942 getConntrackCount: _luci2.rpc.declare({
943 object: 'luci2.network',
944 method: 'conntrack_count',
945 expect: { '': { count: 0, limit: 0 } }
950 listDeviceNames: _luci2.rpc.declare({
953 expect: { 'devices': [ ] },
954 filter: function(data) {
960 getDeviceStatus: _luci2.rpc.declare({
963 params: [ 'device' ],
965 filter: function(data, params) {
966 if (!$.isEmptyObject(data))
968 data['device'] = params['device'];
975 getAssocList: _luci2.rpc.declare({
978 params: [ 'device' ],
979 expect: { results: [ ] },
980 filter: function(data, params) {
981 for (var i = 0; i < data.length; i++)
982 data[i]['device'] = params['device'];
984 data.sort(function(a, b) {
985 if (a.bssid < b.bssid)
987 else if (a.bssid > b.bssid)
997 getWirelessStatus: function() {
998 return this.listDeviceNames().then(function(names) {
1001 for (var i = 0; i < names.length; i++)
1002 _luci2.wireless.getDeviceStatus(names[i]);
1004 return _luci2.rpc.flush();
1005 }).then(function(networks) {
1009 'country', 'channel', 'frequency', 'frequency_offset',
1010 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1014 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1015 'signal', 'noise', 'bitrate', 'encryption'
1018 for (var i = 0; i < networks.length; i++)
1020 var phy = rv[networks[i].phy] || (
1021 rv[networks[i].phy] = { networks: [ ] }
1025 device: networks[i].device
1028 for (var j = 0; j < phy_attrs.length; j++)
1029 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1031 for (var j = 0; j < net_attrs.length; j++)
1032 net[net_attrs[j]] = networks[i][net_attrs[j]];
1034 phy.networks.push(net);
1041 getAssocLists: function()
1043 return this.listDeviceNames().then(function(names) {
1046 for (var i = 0; i < names.length; i++)
1047 _luci2.wireless.getAssocList(names[i]);
1049 return _luci2.rpc.flush();
1050 }).then(function(assoclists) {
1053 for (var i = 0; i < assoclists.length; i++)
1054 for (var j = 0; j < assoclists[i].length; j++)
1055 rv.push(assoclists[i][j]);
1061 formatEncryption: function(enc)
1063 var format_list = function(l, s)
1066 for (var i = 0; i < l.length; i++)
1067 rv.push(l[i].toUpperCase());
1068 return rv.join(s ? s : ', ');
1071 if (!enc || !enc.enabled)
1072 return _luci2.tr('None');
1076 if (enc.wep.length == 2)
1077 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1078 else if (enc.wep[0] == 'shared')
1079 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1081 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1085 if (enc.wpa.length == 2)
1086 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1087 format_list(enc.authentication, '/'),
1088 format_list(enc.ciphers, ', ')
1090 else if (enc.wpa[0] == 2)
1091 return 'WPA2 %s (%s)'.format(
1092 format_list(enc.authentication, '/'),
1093 format_list(enc.ciphers, ', ')
1096 return 'WPA %s (%s)'.format(
1097 format_list(enc.authentication, '/'),
1098 format_list(enc.ciphers, ', ')
1102 return _luci2.tr('Unknown');
1107 getSystemInfo: _luci2.rpc.declare({
1113 getBoardInfo: _luci2.rpc.declare({
1119 getDiskInfo: _luci2.rpc.declare({
1120 object: 'luci2.system',
1125 getInfo: function(cb)
1129 this.getSystemInfo();
1130 this.getBoardInfo();
1133 return _luci2.rpc.flush().then(function(info) {
1136 $.extend(rv, info[0]);
1137 $.extend(rv, info[1]);
1138 $.extend(rv, info[2]);
1144 getProcessList: _luci2.rpc.declare({
1145 object: 'luci2.system',
1146 method: 'process_list',
1147 expect: { processes: [ ] },
1148 filter: function(data) {
1149 data.sort(function(a, b) { return a.pid - b.pid });
1154 getSystemLog: _luci2.rpc.declare({
1155 object: 'luci2.system',
1160 getKernelLog: _luci2.rpc.declare({
1161 object: 'luci2.system',
1166 getZoneInfo: function(cb)
1168 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1171 sendSignal: _luci2.rpc.declare({
1172 object: 'luci2.system',
1173 method: 'process_signal',
1174 params: [ 'pid', 'signal' ],
1175 filter: function(data) {
1180 initList: _luci2.rpc.declare({
1181 object: 'luci2.system',
1182 method: 'init_list',
1183 expect: { initscripts: [ ] },
1184 filter: function(data) {
1185 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1190 initEnabled: function(init, cb)
1192 return this.initList().then(function(list) {
1193 for (var i = 0; i < list.length; i++)
1194 if (list[i].name == init)
1195 return !!list[i].enabled;
1201 initRun: _luci2.rpc.declare({
1202 object: 'luci2.system',
1203 method: 'init_action',
1204 params: [ 'name', 'action' ],
1205 filter: function(data) {
1210 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1211 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1212 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1213 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1214 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1215 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1218 getRcLocal: _luci2.rpc.declare({
1219 object: 'luci2.system',
1220 method: 'rclocal_get',
1221 expect: { data: '' }
1224 setRcLocal: _luci2.rpc.declare({
1225 object: 'luci2.system',
1226 method: 'rclocal_set',
1231 getCrontab: _luci2.rpc.declare({
1232 object: 'luci2.system',
1233 method: 'crontab_get',
1234 expect: { data: '' }
1237 setCrontab: _luci2.rpc.declare({
1238 object: 'luci2.system',
1239 method: 'crontab_set',
1244 getSSHKeys: _luci2.rpc.declare({
1245 object: 'luci2.system',
1246 method: 'sshkeys_get',
1247 expect: { keys: [ ] }
1250 setSSHKeys: _luci2.rpc.declare({
1251 object: 'luci2.system',
1252 method: 'sshkeys_set',
1257 setPassword: _luci2.rpc.declare({
1258 object: 'luci2.system',
1259 method: 'password_set',
1260 params: [ 'user', 'password' ]
1264 listLEDs: _luci2.rpc.declare({
1265 object: 'luci2.system',
1267 expect: { leds: [ ] }
1270 listUSBDevices: _luci2.rpc.declare({
1271 object: 'luci2.system',
1273 expect: { devices: [ ] }
1277 testUpgrade: _luci2.rpc.declare({
1278 object: 'luci2.system',
1279 method: 'upgrade_test',
1283 startUpgrade: _luci2.rpc.declare({
1284 object: 'luci2.system',
1285 method: 'upgrade_start',
1289 cleanUpgrade: _luci2.rpc.declare({
1290 object: 'luci2.system',
1291 method: 'upgrade_clean'
1295 restoreBackup: _luci2.rpc.declare({
1296 object: 'luci2.system',
1297 method: 'backup_restore'
1300 cleanBackup: _luci2.rpc.declare({
1301 object: 'luci2.system',
1302 method: 'backup_clean'
1306 getBackupConfig: _luci2.rpc.declare({
1307 object: 'luci2.system',
1308 method: 'backup_config_get',
1309 expect: { config: '' }
1312 setBackupConfig: _luci2.rpc.declare({
1313 object: 'luci2.system',
1314 method: 'backup_config_set',
1319 listBackup: _luci2.rpc.declare({
1320 object: 'luci2.system',
1321 method: 'backup_list',
1322 expect: { files: [ ] }
1326 testReset: _luci2.rpc.declare({
1327 object: 'luci2.system',
1328 method: 'reset_test',
1329 expect: { supported: false }
1332 startReset: _luci2.rpc.declare({
1333 object: 'luci2.system',
1334 method: 'reset_start'
1338 performReboot: _luci2.rpc.declare({
1339 object: 'luci2.system',
1345 updateLists: _luci2.rpc.declare({
1346 object: 'luci2.opkg',
1351 _allPackages: _luci2.rpc.declare({
1352 object: 'luci2.opkg',
1354 params: [ 'offset', 'limit', 'pattern' ],
1358 _installedPackages: _luci2.rpc.declare({
1359 object: 'luci2.opkg',
1360 method: 'list_installed',
1361 params: [ 'offset', 'limit', 'pattern' ],
1365 _findPackages: _luci2.rpc.declare({
1366 object: 'luci2.opkg',
1368 params: [ 'offset', 'limit', 'pattern' ],
1372 _fetchPackages: function(action, offset, limit, pattern)
1376 return action(offset, limit, pattern).then(function(list) {
1377 if (!list.total || !list.packages)
1378 return { length: 0, total: 0 };
1380 packages.push.apply(packages, list.packages);
1381 packages.total = list.total;
1386 if (packages.length >= limit)
1391 for (var i = offset + packages.length; i < limit; i += 100)
1392 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1394 return _luci2.rpc.flush();
1395 }).then(function(lists) {
1396 for (var i = 0; i < lists.length; i++)
1398 if (!lists[i].total || !lists[i].packages)
1401 packages.push.apply(packages, lists[i].packages);
1402 packages.total = lists[i].total;
1409 listPackages: function(offset, limit, pattern)
1411 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1414 installedPackages: function(offset, limit, pattern)
1416 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1419 findPackages: function(offset, limit, pattern)
1421 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1424 installPackage: _luci2.rpc.declare({
1425 object: 'luci2.opkg',
1427 params: [ 'package' ],
1431 removePackage: _luci2.rpc.declare({
1432 object: 'luci2.opkg',
1434 params: [ 'package' ],
1438 getConfig: _luci2.rpc.declare({
1439 object: 'luci2.opkg',
1440 method: 'config_get',
1441 expect: { config: '' }
1444 setConfig: _luci2.rpc.declare({
1445 object: 'luci2.opkg',
1446 method: 'config_set',
1453 login: _luci2.rpc.declare({
1456 params: [ 'username', 'password' ],
1460 access: _luci2.rpc.declare({
1463 params: [ 'scope', 'object', 'function' ],
1464 expect: { access: false }
1469 return _luci2.session.access('ubus', 'session', 'access');
1472 startHeartbeat: function()
1474 this._hearbeatInterval = window.setInterval(function() {
1475 _luci2.session.isAlive().then(function(alive) {
1478 _luci2.session.stopHeartbeat();
1479 _luci2.ui.login(true);
1483 }, _luci2.globals.timeout * 2);
1486 stopHeartbeat: function()
1488 if (typeof(this._hearbeatInterval) != 'undefined')
1490 window.clearInterval(this._hearbeatInterval);
1491 delete this._hearbeatInterval;
1498 saveScrollTop: function()
1500 this._scroll_top = $(document).scrollTop();
1503 restoreScrollTop: function()
1505 if (typeof(this._scroll_top) == 'undefined')
1508 $(document).scrollTop(this._scroll_top);
1510 delete this._scroll_top;
1513 loading: function(enable)
1515 var win = $(window);
1516 var body = $('body');
1518 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1520 .addClass('cbi-modal-loader')
1521 .append($('<div />').text(_luci2.tr('Loading data...')))
1527 body.css('overflow', 'hidden');
1528 body.css('padding', 0);
1529 body.css('width', win.width());
1530 body.css('height', win.height());
1531 state.modal.css('width', win.width());
1532 state.modal.css('height', win.height());
1538 body.css('overflow', '');
1539 body.css('padding', '');
1540 body.css('width', '');
1541 body.css('height', '');
1545 dialog: function(title, content, options)
1547 var win = $(window);
1548 var body = $('body');
1550 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1551 dialog: $('<div />')
1552 .addClass('cbi-modal-dialog')
1553 .append($('<div />')
1554 .append($('<div />')
1555 .addClass('cbi-modal-dialog-header'))
1556 .append($('<div />')
1557 .addClass('cbi-modal-dialog-body'))
1558 .append($('<div />')
1559 .addClass('cbi-modal-dialog-footer')
1560 .append($('<button />')
1561 .addClass('cbi-button')
1562 .text(_luci2.tr('Close'))
1565 .css('overflow', '')
1570 $(this).parent().parent().parent().hide();
1575 if (typeof(options) != 'object')
1578 if (title === false)
1581 .css('overflow', '')
1586 state.dialog.hide();
1591 var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1592 var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1596 if (options.style == 'confirm')
1598 ftr.append($('<button />')
1599 .addClass('cbi-button')
1600 .text(_luci2.tr('Ok'))
1601 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1603 ftr.append($('<button />')
1604 .addClass('cbi-button')
1605 .text(_luci2.tr('Cancel'))
1606 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1608 else if (options.style == 'close')
1610 ftr.append($('<button />')
1611 .addClass('cbi-button')
1612 .text(_luci2.tr('Close'))
1613 .click(options.close || function() { _luci2.ui.dialog(false) }));
1615 else if (options.style == 'wait')
1617 ftr.append($('<button />')
1618 .addClass('cbi-button')
1619 .text(_luci2.tr('Close'))
1620 .attr('disabled', true));
1623 state.dialog.find('div.cbi-modal-dialog-header').text(title);
1624 state.dialog.show();
1627 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1631 state.dialog.children()
1632 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1634 body.css('overflow', 'hidden');
1635 body.css('padding', 0);
1636 body.css('width', win.width());
1637 body.css('height', win.height());
1638 state.dialog.css('width', win.width());
1639 state.dialog.css('height', win.height());
1642 upload: function(title, content, options)
1644 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1646 .attr('method', 'post')
1647 .attr('action', '/cgi-bin/luci-upload')
1648 .attr('enctype', 'multipart/form-data')
1649 .attr('target', 'cbi-fileupload-frame')
1651 .append($('<input />')
1652 .attr('type', 'hidden')
1653 .attr('name', 'sessionid'))
1654 .append($('<input />')
1655 .attr('type', 'hidden')
1656 .attr('name', 'filename'))
1657 .append($('<input />')
1658 .attr('type', 'file')
1659 .attr('name', 'filedata')
1660 .addClass('cbi-input-file'))
1661 .append($('<div />')
1662 .css('width', '100%')
1663 .addClass('progressbar')
1664 .addClass('intermediate')
1665 .append($('<div />')
1666 .css('width', '100%')))
1667 .append($('<iframe />')
1668 .attr('name', 'cbi-fileupload-frame')
1669 .css('width', '1px')
1670 .css('height', '1px')
1671 .css('visibility', 'hidden')),
1673 finish_cb: function(ev) {
1674 $(this).off('load');
1676 var body = (this.contentDocument || this.contentWindow.document).body;
1677 if (body.firstChild.tagName.toLowerCase() == 'pre')
1678 body = body.firstChild;
1682 json = $.parseJSON(body.innerHTML);
1685 message: _luci2.tr('Invalid server response received'),
1686 error: [ -1, _luci2.tr('Invalid data') ]
1692 L.ui.dialog(L.tr('File upload'), [
1693 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1694 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1695 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1696 ], { style: 'close' });
1698 else if (typeof(state.success_cb) == 'function')
1700 state.success_cb(json);
1704 confirm_cb: function() {
1705 var f = state.form.find('.cbi-input-file');
1706 var b = state.form.find('.progressbar');
1707 var p = state.form.find('p');
1712 state.form.find('iframe').on('load', state.finish_cb);
1713 state.form.submit();
1717 p.text(_luci2.tr('File upload in progress …'));
1719 state.form.parent().parent().find('button').prop('disabled', true);
1723 state.form.find('.progressbar').hide();
1724 state.form.find('.cbi-input-file').val('').show();
1725 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1727 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1728 state.form.find('[name=filename]').val(options.filename);
1730 state.success_cb = options.success;
1732 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1734 confirm: state.confirm_cb
1738 reconnect: function()
1740 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1741 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1742 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1744 var interval, timeout;
1747 _luci2.tr('Waiting for device'), [
1748 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1750 .css('width', '100%')
1751 .addClass('progressbar')
1752 .addClass('intermediate')
1753 .append($('<div />')
1754 .css('width', '100%'))
1755 ], { style: 'wait' }
1758 for (var i = 0; i < protocols.length; i++)
1759 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1761 //_luci2.network.getNetworkStatus(function(s) {
1762 // for (var i = 0; i < protocols.length; i++)
1764 // for (var j = 0; j < s.length; j++)
1766 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1767 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1769 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1770 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1773 //}).then(function() {
1774 images.on('load', function() {
1775 var url = this.getAttribute('url');
1776 _luci2.session.isAlive().then(function(access) {
1779 window.clearTimeout(timeout);
1780 window.clearInterval(interval);
1781 _luci2.ui.dialog(false);
1786 location.href = url;
1791 interval = window.setInterval(function() {
1792 images.each(function() {
1793 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1797 timeout = window.setTimeout(function() {
1798 window.clearInterval(interval);
1802 _luci2.tr('Device not responding'),
1803 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1810 login: function(invalid)
1812 var state = _luci2.ui._login || (_luci2.ui._login = {
1815 .attr('method', 'post')
1817 .addClass('alert-message')
1818 .text(_luci2.tr('Wrong username or password given!')))
1820 .append($('<label />')
1821 .text(_luci2.tr('Username'))
1822 .append($('<br />'))
1823 .append($('<input />')
1824 .attr('type', 'text')
1825 .attr('name', 'username')
1826 .attr('value', 'root')
1827 .addClass('cbi-input-text')
1828 .keypress(function(ev) {
1829 if (ev.which == 10 || ev.which == 13)
1833 .append($('<label />')
1834 .text(_luci2.tr('Password'))
1835 .append($('<br />'))
1836 .append($('<input />')
1837 .attr('type', 'password')
1838 .attr('name', 'password')
1839 .addClass('cbi-input-password')
1840 .keypress(function(ev) {
1841 if (ev.which == 10 || ev.which == 13)
1845 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1847 response_cb: function(response) {
1848 if (!response.ubus_rpc_session)
1850 _luci2.ui.login(true);
1854 _luci2.globals.sid = response.ubus_rpc_session;
1855 _luci2.setHash('id', _luci2.globals.sid);
1856 _luci2.session.startHeartbeat();
1857 _luci2.ui.dialog(false);
1858 state.deferred.resolve();
1862 confirm_cb: function() {
1863 var u = state.form.find('[name=username]').val();
1864 var p = state.form.find('[name=password]').val();
1870 _luci2.tr('Logging in'), [
1871 $('<p />').text(_luci2.tr('Log in in progress …')),
1873 .css('width', '100%')
1874 .addClass('progressbar')
1875 .addClass('intermediate')
1876 .append($('<div />')
1877 .css('width', '100%'))
1878 ], { style: 'wait' }
1881 _luci2.globals.sid = '00000000000000000000000000000000';
1882 _luci2.session.login(u, p).then(state.response_cb);
1886 if (!state.deferred || state.deferred.state() != 'pending')
1887 state.deferred = $.Deferred();
1889 /* try to find sid from hash */
1890 var sid = _luci2.getHash('id');
1891 if (sid && sid.match(/^[a-f0-9]{32}$/))
1893 _luci2.globals.sid = sid;
1894 _luci2.session.isAlive().then(function(access) {
1897 _luci2.session.startHeartbeat();
1898 state.deferred.resolve();
1902 _luci2.setHash('id', undefined);
1907 return state.deferred;
1911 state.form.find('.alert-message').show();
1913 state.form.find('.alert-message').hide();
1915 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
1917 confirm: state.confirm_cb
1920 state.form.find('[name=password]').focus();
1922 return state.deferred;
1925 cryptPassword: _luci2.rpc.declare({
1929 expect: { crypt: '' }
1933 _acl_merge_scope: function(acl_scope, scope)
1935 if ($.isArray(scope))
1937 for (var i = 0; i < scope.length; i++)
1938 acl_scope[scope[i]] = true;
1940 else if ($.isPlainObject(scope))
1942 for (var object_name in scope)
1944 if (!$.isArray(scope[object_name]))
1947 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
1949 for (var i = 0; i < scope[object_name].length; i++)
1950 acl_object[scope[object_name][i]] = true;
1955 _acl_merge_permission: function(acl_perm, perm)
1957 if ($.isPlainObject(perm))
1959 for (var scope_name in perm)
1961 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
1962 this._acl_merge_scope(acl_scope, perm[scope_name]);
1967 _acl_merge_group: function(acl_group, group)
1969 if ($.isPlainObject(group))
1971 if (!acl_group.description)
1972 acl_group.description = group.description;
1976 var acl_perm = acl_group.read || (acl_group.read = { });
1977 this._acl_merge_permission(acl_perm, group.read);
1982 var acl_perm = acl_group.write || (acl_group.write = { });
1983 this._acl_merge_permission(acl_perm, group.write);
1988 _acl_merge_tree: function(acl_tree, tree)
1990 if ($.isPlainObject(tree))
1992 for (var group_name in tree)
1994 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
1995 this._acl_merge_group(acl_group, tree[group_name]);
2000 listAvailableACLs: _luci2.rpc.declare({
2003 expect: { acls: [ ] },
2004 filter: function(trees) {
2006 for (var i = 0; i < trees.length; i++)
2007 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2012 renderMainMenu: _luci2.rpc.declare({
2015 expect: { menu: { } },
2016 filter: function(entries) {
2017 _luci2.globals.mainMenu = new _luci2.ui.menu();
2018 _luci2.globals.mainMenu.entries(entries);
2022 .append(_luci2.globals.mainMenu.render(0, 1));
2026 renderViewMenu: function()
2030 .append(_luci2.globals.mainMenu.render(2, 900));
2033 renderView: function(node)
2035 var name = node.view.split(/\//).join('.');
2037 _luci2.ui.renderViewMenu();
2040 _luci2._views = { };
2042 _luci2.setHash('view', node.view);
2044 if (_luci2._views[name] instanceof _luci2.ui.view)
2045 return _luci2._views[name].render();
2047 var url = _luci2.globals.resource + '/view/' + name + '.js';
2049 return $.ajax(url, {
2053 }).then(function(data) {
2055 var viewConstructorSource = (
2056 '(function(L, $) {\n' +
2058 '})(_luci2, $);\n\n' +
2060 ).format(data, url);
2062 var viewConstructor = eval(viewConstructorSource);
2064 _luci2._views[name] = new viewConstructor({
2066 acls: node.write || { }
2069 return _luci2._views[name].render();
2072 alert('Unable to instantiate view "%s": %s'.format(url, e));
2075 return $.Deferred().resolve();
2079 updateHostname: function()
2081 return _luci2.system.getBoardInfo().then(function(info) {
2083 $('#hostname').text(info.hostname);
2087 updateChanges: function()
2089 return _luci2.uci.changes().then(function(changes) {
2093 for (var config in changes)
2097 for (var i = 0; i < changes[config].length; i++)
2099 var c = changes[config][i];
2108 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2110 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2115 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2117 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2121 log.push('uci add %s (= <ins><strong>%s</strong></ins>)'.format(config, c[1]));
2125 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2129 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2134 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2136 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2141 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2142 n += changes[config].length;
2153 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2154 .click(function(ev) {
2155 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2156 ev.preventDefault();
2166 _luci2.ui.loading(true);
2169 _luci2.ui.updateHostname(),
2170 _luci2.ui.updateChanges(),
2171 _luci2.ui.renderMainMenu()
2173 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2174 _luci2.ui.loading(false);
2180 var AbstractWidget = Class.extend({
2181 i18n: function(text) {
2185 toString: function() {
2186 var x = document.createElement('div');
2187 x.appendChild(this.render());
2192 insertInto: function(id) {
2193 return $(id).empty().append(this.render());
2197 this.ui.view = AbstractWidget.extend({
2198 _fetch_template: function()
2200 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2204 success: function(data) {
2205 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2206 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2213 return _luci2.tr(p2);
2216 return _luci2.globals[p2] || '';
2219 return '(?' + match + ')';
2223 $('#maincontent').append(data);
2230 throw "Not implemented";
2235 var container = $('#maincontent');
2240 container.append($('<h2 />').append(this.title));
2242 if (this.description)
2243 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2246 return this._fetch_template().then(function() {
2247 return _luci2.deferrable(self.execute());
2252 this.ui.menu = AbstractWidget.extend({
2257 entries: function(entries)
2259 for (var entry in entries)
2261 var path = entry.split(/\//);
2262 var node = this._nodes;
2264 for (i = 0; i < path.length; i++)
2269 if (!node.childs[path[i]])
2270 node.childs[path[i]] = { };
2272 node = node.childs[path[i]];
2275 $.extend(node, entries[entry]);
2279 _indexcmp: function(a, b)
2281 var x = a.index || 0;
2282 var y = b.index || 0;
2286 firstChildView: function(node)
2292 for (var child in (node.childs || { }))
2293 nodes.push(node.childs[child]);
2295 nodes.sort(this._indexcmp);
2297 for (var i = 0; i < nodes.length; i++)
2299 var child = this.firstChildView(nodes[i]);
2302 $.extend(node, child);
2310 _onclick: function(ev)
2312 _luci2.ui.loading(true);
2313 _luci2.ui.renderView(ev.data).then(function() {
2314 _luci2.ui.loading(false);
2317 ev.preventDefault();
2321 _render: function(childs, level, min, max)
2324 for (var node in childs)
2326 var child = this.firstChildView(childs[node]);
2328 nodes.push(childs[node]);
2331 nodes.sort(this._indexcmp);
2333 var list = $('<ul />');
2336 list.addClass('nav');
2337 else if (level == 1)
2338 list.addClass('dropdown-menu');
2340 for (var i = 0; i < nodes.length; i++)
2342 if (!_luci2.globals.defaultNode)
2344 var v = _luci2.getHash('view');
2345 if (!v || v == nodes[i].view)
2346 _luci2.globals.defaultNode = nodes[i];
2349 var item = $('<li />')
2352 .text(_luci2.tr(nodes[i].title))
2353 .click(nodes[i], this._onclick))
2356 if (nodes[i].childs && level < max)
2358 item.addClass('dropdown');
2359 item.find('a').addClass('menu');
2360 item.append(this._render(nodes[i].childs, level + 1));
2367 render: function(min, max)
2369 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2370 return this._render(top.childs, 0, min, max);
2373 getNode: function(path, max)
2375 var p = path.split(/\//);
2376 var n = this._nodes;
2378 if (typeof(max) == 'undefined')
2381 for (var i = 0; i < max; i++)
2383 if (!n.childs[p[i]])
2393 this.ui.table = AbstractWidget.extend({
2399 row: function(values)
2401 if ($.isArray(values))
2403 this._rows.push(values);
2405 else if ($.isPlainObject(values))
2408 for (var i = 0; i < this.options.columns.length; i++)
2410 var col = this.options.columns[i];
2412 if (typeof col.key == 'string')
2413 v.push(values[col.key]);
2421 rows: function(rows)
2423 for (var i = 0; i < rows.length; i++)
2427 render: function(id)
2429 var fieldset = document.createElement('fieldset');
2430 fieldset.className = 'cbi-section';
2432 if (this.options.caption)
2434 var legend = document.createElement('legend');
2435 $(legend).append(this.options.caption);
2436 fieldset.appendChild(legend);
2439 var table = document.createElement('table');
2440 table.className = 'cbi-section-table';
2442 var has_caption = false;
2443 var has_description = false;
2445 for (var i = 0; i < this.options.columns.length; i++)
2446 if (this.options.columns[i].caption)
2451 else if (this.options.columns[i].description)
2453 has_description = true;
2459 var tr = table.insertRow(-1);
2460 tr.className = 'cbi-section-table-titles';
2462 for (var i = 0; i < this.options.columns.length; i++)
2464 var col = this.options.columns[i];
2465 var th = document.createElement('th');
2466 th.className = 'cbi-section-table-cell';
2471 th.style.width = col.width;
2474 th.style.textAlign = col.align;
2477 $(th).append(col.caption);
2481 if (has_description)
2483 var tr = table.insertRow(-1);
2484 tr.className = 'cbi-section-table-descr';
2486 for (var i = 0; i < this.options.columns.length; i++)
2488 var col = this.options.columns[i];
2489 var th = document.createElement('th');
2490 th.className = 'cbi-section-table-cell';
2495 th.style.width = col.width;
2498 th.style.textAlign = col.align;
2500 if (col.description)
2501 $(th).append(col.description);
2505 if (this._rows.length == 0)
2507 if (this.options.placeholder)
2509 var tr = table.insertRow(-1);
2510 var td = tr.insertCell(-1);
2511 td.className = 'cbi-section-table-cell';
2513 td.colSpan = this.options.columns.length;
2514 $(td).append(this.options.placeholder);
2519 for (var i = 0; i < this._rows.length; i++)
2521 var tr = table.insertRow(-1);
2523 for (var j = 0; j < this.options.columns.length; j++)
2525 var col = this.options.columns[j];
2526 var td = tr.insertCell(-1);
2528 var val = this._rows[i][j];
2530 if (typeof(val) == 'undefined')
2531 val = col.placeholder;
2533 if (typeof(val) == 'undefined')
2537 td.style.width = col.width;
2540 td.style.textAlign = col.align;
2542 if (typeof col.format == 'string')
2543 $(td).append(col.format.format(val));
2544 else if (typeof col.format == 'function')
2545 $(td).append(col.format(val, i));
2553 fieldset.appendChild(table);
2559 this.ui.progress = AbstractWidget.extend({
2562 var vn = parseInt(this.options.value) || 0;
2563 var mn = parseInt(this.options.max) || 100;
2564 var pc = Math.floor((100 / mn) * vn);
2566 var bar = document.createElement('div');
2567 bar.className = 'progressbar';
2569 bar.appendChild(document.createElement('div'));
2570 bar.lastChild.appendChild(document.createElement('div'));
2571 bar.lastChild.style.width = pc + '%';
2573 if (typeof(this.options.format) == 'string')
2574 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2575 else if (typeof(this.options.format) == 'function')
2576 $(bar.lastChild.lastChild).append(this.options.format(pc));
2578 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2584 this.ui.devicebadge = AbstractWidget.extend({
2587 var dev = this.options.l3_device || this.options.device || '?';
2589 var span = document.createElement('span');
2590 span.className = 'ifacebadge';
2592 if (typeof(this.options.signal) == 'number' ||
2593 typeof(this.options.noise) == 'number')
2596 if (typeof(this.options.signal) != 'undefined' &&
2597 typeof(this.options.noise) != 'undefined')
2599 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2612 span.appendChild(document.createElement('img'));
2613 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2616 span.title = _luci2.tr('No signal');
2618 span.title = '%s: %d %s / %s: %d %s'.format(
2619 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2620 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2625 var type = 'ethernet';
2626 var desc = _luci2.tr('Ethernet device');
2628 if (this.options.l3_device != this.options.device)
2631 desc = _luci2.tr('Tunnel interface');
2633 else if (dev.indexOf('br-') == 0)
2636 desc = _luci2.tr('Bridge');
2638 else if (dev.indexOf('.') > 0)
2641 desc = _luci2.tr('VLAN interface');
2643 else if (dev.indexOf('wlan') == 0 ||
2644 dev.indexOf('ath') == 0 ||
2645 dev.indexOf('wl') == 0)
2648 desc = _luci2.tr('Wireless Network');
2651 span.appendChild(document.createElement('img'));
2652 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2656 $(span).append(' ');
2657 $(span).append(dev);
2663 var type = function(f, l)
2673 _luci2.cbi.validation.message = _luci2.tr(msg);
2676 compile: function(code)
2681 var types = _luci2.cbi.validation.types;
2686 for (var i = 0; i < code.length; i++)
2694 switch (code.charCodeAt(i))
2706 var label = code.substring(pos, i);
2707 label = label.replace(/\\(.)/g, '$1');
2708 label = label.replace(/^[ \t]+/g, '');
2709 label = label.replace(/[ \t]+$/g, '');
2711 if (label && !isNaN(label))
2713 stack.push(parseFloat(label));
2715 else if (label.match(/^(['"]).*\1$/))
2717 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2719 else if (typeof types[label] == 'function')
2721 stack.push(types[label]);
2726 throw "Syntax error, unhandled token '"+label+"'";
2731 depth += (code.charCodeAt(i) == 40);
2737 if (typeof stack[stack.length-2] != 'function')
2738 throw "Syntax error, argument list follows non-function";
2740 stack[stack.length-1] =
2741 arguments.callee(code.substring(pos, i));
2754 var validation = this.cbi.validation;
2756 validation.types = {
2757 'integer': function()
2759 if (this.match(/^-?[0-9]+$/) != null)
2762 validation.i18n('Must be a valid integer');
2766 'uinteger': function()
2768 if (validation.types['integer'].apply(this) && (this >= 0))
2771 validation.i18n('Must be a positive integer');
2777 if (!isNaN(parseFloat(this)))
2780 validation.i18n('Must be a valid number');
2784 'ufloat': function()
2786 if (validation.types['float'].apply(this) && (this >= 0))
2789 validation.i18n('Must be a positive number');
2793 'ipaddr': function()
2795 if (validation.types['ip4addr'].apply(this) ||
2796 validation.types['ip6addr'].apply(this))
2799 validation.i18n('Must be a valid IP address');
2803 'ip4addr': function()
2805 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2807 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2808 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2809 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2810 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2811 ((RegExp.$6.indexOf('.') < 0)
2812 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2813 : (validation.types['ip4addr'].apply(RegExp.$6))))
2817 validation.i18n('Must be a valid IPv4 address');
2821 'ip6addr': function()
2823 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2825 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2827 var addr = RegExp.$1;
2834 if (addr.indexOf('.') > 0)
2836 var off = addr.lastIndexOf(':');
2838 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2840 validation.i18n('Must be a valid IPv6 address');
2844 addr = addr.substr(0, off) + ':0:0';
2847 if (addr.indexOf('::') >= 0)
2852 for (var i = 1; i < (addr.length-1); i++)
2853 if (addr.charAt(i) == ':')
2858 validation.i18n('Must be a valid IPv6 address');
2862 for (var i = 0; i < (7 - colons); i++)
2865 if (addr.match(/^(.*?)::(.*?)$/))
2866 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2867 (RegExp.$2 ? ':' + RegExp.$2 : '');
2870 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2873 validation.i18n('Must be a valid IPv6 address');
2883 if (validation.types['integer'].apply(this) &&
2884 (this >= 0) && (this <= 65535))
2887 validation.i18n('Must be a valid port number');
2891 'portrange': function()
2893 if (this.match(/^(\d+)-(\d+)$/))
2898 if (validation.types['port'].apply(p1) &&
2899 validation.types['port'].apply(p2) &&
2900 (parseInt(p1) <= parseInt(p2)))
2903 else if (validation.types['port'].apply(this))
2908 validation.i18n('Must be a valid port range');
2912 'macaddr': function()
2914 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2917 validation.i18n('Must be a valid MAC address');
2923 if (validation.types['hostname'].apply(this) ||
2924 validation.types['ipaddr'].apply(this))
2927 validation.i18n('Must be a valid hostname or IP address');
2931 'hostname': function()
2933 if ((this.length <= 253) &&
2934 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2935 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2936 this.match(/[^0-9.]/)))))
2939 validation.i18n('Must be a valid host name');
2943 'network': function()
2945 if (validation.types['uciname'].apply(this) ||
2946 validation.types['host'].apply(this))
2949 validation.i18n('Must be a valid network name');
2953 'wpakey': function()
2957 if ((v.length == 64)
2958 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2959 : ((v.length >= 8) && (v.length <= 63)))
2962 validation.i18n('Must be a valid WPA key');
2966 'wepkey': function()
2970 if (v.substr(0,2) == 's:')
2973 if (((v.length == 10) || (v.length == 26))
2974 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2975 : ((v.length == 5) || (v.length == 13)))
2978 validation.i18n('Must be a valid WEP key');
2982 'uciname': function()
2984 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2987 validation.i18n('Must be a valid UCI identifier');
2991 'range': function(min, max)
2993 var val = parseFloat(this);
2995 if (validation.types['integer'].apply(this) &&
2996 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
2999 validation.i18n('Must be a number between %d and %d');
3003 'min': function(min)
3005 var val = parseFloat(this);
3007 if (validation.types['integer'].apply(this) &&
3008 !isNaN(min) && !isNaN(val) && (val >= min))
3011 validation.i18n('Must be a number greater or equal to %d');
3015 'max': function(max)
3017 var val = parseFloat(this);
3019 if (validation.types['integer'].apply(this) &&
3020 !isNaN(max) && !isNaN(val) && (val <= max))
3023 validation.i18n('Must be a number lower or equal to %d');
3027 'rangelength': function(min, max)
3029 var val = '' + this;
3031 if (!isNaN(min) && !isNaN(max) &&
3032 (val.length >= min) && (val.length <= max))
3035 validation.i18n('Must be between %d and %d characters');
3039 'minlength': function(min)
3041 var val = '' + this;
3043 if (!isNaN(min) && (val.length >= min))
3046 validation.i18n('Must be at least %d characters');
3050 'maxlength': function(max)
3052 var val = '' + this;
3054 if (!isNaN(max) && (val.length <= max))
3057 validation.i18n('Must be at most %d characters');
3065 for (var i = 0; i < arguments.length; i += 2)
3067 delete validation.message;
3069 if (typeof(arguments[i]) != 'function')
3071 if (arguments[i] == this)
3075 else if (arguments[i].apply(this, arguments[i+1]))
3080 if (validation.message)
3081 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3084 validation.message = msgs.join( _luci2.tr(' - or - '));
3092 for (var i = 0; i < arguments.length; i += 2)
3094 delete validation.message;
3096 if (typeof arguments[i] != 'function')
3098 if (arguments[i] != this)
3102 else if (!arguments[i].apply(this, arguments[i+1]))
3107 if (validation.message)
3108 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3111 validation.message = msgs.join(', ');
3117 return validation.types['or'].apply(
3118 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3121 'list': function(subvalidator, subargs)
3123 if (typeof subvalidator != 'function')
3126 var tokens = this.match(/[^ \t]+/g);
3127 for (var i = 0; i < tokens.length; i++)
3128 if (!subvalidator.apply(tokens[i], subargs))
3134 'phonedigit': function()
3136 if (this.match(/^[0-9\*#!\.]+$/) != null)
3139 validation.i18n('Must be a valid phone number digit');
3143 'string': function()
3150 this.cbi.AbstractValue = AbstractWidget.extend({
3151 init: function(name, options)
3154 this.instance = { };
3155 this.dependencies = [ ];
3156 this.rdependency = { };
3158 this.options = _luci2.defaults(options, {
3168 return this.section.id('field', sid || '__unknown__', this.name);
3171 render: function(sid)
3173 var i = this.instance[sid] = { };
3175 i.top = $('<div />').addClass('cbi-value');
3177 if (typeof(this.options.caption) == 'string')
3179 .addClass('cbi-value-title')
3180 .attr('for', this.id(sid))
3181 .text(this.options.caption)
3184 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
3185 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
3187 if (typeof(this.options.description) == 'string')
3189 .addClass('cbi-value-description')
3190 .text(this.options.description)
3196 ucipath: function(sid)
3199 config: (this.options.uci_package || this.map.uci_package),
3200 section: (this.options.uci_section || sid),
3201 option: (this.options.uci_option || this.name)
3205 ucivalue: function(sid)
3207 var uci = this.ucipath(sid);
3208 var val = this.map.get(uci.config, uci.section, uci.option);
3210 if (typeof(val) == 'undefined')
3211 return this.options.initial;
3216 formvalue: function(sid)
3218 var v = $('#' + this.id(sid)).val();
3219 return (v === '') ? undefined : v;
3222 textvalue: function(sid)
3224 var v = this.formvalue(sid);
3226 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3227 v = this.ucivalue(sid);
3229 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3230 v = this.options.placeholder;
3232 if (typeof(v) == 'undefined' || v === '')
3235 if (typeof(v) == 'string' && $.isArray(this.choices))
3237 for (var i = 0; i < this.choices.length; i++)
3238 if (v === this.choices[i][0])
3239 return this.choices[i][1];
3241 else if (v === true)
3242 return _luci2.tr('yes');
3243 else if (v === false)
3244 return _luci2.tr('no');
3245 else if ($.isArray(v))
3246 return v.join(', ');
3251 changed: function(sid)
3253 var a = this.ucivalue(sid);
3254 var b = this.formvalue(sid);
3256 if (typeof(a) != typeof(b))
3259 if (typeof(a) == 'object')
3261 if (a.length != b.length)
3264 for (var i = 0; i < a.length; i++)
3276 var uci = this.ucipath(sid);
3278 if (this.instance[sid].disabled)
3280 if (!this.options.keep)
3281 return this.map.set(uci.config, uci.section, uci.option, undefined);
3286 var chg = this.changed(sid);
3287 var val = this.formvalue(sid);
3290 this.map.set(uci.config, uci.section, uci.option, val);
3295 validator: function(sid, elem, multi)
3297 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3301 if (typeof(this.options.datatype) == 'string')
3304 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3307 else if (typeof(this.options.datatype) == 'function')
3309 var vfunc = this.options.datatype;
3310 vstack = [ function(elem) {
3311 var rv = vfunc(this, elem);
3313 validation.message = rv;
3314 return (rv === true);
3323 inst: this.instance[sid],
3324 opt: this.options.optional
3327 var validator = function(ev)
3331 var val = d.elem.val();
3333 if (vstack && typeof(vstack[0]) == 'function')
3335 delete validation.message;
3337 if ((val.length == 0 && !d.opt))
3339 d.elem.addClass('error');
3340 d.inst.top.addClass('error');
3341 d.inst.error.text(_luci2.tr('Field must not be empty'));
3344 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3346 d.elem.addClass('error');
3347 d.inst.top.addClass('error');
3348 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3353 d.elem.removeClass('error');
3355 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3361 d.inst.top.removeClass('error');
3362 d.inst.error.text('');
3369 for (var field in d.self.rdependency)
3370 d.self.rdependency[field].toggle(d.sid);
3376 if (elem.prop('tagName') == 'SELECT')
3378 elem.change(evdata, validator);
3380 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3382 elem.click(evdata, validator);
3383 elem.blur(evdata, validator);
3387 elem.keyup(evdata, validator);
3388 elem.blur(evdata, validator);
3391 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3396 validate: function(sid)
3398 var i = this.instance[sid];
3400 i.widget.find('[cbi-validate]').trigger('validate');
3402 return (i.disabled || i.error.text() == '');
3405 depends: function(d, v)
3412 for (var i = 0; i < d.length; i++)
3414 if (typeof(d[i]) == 'string')
3416 else if (d[i] instanceof _luci2.cbi.AbstractValue)
3417 dep[d[i].name] = true;
3420 else if (d instanceof _luci2.cbi.AbstractValue)
3423 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3425 else if (typeof(d) == 'object')
3429 else if (typeof(d) == 'string')
3432 dep[d] = (typeof(v) == 'undefined') ? true : v;
3435 if (!dep || $.isEmptyObject(dep))
3438 for (var field in dep)
3440 var f = this.section.fields[field];
3442 f.rdependency[this.name] = this;
3447 if ($.isEmptyObject(dep))
3450 this.dependencies.push(dep);
3455 toggle: function(sid)
3457 var d = this.dependencies;
3458 var i = this.instance[sid];
3463 for (var n = 0; n < d.length; n++)
3467 for (var field in d[n])
3469 var val = this.section.fields[field].formvalue(sid);
3470 var cmp = d[n][field];
3472 if (typeof(cmp) == 'boolean')
3474 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3480 else if (typeof(cmp) == 'string')
3488 else if (typeof(cmp) == 'function')
3496 else if (cmp instanceof RegExp)
3521 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3528 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
3529 widget: function(sid)
3531 var o = this.options;
3533 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3534 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3536 var i = $('<input />')
3537 .attr('id', this.id(sid))
3538 .attr('type', 'checkbox')
3539 .prop('checked', this.ucivalue(sid));
3541 return this.validator(sid, i);
3544 ucivalue: function(sid)
3546 var v = this.callSuper('ucivalue', sid);
3548 if (typeof(v) == 'boolean')
3551 return (v == this.options.enabled);
3554 formvalue: function(sid)
3556 var v = $('#' + this.id(sid)).prop('checked');
3558 if (typeof(v) == 'undefined')
3559 return !!this.options.initial;
3566 var uci = this.ucipath(sid);
3568 if (this.instance[sid].disabled)
3570 if (!this.options.keep)
3571 return this.map.set(uci.config, uci.section, uci.option, undefined);
3576 var chg = this.changed(sid);
3577 var val = this.formvalue(sid);
3581 val = val ? this.options.enabled : this.options.disabled;
3583 if (this.options.optional && val == this.options.initial)
3584 this.map.set(uci.config, uci.section, uci.option, undefined);
3586 this.map.set(uci.config, uci.section, uci.option, val);
3593 this.cbi.InputValue = this.cbi.AbstractValue.extend({
3594 widget: function(sid)
3596 var i = $('<input />')
3597 .attr('id', this.id(sid))
3598 .attr('type', 'text')
3599 .attr('placeholder', this.options.placeholder)
3600 .val(this.ucivalue(sid));
3602 return this.validator(sid, i);
3606 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
3607 widget: function(sid)
3609 var i = $('<input />')
3610 .attr('id', this.id(sid))
3611 .attr('type', 'password')
3612 .attr('placeholder', this.options.placeholder)
3613 .val(this.ucivalue(sid));
3615 var t = $('<img />')
3616 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3617 .attr('title', _luci2.tr('Reveal or hide password'))
3618 .addClass('cbi-button')
3619 .click(function(ev) {
3620 var i = $(this).prev();
3621 var t = i.attr('type');
3622 i.attr('type', (t == 'password') ? 'text' : 'password');
3626 this.validator(sid, i);
3629 .addClass('cbi-input-password')
3635 this.cbi.ListValue = this.cbi.AbstractValue.extend({
3636 widget: function(sid)
3638 var s = $('<select />');
3640 if (this.options.optional)
3643 .text(_luci2.tr('-- Please choose --'))
3647 for (var i = 0; i < this.choices.length; i++)
3649 .attr('value', this.choices[i][0])
3650 .text(this.choices[i][1])
3653 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3655 return this.validator(sid, s);
3658 value: function(k, v)
3663 this.choices.push([k, v || k]);
3668 this.cbi.MultiValue = this.cbi.ListValue.extend({
3669 widget: function(sid)
3671 var v = this.ucivalue(sid);
3672 var t = $('<div />').attr('id', this.id(sid));
3675 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3678 for (var i = 0; i < v.length; i++)
3682 for (var i = 0; i < this.choices.length; i++)
3685 .append($('<input />')
3686 .addClass('cbi-input-checkbox')
3687 .attr('type', 'checkbox')
3688 .attr('value', this.choices[i][0])
3689 .prop('checked', s[this.choices[i][0]]))
3690 .append(this.choices[i][1])
3700 formvalue: function(sid)
3703 var fields = $('#' + this.id(sid) + ' > label > input');
3705 for (var i = 0; i < fields.length; i++)
3706 if (fields[i].checked)
3707 rv.push(fields[i].getAttribute('value'));
3712 textvalue: function(sid)
3714 var v = this.formvalue(sid);
3718 for (var i = 0; i < this.choices.length; i++)
3719 c[this.choices[i][0]] = this.choices[i][1];
3723 for (var i = 0; i < v.length; i++)
3724 t.push(c[v[i]] || v[i]);
3726 return t.join(', ');
3730 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
3731 _change: function(ev)
3734 var self = ev.data.self;
3736 if (s.selectedIndex == (s.options.length - 1))
3738 ev.data.select.hide();
3739 ev.data.input.show().focus();
3741 var v = ev.data.input.val();
3742 ev.data.input.val(' ');
3743 ev.data.input.val(v);
3745 else if (self.options.optional && s.selectedIndex == 0)
3747 ev.data.input.val('');
3751 ev.data.input.val(ev.data.select.val());
3758 var val = this.value;
3759 var self = ev.data.self;
3761 ev.data.select.empty();
3763 if (self.options.optional)
3766 .text(_luci2.tr('-- please choose --'))
3767 .appendTo(ev.data.select);
3770 for (var i = 0; i < self.choices.length; i++)
3772 if (self.choices[i][0] == val)
3776 .attr('value', self.choices[i][0])
3777 .text(self.choices[i][1])
3778 .appendTo(ev.data.select);
3781 if (!seen && val != '')
3785 .appendTo(ev.data.select);
3789 .text(_luci2.tr('-- custom --'))
3790 .appendTo(ev.data.select);
3792 ev.data.input.hide();
3793 ev.data.select.val(val).show().focus();
3796 _enter: function(ev)
3801 ev.preventDefault();
3802 ev.data.self._blur(ev);
3806 widget: function(sid)
3808 var d = $('<div />')
3809 .attr('id', this.id(sid));
3811 var t = $('<input />')
3812 .attr('type', 'text')
3816 var s = $('<select />')
3821 input: this.validator(sid, t),
3822 select: this.validator(sid, s)
3825 s.change(evdata, this._change);
3826 t.blur(evdata, this._blur);
3827 t.keydown(evdata, this._enter);
3829 t.val(this.ucivalue(sid));
3835 value: function(k, v)
3840 this.choices.push([k, v || k]);
3844 formvalue: function(sid)
3846 var v = $('#' + this.id(sid)).children('input').val();
3847 return (v == '') ? undefined : v;
3851 this.cbi.DynamicList = this.cbi.ComboBox.extend({
3852 _redraw: function(focus, add, del, s)
3854 var v = s.values || [ ];
3857 $(s.parent).children('input').each(function(i) {
3859 v.push(this.value || '');
3862 $(s.parent).empty();
3867 v.splice(focus, 0, '');
3869 else if (v.length == 0)
3875 for (var i = 0; i < v.length; i++)
3886 var txt = $('<input />')
3887 .attr('type', 'text')
3889 .appendTo(s.parent);
3891 var sel = $('<select />')
3892 .appendTo(s.parent);
3894 evdata.input = this.validator(s.sid, txt, true);
3895 evdata.select = this.validator(s.sid, sel, true);
3897 sel.change(evdata, this._change);
3898 txt.blur(evdata, this._blur);
3899 txt.keydown(evdata, this._keydown);
3904 if (i == focus || -(i+1) == focus)
3911 var f = $('<input />')
3912 .attr('type', 'text')
3914 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
3915 .addClass('cbi-input-text')
3916 .keydown(evdata, this._keydown)
3917 .keypress(evdata, this._keypress)
3920 f.appendTo(s.parent);
3926 else if (-(i+1) == focus)
3930 /* force cursor to end */
3936 evdata.input = this.validator(s.sid, f, true);
3942 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
3943 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
3944 .addClass('cbi-button')
3945 .click(evdata, this._btnclick)
3946 .appendTo(s.parent);
3949 .appendTo(s.parent);
3957 _keypress: function(ev)
3961 /* backspace, delete */
3964 if (ev.data.input.val() == '')
3966 ev.preventDefault();
3972 /* enter, arrow up, arrow down */
3976 ev.preventDefault();
3983 _keydown: function(ev)
3985 var input = ev.data.input;
3989 /* backspace, delete */
3992 if (input.val().length == 0)
3994 ev.preventDefault();
3996 var index = ev.data.index;
4002 ev.data.self._redraw(focus, -1, index, ev.data);
4010 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4015 var prev = input.prevAll('input:first');
4016 if (prev.is(':visible'))
4019 prev.next('select').focus();
4024 var next = input.nextAll('input:first');
4025 if (next.is(':visible'))
4028 next.next('select').focus();
4035 _btnclick: function(ev)
4037 if (!this.getAttribute('disabled'))
4039 if (ev.target.src.indexOf('remove') > -1)
4041 var index = ev.data.index;
4042 ev.data.self._redraw(-index, -1, index, ev.data);
4046 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4053 widget: function(sid)
4055 this.options.optional = true;
4057 var v = this.ucivalue(sid);
4060 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4062 var d = $('<div />')
4063 .attr('id', this.id(sid))
4064 .addClass('cbi-input-dynlist');
4066 this._redraw(NaN, -1, -1, {
4076 ucivalue: function(sid)
4078 var v = this.callSuper('ucivalue', sid);
4081 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4086 formvalue: function(sid)
4089 var fields = $('#' + this.id(sid) + ' > input');
4091 for (var i = 0; i < fields.length; i++)
4092 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4093 rv.push(fields[i].value);
4099 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4100 widget: function(sid)
4103 .addClass('cbi-value-dummy')
4104 .attr('id', this.id(sid))
4105 .html(this.ucivalue(sid));
4108 formvalue: function(sid)
4110 return this.ucivalue(sid);
4114 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4119 if (!self.interfaces)
4121 self.interfaces = [ ];
4122 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4123 self.interfaces = ifaces;
4131 _device_icon: function(dev)
4133 var type = 'ethernet';
4134 var desc = _luci2.tr('Ethernet device');
4136 if (dev.type == 'IP tunnel')
4139 desc = _luci2.tr('Tunnel interface');
4141 else if (dev['bridge-members'])
4144 desc = _luci2.tr('Bridge');
4146 else if (dev.wireless)
4149 desc = _luci2.tr('Wireless Network');
4151 else if (dev.device.indexOf('.') > 0)
4154 desc = _luci2.tr('VLAN interface');
4158 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4159 .attr('title', '%s (%s)'.format(desc, dev.device));
4162 widget: function(sid)
4164 var id = this.id(sid);
4165 var ul = $('<ul />')
4167 .addClass('cbi-input-networks');
4169 var itype = this.options.multiple ? 'checkbox' : 'radio';
4170 var value = this.ucivalue(sid);
4173 if (!this.options.multiple)
4174 check[value] = true;
4176 for (var i = 0; i < value.length; i++)
4177 check[value[i]] = true;
4179 if (this.interfaces)
4181 for (var i = 0; i < this.interfaces.length; i++)
4183 var iface = this.interfaces[i];
4184 var badge = $('<span />')
4185 .addClass('ifacebadge')
4186 .text('%s: '.format(iface['interface']));
4188 if (iface.device && iface.device.subdevices)
4189 for (var j = 0; j < iface.device.subdevices.length; j++)
4190 badge.append(this._device_icon(iface.device.subdevices[j]));
4191 else if (iface.device)
4192 badge.append(this._device_icon(iface.device));
4194 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4197 .append($('<label />')
4198 .append($('<input />')
4199 .attr('name', itype + id)
4200 .attr('type', itype)
4201 .attr('value', iface['interface'])
4202 .prop('checked', !!check[iface['interface']])
4203 .addClass('cbi-input-' + itype))
4209 if (!this.options.multiple)
4212 .append($('<label />')
4213 .append($('<input />')
4214 .attr('name', itype + id)
4215 .attr('type', itype)
4217 .prop('checked', !value)
4218 .addClass('cbi-input-' + itype))
4219 .append(_luci2.tr('unspecified')))
4226 ucivalue: function(sid)
4228 var v = this.callSuper('ucivalue', sid);
4230 if (!this.options.multiple)
4236 else if (typeof(v) == 'string')
4239 return v ? v[0] : undefined;
4246 if (typeof(v) == 'string')
4247 v = v.match(/\S+/g);
4253 formvalue: function(sid)
4255 var inputs = $('#' + this.id(sid) + ' input');
4257 if (!this.options.multiple)
4259 for (var i = 0; i < inputs.length; i++)
4260 if (inputs[i].checked && inputs[i].value !== '')
4261 return inputs[i].value;
4268 for (var i = 0; i < inputs.length; i++)
4269 if (inputs[i].checked)
4270 rv.push(inputs[i].value);
4272 return rv.length ? rv : undefined;
4277 this.cbi.AbstractSection = AbstractWidget.extend({
4280 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4282 for (var i = 1; i < arguments.length; i++)
4283 s.push(arguments[i].replace(/\./g, '_'));
4288 option: function(widget, name, options)
4290 if (this.tabs.length == 0)
4291 this.tab({ id: '__default__', selected: true });
4293 return this.taboption('__default__', widget, name, options);
4296 tab: function(options)
4298 if (options.selected)
4299 this.tabs.selected = this.tabs.length;
4303 caption: options.caption,
4304 description: options.description,
4310 taboption: function(tabid, widget, name, options)
4313 for (var i = 0; i < this.tabs.length; i++)
4315 if (this.tabs[i].id == tabid)
4323 throw 'Cannot append to unknown tab ' + tabid;
4325 var w = widget ? new widget(name, options) : null;
4327 if (!(w instanceof _luci2.cbi.AbstractValue))
4328 throw 'Widget must be an instance of AbstractValue';
4333 this.fields[name] = w;
4339 ucipackages: function(pkg)
4341 for (var i = 0; i < this.tabs.length; i++)
4342 for (var j = 0; j < this.tabs[i].fields.length; j++)
4343 if (this.tabs[i].fields[j].options.uci_package)
4344 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4347 formvalue: function()
4351 this.sections(function(s) {
4352 var sid = s['.name'];
4353 var sv = rv[sid] || (rv[sid] = { });
4355 for (var i = 0; i < this.tabs.length; i++)
4356 for (var j = 0; j < this.tabs[i].fields.length; j++)
4358 var val = this.tabs[i].fields[j].formvalue(sid);
4359 sv[this.tabs[i].fields[j].name] = val;
4366 validate: function(sid)
4372 var as = this.sections();
4373 for (var i = 0; i < as.length; i++)
4374 if (!this.validate(as[i]['.name']))
4379 var inst = this.instance[sid];
4380 var sv = rv[sid] || (rv[sid] = { });
4383 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4385 legend.children('span').detach();
4387 for (var i = 0; i < this.tabs.length; i++)
4390 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4392 tab.children('span').detach();
4394 for (var j = 0; j < this.tabs[i].fields.length; j++)
4395 if (!this.tabs[i].fields[j].validate(sid))
4402 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4415 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4423 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
4424 init: function(uci_type, options)
4426 this.uci_type = uci_type;
4427 this.options = options;
4430 this.active_panel = 0;
4431 this.active_tab = { };
4434 filter: function(section)
4439 sections: function(cb)
4441 var s1 = this.map.ucisections(this.map.uci_package);
4444 for (var i = 0; i < s1.length; i++)
4445 if (s1[i]['.type'] == this.uci_type)
4446 if (this.filter(s1[i]))
4449 if (typeof(cb) == 'function')
4450 for (var i = 0; i < s2.length; i++)
4451 cb.apply(this, [ s2[i] ]);
4458 this.map.add(this.map.uci_package, this.uci_type, name);
4461 remove: function(sid)
4463 this.map.remove(this.map.uci_package, sid);
4469 var name = undefined;
4470 var self = ev.data.self;
4472 if (addb.prev().prop('nodeName') == 'INPUT')
4473 name = addb.prev().val();
4475 if (addb.prop('disabled') || name === '')
4478 _luci2.ui.saveScrollTop();
4480 self.active_panel = -1;
4485 _luci2.ui.restoreScrollTop();
4488 _remove: function(ev)
4490 var self = ev.data.self;
4491 var sid = ev.data.sid;
4493 if (ev.data.index == (self.sections().length - 1))
4494 self.active_panel = -1;
4496 _luci2.ui.saveScrollTop();
4502 _luci2.ui.restoreScrollTop();
4504 ev.stopPropagation();
4509 var self = ev.data.self;
4511 var addb = text.next();
4512 var errt = addb.next();
4513 var name = text.val();
4516 if (!/^[a-zA-Z0-9_]*$/.test(name))
4518 errt.text(_luci2.tr('Invalid section name')).show();
4519 text.addClass('error');
4520 addb.prop('disabled', true);
4524 for (var sid in self.map.uci.values[self.map.uci_package])
4531 for (var sid in self.map.uci.creates[self.map.uci_package])
4540 errt.text(_luci2.tr('Name already used')).show();
4541 text.addClass('error');
4542 addb.prop('disabled', true);
4546 errt.text('').hide();
4547 text.removeClass('error');
4548 addb.prop('disabled', false);
4552 teaser: function(sid)
4554 var tf = this.teaser_fields;
4558 tf = this.teaser_fields = [ ];
4560 if ($.isArray(this.options.teasers))
4562 for (var i = 0; i < this.options.teasers.length; i++)
4564 var f = this.options.teasers[i];
4565 if (f instanceof _luci2.cbi.AbstractValue)
4567 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
4568 tf.push(this.fields[f]);
4573 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4574 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4575 tf.push(this.tabs[i].fields[j]);
4581 for (var i = 0; i < tf.length; i++)
4583 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4586 var n = tf[i].options.caption || tf[i].name;
4587 var v = tf[i].textvalue(sid);
4589 if (typeof(v) == 'undefined')
4592 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4598 _render_add: function()
4600 var text = _luci2.tr('Add section');
4601 var ttip = _luci2.tr('Create new section...');
4603 if ($.isArray(this.options.add_caption))
4604 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4605 else if (typeof(this.options.add_caption) == 'string')
4606 text = this.options.add_caption, ttip = '';
4608 var add = $('<div />').addClass('cbi-section-add');
4610 if (this.options.anonymous === false)
4613 .addClass('cbi-input-text')
4614 .attr('type', 'text')
4615 .attr('placeholder', ttip)
4616 .blur({ self: this }, this._sid)
4617 .keyup({ self: this }, this._sid)
4621 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4622 .attr('title', text)
4623 .addClass('cbi-button')
4624 .click({ self: this }, this._add)
4628 .addClass('cbi-value-error')
4635 .attr('type', 'button')
4636 .addClass('cbi-button')
4637 .addClass('cbi-button-add')
4638 .val(text).attr('title', ttip)
4639 .click({ self: this }, this._add)
4646 _render_remove: function(sid, index)
4648 var text = _luci2.tr('Remove');
4649 var ttip = _luci2.tr('Remove this section');
4651 if ($.isArray(this.options.remove_caption))
4652 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4653 else if (typeof(this.options.remove_caption) == 'string')
4654 text = this.options.remove_caption, ttip = '';
4656 return $('<input />')
4657 .attr('type', 'button')
4658 .addClass('cbi-button')
4659 .addClass('cbi-button-remove')
4660 .val(text).attr('title', ttip)
4661 .click({ self: this, sid: sid, index: index }, this._remove);
4664 _render_caption: function(sid)
4666 if (typeof(this.options.caption) == 'string')
4668 return $('<legend />')
4669 .text(this.options.caption.format(sid));
4671 else if (typeof(this.options.caption) == 'function')
4673 return $('<legend />')
4674 .text(this.options.caption.call(this, sid));
4682 var allsections = $();
4683 var panel_index = 0;
4685 this.instance = { };
4687 var s = this.sections();
4691 var fieldset = $('<fieldset />')
4692 .addClass('cbi-section');
4694 var head = $('<div />')
4695 .addClass('cbi-section-head')
4696 .appendTo(fieldset);
4698 head.append(this._render_caption(undefined));
4700 if (typeof(this.options.description) == 'string')
4703 .addClass('cbi-section-descr')
4704 .text(this.options.description)
4708 allsections = allsections.add(fieldset);
4711 for (var i = 0; i < s.length; i++)
4713 var sid = s[i]['.name'];
4714 var inst = this.instance[sid] = { tabs: [ ] };
4716 var fieldset = $('<fieldset />')
4717 .attr('id', this.id('sort', sid))
4718 .addClass('cbi-section');
4720 var head = $('<div />')
4721 .addClass('cbi-section-head')
4722 .attr('cbi-section-num', this.index)
4723 .attr('cbi-section-id', sid);
4725 head.append(this._render_caption(sid));
4727 if (typeof(this.options.description) == 'string')
4730 .addClass('cbi-section-descr')
4731 .text(this.options.description)
4736 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4737 teaser = $('<div />')
4738 .addClass('cbi-section-teaser')
4741 if (this.options.addremove)
4743 .addClass('cbi-section-remove')
4745 .append(this._render_remove(sid, panel_index))
4748 var body = $('<div />')
4749 .attr('index', panel_index++);
4751 var fields = $('<fieldset />')
4752 .addClass('cbi-section-node');
4754 if (this.tabs.length > 1)
4756 var menu = $('<ul />')
4757 .addClass('cbi-tabmenu');
4759 for (var j = 0; j < this.tabs.length; j++)
4761 var tabid = this.id('tab', sid, this.tabs[j].id);
4762 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4764 var tabc = $('<div />')
4765 .addClass('cbi-tabcontainer')
4769 if (typeof(this.tabs[j].description) == 'string')
4772 .addClass('cbi-tab-descr')
4773 .text(this.tabs[j].description)
4777 for (var k = 0; k < this.tabs[j].fields.length; k++)
4778 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4780 tabc.appendTo(fields);
4783 $('<li />').attr('id', theadid).append(
4785 .text(this.tabs[j].caption.format(this.tabs[j].id))
4786 .attr('href', '#' + tabid)
4790 menu.appendTo(body);
4793 fields.appendTo(body);
4796 var t = body.tabs({ active: this.active_tab[sid] });
4798 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4801 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4806 for (var j = 0; j < this.tabs[0].fields.length; j++)
4807 this.tabs[0].fields[j].render(sid).appendTo(fields);
4809 fields.appendTo(body);
4813 head.appendTo(fieldset);
4816 body.appendTo(fieldset);
4819 allsections = allsections.add(fieldset);
4822 //this.validate(sid);
4825 // teaser.append(this.teaser(sid));
4828 if (this.options.collabsible && s.length > 1)
4830 var a = $('<div />').append(allsections).accordion({
4831 header: '> fieldset > div.cbi-section-head',
4832 heightStyle: 'content',
4833 active: this.active_panel
4836 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4837 var h = ui.oldHeader;
4838 var s = ev.data.self;
4839 var i = h.attr('cbi-section-id');
4841 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4845 a.on('accordionactivate', { self: this }, function(ev, ui) {
4846 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4849 if (this.options.sortable)
4851 var s = a.sortable({
4853 handle: 'div.cbi-section-head'
4856 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4858 for (var i = 0; i < ev.data.ids.length; i++)
4859 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4860 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4863 s.on('sortstop', function(ev, ui) {
4864 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4868 if (this.options.addremove)
4869 this._render_add().appendTo(a);
4874 if (this.options.addremove)
4875 allsections = allsections.add(this._render_add());
4882 var s = this.sections();
4884 for (var i = 0; i < s.length; i++)
4886 var sid = s[i]['.name'];
4890 $('#' + this.id('sort', sid))
4891 .children('.cbi-section-head')
4892 .children('.cbi-section-teaser')
4893 .append(this.teaser(sid));
4898 this.cbi.TableSection = this.cbi.TypedSection.extend({
4901 var allsections = $();
4902 var panel_index = 0;
4904 this.instance = { };
4906 var s = this.sections();
4908 var fieldset = $('<fieldset />')
4909 .addClass('cbi-section');
4911 fieldset.append(this._render_caption(sid));
4913 if (typeof(this.options.description) == 'string')
4916 .addClass('cbi-section-descr')
4917 .text(this.options.description)
4918 .appendTo(fieldset);
4921 var fields = $('<div />')
4922 .addClass('cbi-section-node')
4923 .appendTo(fieldset);
4925 var table = $('<table />')
4926 .addClass('cbi-section-table')
4929 var thead = $('<thead />')
4930 .append($('<tr />').addClass('cbi-section-table-titles'))
4933 for (var j = 0; j < this.tabs[0].fields.length; j++)
4935 .addClass('cbi-section-table-cell')
4936 .css('width', this.tabs[0].fields[j].options.width || '')
4937 .append(this.tabs[0].fields[j].options.caption)
4938 .appendTo(thead.children());
4940 if (this.options.sortable)
4941 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4943 if (this.options.addremove !== false)
4944 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4946 var tbody = $('<tbody />')
4952 .addClass('cbi-section-table-row')
4955 .addClass('cbi-section-table-cell')
4956 .addClass('cbi-section-table-placeholder')
4957 .attr('colspan', thead.children().children().length)
4958 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
4962 for (var i = 0; i < s.length; i++)
4964 var sid = s[i]['.name'];
4965 var inst = this.instance[sid] = { tabs: [ ] };
4967 var row = $('<tr />')
4968 .addClass('cbi-section-table-row')
4971 for (var j = 0; j < this.tabs[0].fields.length; j++)
4974 .addClass('cbi-section-table-cell')
4975 .css('width', this.tabs[0].fields[j].options.width || '')
4976 .append(this.tabs[0].fields[j].render(sid, true))
4980 if (this.options.sortable)
4983 .addClass('cbi-section-table-cell')
4984 .addClass('cbi-section-table-sort')
4985 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
4986 .append($('<br />'))
4987 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
4991 if (this.options.addremove !== false)
4994 .addClass('cbi-section-table-cell')
4995 .append(this._render_remove(sid))
5004 if (this.options.sortable)
5006 var s = tbody.sortable({
5007 handle: 'td.cbi-section-table-sort'
5010 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
5012 for (var i = 0; i < ev.data.ids.length; i++)
5013 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
5014 _luci2.uci.order(ev.data.self.map.uci_package, sections);
5017 s.on('sortstop', function(ev, ui) {
5018 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
5022 if (this.options.addremove)
5023 this._render_add().appendTo(fieldset);
5025 fields = table = thead = tbody = null;
5031 this.cbi.NamedSection = this.cbi.TypedSection.extend({
5032 sections: function(cb)
5035 var pkg = this.map.uci.values[this.map.uci_package];
5038 if (pkg[s]['.name'] == this.uci_type)
5044 if (typeof(cb) == 'function' && sa.length > 0)
5045 cb.apply(this, [ sa[0] ]);
5051 this.cbi.DummySection = this.cbi.TypedSection.extend({
5052 sections: function(cb)
5054 if (typeof(cb) == 'function')
5055 cb.apply(this, [ { '.name': this.uci_type } ]);
5057 return [ { '.name': this.uci_type } ];
5061 this.cbi.Map = AbstractWidget.extend({
5062 init: function(uci_package, options)
5066 this.uci_package = uci_package;
5067 this.sections = [ ];
5068 this.options = _luci2.defaults(options, {
5069 save: function() { },
5070 prepare: function() {
5071 return _luci2.uci.writable(function(writable) {
5072 self.options.readonly = !writable;
5088 if (typeof(this.active_panel) == 'undefined')
5089 this.active_panel = 0;
5093 for (var i = 0; i < this.sections.length; i++)
5094 this.sections[i].ucipackages(packages);
5096 packages[this.uci_package] = true;
5098 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
5099 for (var i = 0; i < packages.length; i++)
5101 this.uci.values[packages[i]['.package']] = packages[i];
5102 delete packages[i]['.package'];
5105 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5107 for (var i = 0; i < this.sections.length; i++)
5109 for (var f in this.sections[i].fields)
5111 if (typeof(this.sections[i].fields[f].load) != 'function')
5114 var s = this.sections[i].sections();
5115 for (var j = 0; j < s.length; j++)
5117 var rv = this.sections[i].fields[f].load(s[j]['.name']);
5118 if (_luci2.isDeferred(rv))
5124 return $.when.apply($, deferreds);
5129 for (var pkg in packages)
5130 _luci2.uci.get_all(pkg);
5132 return _luci2.rpc.flush().then(load_cb);
5137 var map = $('<div />').addClass('cbi-map');
5139 if (typeof(this.options.caption) == 'string')
5140 $('<h2 />').text(this.options.caption).appendTo(map);
5142 if (typeof(this.options.description) == 'string')
5143 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
5145 var sections = $('<div />').appendTo(map);
5147 for (var i = 0; i < this.sections.length; i++)
5149 var s = this.sections[i].render();
5151 if (this.options.readonly || this.sections[i].options.readonly)
5152 s.find('input, select, button, img.cbi-button').attr('disabled', true);
5154 s.appendTo(sections);
5156 if (this.sections[i].options.active)
5157 this.active_panel = i;
5160 if (this.options.collabsible)
5162 var a = sections.accordion({
5163 header: '> fieldset > div.cbi-section-head',
5164 heightStyle: 'content',
5165 active: this.active_panel
5168 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
5169 var h = ui.oldHeader;
5170 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
5171 var i = h.attr('cbi-section-id');
5173 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
5175 for (var i = 0; i < ev.data.self.sections.length; i++)
5176 ev.data.self.sections[i].validate();
5179 a.on('accordionactivate', { self: this }, function(ev, ui) {
5180 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
5184 if (this.options.pageaction !== false)
5186 var a = $('<div />')
5187 .addClass('cbi-page-actions')
5191 .addClass('cbi-button').addClass('cbi-button-apply')
5192 .attr('type', 'button')
5193 .val(_luci2.tr('Save & Apply'))
5197 .addClass('cbi-button').addClass('cbi-button-save')
5198 .attr('type', 'button')
5199 .val(_luci2.tr('Save'))
5200 .click({ self: this }, function(ev) { ev.data.self.send(); })
5204 .addClass('cbi-button').addClass('cbi-button-reset')
5205 .attr('type', 'button')
5206 .val(_luci2.tr('Reset'))
5207 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
5213 var top = $('<form />').append(map);
5222 for (var i = 0; i < this.sections.length; i++)
5223 this.sections[i].finish();
5230 this.target.hide().empty().append(this.render());
5235 section: function(widget, uci_type, options)
5237 var w = widget ? new widget(uci_type, options) : null;
5239 if (!(w instanceof _luci2.cbi.AbstractSection))
5240 throw 'Widget must be an instance of AbstractSection';
5243 w.index = this.sections.length;
5245 this.sections.push(w);
5249 formvalue: function()
5253 for (var i = 0; i < this.sections.length; i++)
5255 var sids = this.sections[i].formvalue();
5256 for (var sid in sids)
5258 var s = rv[sid] || (rv[sid] = { });
5259 $.extend(s, sids[sid]);
5266 add: function(conf, type, name)
5268 var c = this.uci.creates;
5269 var s = '.new.%d'.format(this.uci.newid++);
5284 remove: function(conf, sid)
5286 var n = this.uci.creates;
5287 var c = this.uci.changes;
5288 var d = this.uci.deletes;
5290 /* requested deletion of a just created section */
5291 if (sid.indexOf('.new.') == 0)
5294 delete n[conf][sid];
5299 delete c[conf][sid];
5304 d[conf][sid] = true;
5308 ucisections: function(conf, cb)
5311 var pkg = this.uci.values[conf];
5312 var crt = this.uci.creates[conf];
5313 var del = this.uci.deletes[conf];
5319 if (!del || del[s] !== true)
5322 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5328 if (typeof(cb) == 'function')
5329 for (var i = 0; i < sa.length; i++)
5330 cb.apply(this, [ sa[i] ]);
5335 get: function(conf, sid, opt)
5337 var v = this.uci.values;
5338 var n = this.uci.creates;
5339 var c = this.uci.changes;
5340 var d = this.uci.deletes;
5342 /* requested option in a just created section */
5343 if (sid.indexOf('.new.') == 0)
5348 if (typeof(opt) == 'undefined')
5349 return (n[conf][sid] || { });
5351 return n[conf][sid][opt];
5354 /* requested an option value */
5355 if (typeof(opt) != 'undefined')
5357 /* check whether option was deleted */
5358 if (d[conf] && d[conf][sid])
5360 if (d[conf][sid] === true)
5363 for (var i = 0; i < d[conf][sid].length; i++)
5364 if (d[conf][sid][i] == opt)
5368 /* check whether option was changed */
5369 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5370 return c[conf][sid][opt];
5372 /* return base value */
5373 if (v[conf] && v[conf][sid])
5374 return v[conf][sid][opt];
5379 /* requested an entire section */
5381 return (v[conf][sid] || { });
5386 set: function(conf, sid, opt, val)
5388 var n = this.uci.creates;
5389 var c = this.uci.changes;
5390 var d = this.uci.deletes;
5392 if (sid.indexOf('.new.') == 0)
5394 if (n[conf] && n[conf][sid])
5396 if (typeof(val) != 'undefined')
5397 n[conf][sid][opt] = val;
5399 delete n[conf][sid][opt];
5402 else if (typeof(val) != 'undefined')
5410 c[conf][sid][opt] = val;
5420 d[conf][sid].push(opt);
5424 validate: function()
5428 for (var i = 0; i < this.sections.length; i++)
5429 if (!this.sections[i].validate())
5437 if (this.options.readonly)
5438 return _luci2.deferrable();
5440 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5442 for (var i = 0; i < this.sections.length; i++)
5444 if (this.sections[i].options.readonly)
5447 for (var f in this.sections[i].fields)
5449 if (typeof(this.sections[i].fields[f].save) != 'function')
5452 var s = this.sections[i].sections();
5453 for (var j = 0; j < s.length; j++)
5455 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5456 if (_luci2.isDeferred(rv))
5462 return $.when.apply($, deferreds);
5467 if (!this.validate())
5468 return _luci2.deferrable();
5470 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5473 if (this.uci.creates)
5474 for (var c in this.uci.creates)
5475 for (var s in this.uci.creates[c])
5482 for (var k in this.uci.creates[c][s])
5485 r.type = this.uci.creates[c][s][k];
5486 else if (k == '.create')
5487 r.name = this.uci.creates[c][s][k];
5488 else if (k.charAt(0) != '.')
5489 r.values[k] = this.uci.creates[c][s][k];
5492 _luci2.uci.add(r.config, r.type, r.name, r.values);
5495 if (this.uci.changes)
5496 for (var c in this.uci.changes)
5497 for (var s in this.uci.changes[c])
5498 _luci2.uci.set(c, s, this.uci.changes[c][s]);
5500 if (this.uci.deletes)
5501 for (var c in this.uci.deletes)
5502 for (var s in this.uci.deletes[c])
5504 var o = this.uci.deletes[c][s];
5505 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
5508 return _luci2.rpc.flush().then(function() {
5509 return _luci2.ui.updateChanges();
5515 _luci2.ui.saveScrollTop();
5516 _luci2.ui.loading(true);
5518 return this.save().then(send_cb).then(function() {
5520 }).then(function() {
5524 _luci2.ui.loading(false);
5525 _luci2.ui.restoreScrollTop();
5529 dialog: function(id)
5531 var d = $('<div />');
5535 .attr('src', _luci2.globals.resource + '/icons/loading.gif')
5536 .css('vertical-align', 'middle')
5537 .css('padding-right', '10px')
5540 p.append(_luci2.tr('Loading data...'));
5551 $(this).parent().children('.ui-dialog-titlebar').hide();
5556 insertInto: function(id)
5559 self.target = $(id);
5561 _luci2.ui.loading(true);
5564 return self.load().then(function() {
5565 self.target.empty().append(self.render());
5569 _luci2.ui.loading(false);