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 changes: _luci2.rpc.declare({
590 params: [ 'config' ],
591 expect: { changes: [ ] }
594 commit: _luci2.rpc.declare({
600 _delete_one: _luci2.rpc.declare({
603 params: [ 'config', 'section', 'option' ]
606 _delete_multiple: _luci2.rpc.declare({
609 params: [ 'config', 'section', 'options' ]
612 'delete': function(config, section, option)
614 if ($.isArray(option))
615 return this._delete_multiple(config, section, option);
617 return this._delete_one(config, section, option);
620 delete_all: _luci2.rpc.declare({
623 params: [ 'config', 'type', 'match' ]
626 _foreach: _luci2.rpc.declare({
629 params: [ 'config', 'type' ],
630 expect: { values: { } }
633 foreach: function(config, type, cb)
635 return this._foreach(config, type).then(function(sections) {
636 for (var s in sections)
641 get: _luci2.rpc.declare({
644 params: [ 'config', 'section', 'option' ],
646 filter: function(data, params) {
647 if (typeof(params.option) == 'undefined')
648 return data.values ? data.values['.type'] : undefined;
654 get_all: _luci2.rpc.declare({
657 params: [ 'config', 'section' ],
658 expect: { values: { } },
659 filter: function(data, params) {
660 if (typeof(params.section) == 'string')
661 data['.section'] = params.section;
662 else if (typeof(params.config) == 'string')
663 data['.package'] = params.config;
668 get_first: function(config, type, option)
670 return this._foreach(config, type).then(function(sections) {
671 for (var s in sections)
673 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
675 if (typeof(val) != 'undefined')
683 section: _luci2.rpc.declare({
686 params: [ 'config', 'type', 'name', 'values' ],
687 expect: { section: '' }
690 _set: _luci2.rpc.declare({
693 params: [ 'config', 'section', 'values' ]
696 set: function(config, section, option, value)
698 if (typeof(value) == 'undefined' && typeof(option) == 'string')
699 return this.section(config, section, option); /* option -> type */
700 else if ($.isPlainObject(option))
701 return this._set(config, section, option); /* option -> values */
704 values[option] = value;
706 return this._set(config, section, values);
709 order: _luci2.rpc.declare({
712 params: [ 'config', 'sections' ]
717 listNetworkNames: function() {
718 return _luci2.rpc.list('network.interface.*').then(function(list) {
720 for (var name in list)
721 if (name != 'network.interface.loopback')
722 names.push(name.substring(18));
728 listDeviceNames: _luci2.rpc.declare({
729 object: 'network.device',
732 filter: function(data) {
734 for (var name in data)
742 getNetworkStatus: function()
747 return this.listNetworkNames().then(function(names) {
750 for (var i = 0; i < names.length; i++)
751 _luci2.network.getInterfaceStatus(names[i]);
753 return _luci2.rpc.flush();
754 }).then(function(networks) {
755 for (var i = 0; i < networks.length; i++)
757 var net = nets[i] = networks[i];
758 var dev = net.l3_device || net.l2_device;
760 net.device = devs[dev] = { };
765 for (var dev in devs)
766 _luci2.network.listDeviceNamestatus(dev);
768 return _luci2.rpc.flush();
769 }).then(function(devices) {
772 for (var i = 0; i < devices.length; i++)
774 var brm = devices[i]['bridge-members'];
775 delete devices[i]['bridge-members'];
777 $.extend(devs[devices[i]['device']], devices[i]);
782 devs[devices[i]['device']].subdevices = [ ];
784 for (var j = 0; j < brm.length; j++)
789 _luci2.network.listDeviceNamestatus(brm[j]);
792 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
796 return _luci2.rpc.flush();
797 }).then(function(subdevices) {
798 for (var i = 0; i < subdevices.length; i++)
799 $.extend(devs[subdevices[i]['device']], subdevices[i]);
803 for (var dev in devs)
804 _luci2.wireless.getDeviceStatus(dev);
806 return _luci2.rpc.flush();
807 }).then(function(wifidevices) {
808 for (var i = 0; i < wifidevices.length; i++)
810 devs[wifidevices[i]['device']].wireless = wifidevices[i];
812 nets.sort(function(a, b) {
813 if (a['interface'] < b['interface'])
815 else if (a['interface'] > b['interface'])
825 findWanInterfaces: function(cb)
827 return this.listNetworkNames().then(function(names) {
830 for (var i = 0; i < names.length; i++)
831 _luci2.network.getInterfaceStatus(names[i]);
833 return _luci2.rpc.flush();
834 }).then(function(interfaces) {
835 var rv = [ undefined, undefined ];
837 for (var i = 0; i < interfaces.length; i++)
839 for (var j = 0; j < interfaces[i].route.length; j++)
841 var rt = interfaces[i].route[j];
843 if (typeof(rt.table) != 'undefined')
846 if (rt.target == '0.0.0.0' && rt.mask == 0)
847 rv[0] = interfaces[i];
848 else if (rt.target == '::' && rt.mask == 0)
849 rv[1] = interfaces[i];
857 getDHCPLeases: _luci2.rpc.declare({
858 object: 'luci2.network',
859 method: 'dhcp_leases',
860 expect: { leases: [ ] }
863 getDHCPv6Leases: _luci2.rpc.declare({
864 object: 'luci2.network',
865 method: 'dhcp6_leases',
866 expect: { leases: [ ] }
869 getRoutes: _luci2.rpc.declare({
870 object: 'luci2.network',
872 expect: { routes: [ ] }
875 getIPv6Routes: _luci2.rpc.declare({
876 object: 'luci2.network',
878 expect: { routes: [ ] }
881 getARPTable: _luci2.rpc.declare({
882 object: 'luci2.network',
884 expect: { entries: [ ] }
887 getInterfaceStatus: _luci2.rpc.declare({
888 object: 'network.interface',
890 params: [ 'interface' ],
892 filter: function(data, params) {
893 data['interface'] = params['interface'];
894 data['l2_device'] = data['device'];
895 delete data['device'];
900 listDeviceNamestatus: _luci2.rpc.declare({
901 object: 'network.device',
905 filter: function(data, params) {
906 data['device'] = params['name'];
911 getConntrackCount: _luci2.rpc.declare({
912 object: 'luci2.network',
913 method: 'conntrack_count',
914 expect: { '': { count: 0, limit: 0 } }
919 listDeviceNames: _luci2.rpc.declare({
922 expect: { 'devices': [ ] },
923 filter: function(data) {
929 getDeviceStatus: _luci2.rpc.declare({
932 params: [ 'device' ],
934 filter: function(data, params) {
935 if (!$.isEmptyObject(data))
937 data['device'] = params['device'];
944 getAssocList: _luci2.rpc.declare({
947 params: [ 'device' ],
948 expect: { results: [ ] },
949 filter: function(data, params) {
950 for (var i = 0; i < data.length; i++)
951 data[i]['device'] = params['device'];
953 data.sort(function(a, b) {
954 if (a.bssid < b.bssid)
956 else if (a.bssid > b.bssid)
966 getWirelessStatus: function() {
967 return this.listDeviceNames().then(function(names) {
970 for (var i = 0; i < names.length; i++)
971 _luci2.wireless.getDeviceStatus(names[i]);
973 return _luci2.rpc.flush();
974 }).then(function(networks) {
978 'country', 'channel', 'frequency', 'frequency_offset',
979 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
983 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
984 'signal', 'noise', 'bitrate', 'encryption'
987 for (var i = 0; i < networks.length; i++)
989 var phy = rv[networks[i].phy] || (
990 rv[networks[i].phy] = { networks: [ ] }
994 device: networks[i].device
997 for (var j = 0; j < phy_attrs.length; j++)
998 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1000 for (var j = 0; j < net_attrs.length; j++)
1001 net[net_attrs[j]] = networks[i][net_attrs[j]];
1003 phy.networks.push(net);
1010 getAssocLists: function()
1012 return this.listDeviceNames().then(function(names) {
1015 for (var i = 0; i < names.length; i++)
1016 _luci2.wireless.getAssocList(names[i]);
1018 return _luci2.rpc.flush();
1019 }).then(function(assoclists) {
1022 for (var i = 0; i < assoclists.length; i++)
1023 for (var j = 0; j < assoclists[i].length; j++)
1024 rv.push(assoclists[i][j]);
1030 formatEncryption: function(enc)
1032 var format_list = function(l, s)
1035 for (var i = 0; i < l.length; i++)
1036 rv.push(l[i].toUpperCase());
1037 return rv.join(s ? s : ', ');
1040 if (!enc || !enc.enabled)
1041 return _luci2.tr('None');
1045 if (enc.wep.length == 2)
1046 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1047 else if (enc.wep[0] == 'shared')
1048 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1050 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1054 if (enc.wpa.length == 2)
1055 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1056 format_list(enc.authentication, '/'),
1057 format_list(enc.ciphers, ', ')
1059 else if (enc.wpa[0] == 2)
1060 return 'WPA2 %s (%s)'.format(
1061 format_list(enc.authentication, '/'),
1062 format_list(enc.ciphers, ', ')
1065 return 'WPA %s (%s)'.format(
1066 format_list(enc.authentication, '/'),
1067 format_list(enc.ciphers, ', ')
1071 return _luci2.tr('Unknown');
1076 getSystemInfo: _luci2.rpc.declare({
1082 getBoardInfo: _luci2.rpc.declare({
1088 getDiskInfo: _luci2.rpc.declare({
1089 object: 'luci2.system',
1094 getInfo: function(cb)
1098 this.getSystemInfo();
1099 this.getBoardInfo();
1102 return _luci2.rpc.flush().then(function(info) {
1105 $.extend(rv, info[0]);
1106 $.extend(rv, info[1]);
1107 $.extend(rv, info[2]);
1113 getProcessList: _luci2.rpc.declare({
1114 object: 'luci2.system',
1115 method: 'process_list',
1116 expect: { processes: [ ] },
1117 filter: function(data) {
1118 data.sort(function(a, b) { return a.pid - b.pid });
1123 getSystemLog: _luci2.rpc.declare({
1124 object: 'luci2.system',
1129 getKernelLog: _luci2.rpc.declare({
1130 object: 'luci2.system',
1135 getZoneInfo: function(cb)
1137 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1140 sendSignal: _luci2.rpc.declare({
1141 object: 'luci2.system',
1142 method: 'process_signal',
1143 params: [ 'pid', 'signal' ],
1144 filter: function(data) {
1149 initList: _luci2.rpc.declare({
1150 object: 'luci2.system',
1151 method: 'init_list',
1152 expect: { initscripts: [ ] },
1153 filter: function(data) {
1154 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1159 initEnabled: function(init, cb)
1161 return this.initList().then(function(list) {
1162 for (var i = 0; i < list.length; i++)
1163 if (list[i].name == init)
1164 return !!list[i].enabled;
1170 initRun: _luci2.rpc.declare({
1171 object: 'luci2.system',
1172 method: 'init_action',
1173 params: [ 'name', 'action' ],
1174 filter: function(data) {
1179 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1180 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1181 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1182 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1183 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1184 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1187 getRcLocal: _luci2.rpc.declare({
1188 object: 'luci2.system',
1189 method: 'rclocal_get',
1190 expect: { data: '' }
1193 setRcLocal: _luci2.rpc.declare({
1194 object: 'luci2.system',
1195 method: 'rclocal_set',
1200 getCrontab: _luci2.rpc.declare({
1201 object: 'luci2.system',
1202 method: 'crontab_get',
1203 expect: { data: '' }
1206 setCrontab: _luci2.rpc.declare({
1207 object: 'luci2.system',
1208 method: 'crontab_set',
1213 getSSHKeys: _luci2.rpc.declare({
1214 object: 'luci2.system',
1215 method: 'sshkeys_get',
1216 expect: { keys: [ ] }
1219 setSSHKeys: _luci2.rpc.declare({
1220 object: 'luci2.system',
1221 method: 'sshkeys_set',
1226 setPassword: _luci2.rpc.declare({
1227 object: 'luci2.system',
1228 method: 'password_set',
1229 params: [ 'user', 'password' ]
1233 listLEDs: _luci2.rpc.declare({
1234 object: 'luci2.system',
1236 expect: { leds: [ ] }
1239 listUSBDevices: _luci2.rpc.declare({
1240 object: 'luci2.system',
1242 expect: { devices: [ ] }
1246 testUpgrade: _luci2.rpc.declare({
1247 object: 'luci2.system',
1248 method: 'upgrade_test',
1252 startUpgrade: _luci2.rpc.declare({
1253 object: 'luci2.system',
1254 method: 'upgrade_start',
1258 cleanUpgrade: _luci2.rpc.declare({
1259 object: 'luci2.system',
1260 method: 'upgrade_clean'
1264 restoreBackup: _luci2.rpc.declare({
1265 object: 'luci2.system',
1266 method: 'backup_restore'
1269 cleanBackup: _luci2.rpc.declare({
1270 object: 'luci2.system',
1271 method: 'backup_clean'
1275 getBackupConfig: _luci2.rpc.declare({
1276 object: 'luci2.system',
1277 method: 'backup_config_get',
1278 expect: { config: '' }
1281 setBackupConfig: _luci2.rpc.declare({
1282 object: 'luci2.system',
1283 method: 'backup_config_set',
1288 listBackup: _luci2.rpc.declare({
1289 object: 'luci2.system',
1290 method: 'backup_list',
1291 expect: { files: [ ] }
1295 performReboot: _luci2.rpc.declare({
1296 object: 'luci2.system',
1302 updateLists: _luci2.rpc.declare({
1303 object: 'luci2.opkg',
1308 _allPackages: _luci2.rpc.declare({
1309 object: 'luci2.opkg',
1311 params: [ 'offset', 'limit', 'pattern' ],
1315 _installedPackages: _luci2.rpc.declare({
1316 object: 'luci2.opkg',
1317 method: 'list_installed',
1318 params: [ 'offset', 'limit', 'pattern' ],
1322 _findPackages: _luci2.rpc.declare({
1323 object: 'luci2.opkg',
1325 params: [ 'offset', 'limit', 'pattern' ],
1329 _fetchPackages: function(action, offset, limit, pattern)
1333 return action(offset, limit, pattern).then(function(list) {
1334 if (!list.total || !list.packages)
1335 return { length: 0, total: 0 };
1337 packages.push.apply(packages, list.packages);
1338 packages.total = list.total;
1343 if (packages.length >= limit)
1348 for (var i = offset + packages.length; i < limit; i += 100)
1349 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1351 return _luci2.rpc.flush();
1352 }).then(function(lists) {
1353 for (var i = 0; i < lists.length; i++)
1355 if (!lists[i].total || !lists[i].packages)
1358 packages.push.apply(packages, lists[i].packages);
1359 packages.total = lists[i].total;
1366 listPackages: function(offset, limit, pattern)
1368 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1371 installedPackages: function(offset, limit, pattern)
1373 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1376 findPackages: function(offset, limit, pattern)
1378 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1381 installPackage: _luci2.rpc.declare({
1382 object: 'luci2.opkg',
1384 params: [ 'package' ],
1388 removePackage: _luci2.rpc.declare({
1389 object: 'luci2.opkg',
1391 params: [ 'package' ],
1395 getConfig: _luci2.rpc.declare({
1396 object: 'luci2.opkg',
1397 method: 'config_get',
1398 expect: { config: '' }
1401 setConfig: _luci2.rpc.declare({
1402 object: 'luci2.opkg',
1403 method: 'config_set',
1410 login: _luci2.rpc.declare({
1413 params: [ 'username', 'password' ],
1417 access: _luci2.rpc.declare({
1420 params: [ 'scope', 'object', 'function' ],
1421 expect: { access: false }
1426 return _luci2.session.access('ubus', 'session', 'access');
1429 startHeartbeat: function()
1431 this._hearbeatInterval = window.setInterval(function() {
1432 _luci2.session.isAlive().then(function(alive) {
1435 _luci2.session.stopHeartbeat();
1436 _luci2.ui.login(true);
1440 }, _luci2.globals.timeout * 2);
1443 stopHeartbeat: function()
1445 if (typeof(this._hearbeatInterval) != 'undefined')
1447 window.clearInterval(this._hearbeatInterval);
1448 delete this._hearbeatInterval;
1455 saveScrollTop: function()
1457 this._scroll_top = $(document).scrollTop();
1460 restoreScrollTop: function()
1462 if (typeof(this._scroll_top) == 'undefined')
1465 $(document).scrollTop(this._scroll_top);
1467 delete this._scroll_top;
1470 loading: function(enable)
1472 var win = $(window);
1473 var body = $('body');
1474 var div = _luci2._modal || (
1475 _luci2._modal = $('<div />')
1476 .addClass('cbi-modal-loader')
1477 .append($('<div />').text(_luci2.tr('Loading data...')))
1483 body.css('overflow', 'hidden');
1484 body.css('padding', 0);
1485 body.css('width', win.width());
1486 body.css('height', win.height());
1487 div.css('width', win.width());
1488 div.css('height', win.height());
1494 body.css('overflow', '');
1495 body.css('padding', '');
1496 body.css('width', '');
1497 body.css('height', '');
1501 dialog: function(title, content, options)
1503 var win = $(window);
1504 var body = $('body');
1505 var div = _luci2._dialog || (
1506 _luci2._dialog = $('<div />')
1507 .addClass('cbi-modal-dialog')
1508 .append($('<div />')
1509 .append($('<div />')
1510 .addClass('cbi-modal-dialog-header'))
1511 .append($('<div />')
1512 .addClass('cbi-modal-dialog-body'))
1513 .append($('<div />')
1514 .addClass('cbi-modal-dialog-footer')
1515 .append($('<button />')
1516 .addClass('cbi-button')
1517 .text(_luci2.tr('Close'))
1520 .css('overflow', '')
1525 $(this).parent().parent().parent().hide();
1530 if (typeof(options) != 'object')
1533 if (title === false)
1536 .css('overflow', '')
1541 _luci2._dialog.hide();
1546 var cnt = div.children().children('div.cbi-modal-dialog-body');
1547 var ftr = div.children().children('div.cbi-modal-dialog-footer');
1551 if (options.style == 'confirm')
1553 ftr.append($('<button />')
1554 .addClass('cbi-button')
1555 .text(_luci2.tr('Ok'))
1556 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1558 ftr.append($('<button />')
1559 .addClass('cbi-button')
1560 .text(_luci2.tr('Cancel'))
1561 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1563 else if (options.style == 'close')
1565 ftr.append($('<button />')
1566 .addClass('cbi-button')
1567 .text(_luci2.tr('Close'))
1568 .click(options.close || function() { _luci2.ui.dialog(false) }));
1570 else if (options.style == 'wait')
1572 ftr.append($('<button />')
1573 .addClass('cbi-button')
1574 .text(_luci2.tr('Close'))
1575 .attr('disabled', true));
1578 div.find('div.cbi-modal-dialog-header').text(title);
1582 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1587 .css('margin-top', -Math.floor(div.children().height() / 2) + 'px');
1589 body.css('overflow', 'hidden');
1590 body.css('padding', 0);
1591 body.css('width', win.width());
1592 body.css('height', win.height());
1593 div.css('width', win.width());
1594 div.css('height', win.height());
1597 upload: function(title, content, options)
1599 var form = _luci2._upload || (
1600 _luci2._upload = $('<form />')
1601 .attr('method', 'post')
1602 .attr('action', '/cgi-bin/luci-upload')
1603 .attr('enctype', 'multipart/form-data')
1604 .attr('target', 'cbi-fileupload-frame')
1606 .append($('<input />')
1607 .attr('type', 'hidden')
1608 .attr('name', 'sessionid')
1609 .attr('value', _luci2.globals.sid))
1610 .append($('<input />')
1611 .attr('type', 'hidden')
1612 .attr('name', 'filename')
1613 .attr('value', options.filename))
1614 .append($('<input />')
1615 .attr('type', 'file')
1616 .attr('name', 'filedata')
1617 .addClass('cbi-input-file'))
1618 .append($('<div />')
1619 .css('width', '100%')
1620 .addClass('progressbar')
1621 .addClass('intermediate')
1622 .append($('<div />')
1623 .css('width', '100%')))
1624 .append($('<iframe />')
1625 .attr('name', 'cbi-fileupload-frame')
1626 .css('width', '1px')
1627 .css('height', '1px')
1628 .css('visibility', 'hidden'))
1631 var finish = _luci2._upload_finish_cb || (
1632 _luci2._upload_finish_cb = function(ev) {
1633 $(this).off('load');
1635 var body = (this.contentDocument || this.contentWindow.document).body;
1636 if (body.firstChild.tagName.toLowerCase() == 'pre')
1637 body = body.firstChild;
1641 json = $.parseJSON(body.innerHTML);
1644 message: _luci2.tr('Invalid server response received'),
1645 error: [ -1, _luci2.tr('Invalid data') ]
1651 L.ui.dialog(L.tr('File upload'), [
1652 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1653 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1654 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1655 ], { style: 'close' });
1657 else if (typeof(ev.data.cb) == 'function')
1664 var confirm = _luci2._upload_confirm_cb || (
1665 _luci2._upload_confirm_cb = function() {
1666 var d = _luci2._upload;
1667 var f = d.find('.cbi-input-file');
1668 var b = d.find('.progressbar');
1669 var p = d.find('p');
1674 d.find('iframe').on('load', { cb: options.success }, finish);
1679 p.text(_luci2.tr('File upload in progress …'));
1681 _luci2._dialog.find('button').prop('disabled', true);
1685 _luci2._upload.find('.progressbar').hide();
1686 _luci2._upload.find('.cbi-input-file').val('').show();
1687 _luci2._upload.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1689 _luci2.ui.dialog(title || _luci2.tr('File upload'), _luci2._upload, {
1695 reconnect: function()
1697 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1698 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1699 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1701 var interval, timeout;
1704 _luci2.tr('Waiting for device'), [
1705 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1707 .css('width', '100%')
1708 .addClass('progressbar')
1709 .addClass('intermediate')
1710 .append($('<div />')
1711 .css('width', '100%'))
1712 ], { style: 'wait' }
1715 for (var i = 0; i < protocols.length; i++)
1716 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1718 //_luci2.network.getNetworkStatus(function(s) {
1719 // for (var i = 0; i < protocols.length; i++)
1721 // for (var j = 0; j < s.length; j++)
1723 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1724 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1726 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1727 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1730 //}).then(function() {
1731 images.on('load', function() {
1732 var url = this.getAttribute('url');
1733 _luci2.session.isAlive().then(function(access) {
1736 window.clearTimeout(timeout);
1737 window.clearInterval(interval);
1738 _luci2.ui.dialog(false);
1743 location.href = url;
1748 interval = window.setInterval(function() {
1749 images.each(function() {
1750 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1754 timeout = window.setTimeout(function() {
1755 window.clearInterval(interval);
1759 _luci2.tr('Device not responding'),
1760 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1767 login: function(invalid)
1769 if (!_luci2._login_deferred || _luci2._login_deferred.state() != 'pending')
1770 _luci2._login_deferred = $.Deferred();
1772 /* try to find sid from hash */
1773 var sid = _luci2.getHash('id');
1774 if (sid && sid.match(/^[a-f0-9]{32}$/))
1776 _luci2.globals.sid = sid;
1777 _luci2.session.isAlive().then(function(access) {
1780 _luci2.session.startHeartbeat();
1781 _luci2._login_deferred.resolve();
1785 _luci2.setHash('id', undefined);
1790 return _luci2._login_deferred;
1793 var form = _luci2._login || (
1794 _luci2._login = $('<div />')
1796 .addClass('alert-message')
1797 .text(_luci2.tr('Wrong username or password given!')))
1799 .append($('<label />')
1800 .text(_luci2.tr('Username'))
1801 .append($('<br />'))
1802 .append($('<input />')
1803 .attr('type', 'text')
1804 .attr('name', 'username')
1805 .attr('value', 'root')
1806 .addClass('cbi-input-text'))))
1808 .append($('<label />')
1809 .text(_luci2.tr('Password'))
1810 .append($('<br />'))
1811 .append($('<input />')
1812 .attr('type', 'password')
1813 .attr('name', 'password')
1814 .addClass('cbi-input-password'))))
1816 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok'))))
1819 var response_cb = _luci2._login_response_cb || (
1820 _luci2._login_response_cb = function(response) {
1821 if (!response.ubus_rpc_session)
1823 _luci2.ui.login(true);
1827 _luci2.globals.sid = response.ubus_rpc_session;
1828 _luci2.setHash('id', _luci2.globals.sid);
1829 _luci2.session.startHeartbeat();
1830 _luci2.ui.dialog(false);
1831 _luci2._login_deferred.resolve();
1836 var confirm_cb = _luci2._login_confirm_cb || (
1837 _luci2._login_confirm_cb = function() {
1838 var d = _luci2._login;
1839 var u = d.find('[name=username]').val();
1840 var p = d.find('[name=password]').val();
1846 _luci2.tr('Logging in'), [
1847 $('<p />').text(_luci2.tr('Log in in progress …')),
1849 .css('width', '100%')
1850 .addClass('progressbar')
1851 .addClass('intermediate')
1852 .append($('<div />')
1853 .css('width', '100%'))
1854 ], { style: 'wait' }
1857 _luci2.globals.sid = '00000000000000000000000000000000';
1858 _luci2.session.login(u, p).then(response_cb);
1863 form.find('.alert-message').show();
1865 form.find('.alert-message').hide();
1867 _luci2.ui.dialog(_luci2.tr('Authorization Required'), form, {
1872 return _luci2._login_deferred;
1875 cryptPassword: _luci2.rpc.declare({
1879 expect: { crypt: '' }
1883 _acl_merge_scope: function(acl_scope, scope)
1885 if ($.isArray(scope))
1887 for (var i = 0; i < scope.length; i++)
1888 acl_scope[scope[i]] = true;
1890 else if ($.isPlainObject(scope))
1892 for (var object_name in scope)
1894 if (!$.isArray(scope[object_name]))
1897 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
1899 for (var i = 0; i < scope[object_name].length; i++)
1900 acl_object[scope[object_name][i]] = true;
1905 _acl_merge_permission: function(acl_perm, perm)
1907 if ($.isPlainObject(perm))
1909 for (var scope_name in perm)
1911 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
1912 this._acl_merge_scope(acl_scope, perm[scope_name]);
1917 _acl_merge_group: function(acl_group, group)
1919 if ($.isPlainObject(group))
1921 if (!acl_group.description)
1922 acl_group.description = group.description;
1926 var acl_perm = acl_group.read || (acl_group.read = { });
1927 this._acl_merge_permission(acl_perm, group.read);
1932 var acl_perm = acl_group.write || (acl_group.write = { });
1933 this._acl_merge_permission(acl_perm, group.write);
1938 _acl_merge_tree: function(acl_tree, tree)
1940 if ($.isPlainObject(tree))
1942 for (var group_name in tree)
1944 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
1945 this._acl_merge_group(acl_group, tree[group_name]);
1950 listAvailableACLs: _luci2.rpc.declare({
1953 expect: { acls: [ ] },
1954 filter: function(trees) {
1956 for (var i = 0; i < trees.length; i++)
1957 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
1962 renderMainMenu: _luci2.rpc.declare({
1965 expect: { menu: { } },
1966 filter: function(entries) {
1967 _luci2.globals.mainMenu = new _luci2.ui.menu();
1968 _luci2.globals.mainMenu.entries(entries);
1972 .append(_luci2.globals.mainMenu.render(0, 1));
1976 renderViewMenu: function()
1980 .append(_luci2.globals.mainMenu.render(2, 900));
1983 renderView: function(node)
1985 var name = node.view.split(/\//).join('.');
1987 _luci2.ui.renderViewMenu();
1990 _luci2._views = { };
1992 _luci2.setHash('view', node.view);
1994 if (_luci2._views[name] instanceof _luci2.ui.view)
1995 return _luci2._views[name].render();
1997 var url = _luci2.globals.resource + '/view/' + name + '.js';
1999 return $.ajax(url, {
2003 }).then(function(data) {
2005 var viewConstructorSource = (
2006 '(function(L, $) {\n' +
2008 '})(_luci2, $);\n\n' +
2010 ).format(data, url);
2012 var viewConstructor = eval(viewConstructorSource);
2014 _luci2._views[name] = new viewConstructor({
2016 acls: node.write || { }
2019 return _luci2._views[name].render();
2022 alert('Unable to instantiate view "%s": %s'.format(url, e));
2025 return $.Deferred().resolve();
2029 updateHostname: function()
2031 return _luci2.system.getBoardInfo().then(function(info) {
2033 $('#hostname').text(info.hostname);
2039 _luci2.ui.loading(true);
2042 _luci2.ui.updateHostname(),
2043 _luci2.ui.renderMainMenu()
2045 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2046 _luci2.ui.loading(false);
2052 var AbstractWidget = Class.extend({
2053 i18n: function(text) {
2057 toString: function() {
2058 var x = document.createElement('div');
2059 x.appendChild(this.render());
2064 insertInto: function(id) {
2065 return $(id).empty().append(this.render());
2069 this.ui.view = AbstractWidget.extend({
2070 _fetch_template: function()
2072 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2076 success: function(data) {
2077 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2078 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2085 return _luci2.tr(p2);
2088 return _luci2.globals[p2] || '';
2091 return '(?' + match + ')';
2095 $('#maincontent').append(data);
2102 throw "Not implemented";
2107 var container = $('#maincontent');
2112 container.append($('<h2 />').append(this.title));
2114 if (this.description)
2115 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2118 return this._fetch_template().then(function() {
2119 return _luci2.deferrable(self.execute());
2124 this.ui.menu = AbstractWidget.extend({
2129 entries: function(entries)
2131 for (var entry in entries)
2133 var path = entry.split(/\//);
2134 var node = this._nodes;
2136 for (i = 0; i < path.length; i++)
2141 if (!node.childs[path[i]])
2142 node.childs[path[i]] = { };
2144 node = node.childs[path[i]];
2147 $.extend(node, entries[entry]);
2151 _indexcmp: function(a, b)
2153 var x = a.index || 0;
2154 var y = b.index || 0;
2158 firstChildView: function(node)
2164 for (var child in (node.childs || { }))
2165 nodes.push(node.childs[child]);
2167 nodes.sort(this._indexcmp);
2169 for (var i = 0; i < nodes.length; i++)
2171 var child = this.firstChildView(nodes[i]);
2174 $.extend(node, child);
2182 _onclick: function(ev)
2184 _luci2.ui.loading(true);
2185 _luci2.ui.renderView(ev.data).then(function() {
2186 _luci2.ui.loading(false);
2189 ev.preventDefault();
2193 _render: function(childs, level, min, max)
2196 for (var node in childs)
2198 var child = this.firstChildView(childs[node]);
2200 nodes.push(childs[node]);
2203 nodes.sort(this._indexcmp);
2205 var list = $('<ul />');
2208 list.addClass('nav');
2209 else if (level == 1)
2210 list.addClass('dropdown-menu');
2212 for (var i = 0; i < nodes.length; i++)
2214 if (!_luci2.globals.defaultNode)
2216 var v = _luci2.getHash('view');
2217 if (!v || v == nodes[i].view)
2218 _luci2.globals.defaultNode = nodes[i];
2221 var item = $('<li />')
2224 .text(_luci2.tr(nodes[i].title))
2225 .click(nodes[i], this._onclick))
2228 if (nodes[i].childs && level < max)
2230 item.addClass('dropdown');
2231 item.find('a').addClass('menu');
2232 item.append(this._render(nodes[i].childs, level + 1));
2239 render: function(min, max)
2241 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2242 return this._render(top.childs, 0, min, max);
2245 getNode: function(path, max)
2247 var p = path.split(/\//);
2248 var n = this._nodes;
2250 if (typeof(max) == 'undefined')
2253 for (var i = 0; i < max; i++)
2255 if (!n.childs[p[i]])
2265 this.ui.table = AbstractWidget.extend({
2271 row: function(values)
2273 if ($.isArray(values))
2275 this._rows.push(values);
2277 else if ($.isPlainObject(values))
2280 for (var i = 0; i < this.options.columns.length; i++)
2282 var col = this.options.columns[i];
2284 if (typeof col.key == 'string')
2285 v.push(values[col.key]);
2293 rows: function(rows)
2295 for (var i = 0; i < rows.length; i++)
2299 render: function(id)
2301 var fieldset = document.createElement('fieldset');
2302 fieldset.className = 'cbi-section';
2304 if (this.options.caption)
2306 var legend = document.createElement('legend');
2307 $(legend).append(this.options.caption);
2308 fieldset.appendChild(legend);
2311 var table = document.createElement('table');
2312 table.className = 'cbi-section-table';
2314 var has_caption = false;
2315 var has_description = false;
2317 for (var i = 0; i < this.options.columns.length; i++)
2318 if (this.options.columns[i].caption)
2323 else if (this.options.columns[i].description)
2325 has_description = true;
2331 var tr = table.insertRow(-1);
2332 tr.className = 'cbi-section-table-titles';
2334 for (var i = 0; i < this.options.columns.length; i++)
2336 var col = this.options.columns[i];
2337 var th = document.createElement('th');
2338 th.className = 'cbi-section-table-cell';
2343 th.style.width = col.width;
2346 th.style.textAlign = col.align;
2349 $(th).append(col.caption);
2353 if (has_description)
2355 var tr = table.insertRow(-1);
2356 tr.className = 'cbi-section-table-descr';
2358 for (var i = 0; i < this.options.columns.length; i++)
2360 var col = this.options.columns[i];
2361 var th = document.createElement('th');
2362 th.className = 'cbi-section-table-cell';
2367 th.style.width = col.width;
2370 th.style.textAlign = col.align;
2372 if (col.description)
2373 $(th).append(col.description);
2377 if (this._rows.length == 0)
2379 if (this.options.placeholder)
2381 var tr = table.insertRow(-1);
2382 var td = tr.insertCell(-1);
2383 td.className = 'cbi-section-table-cell';
2385 td.colSpan = this.options.columns.length;
2386 $(td).append(this.options.placeholder);
2391 for (var i = 0; i < this._rows.length; i++)
2393 var tr = table.insertRow(-1);
2395 for (var j = 0; j < this.options.columns.length; j++)
2397 var col = this.options.columns[j];
2398 var td = tr.insertCell(-1);
2400 var val = this._rows[i][j];
2402 if (typeof(val) == 'undefined')
2403 val = col.placeholder;
2405 if (typeof(val) == 'undefined')
2409 td.style.width = col.width;
2412 td.style.textAlign = col.align;
2414 if (typeof col.format == 'string')
2415 $(td).append(col.format.format(val));
2416 else if (typeof col.format == 'function')
2417 $(td).append(col.format(val, i));
2425 fieldset.appendChild(table);
2431 this.ui.progress = AbstractWidget.extend({
2434 var vn = parseInt(this.options.value) || 0;
2435 var mn = parseInt(this.options.max) || 100;
2436 var pc = Math.floor((100 / mn) * vn);
2438 var bar = document.createElement('div');
2439 bar.className = 'progressbar';
2441 bar.appendChild(document.createElement('div'));
2442 bar.lastChild.appendChild(document.createElement('div'));
2443 bar.lastChild.style.width = pc + '%';
2445 if (typeof(this.options.format) == 'string')
2446 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2447 else if (typeof(this.options.format) == 'function')
2448 $(bar.lastChild.lastChild).append(this.options.format(pc));
2450 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2456 this.ui.devicebadge = AbstractWidget.extend({
2459 var dev = this.options.l3_device || this.options.device || '?';
2461 var span = document.createElement('span');
2462 span.className = 'ifacebadge';
2464 if (typeof(this.options.signal) == 'number' ||
2465 typeof(this.options.noise) == 'number')
2468 if (typeof(this.options.signal) != 'undefined' &&
2469 typeof(this.options.noise) != 'undefined')
2471 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2484 span.appendChild(document.createElement('img'));
2485 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2488 span.title = _luci2.tr('No signal');
2490 span.title = '%s: %d %s / %s: %d %s'.format(
2491 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2492 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2497 var type = 'ethernet';
2498 var desc = _luci2.tr('Ethernet device');
2500 if (this.options.l3_device != this.options.device)
2503 desc = _luci2.tr('Tunnel interface');
2505 else if (dev.indexOf('br-') == 0)
2508 desc = _luci2.tr('Bridge');
2510 else if (dev.indexOf('.') > 0)
2513 desc = _luci2.tr('VLAN interface');
2515 else if (dev.indexOf('wlan') == 0 ||
2516 dev.indexOf('ath') == 0 ||
2517 dev.indexOf('wl') == 0)
2520 desc = _luci2.tr('Wireless Network');
2523 span.appendChild(document.createElement('img'));
2524 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2528 $(span).append(' ');
2529 $(span).append(dev);
2535 var type = function(f, l)
2545 _luci2.cbi.validation.message = _luci2.tr(msg);
2548 compile: function(code)
2553 var types = _luci2.cbi.validation.types;
2558 for (var i = 0; i < code.length; i++)
2566 switch (code.charCodeAt(i))
2578 var label = code.substring(pos, i);
2579 label = label.replace(/\\(.)/g, '$1');
2580 label = label.replace(/^[ \t]+/g, '');
2581 label = label.replace(/[ \t]+$/g, '');
2583 if (label && !isNaN(label))
2585 stack.push(parseFloat(label));
2587 else if (label.match(/^(['"]).*\1$/))
2589 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2591 else if (typeof types[label] == 'function')
2593 stack.push(types[label]);
2598 throw "Syntax error, unhandled token '"+label+"'";
2603 depth += (code.charCodeAt(i) == 40);
2609 if (typeof stack[stack.length-2] != 'function')
2610 throw "Syntax error, argument list follows non-function";
2612 stack[stack.length-1] =
2613 arguments.callee(code.substring(pos, i));
2626 var validation = this.cbi.validation;
2628 validation.types = {
2629 'integer': function()
2631 if (this.match(/^-?[0-9]+$/) != null)
2634 validation.i18n('Must be a valid integer');
2638 'uinteger': function()
2640 if (validation.types['integer'].apply(this) && (this >= 0))
2643 validation.i18n('Must be a positive integer');
2649 if (!isNaN(parseFloat(this)))
2652 validation.i18n('Must be a valid number');
2656 'ufloat': function()
2658 if (validation.types['float'].apply(this) && (this >= 0))
2661 validation.i18n('Must be a positive number');
2665 'ipaddr': function()
2667 if (validation.types['ip4addr'].apply(this) ||
2668 validation.types['ip6addr'].apply(this))
2671 validation.i18n('Must be a valid IP address');
2675 'ip4addr': function()
2677 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2679 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2680 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2681 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2682 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2683 ((RegExp.$6.indexOf('.') < 0)
2684 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2685 : (validation.types['ip4addr'].apply(RegExp.$6))))
2689 validation.i18n('Must be a valid IPv4 address');
2693 'ip6addr': function()
2695 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2697 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2699 var addr = RegExp.$1;
2706 if (addr.indexOf('.') > 0)
2708 var off = addr.lastIndexOf(':');
2710 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2712 validation.i18n('Must be a valid IPv6 address');
2716 addr = addr.substr(0, off) + ':0:0';
2719 if (addr.indexOf('::') >= 0)
2724 for (var i = 1; i < (addr.length-1); i++)
2725 if (addr.charAt(i) == ':')
2730 validation.i18n('Must be a valid IPv6 address');
2734 for (var i = 0; i < (7 - colons); i++)
2737 if (addr.match(/^(.*?)::(.*?)$/))
2738 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2739 (RegExp.$2 ? ':' + RegExp.$2 : '');
2742 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2745 validation.i18n('Must be a valid IPv6 address');
2755 if (validation.types['integer'].apply(this) &&
2756 (this >= 0) && (this <= 65535))
2759 validation.i18n('Must be a valid port number');
2763 'portrange': function()
2765 if (this.match(/^(\d+)-(\d+)$/))
2770 if (validation.types['port'].apply(p1) &&
2771 validation.types['port'].apply(p2) &&
2772 (parseInt(p1) <= parseInt(p2)))
2775 else if (validation.types['port'].apply(this))
2780 validation.i18n('Must be a valid port range');
2784 'macaddr': function()
2786 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2789 validation.i18n('Must be a valid MAC address');
2795 if (validation.types['hostname'].apply(this) ||
2796 validation.types['ipaddr'].apply(this))
2799 validation.i18n('Must be a valid hostname or IP address');
2803 'hostname': function()
2805 if ((this.length <= 253) &&
2806 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2807 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2808 this.match(/[^0-9.]/)))))
2811 validation.i18n('Must be a valid host name');
2815 'network': function()
2817 if (validation.types['uciname'].apply(this) ||
2818 validation.types['host'].apply(this))
2821 validation.i18n('Must be a valid network name');
2825 'wpakey': function()
2829 if ((v.length == 64)
2830 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2831 : ((v.length >= 8) && (v.length <= 63)))
2834 validation.i18n('Must be a valid WPA key');
2838 'wepkey': function()
2842 if (v.substr(0,2) == 's:')
2845 if (((v.length == 10) || (v.length == 26))
2846 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2847 : ((v.length == 5) || (v.length == 13)))
2850 validation.i18n('Must be a valid WEP key');
2854 'uciname': function()
2856 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2859 validation.i18n('Must be a valid UCI identifier');
2863 'range': function(min, max)
2865 var val = parseFloat(this);
2867 if (validation.types['integer'].apply(this) &&
2868 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
2871 validation.i18n('Must be a number between %d and %d');
2875 'min': function(min)
2877 var val = parseFloat(this);
2879 if (validation.types['integer'].apply(this) &&
2880 !isNaN(min) && !isNaN(val) && (val >= min))
2883 validation.i18n('Must be a number greater or equal to %d');
2887 'max': function(max)
2889 var val = parseFloat(this);
2891 if (validation.types['integer'].apply(this) &&
2892 !isNaN(max) && !isNaN(val) && (val <= max))
2895 validation.i18n('Must be a number lower or equal to %d');
2899 'rangelength': function(min, max)
2901 var val = '' + this;
2903 if (!isNaN(min) && !isNaN(max) &&
2904 (val.length >= min) && (val.length <= max))
2907 validation.i18n('Must be between %d and %d characters');
2911 'minlength': function(min)
2913 var val = '' + this;
2915 if (!isNaN(min) && (val.length >= min))
2918 validation.i18n('Must be at least %d characters');
2922 'maxlength': function(max)
2924 var val = '' + this;
2926 if (!isNaN(max) && (val.length <= max))
2929 validation.i18n('Must be at most %d characters');
2937 for (var i = 0; i < arguments.length; i += 2)
2939 delete validation.message;
2941 if (typeof(arguments[i]) != 'function')
2943 if (arguments[i] == this)
2947 else if (arguments[i].apply(this, arguments[i+1]))
2952 if (validation.message)
2953 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2956 validation.message = msgs.join( _luci2.tr(' - or - '));
2964 for (var i = 0; i < arguments.length; i += 2)
2966 delete validation.message;
2968 if (typeof arguments[i] != 'function')
2970 if (arguments[i] != this)
2974 else if (!arguments[i].apply(this, arguments[i+1]))
2979 if (validation.message)
2980 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2983 validation.message = msgs.join(', ');
2989 return validation.types['or'].apply(
2990 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
2993 'list': function(subvalidator, subargs)
2995 if (typeof subvalidator != 'function')
2998 var tokens = this.match(/[^ \t]+/g);
2999 for (var i = 0; i < tokens.length; i++)
3000 if (!subvalidator.apply(tokens[i], subargs))
3006 'phonedigit': function()
3008 if (this.match(/^[0-9\*#!\.]+$/) != null)
3011 validation.i18n('Must be a valid phone number digit');
3015 'string': function()
3022 this.cbi.AbstractValue = AbstractWidget.extend({
3023 init: function(name, options)
3026 this.instance = { };
3027 this.dependencies = [ ];
3028 this.rdependency = { };
3030 this.options = _luci2.defaults(options, {
3040 return this.section.id('field', sid || '__unknown__', this.name);
3043 render: function(sid)
3045 var i = this.instance[sid] = { };
3047 i.top = $('<div />').addClass('cbi-value');
3049 if (typeof(this.options.caption) == 'string')
3051 .addClass('cbi-value-title')
3052 .attr('for', this.id(sid))
3053 .text(this.options.caption)
3056 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
3057 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
3059 if (typeof(this.options.description) == 'string')
3061 .addClass('cbi-value-description')
3062 .text(this.options.description)
3068 ucipath: function(sid)
3071 config: (this.options.uci_package || this.map.uci_package),
3072 section: (this.options.uci_section || sid),
3073 option: (this.options.uci_option || this.name)
3077 ucivalue: function(sid)
3079 var uci = this.ucipath(sid);
3080 var val = this.map.get(uci.config, uci.section, uci.option);
3082 if (typeof(val) == 'undefined')
3083 return this.options.initial;
3088 formvalue: function(sid)
3090 var v = $('#' + this.id(sid)).val();
3091 return (v === '') ? undefined : v;
3094 textvalue: function(sid)
3096 var v = this.formvalue(sid);
3098 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3099 v = this.ucivalue(sid);
3101 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3102 v = this.options.placeholder;
3104 if (typeof(v) == 'undefined' || v === '')
3107 if (typeof(v) == 'string' && $.isArray(this.choices))
3109 for (var i = 0; i < this.choices.length; i++)
3110 if (v === this.choices[i][0])
3111 return this.choices[i][1];
3113 else if (v === true)
3114 return _luci2.tr('yes');
3115 else if (v === false)
3116 return _luci2.tr('no');
3117 else if ($.isArray(v))
3118 return v.join(', ');
3123 changed: function(sid)
3125 var a = this.ucivalue(sid);
3126 var b = this.formvalue(sid);
3128 if (typeof(a) != typeof(b))
3131 if (typeof(a) == 'object')
3133 if (a.length != b.length)
3136 for (var i = 0; i < a.length; i++)
3148 var uci = this.ucipath(sid);
3150 if (this.instance[sid].disabled)
3152 if (!this.options.keep)
3153 return this.map.set(uci.config, uci.section, uci.option, undefined);
3158 var chg = this.changed(sid);
3159 var val = this.formvalue(sid);
3162 this.map.set(uci.config, uci.section, uci.option, val);
3167 validator: function(sid, elem, multi)
3169 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3173 if (typeof(this.options.datatype) == 'string')
3176 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3179 else if (typeof(this.options.datatype) == 'function')
3181 var vfunc = this.options.datatype;
3182 vstack = [ function(elem) {
3183 var rv = vfunc(this, elem);
3185 validation.message = rv;
3186 return (rv === true);
3195 inst: this.instance[sid],
3196 opt: this.options.optional
3199 var validator = function(ev)
3203 var val = d.elem.val();
3205 if (vstack && typeof(vstack[0]) == 'function')
3207 delete validation.message;
3209 if ((val.length == 0 && !d.opt))
3211 d.elem.addClass('error');
3212 d.inst.top.addClass('error');
3213 d.inst.error.text(_luci2.tr('Field must not be empty'));
3216 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3218 d.elem.addClass('error');
3219 d.inst.top.addClass('error');
3220 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3225 d.elem.removeClass('error');
3227 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3233 d.inst.top.removeClass('error');
3234 d.inst.error.text('');
3241 for (var field in d.self.rdependency)
3242 d.self.rdependency[field].toggle(d.sid);
3248 if (elem.prop('tagName') == 'SELECT')
3250 elem.change(evdata, validator);
3252 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3254 elem.click(evdata, validator);
3255 elem.blur(evdata, validator);
3259 elem.keyup(evdata, validator);
3260 elem.blur(evdata, validator);
3263 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3268 validate: function(sid)
3270 var i = this.instance[sid];
3272 i.widget.find('[cbi-validate]').trigger('validate');
3274 return (i.disabled || i.error.text() == '');
3277 depends: function(d, v)
3284 for (var i = 0; i < d.length; i++)
3286 if (typeof(d[i]) == 'string')
3288 else if (d[i] instanceof _luci2.cbi.AbstractValue)
3289 dep[d[i].name] = true;
3292 else if (d instanceof _luci2.cbi.AbstractValue)
3295 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3297 else if (typeof(d) == 'object')
3301 else if (typeof(d) == 'string')
3304 dep[d] = (typeof(v) == 'undefined') ? true : v;
3307 if (!dep || $.isEmptyObject(dep))
3310 for (var field in dep)
3312 var f = this.section.fields[field];
3314 f.rdependency[this.name] = this;
3319 if ($.isEmptyObject(dep))
3322 this.dependencies.push(dep);
3327 toggle: function(sid)
3329 var d = this.dependencies;
3330 var i = this.instance[sid];
3335 for (var n = 0; n < d.length; n++)
3339 for (var field in d[n])
3341 var val = this.section.fields[field].formvalue(sid);
3342 var cmp = d[n][field];
3344 if (typeof(cmp) == 'boolean')
3346 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3352 else if (typeof(cmp) == 'string')
3360 else if (typeof(cmp) == 'function')
3368 else if (cmp instanceof RegExp)
3393 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3400 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
3401 widget: function(sid)
3403 var o = this.options;
3405 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3406 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3408 var i = $('<input />')
3409 .attr('id', this.id(sid))
3410 .attr('type', 'checkbox')
3411 .prop('checked', this.ucivalue(sid));
3413 return this.validator(sid, i);
3416 ucivalue: function(sid)
3418 var v = this.callSuper('ucivalue', sid);
3420 if (typeof(v) == 'boolean')
3423 return (v == this.options.enabled);
3426 formvalue: function(sid)
3428 var v = $('#' + this.id(sid)).prop('checked');
3430 if (typeof(v) == 'undefined')
3431 return !!this.options.initial;
3438 var uci = this.ucipath(sid);
3440 if (this.instance[sid].disabled)
3442 if (!this.options.keep)
3443 return this.map.set(uci.config, uci.section, uci.option, undefined);
3448 var chg = this.changed(sid);
3449 var val = this.formvalue(sid);
3453 val = val ? this.options.enabled : this.options.disabled;
3455 if (this.options.optional && val == this.options.initial)
3456 this.map.set(uci.config, uci.section, uci.option, undefined);
3458 this.map.set(uci.config, uci.section, uci.option, val);
3465 this.cbi.InputValue = this.cbi.AbstractValue.extend({
3466 widget: function(sid)
3468 var i = $('<input />')
3469 .attr('id', this.id(sid))
3470 .attr('type', 'text')
3471 .attr('placeholder', this.options.placeholder)
3472 .val(this.ucivalue(sid));
3474 return this.validator(sid, i);
3478 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
3479 widget: function(sid)
3481 var i = $('<input />')
3482 .attr('id', this.id(sid))
3483 .attr('type', 'password')
3484 .attr('placeholder', this.options.placeholder)
3485 .val(this.ucivalue(sid));
3487 var t = $('<img />')
3488 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3489 .attr('title', _luci2.tr('Reveal or hide password'))
3490 .addClass('cbi-button')
3491 .click(function(ev) {
3492 var i = $(this).prev();
3493 var t = i.attr('type');
3494 i.attr('type', (t == 'password') ? 'text' : 'password');
3498 this.validator(sid, i);
3501 .addClass('cbi-input-password')
3507 this.cbi.ListValue = this.cbi.AbstractValue.extend({
3508 widget: function(sid)
3510 var s = $('<select />');
3512 if (this.options.optional)
3515 .text(_luci2.tr('-- Please choose --'))
3519 for (var i = 0; i < this.choices.length; i++)
3521 .attr('value', this.choices[i][0])
3522 .text(this.choices[i][1])
3525 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3527 return this.validator(sid, s);
3530 value: function(k, v)
3535 this.choices.push([k, v || k]);
3540 this.cbi.MultiValue = this.cbi.ListValue.extend({
3541 widget: function(sid)
3543 var v = this.ucivalue(sid);
3544 var t = $('<div />').attr('id', this.id(sid));
3547 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3550 for (var i = 0; i < v.length; i++)
3554 for (var i = 0; i < this.choices.length; i++)
3557 .append($('<input />')
3558 .addClass('cbi-input-checkbox')
3559 .attr('type', 'checkbox')
3560 .attr('value', this.choices[i][0])
3561 .prop('checked', s[this.choices[i][0]]))
3562 .append(this.choices[i][1])
3572 formvalue: function(sid)
3575 var fields = $('#' + this.id(sid) + ' > label > input');
3577 for (var i = 0; i < fields.length; i++)
3578 if (fields[i].checked)
3579 rv.push(fields[i].getAttribute('value'));
3584 textvalue: function(sid)
3586 var v = this.formvalue(sid);
3590 for (var i = 0; i < this.choices.length; i++)
3591 c[this.choices[i][0]] = this.choices[i][1];
3595 for (var i = 0; i < v.length; i++)
3596 t.push(c[v[i]] || v[i]);
3598 return t.join(', ');
3602 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
3603 _change: function(ev)
3606 var self = ev.data.self;
3608 if (s.selectedIndex == (s.options.length - 1))
3610 ev.data.select.hide();
3611 ev.data.input.show().focus();
3613 var v = ev.data.input.val();
3614 ev.data.input.val(' ');
3615 ev.data.input.val(v);
3617 else if (self.options.optional && s.selectedIndex == 0)
3619 ev.data.input.val('');
3623 ev.data.input.val(ev.data.select.val());
3630 var val = this.value;
3631 var self = ev.data.self;
3633 ev.data.select.empty();
3635 if (self.options.optional)
3638 .text(_luci2.tr('-- please choose --'))
3639 .appendTo(ev.data.select);
3642 for (var i = 0; i < self.choices.length; i++)
3644 if (self.choices[i][0] == val)
3648 .attr('value', self.choices[i][0])
3649 .text(self.choices[i][1])
3650 .appendTo(ev.data.select);
3653 if (!seen && val != '')
3657 .appendTo(ev.data.select);
3661 .text(_luci2.tr('-- custom --'))
3662 .appendTo(ev.data.select);
3664 ev.data.input.hide();
3665 ev.data.select.val(val).show().focus();
3668 _enter: function(ev)
3673 ev.preventDefault();
3674 ev.data.self._blur(ev);
3678 widget: function(sid)
3680 var d = $('<div />')
3681 .attr('id', this.id(sid));
3683 var t = $('<input />')
3684 .attr('type', 'text')
3688 var s = $('<select />')
3693 input: this.validator(sid, t),
3694 select: this.validator(sid, s)
3697 s.change(evdata, this._change);
3698 t.blur(evdata, this._blur);
3699 t.keydown(evdata, this._enter);
3701 t.val(this.ucivalue(sid));
3707 value: function(k, v)
3712 this.choices.push([k, v || k]);
3716 formvalue: function(sid)
3718 var v = $('#' + this.id(sid)).children('input').val();
3719 return (v == '') ? undefined : v;
3723 this.cbi.DynamicList = this.cbi.ComboBox.extend({
3724 _redraw: function(focus, add, del, s)
3726 var v = s.values || [ ];
3729 $(s.parent).children('input').each(function(i) {
3731 v.push(this.value || '');
3734 $(s.parent).empty();
3739 v.splice(focus, 0, '');
3741 else if (v.length == 0)
3747 for (var i = 0; i < v.length; i++)
3758 var txt = $('<input />')
3759 .attr('type', 'text')
3761 .appendTo(s.parent);
3763 var sel = $('<select />')
3764 .appendTo(s.parent);
3766 evdata.input = this.validator(s.sid, txt, true);
3767 evdata.select = this.validator(s.sid, sel, true);
3769 sel.change(evdata, this._change);
3770 txt.blur(evdata, this._blur);
3771 txt.keydown(evdata, this._keydown);
3776 if (i == focus || -(i+1) == focus)
3783 var f = $('<input />')
3784 .attr('type', 'text')
3786 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
3787 .addClass('cbi-input-text')
3788 .keydown(evdata, this._keydown)
3789 .keypress(evdata, this._keypress)
3792 f.appendTo(s.parent);
3798 else if (-(i+1) == focus)
3802 /* force cursor to end */
3808 evdata.input = this.validator(s.sid, f, true);
3814 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
3815 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
3816 .addClass('cbi-button')
3817 .click(evdata, this._btnclick)
3818 .appendTo(s.parent);
3821 .appendTo(s.parent);
3829 _keypress: function(ev)
3833 /* backspace, delete */
3836 if (ev.data.input.val() == '')
3838 ev.preventDefault();
3844 /* enter, arrow up, arrow down */
3848 ev.preventDefault();
3855 _keydown: function(ev)
3857 var input = ev.data.input;
3861 /* backspace, delete */
3864 if (input.val().length == 0)
3866 ev.preventDefault();
3868 var index = ev.data.index;
3874 ev.data.self._redraw(focus, -1, index, ev.data);
3882 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
3887 var prev = input.prevAll('input:first');
3888 if (prev.is(':visible'))
3891 prev.next('select').focus();
3896 var next = input.nextAll('input:first');
3897 if (next.is(':visible'))
3900 next.next('select').focus();
3907 _btnclick: function(ev)
3909 if (!this.getAttribute('disabled'))
3911 if (ev.target.src.indexOf('remove') > -1)
3913 var index = ev.data.index;
3914 ev.data.self._redraw(-index, -1, index, ev.data);
3918 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
3925 widget: function(sid)
3927 this.options.optional = true;
3929 var v = this.ucivalue(sid);
3932 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3934 var d = $('<div />')
3935 .attr('id', this.id(sid))
3936 .addClass('cbi-input-dynlist');
3938 this._redraw(NaN, -1, -1, {
3948 ucivalue: function(sid)
3950 var v = this.callSuper('ucivalue', sid);
3953 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3958 formvalue: function(sid)
3961 var fields = $('#' + this.id(sid) + ' > input');
3963 for (var i = 0; i < fields.length; i++)
3964 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
3965 rv.push(fields[i].value);
3971 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
3972 widget: function(sid)
3975 .addClass('cbi-value-dummy')
3976 .attr('id', this.id(sid))
3977 .html(this.ucivalue(sid));
3980 formvalue: function(sid)
3982 return this.ucivalue(sid);
3986 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
3991 if (!self.interfaces)
3993 self.interfaces = [ ];
3994 return _luci2.network.getNetworkStatus().then(function(ifaces) {
3995 self.interfaces = ifaces;
4003 _device_icon: function(dev)
4005 var type = 'ethernet';
4006 var desc = _luci2.tr('Ethernet device');
4008 if (dev.type == 'IP tunnel')
4011 desc = _luci2.tr('Tunnel interface');
4013 else if (dev['bridge-members'])
4016 desc = _luci2.tr('Bridge');
4018 else if (dev.wireless)
4021 desc = _luci2.tr('Wireless Network');
4023 else if (dev.device.indexOf('.') > 0)
4026 desc = _luci2.tr('VLAN interface');
4030 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4031 .attr('title', '%s (%s)'.format(desc, dev.device));
4034 widget: function(sid)
4036 var id = this.id(sid);
4037 var ul = $('<ul />')
4039 .addClass('cbi-input-networks');
4041 var itype = this.options.multiple ? 'checkbox' : 'radio';
4042 var value = this.ucivalue(sid);
4045 if (!this.options.multiple)
4046 check[value] = true;
4048 for (var i = 0; i < value.length; i++)
4049 check[value[i]] = true;
4051 if (this.interfaces)
4053 for (var i = 0; i < this.interfaces.length; i++)
4055 var iface = this.interfaces[i];
4056 var badge = $('<span />')
4057 .addClass('ifacebadge')
4058 .text('%s: '.format(iface['interface']));
4060 if (iface.device && iface.device.subdevices)
4061 for (var j = 0; j < iface.device.subdevices.length; j++)
4062 badge.append(this._device_icon(iface.device.subdevices[j]));
4063 else if (iface.device)
4064 badge.append(this._device_icon(iface.device));
4066 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4069 .append($('<label />')
4070 .append($('<input />')
4071 .attr('name', itype + id)
4072 .attr('type', itype)
4073 .attr('value', iface['interface'])
4074 .prop('checked', !!check[iface['interface']])
4075 .addClass('cbi-input-' + itype))
4081 if (!this.options.multiple)
4084 .append($('<label />')
4085 .append($('<input />')
4086 .attr('name', itype + id)
4087 .attr('type', itype)
4089 .prop('checked', !value)
4090 .addClass('cbi-input-' + itype))
4091 .append(_luci2.tr('unspecified')))
4098 ucivalue: function(sid)
4100 var v = this.callSuper('ucivalue', sid);
4102 if (!this.options.multiple)
4108 else if (typeof(v) == 'string')
4111 return v ? v[0] : undefined;
4118 if (typeof(v) == 'string')
4119 v = v.match(/\S+/g);
4125 formvalue: function(sid)
4127 var inputs = $('#' + this.id(sid) + ' input');
4129 if (!this.options.multiple)
4131 for (var i = 0; i < inputs.length; i++)
4132 if (inputs[i].checked && inputs[i].value !== '')
4133 return inputs[i].value;
4140 for (var i = 0; i < inputs.length; i++)
4141 if (inputs[i].checked)
4142 rv.push(inputs[i].value);
4144 return rv.length ? rv : undefined;
4149 this.cbi.AbstractSection = AbstractWidget.extend({
4152 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4154 for (var i = 1; i < arguments.length; i++)
4155 s.push(arguments[i].replace(/\./g, '_'));
4160 option: function(widget, name, options)
4162 if (this.tabs.length == 0)
4163 this.tab({ id: '__default__', selected: true });
4165 return this.taboption('__default__', widget, name, options);
4168 tab: function(options)
4170 if (options.selected)
4171 this.tabs.selected = this.tabs.length;
4175 caption: options.caption,
4176 description: options.description,
4182 taboption: function(tabid, widget, name, options)
4185 for (var i = 0; i < this.tabs.length; i++)
4187 if (this.tabs[i].id == tabid)
4195 throw 'Cannot append to unknown tab ' + tabid;
4197 var w = widget ? new widget(name, options) : null;
4199 if (!(w instanceof _luci2.cbi.AbstractValue))
4200 throw 'Widget must be an instance of AbstractValue';
4205 this.fields[name] = w;
4211 ucipackages: function(pkg)
4213 for (var i = 0; i < this.tabs.length; i++)
4214 for (var j = 0; j < this.tabs[i].fields.length; j++)
4215 if (this.tabs[i].fields[j].options.uci_package)
4216 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4219 formvalue: function()
4223 this.sections(function(s) {
4224 var sid = s['.name'];
4225 var sv = rv[sid] || (rv[sid] = { });
4227 for (var i = 0; i < this.tabs.length; i++)
4228 for (var j = 0; j < this.tabs[i].fields.length; j++)
4230 var val = this.tabs[i].fields[j].formvalue(sid);
4231 sv[this.tabs[i].fields[j].name] = val;
4238 validate: function(sid)
4244 var as = this.sections();
4245 for (var i = 0; i < as.length; i++)
4246 if (!this.validate(as[i]['.name']))
4251 var inst = this.instance[sid];
4252 var sv = rv[sid] || (rv[sid] = { });
4255 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4257 legend.children('span').detach();
4259 for (var i = 0; i < this.tabs.length; i++)
4262 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4264 tab.children('span').detach();
4266 for (var j = 0; j < this.tabs[i].fields.length; j++)
4267 if (!this.tabs[i].fields[j].validate(sid))
4274 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4287 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4295 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
4296 init: function(uci_type, options)
4298 this.uci_type = uci_type;
4299 this.options = options;
4302 this.active_panel = 0;
4303 this.active_tab = { };
4306 filter: function(section)
4311 sections: function(cb)
4313 var s1 = this.map.ucisections(this.map.uci_package);
4316 for (var i = 0; i < s1.length; i++)
4317 if (s1[i]['.type'] == this.uci_type)
4318 if (this.filter(s1[i]))
4321 if (typeof(cb) == 'function')
4322 for (var i = 0; i < s2.length; i++)
4323 cb.apply(this, [ s2[i] ]);
4330 this.map.add(this.map.uci_package, this.uci_type, name);
4333 remove: function(sid)
4335 this.map.remove(this.map.uci_package, sid);
4341 var name = undefined;
4342 var self = ev.data.self;
4344 if (addb.prev().prop('nodeName') == 'INPUT')
4345 name = addb.prev().val();
4347 if (addb.prop('disabled') || name === '')
4350 _luci2.ui.saveScrollTop();
4352 self.active_panel = -1;
4357 _luci2.ui.restoreScrollTop();
4360 _remove: function(ev)
4362 var self = ev.data.self;
4363 var sid = ev.data.sid;
4365 if (ev.data.index == (self.sections().length - 1))
4366 self.active_panel = -1;
4368 _luci2.ui.saveScrollTop();
4374 _luci2.ui.restoreScrollTop();
4376 ev.stopPropagation();
4381 var self = ev.data.self;
4383 var addb = text.next();
4384 var errt = addb.next();
4385 var name = text.val();
4388 if (!/^[a-zA-Z0-9_]*$/.test(name))
4390 errt.text(_luci2.tr('Invalid section name')).show();
4391 text.addClass('error');
4392 addb.prop('disabled', true);
4396 for (var sid in self.map.uci.values[self.map.uci_package])
4403 for (var sid in self.map.uci.creates[self.map.uci_package])
4412 errt.text(_luci2.tr('Name already used')).show();
4413 text.addClass('error');
4414 addb.prop('disabled', true);
4418 errt.text('').hide();
4419 text.removeClass('error');
4420 addb.prop('disabled', false);
4424 teaser: function(sid)
4426 var tf = this.teaser_fields;
4430 tf = this.teaser_fields = [ ];
4432 if ($.isArray(this.options.teasers))
4434 for (var i = 0; i < this.options.teasers.length; i++)
4436 var f = this.options.teasers[i];
4437 if (f instanceof _luci2.cbi.AbstractValue)
4439 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
4440 tf.push(this.fields[f]);
4445 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4446 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4447 tf.push(this.tabs[i].fields[j]);
4453 for (var i = 0; i < tf.length; i++)
4455 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4458 var n = tf[i].options.caption || tf[i].name;
4459 var v = tf[i].textvalue(sid);
4461 if (typeof(v) == 'undefined')
4464 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4470 _render_add: function()
4472 var text = _luci2.tr('Add section');
4473 var ttip = _luci2.tr('Create new section...');
4475 if ($.isArray(this.options.add_caption))
4476 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4477 else if (typeof(this.options.add_caption) == 'string')
4478 text = this.options.add_caption, ttip = '';
4480 var add = $('<div />').addClass('cbi-section-add');
4482 if (this.options.anonymous === false)
4485 .addClass('cbi-input-text')
4486 .attr('type', 'text')
4487 .attr('placeholder', ttip)
4488 .blur({ self: this }, this._sid)
4489 .keyup({ self: this }, this._sid)
4493 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4494 .attr('title', text)
4495 .addClass('cbi-button')
4496 .click({ self: this }, this._add)
4500 .addClass('cbi-value-error')
4507 .attr('type', 'button')
4508 .addClass('cbi-button')
4509 .addClass('cbi-button-add')
4510 .val(text).attr('title', ttip)
4511 .click({ self: this }, this._add)
4518 _render_remove: function(sid, index)
4520 var text = _luci2.tr('Remove');
4521 var ttip = _luci2.tr('Remove this section');
4523 if ($.isArray(this.options.remove_caption))
4524 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4525 else if (typeof(this.options.remove_caption) == 'string')
4526 text = this.options.remove_caption, ttip = '';
4528 return $('<input />')
4529 .attr('type', 'button')
4530 .addClass('cbi-button')
4531 .addClass('cbi-button-remove')
4532 .val(text).attr('title', ttip)
4533 .click({ self: this, sid: sid, index: index }, this._remove);
4536 _render_caption: function(sid)
4538 if (typeof(this.options.caption) == 'string')
4540 return $('<legend />')
4541 .text(this.options.caption.format(sid));
4543 else if (typeof(this.options.caption) == 'function')
4545 return $('<legend />')
4546 .text(this.options.caption.call(this, sid));
4554 var allsections = $();
4555 var panel_index = 0;
4557 this.instance = { };
4559 var s = this.sections();
4563 var fieldset = $('<fieldset />')
4564 .addClass('cbi-section');
4566 var head = $('<div />')
4567 .addClass('cbi-section-head')
4568 .appendTo(fieldset);
4570 head.append(this._render_caption(undefined));
4572 if (typeof(this.options.description) == 'string')
4575 .addClass('cbi-section-descr')
4576 .text(this.options.description)
4580 allsections = allsections.add(fieldset);
4583 for (var i = 0; i < s.length; i++)
4585 var sid = s[i]['.name'];
4586 var inst = this.instance[sid] = { tabs: [ ] };
4588 var fieldset = $('<fieldset />')
4589 .attr('id', this.id('sort', sid))
4590 .addClass('cbi-section');
4592 var head = $('<div />')
4593 .addClass('cbi-section-head')
4594 .attr('cbi-section-num', this.index)
4595 .attr('cbi-section-id', sid);
4597 head.append(this._render_caption(sid));
4599 if (typeof(this.options.description) == 'string')
4602 .addClass('cbi-section-descr')
4603 .text(this.options.description)
4608 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4609 teaser = $('<div />')
4610 .addClass('cbi-section-teaser')
4613 if (this.options.addremove)
4615 .addClass('cbi-section-remove')
4617 .append(this._render_remove(sid, panel_index))
4620 var body = $('<div />')
4621 .attr('index', panel_index++);
4623 var fields = $('<fieldset />')
4624 .addClass('cbi-section-node');
4626 if (this.tabs.length > 1)
4628 var menu = $('<ul />')
4629 .addClass('cbi-tabmenu');
4631 for (var j = 0; j < this.tabs.length; j++)
4633 var tabid = this.id('tab', sid, this.tabs[j].id);
4634 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4636 var tabc = $('<div />')
4637 .addClass('cbi-tabcontainer')
4641 if (typeof(this.tabs[j].description) == 'string')
4644 .addClass('cbi-tab-descr')
4645 .text(this.tabs[j].description)
4649 for (var k = 0; k < this.tabs[j].fields.length; k++)
4650 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4652 tabc.appendTo(fields);
4655 $('<li />').attr('id', theadid).append(
4657 .text(this.tabs[j].caption.format(this.tabs[j].id))
4658 .attr('href', '#' + tabid)
4662 menu.appendTo(body);
4665 fields.appendTo(body);
4668 var t = body.tabs({ active: this.active_tab[sid] });
4670 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4673 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4678 for (var j = 0; j < this.tabs[0].fields.length; j++)
4679 this.tabs[0].fields[j].render(sid).appendTo(fields);
4681 fields.appendTo(body);
4685 head.appendTo(fieldset);
4688 body.appendTo(fieldset);
4691 allsections = allsections.add(fieldset);
4694 //this.validate(sid);
4697 // teaser.append(this.teaser(sid));
4700 if (this.options.collabsible && s.length > 1)
4702 var a = $('<div />').append(allsections).accordion({
4703 header: '> fieldset > div.cbi-section-head',
4704 heightStyle: 'content',
4705 active: this.active_panel
4708 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4709 var h = ui.oldHeader;
4710 var s = ev.data.self;
4711 var i = h.attr('cbi-section-id');
4713 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4717 a.on('accordionactivate', { self: this }, function(ev, ui) {
4718 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4721 if (this.options.sortable)
4723 var s = a.sortable({
4725 handle: 'div.cbi-section-head'
4728 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4730 for (var i = 0; i < ev.data.ids.length; i++)
4731 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4732 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4735 s.on('sortstop', function(ev, ui) {
4736 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4740 if (this.options.addremove)
4741 this._render_add().appendTo(a);
4746 if (this.options.addremove)
4747 allsections = allsections.add(this._render_add());
4754 var s = this.sections();
4756 for (var i = 0; i < s.length; i++)
4758 var sid = s[i]['.name'];
4762 $('#' + this.id('sort', sid))
4763 .children('.cbi-section-head')
4764 .children('.cbi-section-teaser')
4765 .append(this.teaser(sid));
4770 this.cbi.TableSection = this.cbi.TypedSection.extend({
4773 var allsections = $();
4774 var panel_index = 0;
4776 this.instance = { };
4778 var s = this.sections();
4780 var fieldset = $('<fieldset />')
4781 .addClass('cbi-section');
4783 fieldset.append(this._render_caption(sid));
4785 if (typeof(this.options.description) == 'string')
4788 .addClass('cbi-section-descr')
4789 .text(this.options.description)
4790 .appendTo(fieldset);
4793 var fields = $('<div />')
4794 .addClass('cbi-section-node')
4795 .appendTo(fieldset);
4797 var table = $('<table />')
4798 .addClass('cbi-section-table')
4801 var thead = $('<thead />')
4802 .append($('<tr />').addClass('cbi-section-table-titles'))
4805 for (var j = 0; j < this.tabs[0].fields.length; j++)
4807 .addClass('cbi-section-table-cell')
4808 .css('width', this.tabs[0].fields[j].options.width || '')
4809 .append(this.tabs[0].fields[j].options.caption)
4810 .appendTo(thead.children());
4812 if (this.options.sortable)
4813 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4815 if (this.options.addremove !== false)
4816 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4818 var tbody = $('<tbody />')
4824 .addClass('cbi-section-table-row')
4827 .addClass('cbi-section-table-cell')
4828 .addClass('cbi-section-table-placeholder')
4829 .attr('colspan', thead.children().children().length)
4830 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
4834 for (var i = 0; i < s.length; i++)
4836 var sid = s[i]['.name'];
4837 var inst = this.instance[sid] = { tabs: [ ] };
4839 var row = $('<tr />')
4840 .addClass('cbi-section-table-row')
4843 for (var j = 0; j < this.tabs[0].fields.length; j++)
4846 .addClass('cbi-section-table-cell')
4847 .css('width', this.tabs[0].fields[j].options.width || '')
4848 .append(this.tabs[0].fields[j].render(sid, true))
4852 if (this.options.sortable)
4855 .addClass('cbi-section-table-cell')
4856 .addClass('cbi-section-table-sort')
4857 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
4858 .append($('<br />'))
4859 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
4863 if (this.options.addremove !== false)
4866 .addClass('cbi-section-table-cell')
4867 .append(this._render_remove(sid))
4876 if (this.options.sortable)
4878 var s = tbody.sortable({
4879 handle: 'td.cbi-section-table-sort'
4882 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4884 for (var i = 0; i < ev.data.ids.length; i++)
4885 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4886 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4889 s.on('sortstop', function(ev, ui) {
4890 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4894 if (this.options.addremove)
4895 this._render_add().appendTo(fieldset);
4897 fields = table = thead = tbody = null;
4903 this.cbi.NamedSection = this.cbi.TypedSection.extend({
4904 sections: function(cb)
4907 var pkg = this.map.uci.values[this.map.uci_package];
4910 if (pkg[s]['.name'] == this.uci_type)
4916 if (typeof(cb) == 'function' && sa.length > 0)
4917 cb.apply(this, [ sa[0] ]);
4923 this.cbi.DummySection = this.cbi.TypedSection.extend({
4924 sections: function(cb)
4926 if (typeof(cb) == 'function')
4927 cb.apply(this, [ { '.name': this.uci_type } ]);
4929 return [ { '.name': this.uci_type } ];
4933 this.cbi.Map = AbstractWidget.extend({
4934 init: function(uci_package, options)
4938 this.uci_package = uci_package;
4939 this.sections = [ ];
4940 this.options = _luci2.defaults(options, {
4941 save: function() { },
4942 prepare: function() {
4943 return _luci2.uci.writable(function(writable) {
4944 self.options.readonly = !writable;
4960 if (typeof(this.active_panel) == 'undefined')
4961 this.active_panel = 0;
4965 for (var i = 0; i < this.sections.length; i++)
4966 this.sections[i].ucipackages(packages);
4968 packages[this.uci_package] = true;
4970 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
4971 for (var i = 0; i < packages.length; i++)
4973 this.uci.values[packages[i]['.package']] = packages[i];
4974 delete packages[i]['.package'];
4977 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
4979 for (var i = 0; i < this.sections.length; i++)
4981 for (var f in this.sections[i].fields)
4983 if (typeof(this.sections[i].fields[f].load) != 'function')
4986 var s = this.sections[i].sections();
4987 for (var j = 0; j < s.length; j++)
4989 var rv = this.sections[i].fields[f].load(s[j]['.name']);
4990 if (_luci2.isDeferred(rv))
4996 return $.when.apply($, deferreds);
5001 for (var pkg in packages)
5002 _luci2.uci.get_all(pkg);
5004 return _luci2.rpc.flush().then(load_cb);
5009 var map = $('<div />').addClass('cbi-map');
5011 if (typeof(this.options.caption) == 'string')
5012 $('<h2 />').text(this.options.caption).appendTo(map);
5014 if (typeof(this.options.description) == 'string')
5015 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
5017 var sections = $('<div />').appendTo(map);
5019 for (var i = 0; i < this.sections.length; i++)
5021 var s = this.sections[i].render();
5023 if (this.options.readonly || this.sections[i].options.readonly)
5024 s.find('input, select, button, img.cbi-button').attr('disabled', true);
5026 s.appendTo(sections);
5028 if (this.sections[i].options.active)
5029 this.active_panel = i;
5032 if (this.options.collabsible)
5034 var a = sections.accordion({
5035 header: '> fieldset > div.cbi-section-head',
5036 heightStyle: 'content',
5037 active: this.active_panel
5040 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
5041 var h = ui.oldHeader;
5042 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
5043 var i = h.attr('cbi-section-id');
5045 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
5047 for (var i = 0; i < ev.data.self.sections.length; i++)
5048 ev.data.self.sections[i].validate();
5051 a.on('accordionactivate', { self: this }, function(ev, ui) {
5052 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
5056 if (this.options.pageaction !== false)
5058 var a = $('<div />')
5059 .addClass('cbi-page-actions')
5063 .addClass('cbi-button').addClass('cbi-button-apply')
5064 .attr('type', 'button')
5065 .val(_luci2.tr('Save & Apply'))
5069 .addClass('cbi-button').addClass('cbi-button-save')
5070 .attr('type', 'button')
5071 .val(_luci2.tr('Save'))
5072 .click({ self: this }, function(ev) { ev.data.self.send(); })
5076 .addClass('cbi-button').addClass('cbi-button-reset')
5077 .attr('type', 'button')
5078 .val(_luci2.tr('Reset'))
5079 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
5085 var top = $('<form />').append(map);
5094 for (var i = 0; i < this.sections.length; i++)
5095 this.sections[i].finish();
5102 this.target.hide().empty().append(this.render());
5107 section: function(widget, uci_type, options)
5109 var w = widget ? new widget(uci_type, options) : null;
5111 if (!(w instanceof _luci2.cbi.AbstractSection))
5112 throw 'Widget must be an instance of AbstractSection';
5115 w.index = this.sections.length;
5117 this.sections.push(w);
5121 formvalue: function()
5125 for (var i = 0; i < this.sections.length; i++)
5127 var sids = this.sections[i].formvalue();
5128 for (var sid in sids)
5130 var s = rv[sid] || (rv[sid] = { });
5131 $.extend(s, sids[sid]);
5138 add: function(conf, type, name)
5140 var c = this.uci.creates;
5141 var s = '.new.%d'.format(this.uci.newid++);
5156 remove: function(conf, sid)
5158 var n = this.uci.creates;
5159 var c = this.uci.changes;
5160 var d = this.uci.deletes;
5162 /* requested deletion of a just created section */
5163 if (sid.indexOf('.new.') == 0)
5166 delete n[conf][sid];
5171 delete c[conf][sid];
5176 d[conf][sid] = true;
5180 ucisections: function(conf, cb)
5183 var pkg = this.uci.values[conf];
5184 var crt = this.uci.creates[conf];
5185 var del = this.uci.deletes[conf];
5191 if (!del || del[s] !== true)
5194 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5200 if (typeof(cb) == 'function')
5201 for (var i = 0; i < sa.length; i++)
5202 cb.apply(this, [ sa[i] ]);
5207 get: function(conf, sid, opt)
5209 var v = this.uci.values;
5210 var n = this.uci.creates;
5211 var c = this.uci.changes;
5212 var d = this.uci.deletes;
5214 /* requested option in a just created section */
5215 if (sid.indexOf('.new.') == 0)
5220 if (typeof(opt) == 'undefined')
5221 return (n[conf][sid] || { });
5223 return n[conf][sid][opt];
5226 /* requested an option value */
5227 if (typeof(opt) != 'undefined')
5229 /* check whether option was deleted */
5230 if (d[conf] && d[conf][sid])
5232 if (d[conf][sid] === true)
5235 for (var i = 0; i < d[conf][sid].length; i++)
5236 if (d[conf][sid][i] == opt)
5240 /* check whether option was changed */
5241 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5242 return c[conf][sid][opt];
5244 /* return base value */
5245 if (v[conf] && v[conf][sid])
5246 return v[conf][sid][opt];
5251 /* requested an entire section */
5253 return (v[conf][sid] || { });
5258 set: function(conf, sid, opt, val)
5260 var n = this.uci.creates;
5261 var c = this.uci.changes;
5262 var d = this.uci.deletes;
5264 if (sid.indexOf('.new.') == 0)
5266 if (n[conf] && n[conf][sid])
5268 if (typeof(val) != 'undefined')
5269 n[conf][sid][opt] = val;
5271 delete n[conf][sid][opt];
5274 else if (typeof(val) != 'undefined')
5282 c[conf][sid][opt] = val;
5292 d[conf][sid].push(opt);
5296 validate: function()
5300 for (var i = 0; i < this.sections.length; i++)
5301 if (!this.sections[i].validate())
5309 if (this.options.readonly)
5310 return _luci2.deferrable();
5312 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5314 for (var i = 0; i < this.sections.length; i++)
5316 if (this.sections[i].options.readonly)
5319 for (var f in this.sections[i].fields)
5321 if (typeof(this.sections[i].fields[f].save) != 'function')
5324 var s = this.sections[i].sections();
5325 for (var j = 0; j < s.length; j++)
5327 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5328 if (_luci2.isDeferred(rv))
5334 return $.when.apply($, deferreds);
5339 if (!this.validate())
5340 return _luci2.deferrable();
5342 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5345 if (this.uci.creates)
5346 for (var c in this.uci.creates)
5347 for (var s in this.uci.creates[c])
5354 for (var k in this.uci.creates[c][s])
5357 r.type = this.uci.creates[c][s][k];
5358 else if (k == '.create')
5359 r.name = this.uci.creates[c][s][k];
5360 else if (k.charAt(0) != '.')
5361 r.values[k] = this.uci.creates[c][s][k];
5364 _luci2.uci.add(r.config, r.type, r.name, r.values);
5367 if (this.uci.changes)
5368 for (var c in this.uci.changes)
5369 for (var s in this.uci.changes[c])
5370 _luci2.uci.set(c, s, this.uci.changes[c][s]);
5372 if (this.uci.deletes)
5373 for (var c in this.uci.deletes)
5374 for (var s in this.uci.deletes[c])
5376 var o = this.uci.deletes[c][s];
5377 _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
5380 return _luci2.rpc.flush();
5385 _luci2.ui.saveScrollTop();
5386 _luci2.ui.loading(true);
5388 return this.save().then(send_cb).then(function() {
5390 }).then(function() {
5394 _luci2.ui.loading(false);
5395 _luci2.ui.restoreScrollTop();
5399 dialog: function(id)
5401 var d = $('<div />');
5405 .attr('src', _luci2.globals.resource + '/icons/loading.gif')
5406 .css('vertical-align', 'middle')
5407 .css('padding-right', '10px')
5410 p.append(_luci2.tr('Loading data...'));
5421 $(this).parent().children('.ui-dialog-titlebar').hide();
5426 insertInto: function(id)
5429 self.target = $(id);
5431 _luci2.ui.loading(true);
5434 return self.load().then(function() {
5435 self.target.empty().append(self.render());
5439 _luci2.ui.loading(false);