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 alphacmp = function(a, b)
190 var retcb = function(cb, rv)
192 if (typeof(cb) == 'function')
198 var isa = function(x, t)
200 if (typeof(x) != 'string' && typeof(t) == 'string')
201 return (Object.prototype.toString.call(x) == '[object ' + t + ']');
203 return (Object.prototype.toString.call(x) == Object.prototype.toString.call(t));
206 var rcall = function(obj, func, params, res_attr, res_default, cb, filter)
208 if (typeof(params) == 'undefined')
211 return _luci2.rpc.call(obj, func, params).then(function(res) {
212 if (res[0] != 0 || typeof(res[1]) == 'undefined')
213 return retcb(cb, res_default);
215 var rv = (typeof(res_attr) != 'undefined') ? res[1][res_attr] : res[1];
216 if (typeof(rv) == 'undefined' || (typeof(res_default) != 'undefined' && !isa(rv, res_default)))
217 return retcb(cb, res_default);
219 if (typeof(filter) == 'function')
222 return retcb(cb, rv);
226 var Class = function() { };
228 Class.extend = function(properties)
230 Class.initializing = true;
232 var prototype = new this();
233 var superprot = this.prototype;
235 Class.initializing = false;
237 $.extend(prototype, properties, {
238 callSuper: function() {
240 var meth = arguments[0];
242 if (typeof(superprot[meth]) != 'function')
245 for (var i = 1; i < arguments.length; i++)
246 args.push(arguments[i]);
248 return superprot[meth].apply(this, args);
254 this.options = arguments[0] || { };
256 if (!Class.initializing && typeof(this.init) == 'function')
257 this.init.apply(this, arguments);
260 _class.prototype = prototype;
261 _class.prototype.constructor = _class;
263 _class.extend = arguments.callee;
268 this.defaults = function(obj, def)
271 if (typeof(obj[key]) == 'undefined')
277 this.deferred = function(x)
279 return (typeof(x) == 'object' &&
280 typeof(x.then) == 'function' &&
281 typeof(x.promise) == 'function');
284 this.deferrable = function()
286 if (this.deferred(arguments[0]))
289 var d = $.Deferred();
290 d.resolve.apply(d, arguments);
299 plural: function(n) { return 0 + (n != 1) },
302 if (_luci2.i18n.loaded)
305 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
306 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
308 for (var i = 0; i < langs.length; i++)
309 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
313 success: function(data) {
314 $.extend(_luci2.i18n.catalog, data);
316 var pe = _luci2.i18n.catalog[''];
319 delete _luci2.i18n.catalog[''];
321 var pf = new Function('n', 'return 0 + (' + pe + ')');
322 _luci2.i18n.plural = pf;
328 _luci2.i18n.loaded = true;
333 this.tr = function(msgid)
337 var msgstr = _luci2.i18n.catalog[msgid];
339 if (typeof(msgstr) == 'undefined')
341 else if (typeof(msgstr) == 'string')
347 this.trp = function(msgid, msgid_plural, count)
351 var msgstr = _luci2.i18n.catalog[msgid];
353 if (typeof(msgstr) == 'undefined')
354 return (count == 1) ? msgid : msgid_plural;
355 else if (typeof(msgstr) == 'string')
358 return msgstr[_luci2.i18n.plural(count)];
361 this.trc = function(msgctx, msgid)
365 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
367 if (typeof(msgstr) == 'undefined')
369 else if (typeof(msgstr) == 'string')
375 this.trcp = function(msgctx, msgid, msgid_plural, count)
379 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
381 if (typeof(msgstr) == 'undefined')
382 return (count == 1) ? msgid : msgid_plural;
383 else if (typeof(msgstr) == 'string')
386 return msgstr[_luci2.i18n.plural(count)];
389 this.setHash = function(key, value)
392 var data = this.getHash(undefined);
394 if (typeof(value) == 'undefined')
405 for (var i = 0; i < keys.length; i++)
410 h += keys[i] + ':' + data[keys[i]];
414 location.hash = '#' + h;
417 this.getHash = function(key)
420 var tuples = (location.hash || '#').substring(1).split(/,/);
422 for (var i = 0; i < tuples.length; i++)
424 var tuple = tuples[i].split(/:/);
425 if (tuple.length == 2)
426 data[tuple[0]] = tuple[1];
429 if (typeof(key) != 'undefined')
443 _wrap_msg: function(method, object, func, args)
445 if (typeof(args) != 'object')
449 id: _luci2.rpc._msg_id++,
452 params: (method == 'call') ? [ _luci2.globals.sid, object, func, args ] : object
456 _parse_response: function(keys, priv)
458 return function(data) {
461 obj = $.parseJSON(data);
464 if (typeof(obj) != 'object')
467 /* is a batched response */
471 for (var i = 0; i < obj.length; i++)
473 var p = (typeof(priv) != 'undefined') ? priv[i] : undefined;
475 if ($.isArray(obj[i].result) && typeof(priv) != 'undefined')
476 obj[i].result[2] = p;
478 if (obj[i].jsonrpc != '2.0' || obj[i].error || !obj[i].result)
479 rv[keys[i]] = [ 4 /* UBUS_STATUS_NO_DATA */, undefined, p ];
481 rv[keys[i]] = obj[i].result;
486 if (obj.jsonrpc != '2.0' || obj.error || !obj.result)
487 return [ 4 /* UBUS_STATUS_NO_DATA */, undefined, priv ];
489 if ($.isArray(obj.result) && typeof(priv) != 'undefined')
490 obj.result[2] = priv;
496 _post_msg: function(message, cb, keys, priv)
498 return $.ajax('/ubus', {
500 contentType: 'application/json',
501 data: JSON.stringify(message),
502 dataFilter: _luci2.rpc._parse_response(keys, priv),
509 _post_single: function(object, method, args, cb, priv)
511 var msg = _luci2.rpc._wrap_msg('call', object, method, args, priv);
512 return _luci2.rpc._post_msg(msg, cb, undefined, priv);
515 _post_batch: function(methods, cb)
517 if (typeof(methods) != 'object')
524 for (var k in methods)
526 if (typeof(methods[k]) != 'object' || methods[k].length < 2)
530 priv.push(methods[k][3]);
531 msgs.push(_luci2.rpc._wrap_msg('call', methods[k][0], methods[k][1], methods[k][2]));
535 return _luci2.rpc._post_msg(msgs, cb, keys, priv);
537 return _luci2.deferrable([ ]);
543 if (typeof a[0] == 'string')
544 return _luci2.rpc._post_single(a[0], a[1], a[2], a[3], a[4]);
546 return _luci2.rpc._post_batch(a[0], a[1]);
549 list: function(objects)
551 var msg = _luci2.rpc._wrap_msg('list', objects);
552 return _luci2.rpc._post_msg(msg);
555 access: function(scope, object, method, cb)
557 return _luci2.rpc._post_single('session', 'access', {
558 'sid': _luci2.globals.sid,
563 return retcb(cb, (rv[0] == 0 && rv[1] && rv[1].access == true));
570 writable: function(cb)
572 return _luci2.rpc.access('ubus', 'uci', 'commit', cb);
575 add: function(config, type, cb)
577 return rcall('uci', 'add', { config: config, type: type }, 'section', '', cb);
585 changes: function(config)
587 return rcall('uci', 'changes', { config: config }, 'changes', [ ], cb);
590 commit: function(config)
592 return rcall('uci', 'commit', { config: config }, undefined, undefined, cb);
595 'delete': function(config, section, option)
597 var req = { config: config, section: section };
599 if (isa(option, 'Array'))
600 req.options = option;
604 return rcall('uci', 'delete', req, undefined, undefined, cb);
607 delete_all: function(config, type, matches)
609 return rcall('uci', 'delete', { config: config, type: type, match: matches }, undefined, undefined, cb);
612 foreach: function(config, type, cb)
614 return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
615 for (var s in sections)
620 get: function(config, section, option, cb)
622 return rcall('uci', 'get', { config: config, section: section, option: option }, undefined, { }, function(res) {
623 if (typeof(option) == 'undefined')
624 return retcb(cb, (res.values && res.values['.type']) ? res.values['.type'] : undefined);
626 return retcb(cb, res.value);
630 get_all: function(config, section, cb)
632 return rcall('uci', 'get', { config: config, section: section }, 'values', { }, cb);
635 get_first: function(config, type, option, cb)
637 return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
638 for (var s in sections)
640 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
642 if (typeof(val) != 'undefined')
643 return retcb(cb, val);
646 return retcb(cb, undefined);
650 section: function(config, type, name, values, cb)
652 return rcall('uci', 'add', { config: config, type: type, name: name, values: values }, 'section', undefined, cb);
655 set: function(config, section, option, value, cb)
657 if (typeof(value) == 'undefined' && typeof(option) == 'string')
658 return rcall('uci', 'add', { config: config, section: section, type: option }, undefined, undefined, cb);
659 else if (isa(option, 'Object'))
660 return rcall('uci', 'set', { config: config, section: section, values: option }, undefined, undefined, cb);
664 values[option] = value;
666 return rcall('uci', 'set', { config: config, section: section, values: values }, undefined, undefined, cb);
669 order: function(config, sections, cb)
671 return rcall('uci', 'order', { config: config, sections: sections }, undefined, undefined, cb);
676 getNetworkStatus: function(cb)
679 var assign = function(target, key)
681 return function(value) {
682 if (typeof(value) != 'undefined' && !$.isEmptyObject(value))
687 return _luci2.rpc.list().then(function(data) {
690 for (var i = 0; i < data.length; i++)
692 if (data[i].indexOf('network.interface.') != 0)
695 var ifname = data[i].substring(18);
696 if (ifname == 'loopback')
699 var iface = { 'name': ifname };
702 requests.push(['network.interface', 'status', { 'interface': ifname }, iface]);
705 return _luci2.rpc.call(requests, function(responses) {
706 for (var key in responses)
707 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
708 $.extend(responses[key][2], responses[key][1]);
713 for (var i = 0; i < ifaces.length; i++)
715 var iface = ifaces[i];
717 var dev = iface.l3_device || iface.l2_device;
721 iface.device = { 'name': dev };
722 requests[dev] = ['network.device', 'status', { 'name': dev }, iface.device];
725 return _luci2.rpc.call(requests, function(responses) {
726 for (var key in responses)
727 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
728 $.extend(responses[key][2], responses[key][1]);
733 for (var i = 0; i < ifaces.length; i++)
735 var iface = ifaces[i];
739 var subdevs = iface.device['bridge-members'];
743 iface.subdevices = [ ];
744 for (var j = 0; j < subdevs.length; j++)
746 iface.subdevices[j] = { 'name': subdevs[j] };
747 requests.push(['network.device', 'status', { 'name': subdevs[j] }, iface.subdevices[j]]);
751 return _luci2.rpc.call(requests, function(responses) {
752 for (var key in responses)
753 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
754 $.extend(responses[key][2], responses[key][1]);
759 for (var i = 0; i < ifaces.length; i++)
761 var iface = ifaces[i];
764 requests.push(['iwinfo', 'info', { 'device': iface.device.name }, iface.device]);
766 if (iface.subdevices)
767 for (var j = 0; j < iface.subdevices.length; j++)
768 requests.push(['iwinfo', 'info', { 'device': iface.subdevices[j].name }, iface.subdevices[j]]);
771 return _luci2.rpc.call(requests, function(responses) {
772 for (var key in responses)
773 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
774 if (!$.isEmptyObject(responses[key][1]))
775 responses[key][2].wireless = responses[key][1];
778 ifaces.sort(function(a, b) {
779 if (a['interface'] < b['interface'])
781 else if (a['interface'] > b['interface'])
786 return retcb(cb, ifaces);
790 findWanInterfaces: function(cb)
792 return _luci2.rpc.list().then(function(data) {
794 for (var i = 0; i < data.length; i++)
796 if (data[i].indexOf('network.interface.') == 0)
798 var ifname = data[i].substring(18);
799 requests[ifname] = ['network.interface', 'status', { 'interface': ifname }];
802 return _luci2.rpc.call(requests);
803 }).then(function(responses) {
805 for (var ifname in responses)
807 var response = responses[ifname];
809 if (response[0] != 0 || !response[1] || !response[1].route)
812 for (var rn = 0, rt = response[1].route[rn];
813 rn < response[1].route.length;
814 rn++, rt = response[1].route[rn])
816 if (typeof(rt.table) != 'undefined')
819 if (rt.target == '0.0.0.0' && rt.mask == 0)
821 else if (rt.target == '::' && rt.mask == 0)
826 return retcb(cb, rv);
830 getDHCPLeases: function(cb)
832 return rcall('luci2.network', 'dhcp_leases', undefined, 'leases', [ ], cb);
835 getDHCPv6Leases: function(cb)
837 return rcall('luci2.network', 'dhcp6_leases', undefined, 'leases', [ ], cb);
840 getRoutes: function(cb)
842 return rcall('luci2.network', 'routes', undefined, 'routes', [ ], cb);
845 getIPv6Routes: function(cb)
847 return rcall('luci2.network', 'routes6', undefined, 'routes', [ ], cb);
850 getARPTable: function(cb)
852 return rcall('luci2.network', 'arp_table', undefined, 'entries', [ ], cb);
855 getInterfaceStatus: function(iface, cb)
857 return rcall('network.interface', 'status', { 'interface': iface }, undefined, { }, cb, function(rv) {
858 rv['interface'] = iface;
859 rv['l2_device'] = rv['device'];
864 getDeviceStatus: function(dev, cb)
866 return rcall('network.device', 'status', { name: dev }, undefined, { }, cb, function(rv) {
867 if (typeof(dev) == 'string')
873 getConntrackCount: function(cb)
875 return rcall('luci2.network', 'conntrack_count', undefined, undefined, {
883 getDevices: function(cb) {
884 return rcall('iwinfo', 'devices', undefined, 'devices', [ ], cb, function(rv) {
890 getInfo: function(dev, cb) {
891 var parse_info = function(device, info, rv)
898 var phy = rv[info.phy];
901 'country', 'channel', 'frequency', 'frequency_offset',
902 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
906 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
907 'signal', 'noise', 'bitrate', 'encryption'
910 for (var i = 0; i < phy_attrs.length; i++)
911 phy[phy_attrs[i]] = info[phy_attrs[i]];
917 for (var i = 0; i < net_attrs.length; i++)
918 net[net_attrs[i]] = info[net_attrs[i]];
920 phy.networks.push(net);
927 return _luci2.wireless.getDevices().then(function(devices) {
930 for (var i = 0; i < devices.length; i++)
932 if (devices[i].indexOf('.sta') >= 0)
935 requests[devices[i]] = [ 'iwinfo', 'info', { device: devices[i] } ];
938 return _luci2.rpc.call(requests);
939 }).then(function(responses) {
942 for (var device in responses)
944 var response = responses[device];
946 if (response[0] != 0 || !response[1])
949 parse_info(device, response[1], rv);
952 return retcb(cb, rv);
956 return _luci2.rpc.call('iwinfo', 'info', { device: dev }).then(function(response) {
957 if (response[0] != 0 || !response[1])
958 return retcb(cb, { });
960 return retcb(cb, parse_info(dev, response[1], { }));
964 getAssocList: function(dev, cb)
968 return _luci2.wireless.getDevices().then(function(devices) {
971 for (var i = 0; i < devices.length; i++)
973 if (devices[i].indexOf('.sta') >= 0)
976 requests[devices[i]] = [ 'iwinfo', 'assoclist', { device: devices[i] } ];
979 return _luci2.rpc.call(requests);
980 }).then(function(responses) {
983 for (var device in responses)
985 var response = responses[device];
987 if (response[0] != 0 || !response[1] || !response[1].results)
990 for (var i = 0; i < response[1].results.length; i++)
992 var station = response[1].results[i];
994 station.device = device;
999 rv.sort(function(a, b) {
1000 return (a.device == b.device)
1001 ? (a.bssid < b.bssid)
1002 : (a.device > b.device)
1006 return retcb(cb, rv);
1010 return _luci2.rpc.call('iwinfo', 'assoclist', { device: dev }).then(function(response) {
1013 if (response[0] != 0 || !response[1] || !response[1].results)
1014 return retcb(cb, rv);
1016 for (var i = 0; i < response[1].results.length; i++)
1018 var station = response[1].results[i];
1020 station.device = dev;
1024 rv.sort(function(a, b) {
1025 return (a.bssid < b.bssid);
1028 return retcb(cb, rv);
1032 formatEncryption: function(enc)
1034 var format_list = function(l, s)
1037 for (var i = 0; i < l.length; i++)
1038 rv.push(l[i].toUpperCase());
1039 return rv.join(s ? s : ', ');
1042 if (!enc || !enc.enabled)
1043 return _luci2.tr('None');
1047 if (enc.wep.length == 2)
1048 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1049 else if (enc.wep[0] == 'shared')
1050 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1052 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1056 if (enc.wpa.length == 2)
1057 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1058 format_list(enc.authentication, '/'),
1059 format_list(enc.ciphers, ', ')
1061 else if (enc.wpa[0] == 2)
1062 return 'WPA2 %s (%s)'.format(
1063 format_list(enc.authentication, '/'),
1064 format_list(enc.ciphers, ', ')
1067 return 'WPA %s (%s)'.format(
1068 format_list(enc.authentication, '/'),
1069 format_list(enc.ciphers, ', ')
1073 return _luci2.tr('Unknown');
1078 getInfo: function(cb)
1080 return _luci2.rpc.call({
1081 info: [ 'system', 'info', { } ],
1082 board: [ 'system', 'board', { } ],
1083 disk: [ 'luci2.system', 'diskfree', { } ]
1084 }).then(function(responses) {
1087 if (responses.info[0] == 0)
1088 $.extend(rv, responses.info[1]);
1090 if (responses.board[0] == 0)
1091 $.extend(rv, responses.board[1]);
1093 if (responses.disk[0] == 0)
1094 $.extend(rv, responses.disk[1]);
1096 return retcb(cb, rv);
1100 getProcessList: function(cb)
1102 return rcall('luci2.system', 'process_list', undefined, 'processes', [ ], cb, function(rv) {
1103 rv.sort(function(a, b) { return a.pid - b.pid });
1108 getSystemLog: function(cb)
1110 return rcall('luci2.system', 'syslog', undefined, 'log', '', cb);
1113 getKernelLog: function(cb)
1115 return rcall('luci2.system', 'dmesg', undefined, 'log', '', cb);
1118 getZoneInfo: function(cb)
1120 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1123 canSendSignal: function(cb)
1125 return _luci2.rpc.access('ubus', 'luci2.system', 'process_signal', cb);
1128 sendSignal: function(pid, sig, cb)
1130 return _luci2.rpc.call('luci2.system', 'process_signal', { pid: pid, signal: sig }).then(function(response) {
1131 return retcb(cb, response[0] == 0);
1135 initList: function(cb)
1137 return rcall('luci2.system', 'init_list', undefined, 'initscripts', [ ], cb, function(rv) {
1138 rv.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1143 initEnabled: function(init, cb)
1145 return this.initList(function(list) {
1146 for (var i = 0; i < list.length; i++)
1147 if (list[i].name == init)
1148 return retcb(cb, !!list[i].enabled);
1150 return retcb(cb, false);
1154 initRun: function(init, action, cb)
1156 return _luci2.rpc.call('luci2.system', 'init_action', { name: init, action: action }).then(function(response) {
1157 return retcb(cb, response[0] == 0);
1161 canInitRun: function(cb)
1163 return _luci2.rpc.access('ubus', 'luci2.system', 'init_action', cb);
1166 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1167 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1168 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1169 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1170 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1171 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1174 getRcLocal: function(cb)
1176 return rcall('luci2.system', 'rclocal_get', undefined, 'data', '', cb);
1179 setRcLocal: function(data, cb)
1181 return rcall('luci2.system', 'rclocal_set', { data: data }, undefined, undefined, cb);
1184 canSetRcLocal: function(cb)
1186 return _luci2.rpc.access('ubus', 'luci2.system', 'rclocal_set', cb);
1190 getCrontab: function(cb)
1192 return rcall('luci2.system', 'crontab_get', undefined, 'data', '', cb);
1195 setCrontab: function(data, cb)
1197 return rcall('luci2.system', 'crontab_set', { data: data }, undefined, undefined, cb);
1200 canSetCrontab: function(cb)
1202 return _luci2.rpc.access('ubus', 'luci2.system', 'crontab_set', cb);
1206 getSSHKeys: function(cb)
1208 return rcall('luci2.system', 'sshkeys_get', undefined, 'keys', [ ], cb);
1211 setSSHKeys: function(keys, cb)
1213 return rcall('luci2.system', 'sshkeys_set', { keys: keys }, undefined, undefined, cb);
1216 canSetSSHKeys: function(cb)
1218 return _luci2.rpc.access('ubus', 'luci2.system', 'sshkeys_set', cb);
1222 setPassword: function(user, pass, cb)
1224 return rcall('luci2.system', 'password_set', { user: user, password: pass }, undefined, undefined, cb);
1227 canSetPassword: function(cb)
1229 return _luci2.rpc.access('ubus', 'luci2.system', 'password_set', cb);
1233 listLEDs: function(cb)
1235 return rcall('luci2.system', 'led_list', undefined, 'leds', [ ], cb);
1238 listUSBDevices: function(cb)
1240 return rcall('luci2.system', 'usb_list', undefined, 'devices', [ ], cb);
1244 testUpgrade: function(cb)
1246 return rcall('luci2.system', 'upgrade_test', undefined, undefined, { }, cb);
1249 startUpgrade: function(keep, cb)
1251 return rcall('luci2.system', 'upgrade_start', { keep: !!keep }, undefined, undefined, cb);
1254 cleanUpgrade: function(cb)
1256 return rcall('luci2.system', 'upgrade_clean', undefined, undefined, undefined, cb);
1259 canUpgrade: function(cb)
1261 return _luci2.rpc.access('ubus', 'luci2.system', 'upgrade_start', cb);
1265 restoreBackup: function(cb)
1267 return rcall('luci2.system', 'backup_restore', undefined, undefined, undefined, cb);
1270 cleanBackup: function(cb)
1272 return rcall('luci2.system', 'backup_clean', undefined, undefined, undefined, cb);
1275 canRestoreBackup: function(cb)
1277 return _luci2.rpc.access('ubus', 'luci2.system', 'backup_restore', cb);
1281 getBackupConfig: function(cb)
1283 return rcall('luci2.system', 'backup_config_get', undefined, 'config', '', cb);
1286 setBackupConfig: function(data, cb)
1288 return rcall('luci2.system', 'backup_config_set', { data: data }, undefined, undefined, cb);
1291 canSetBackupConfig: function(cb)
1293 return _luci2.rpc.access('ubus', 'luci2.system', 'backup_config_set', cb);
1297 listBackup: function(cb)
1299 return rcall('luci2.system', 'backup_list', undefined, 'files', [ ], cb);
1303 performReboot: function(cb)
1305 return rcall('luci2.system', 'reboot', undefined, undefined, undefined, cb);
1308 canPerformReboot: function(cb)
1310 return _luci2.rpc.access('ubus', 'luci2.system', 'reboot', cb);
1315 updateLists: function(cb)
1317 return rcall('luci2.opkg', 'update', undefined, undefined, { }, cb);
1320 _fetchPackages: function(action, offset, limit, pattern, cb)
1323 var reqlimit = Math.min(limit, 100);
1328 return _luci2.rpc.call('luci2.opkg', action, { offset: offset, limit: reqlimit, pattern: pattern }).then(function(response) {
1329 if (response[0] != 0 || !response[1] || !response[1].total)
1330 return retcb(cb, { length: 0, total: 0 });
1332 packages.push.apply(packages, response[1].packages);
1333 packages.total = response[1].total;
1336 limit = response[1].total;
1338 if (packages.length >= limit)
1339 return retcb(cb, packages);
1342 for (var i = offset + packages.length; i < limit; i += 100)
1343 requests.push(['luci2.opkg', action, { offset: i, limit: (Math.min(i + 100, limit) % 100) || 100, pattern: pattern }]);
1345 return _luci2.rpc.call(requests);
1346 }).then(function(responses) {
1347 for (var key in responses)
1349 var response = responses[key];
1351 if (response[0] != 0 || !response[1] || !response[1].packages)
1354 packages.push.apply(packages, response[1].packages);
1355 packages.total = response[1].total;
1358 return retcb(cb, packages);
1362 listPackages: function(offset, limit, pattern, cb)
1364 return _luci2.opkg._fetchPackages('list', offset, limit, pattern, cb);
1367 installedPackages: function(offset, limit, pattern, cb)
1369 return _luci2.opkg._fetchPackages('list_installed', offset, limit, pattern, cb);
1372 findPackages: function(offset, limit, pattern, cb)
1374 return _luci2.opkg._fetchPackages('find', offset, limit, pattern, cb);
1377 installPackage: function(name, cb)
1379 return rcall('luci2.opkg', 'install', { 'package': name }, undefined, { }, cb);
1382 removePackage: function(name, cb)
1384 return rcall('luci2.opkg', 'remove', { 'package': name }, undefined, { }, cb);
1387 getConfig: function(cb)
1389 return rcall('luci2.opkg', 'config_get', undefined, 'config', '', cb);
1392 setConfig: function(data, cb)
1394 return rcall('luci2.opkg', 'config_set', { data: data }, undefined, undefined, cb);
1397 canInstallPackage: function(cb)
1399 return _luci2.rpc.access('ubus', 'luci2.opkg', 'install', cb);
1402 canRemovePackage: function(cb)
1404 return _luci2.rpc.access('ubus', 'luci2.opkg', 'remove', cb);
1407 canSetConfig: function(cb)
1409 return _luci2.rpc.access('ubus', 'luci2.opkg', 'config_set', cb);
1415 loading: function(enable)
1417 var win = $(window);
1418 var body = $('body');
1419 var div = _luci2._modal || (
1420 _luci2._modal = $('<div />')
1421 .addClass('cbi-modal-loader')
1422 .append($('<div />').text(_luci2.tr('Loading data...')))
1428 body.css('overflow', 'hidden');
1429 body.css('padding', 0);
1430 body.css('width', win.width());
1431 body.css('height', win.height());
1432 div.css('width', win.width());
1433 div.css('height', win.height());
1439 body.css('overflow', '');
1440 body.css('padding', '');
1441 body.css('width', '');
1442 body.css('height', '');
1446 dialog: function(title, content, options)
1448 var win = $(window);
1449 var body = $('body');
1450 var div = _luci2._dialog || (
1451 _luci2._dialog = $('<div />')
1452 .addClass('cbi-modal-dialog')
1453 .append($('<div />')
1454 .append($('<div />')
1455 .addClass('cbi-modal-dialog-header'))
1456 .append($('<div />')
1457 .addClass('cbi-modal-dialog-body'))
1458 .append($('<div />')
1459 .addClass('cbi-modal-dialog-footer')
1460 .append($('<button />')
1461 .addClass('cbi-button')
1462 .text(_luci2.tr('Close'))
1465 .css('overflow', '')
1470 $(this).parent().parent().parent().hide();
1475 if (typeof(options) != 'object')
1478 if (title === false)
1481 .css('overflow', '')
1486 _luci2._dialog.hide();
1491 var cnt = div.children().children('div.cbi-modal-dialog-body');
1492 var ftr = div.children().children('div.cbi-modal-dialog-footer');
1496 if (options.style == 'confirm')
1498 ftr.append($('<button />')
1499 .addClass('cbi-button')
1500 .text(_luci2.tr('Ok'))
1501 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1503 ftr.append($('<button />')
1504 .addClass('cbi-button')
1505 .text(_luci2.tr('Cancel'))
1506 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1508 else if (options.style == 'close')
1510 ftr.append($('<button />')
1511 .addClass('cbi-button')
1512 .text(_luci2.tr('Close'))
1513 .click(options.close || function() { _luci2.ui.dialog(false) }));
1515 else if (options.style == 'wait')
1517 ftr.append($('<button />')
1518 .addClass('cbi-button')
1519 .text(_luci2.tr('Close'))
1520 .attr('disabled', true));
1523 div.find('div.cbi-modal-dialog-header').text(title);
1527 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1532 .css('margin-top', -Math.floor(div.children().height() / 2) + 'px');
1534 body.css('overflow', 'hidden');
1535 body.css('padding', 0);
1536 body.css('width', win.width());
1537 body.css('height', win.height());
1538 div.css('width', win.width());
1539 div.css('height', win.height());
1542 upload: function(title, content, options)
1544 var form = _luci2._upload || (
1545 _luci2._upload = $('<form />')
1546 .attr('method', 'post')
1547 .attr('action', '/cgi-bin/luci-upload')
1548 .attr('enctype', 'multipart/form-data')
1549 .attr('target', 'cbi-fileupload-frame')
1551 .append($('<input />')
1552 .attr('type', 'hidden')
1553 .attr('name', 'sessionid')
1554 .attr('value', _luci2.globals.sid))
1555 .append($('<input />')
1556 .attr('type', 'hidden')
1557 .attr('name', 'filename')
1558 .attr('value', options.filename))
1559 .append($('<input />')
1560 .attr('type', 'file')
1561 .attr('name', 'filedata')
1562 .addClass('cbi-input-file'))
1563 .append($('<div />')
1564 .css('width', '100%')
1565 .addClass('progressbar')
1566 .addClass('intermediate')
1567 .append($('<div />')
1568 .css('width', '100%')))
1569 .append($('<iframe />')
1570 .attr('name', 'cbi-fileupload-frame')
1571 .css('width', '1px')
1572 .css('height', '1px')
1573 .css('visibility', 'hidden'))
1576 var finish = _luci2._upload_finish_cb || (
1577 _luci2._upload_finish_cb = function(ev) {
1578 $(this).off('load');
1580 var body = (this.contentDocument || this.contentWindow.document).body;
1581 if (body.firstChild.tagName.toLowerCase() == 'pre')
1582 body = body.firstChild;
1586 json = $.parseJSON(body.innerHTML);
1589 message: _luci2.tr('Invalid server response received'),
1590 error: [ -1, _luci2.tr('Invalid data') ]
1596 L.ui.dialog(L.tr('File upload'), [
1597 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1598 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1599 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1600 ], { style: 'close' });
1602 else if (typeof(ev.data.cb) == 'function')
1609 var confirm = _luci2._upload_confirm_cb || (
1610 _luci2._upload_confirm_cb = function() {
1611 var d = _luci2._upload;
1612 var f = d.find('.cbi-input-file');
1613 var b = d.find('.progressbar');
1614 var p = d.find('p');
1619 d.find('iframe').on('load', { cb: options.success }, finish);
1624 p.text(_luci2.tr('File upload in progress …'));
1626 _luci2._dialog.find('button').prop('disabled', true);
1630 _luci2._upload.find('.progressbar').hide();
1631 _luci2._upload.find('.cbi-input-file').val('').show();
1632 _luci2._upload.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1634 _luci2.ui.dialog(title || _luci2.tr('File upload'), _luci2._upload, {
1640 reconnect: function()
1642 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1643 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1644 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1646 var interval, timeout;
1649 _luci2.tr('Waiting for device'), [
1650 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1652 .css('width', '100%')
1653 .addClass('progressbar')
1654 .addClass('intermediate')
1655 .append($('<div />')
1656 .css('width', '100%'))
1657 ], { style: 'wait' }
1660 for (var i = 0; i < protocols.length; i++)
1661 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1663 //_luci2.network.getNetworkStatus(function(s) {
1664 // for (var i = 0; i < protocols.length; i++)
1666 // for (var j = 0; j < s.length; j++)
1668 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1669 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1671 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1672 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1675 //}).then(function() {
1676 images.on('load', function() {
1677 var url = this.getAttribute('url');
1678 _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1679 if (response[0] == 0)
1681 window.clearTimeout(timeout);
1682 window.clearInterval(interval);
1683 _luci2.ui.dialog(false);
1688 location.href = url;
1693 interval = window.setInterval(function() {
1694 images.each(function() {
1695 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1699 timeout = window.setTimeout(function() {
1700 window.clearInterval(interval);
1704 _luci2.tr('Device not responding'),
1705 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1712 login: function(invalid)
1714 if (!_luci2._login_deferred || _luci2._login_deferred.state() != 'pending')
1715 _luci2._login_deferred = $.Deferred();
1717 /* try to find sid from hash */
1718 var sid = _luci2.getHash('id');
1719 if (sid && sid.match(/^[a-f0-9]{32}$/))
1721 _luci2.globals.sid = sid;
1722 _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1723 if (response[0] == 0)
1725 _luci2._login_deferred.resolve();
1729 _luci2.setHash('id', undefined);
1734 return _luci2._login_deferred;
1737 var form = _luci2._login || (
1738 _luci2._login = $('<div />')
1740 .addClass('alert-message')
1741 .text(_luci2.tr('Wrong username or password given!')))
1743 .append($('<label />')
1744 .text(_luci2.tr('Username'))
1745 .append($('<br />'))
1746 .append($('<input />')
1747 .attr('type', 'text')
1748 .attr('name', 'username')
1749 .attr('value', 'root')
1750 .addClass('cbi-input-text'))))
1752 .append($('<label />')
1753 .text(_luci2.tr('Password'))
1754 .append($('<br />'))
1755 .append($('<input />')
1756 .attr('type', 'password')
1757 .attr('name', 'password')
1758 .addClass('cbi-input-password'))))
1760 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok'))))
1763 var response = _luci2._login_response_cb || (
1764 _luci2._login_response_cb = function(data) {
1765 if (typeof(data) == 'object' && typeof(data.sessionid) == 'string')
1767 _luci2.globals.sid = data.sessionid;
1768 _luci2.setHash('id', _luci2.globals.sid);
1770 _luci2.ui.dialog(false);
1771 _luci2._login_deferred.resolve();
1775 _luci2.ui.login(true);
1780 var confirm = _luci2._login_confirm_cb || (
1781 _luci2._login_confirm_cb = function() {
1782 var d = _luci2._login;
1783 var u = d.find('[name=username]').val();
1784 var p = d.find('[name=password]').val();
1790 _luci2.tr('Logging in'), [
1791 $('<p />').text(_luci2.tr('Log in in progress …')),
1793 .css('width', '100%')
1794 .addClass('progressbar')
1795 .addClass('intermediate')
1796 .append($('<div />')
1797 .css('width', '100%'))
1798 ], { style: 'wait' }
1801 $.ajax('/cgi-bin/luci-login', {
1804 data: { username: u, password: p },
1813 form.find('.alert-message').show();
1815 form.find('.alert-message').hide();
1817 _luci2.ui.dialog(_luci2.tr('Authorization Required'), form, {
1822 return _luci2._login_deferred;
1825 renderMainMenu: function()
1827 return rcall('luci2.ui', 'menu', undefined, 'menu', { }, function(entries) {
1828 _luci2.globals.mainMenu = new _luci2.ui.menu();
1829 _luci2.globals.mainMenu.entries(entries);
1833 .append(_luci2.globals.mainMenu.render(0, 1));
1837 renderViewMenu: function()
1841 .append(_luci2.globals.mainMenu.render(2, 900));
1844 renderView: function(node)
1846 var name = node.view.split(/\//).join('.');
1848 _luci2.ui.renderViewMenu();
1851 _luci2._views = { };
1853 _luci2.setHash('view', node.view);
1855 if (_luci2._views[name] instanceof _luci2.ui.view)
1856 return _luci2._views[name].render();
1858 return $.ajax(_luci2.globals.resource + '/view/' + name + '.js', {
1862 }).then(function(data) {
1864 var viewConstructor = (new Function(['L', '$'], 'return ' + data))(_luci2, $);
1866 _luci2._views[name] = new viewConstructor({
1868 acls: node.write || { }
1871 return _luci2._views[name].render();
1875 return $.Deferred().resolve();
1881 _luci2.ui.loading(true);
1884 _luci2.ui.renderMainMenu()
1886 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
1887 _luci2.ui.loading(false);
1893 var AbstractWidget = Class.extend({
1894 i18n: function(text) {
1898 toString: function() {
1899 var x = document.createElement('div');
1900 x.appendChild(this.render());
1905 insertInto: function(id) {
1906 return $(id).empty().append(this.render());
1910 this.ui.view = AbstractWidget.extend({
1911 _fetch_template: function()
1913 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
1917 success: function(data) {
1918 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
1919 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
1926 return _luci2.tr(p2);
1929 return _luci2.globals[p2] || '';
1932 return '(?' + match + ')';
1936 $('#maincontent').append(data);
1943 throw "Not implemented";
1948 var container = $('#maincontent');
1953 container.append($('<h2 />').append(this.title));
1955 if (this.description)
1956 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
1959 return this._fetch_template().then(function() {
1960 return _luci2.deferrable(self.execute());
1965 this.ui.menu = AbstractWidget.extend({
1970 entries: function(entries)
1972 for (var entry in entries)
1974 var path = entry.split(/\//);
1975 var node = this._nodes;
1977 for (i = 0; i < path.length; i++)
1982 if (!node.childs[path[i]])
1983 node.childs[path[i]] = { };
1985 node = node.childs[path[i]];
1988 $.extend(node, entries[entry]);
1992 _indexcmp: function(a, b)
1994 var x = a.index || 0;
1995 var y = b.index || 0;
1999 firstChildView: function(node)
2005 for (var child in (node.childs || { }))
2006 nodes.push(node.childs[child]);
2008 nodes.sort(this._indexcmp);
2010 for (var i = 0; i < nodes.length; i++)
2012 var child = this.firstChildView(nodes[i]);
2015 $.extend(node, child);
2023 _onclick: function(ev)
2025 _luci2.ui.loading(true);
2026 _luci2.ui.renderView(ev.data).then(function() {
2027 _luci2.ui.loading(false);
2030 ev.preventDefault();
2034 _render: function(childs, level, min, max)
2037 for (var node in childs)
2039 var child = this.firstChildView(childs[node]);
2041 nodes.push(childs[node]);
2044 nodes.sort(this._indexcmp);
2046 var list = $('<ul />');
2049 list.addClass('nav');
2050 else if (level == 1)
2051 list.addClass('dropdown-menu');
2053 for (var i = 0; i < nodes.length; i++)
2055 if (!_luci2.globals.defaultNode)
2057 var v = _luci2.getHash('view');
2058 if (!v || v == nodes[i].view)
2059 _luci2.globals.defaultNode = nodes[i];
2062 var item = $('<li />')
2065 .text(_luci2.tr(nodes[i].title))
2066 .click(nodes[i], this._onclick))
2069 if (nodes[i].childs && level < max)
2071 item.addClass('dropdown');
2072 item.find('a').addClass('menu');
2073 item.append(this._render(nodes[i].childs, level + 1));
2080 render: function(min, max)
2082 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2083 return this._render(top.childs, 0, min, max);
2086 getNode: function(path, max)
2088 var p = path.split(/\//);
2089 var n = this._nodes;
2091 if (typeof(max) == 'undefined')
2094 for (var i = 0; i < max; i++)
2096 if (!n.childs[p[i]])
2106 this.ui.table = AbstractWidget.extend({
2112 row: function(values)
2114 if (isa(values, 'Array'))
2116 this._rows.push(values);
2118 else if (isa(values, 'Object'))
2121 for (var i = 0; i < this.options.columns.length; i++)
2123 var col = this.options.columns[i];
2125 if (typeof col.key == 'string')
2126 v.push(values[col.key]);
2134 rows: function(rows)
2136 for (var i = 0; i < rows.length; i++)
2140 render: function(id)
2142 var fieldset = document.createElement('fieldset');
2143 fieldset.className = 'cbi-section';
2145 if (this.options.caption)
2147 var legend = document.createElement('legend');
2148 $(legend).append(this.options.caption);
2149 fieldset.appendChild(legend);
2152 var table = document.createElement('table');
2153 table.className = 'cbi-section-table';
2155 var has_caption = false;
2156 var has_description = false;
2158 for (var i = 0; i < this.options.columns.length; i++)
2159 if (this.options.columns[i].caption)
2164 else if (this.options.columns[i].description)
2166 has_description = true;
2172 var tr = table.insertRow(-1);
2173 tr.className = 'cbi-section-table-titles';
2175 for (var i = 0; i < this.options.columns.length; i++)
2177 var col = this.options.columns[i];
2178 var th = document.createElement('th');
2179 th.className = 'cbi-section-table-cell';
2184 th.style.width = col.width;
2187 th.style.textAlign = col.align;
2190 $(th).append(col.caption);
2194 if (has_description)
2196 var tr = table.insertRow(-1);
2197 tr.className = 'cbi-section-table-descr';
2199 for (var i = 0; i < this.options.columns.length; i++)
2201 var col = this.options.columns[i];
2202 var th = document.createElement('th');
2203 th.className = 'cbi-section-table-cell';
2208 th.style.width = col.width;
2211 th.style.textAlign = col.align;
2213 if (col.description)
2214 $(th).append(col.description);
2218 if (this._rows.length == 0)
2220 if (this.options.placeholder)
2222 var tr = table.insertRow(-1);
2223 var td = tr.insertCell(-1);
2224 td.className = 'cbi-section-table-cell';
2226 td.colSpan = this.options.columns.length;
2227 $(td).append(this.options.placeholder);
2232 for (var i = 0; i < this._rows.length; i++)
2234 var tr = table.insertRow(-1);
2236 for (var j = 0; j < this.options.columns.length; j++)
2238 var col = this.options.columns[j];
2239 var td = tr.insertCell(-1);
2241 var val = this._rows[i][j];
2243 if (typeof(val) == 'undefined')
2244 val = col.placeholder;
2246 if (typeof(val) == 'undefined')
2250 td.style.width = col.width;
2253 td.style.textAlign = col.align;
2255 if (typeof col.format == 'string')
2256 $(td).append(col.format.format(val));
2257 else if (typeof col.format == 'function')
2258 $(td).append(col.format(val, i));
2266 fieldset.appendChild(table);
2272 this.ui.progress = AbstractWidget.extend({
2275 var vn = parseInt(this.options.value) || 0;
2276 var mn = parseInt(this.options.max) || 100;
2277 var pc = Math.floor((100 / mn) * vn);
2279 var bar = document.createElement('div');
2280 bar.className = 'progressbar';
2282 bar.appendChild(document.createElement('div'));
2283 bar.lastChild.appendChild(document.createElement('div'));
2284 bar.lastChild.style.width = pc + '%';
2286 if (typeof(this.options.format) == 'string')
2287 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2288 else if (typeof(this.options.format) == 'function')
2289 $(bar.lastChild.lastChild).append(this.options.format(pc));
2291 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2297 this.ui.devicebadge = AbstractWidget.extend({
2300 var dev = this.options.l3_device || this.options.device || '?';
2302 var span = document.createElement('span');
2303 span.className = 'ifacebadge';
2305 if (typeof(this.options.signal) == 'number' ||
2306 typeof(this.options.noise) == 'number')
2309 if (typeof(this.options.signal) != 'undefined' &&
2310 typeof(this.options.noise) != 'undefined')
2312 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2325 span.appendChild(document.createElement('img'));
2326 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2329 span.title = _luci2.tr('No signal');
2331 span.title = '%s: %d %s / %s: %d %s'.format(
2332 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2333 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2338 var type = 'ethernet';
2339 var desc = _luci2.tr('Ethernet device');
2341 if (this.options.l3_device != this.options.device)
2344 desc = _luci2.tr('Tunnel interface');
2346 else if (dev.indexOf('br-') == 0)
2349 desc = _luci2.tr('Bridge');
2351 else if (dev.indexOf('.') > 0)
2354 desc = _luci2.tr('VLAN interface');
2356 else if (dev.indexOf('wlan') == 0 ||
2357 dev.indexOf('ath') == 0 ||
2358 dev.indexOf('wl') == 0)
2361 desc = _luci2.tr('Wireless Network');
2364 span.appendChild(document.createElement('img'));
2365 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2369 $(span).append(' ');
2370 $(span).append(dev);
2376 var type = function(f, l)
2386 _luci2.cbi.validation.message = _luci2.tr(msg);
2389 compile: function(code)
2394 var types = _luci2.cbi.validation.types;
2399 for (var i = 0; i < code.length; i++)
2407 switch (code.charCodeAt(i))
2419 var label = code.substring(pos, i);
2420 label = label.replace(/\\(.)/g, '$1');
2421 label = label.replace(/^[ \t]+/g, '');
2422 label = label.replace(/[ \t]+$/g, '');
2424 if (label && !isNaN(label))
2426 stack.push(parseFloat(label));
2428 else if (label.match(/^(['"]).*\1$/))
2430 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2432 else if (typeof types[label] == 'function')
2434 stack.push(types[label]);
2439 throw "Syntax error, unhandled token '"+label+"'";
2444 depth += (code.charCodeAt(i) == 40);
2450 if (typeof stack[stack.length-2] != 'function')
2451 throw "Syntax error, argument list follows non-function";
2453 stack[stack.length-1] =
2454 arguments.callee(code.substring(pos, i));
2467 var validation = this.cbi.validation;
2469 validation.types = {
2470 'integer': function()
2472 if (this.match(/^-?[0-9]+$/) != null)
2475 validation.i18n('Must be a valid integer');
2479 'uinteger': function()
2481 if (validation.types['integer'].apply(this) && (this >= 0))
2484 validation.i18n('Must be a positive integer');
2490 if (!isNaN(parseFloat(this)))
2493 validation.i18n('Must be a valid number');
2497 'ufloat': function()
2499 if (validation.types['float'].apply(this) && (this >= 0))
2502 validation.i18n('Must be a positive number');
2506 'ipaddr': function()
2508 if (validation.types['ip4addr'].apply(this) ||
2509 validation.types['ip6addr'].apply(this))
2512 validation.i18n('Must be a valid IP address');
2516 'ip4addr': function()
2518 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2520 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2521 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2522 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2523 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2524 ((RegExp.$6.indexOf('.') < 0)
2525 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2526 : (validation.types['ip4addr'].apply(RegExp.$6))))
2530 validation.i18n('Must be a valid IPv4 address');
2534 'ip6addr': function()
2536 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2538 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2540 var addr = RegExp.$1;
2547 if (addr.indexOf('.') > 0)
2549 var off = addr.lastIndexOf(':');
2551 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2553 validation.i18n('Must be a valid IPv6 address');
2557 addr = addr.substr(0, off) + ':0:0';
2560 if (addr.indexOf('::') >= 0)
2565 for (var i = 1; i < (addr.length-1); i++)
2566 if (addr.charAt(i) == ':')
2571 validation.i18n('Must be a valid IPv6 address');
2575 for (var i = 0; i < (7 - colons); i++)
2578 if (addr.match(/^(.*?)::(.*?)$/))
2579 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2580 (RegExp.$2 ? ':' + RegExp.$2 : '');
2583 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2586 validation.i18n('Must be a valid IPv6 address');
2596 if (validation.types['integer'].apply(this) &&
2597 (this >= 0) && (this <= 65535))
2600 validation.i18n('Must be a valid port number');
2604 'portrange': function()
2606 if (this.match(/^(\d+)-(\d+)$/))
2611 if (validation.types['port'].apply(p1) &&
2612 validation.types['port'].apply(p2) &&
2613 (parseInt(p1) <= parseInt(p2)))
2616 else if (validation.types['port'].apply(this))
2621 validation.i18n('Must be a valid port range');
2625 'macaddr': function()
2627 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2630 validation.i18n('Must be a valid MAC address');
2636 if (validation.types['hostname'].apply(this) ||
2637 validation.types['ipaddr'].apply(this))
2640 validation.i18n('Must be a valid hostname or IP address');
2644 'hostname': function()
2646 if ((this.length <= 253) &&
2647 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2648 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2649 this.match(/[^0-9.]/)))))
2652 validation.i18n('Must be a valid host name');
2656 'network': function()
2658 if (validation.types['uciname'].apply(this) ||
2659 validation.types['host'].apply(this))
2662 validation.i18n('Must be a valid network name');
2666 'wpakey': function()
2670 if ((v.length == 64)
2671 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2672 : ((v.length >= 8) && (v.length <= 63)))
2675 validation.i18n('Must be a valid WPA key');
2679 'wepkey': function()
2683 if (v.substr(0,2) == 's:')
2686 if (((v.length == 10) || (v.length == 26))
2687 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2688 : ((v.length == 5) || (v.length == 13)))
2691 validation.i18n('Must be a valid WEP key');
2695 'uciname': function()
2697 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2700 validation.i18n('Must be a valid UCI identifier');
2704 'range': function(min, max)
2706 var val = parseFloat(this);
2708 if (validation.types['integer'].apply(this) &&
2709 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
2712 validation.i18n('Must be a number between %d and %d');
2716 'min': function(min)
2718 var val = parseFloat(this);
2720 if (validation.types['integer'].apply(this) &&
2721 !isNaN(min) && !isNaN(val) && (val >= min))
2724 validation.i18n('Must be a number greater or equal to %d');
2728 'max': function(max)
2730 var val = parseFloat(this);
2732 if (validation.types['integer'].apply(this) &&
2733 !isNaN(max) && !isNaN(val) && (val <= max))
2736 validation.i18n('Must be a number lower or equal to %d');
2740 'rangelength': function(min, max)
2742 var val = '' + this;
2744 if (!isNaN(min) && !isNaN(max) &&
2745 (val.length >= min) && (val.length <= max))
2748 validation.i18n('Must be between %d and %d characters');
2752 'minlength': function(min)
2754 var val = '' + this;
2756 if (!isNaN(min) && (val.length >= min))
2759 validation.i18n('Must be at least %d characters');
2763 'maxlength': function(max)
2765 var val = '' + this;
2767 if (!isNaN(max) && (val.length <= max))
2770 validation.i18n('Must be at most %d characters');
2778 for (var i = 0; i < arguments.length; i += 2)
2780 delete validation.message;
2782 if (typeof(arguments[i]) != 'function')
2784 if (arguments[i] == this)
2788 else if (arguments[i].apply(this, arguments[i+1]))
2793 if (validation.message)
2794 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2797 validation.message = msgs.join( _luci2.tr(' - or - '));
2805 for (var i = 0; i < arguments.length; i += 2)
2807 delete validation.message;
2809 if (typeof arguments[i] != 'function')
2811 if (arguments[i] != this)
2815 else if (!arguments[i].apply(this, arguments[i+1]))
2820 if (validation.message)
2821 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2824 validation.message = msgs.join(', ');
2830 return validation.types['or'].apply(
2831 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
2834 'list': function(subvalidator, subargs)
2836 if (typeof subvalidator != 'function')
2839 var tokens = this.match(/[^ \t]+/g);
2840 for (var i = 0; i < tokens.length; i++)
2841 if (!subvalidator.apply(tokens[i], subargs))
2847 'phonedigit': function()
2849 if (this.match(/^[0-9\*#!\.]+$/) != null)
2852 validation.i18n('Must be a valid phone number digit');
2856 'string': function()
2863 var AbstractValue = AbstractWidget.extend({
2864 init: function(name, options)
2867 this.instance = { };
2868 this.dependencies = [ ];
2869 this.rdependency = { };
2871 this.options = _luci2.defaults(options, {
2881 return this.section.id('field', sid || '__unknown__', this.name);
2884 render: function(sid)
2886 var i = this.instance[sid] = { };
2888 i.top = $('<div />').addClass('cbi-value');
2890 if (typeof(this.options.caption) == 'string')
2892 .addClass('cbi-value-title')
2893 .attr('for', this.id(sid))
2894 .text(this.options.caption)
2897 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
2898 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
2900 if (typeof(this.options.description) == 'string')
2902 .addClass('cbi-value-description')
2903 .text(this.options.description)
2909 ucipath: function(sid)
2912 config: (this.options.uci_package || this.map.uci_package),
2913 section: (this.options.uci_section || sid),
2914 option: (this.options.uci_option || this.name)
2918 ucivalue: function(sid)
2920 var uci = this.ucipath(sid);
2921 var val = this.map.get(uci.config, uci.section, uci.option);
2923 if (typeof(val) == 'undefined')
2924 return this.options.initial;
2929 formvalue: function(sid)
2931 var v = $('#' + this.id(sid)).val();
2932 return (v === '') ? undefined : v;
2935 textvalue: function(sid)
2937 var v = this.formvalue(sid);
2939 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
2940 v = this.ucivalue(sid);
2942 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
2943 v = this.options.placeholder;
2945 if (typeof(v) == 'undefined' || v === '')
2948 if (typeof(v) == 'string' && $.isArray(this.choices))
2950 for (var i = 0; i < this.choices.length; i++)
2951 if (v === this.choices[i][0])
2952 return this.choices[i][1];
2954 else if (v === true)
2955 return _luci2.tr('yes');
2956 else if (v === false)
2957 return _luci2.tr('no');
2958 else if ($.isArray(v))
2959 return v.join(', ');
2964 changed: function(sid)
2966 var a = this.ucivalue(sid);
2967 var b = this.formvalue(sid);
2969 if (typeof(a) != typeof(b))
2972 if (typeof(a) == 'object')
2974 if (a.length != b.length)
2977 for (var i = 0; i < a.length; i++)
2989 var uci = this.ucipath(sid);
2991 if (this.instance[sid].disabled)
2993 if (!this.options.keep)
2994 return this.map.set(uci.config, uci.section, uci.option, undefined);
2999 var chg = this.changed(sid);
3000 var val = this.formvalue(sid);
3003 this.map.set(uci.config, uci.section, uci.option, val);
3008 validator: function(sid, elem, multi)
3010 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3014 if (typeof(this.options.datatype) == 'string')
3017 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3020 else if (typeof(this.options.datatype) == 'function')
3022 var vfunc = this.options.datatype;
3023 vstack = [ function(elem) {
3024 var rv = vfunc(this, elem);
3026 validation.message = rv;
3027 return (rv === true);
3036 inst: this.instance[sid],
3037 opt: this.options.optional
3040 var validator = function(ev)
3044 var val = d.elem.val();
3046 if (vstack && typeof(vstack[0]) == 'function')
3048 delete validation.message;
3050 if ((val.length == 0 && !d.opt))
3052 d.elem.addClass('error');
3053 d.inst.top.addClass('error');
3054 d.inst.error.text(_luci2.tr('Field must not be empty'));
3057 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3059 d.elem.addClass('error');
3060 d.inst.top.addClass('error');
3061 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3066 d.elem.removeClass('error');
3068 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3074 d.inst.top.removeClass('error');
3075 d.inst.error.text('');
3082 for (var field in d.self.rdependency)
3083 d.self.rdependency[field].toggle(d.sid);
3089 if (elem.prop('tagName') == 'SELECT')
3091 elem.change(evdata, validator);
3093 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3095 elem.click(evdata, validator);
3096 elem.blur(evdata, validator);
3100 elem.keyup(evdata, validator);
3101 elem.blur(evdata, validator);
3104 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3109 validate: function(sid)
3111 var i = this.instance[sid];
3113 i.widget.find('[cbi-validate]').trigger('validate');
3115 return (i.disabled || i.error.text() == '');
3118 depends: function(d, v)
3125 for (var i = 0; i < d.length; i++)
3127 if (typeof(d[i]) == 'string')
3129 else if (d[i] instanceof AbstractValue)
3130 dep[d[i].name] = true;
3133 else if (d instanceof AbstractValue)
3136 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3138 else if (typeof(d) == 'object')
3142 else if (typeof(d) == 'string')
3145 dep[d] = (typeof(v) == 'undefined') ? true : v;
3148 if (!dep || $.isEmptyObject(dep))
3151 for (var field in dep)
3153 var f = this.section.fields[field];
3155 f.rdependency[this.name] = this;
3160 if ($.isEmptyObject(dep))
3163 this.dependencies.push(dep);
3168 toggle: function(sid)
3170 var d = this.dependencies;
3171 var i = this.instance[sid];
3176 for (var n = 0; n < d.length; n++)
3180 for (var field in d[n])
3182 var val = this.section.fields[field].formvalue(sid);
3183 var cmp = d[n][field];
3185 if (typeof(cmp) == 'boolean')
3187 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3193 else if (typeof(cmp) == 'string')
3201 else if (typeof(cmp) == 'function')
3209 else if (cmp instanceof RegExp)
3234 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3241 this.cbi.CheckboxValue = AbstractValue.extend({
3242 widget: function(sid)
3244 var o = this.options;
3246 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3247 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3249 var i = $('<input />')
3250 .attr('id', this.id(sid))
3251 .attr('type', 'checkbox')
3252 .prop('checked', this.ucivalue(sid));
3254 return this.validator(sid, i);
3257 ucivalue: function(sid)
3259 var v = this.callSuper('ucivalue', sid);
3261 if (typeof(v) == 'boolean')
3264 return (v == this.options.enabled);
3267 formvalue: function(sid)
3269 var v = $('#' + this.id(sid)).prop('checked');
3271 if (typeof(v) == 'undefined')
3272 return !!this.options.initial;
3279 var uci = this.ucipath(sid);
3281 if (this.instance[sid].disabled)
3283 if (!this.options.keep)
3284 return this.map.set(uci.config, uci.section, uci.option, undefined);
3289 var chg = this.changed(sid);
3290 var val = this.formvalue(sid);
3294 val = val ? this.options.enabled : this.options.disabled;
3296 if (this.options.optional && val == this.options.initial)
3297 this.map.set(uci.config, uci.section, uci.option, undefined);
3299 this.map.set(uci.config, uci.section, uci.option, val);
3306 this.cbi.InputValue = AbstractValue.extend({
3307 widget: function(sid)
3309 var i = $('<input />')
3310 .attr('id', this.id(sid))
3311 .attr('type', 'text')
3312 .attr('placeholder', this.options.placeholder)
3313 .val(this.ucivalue(sid));
3315 return this.validator(sid, i);
3319 this.cbi.PasswordValue = AbstractValue.extend({
3320 widget: function(sid)
3322 var i = $('<input />')
3323 .attr('id', this.id(sid))
3324 .attr('type', 'password')
3325 .attr('placeholder', this.options.placeholder)
3326 .val(this.ucivalue(sid));
3328 var t = $('<img />')
3329 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3330 .attr('title', _luci2.tr('Reveal or hide password'))
3331 .addClass('cbi-button')
3332 .click(function(ev) {
3333 var i = $(this).prev();
3334 var t = i.attr('type');
3335 i.attr('type', (t == 'password') ? 'text' : 'password');
3339 this.validator(sid, i);
3342 .addClass('cbi-input-password')
3348 this.cbi.ListValue = AbstractValue.extend({
3349 widget: function(sid)
3351 var s = $('<select />');
3353 if (this.options.optional)
3356 .text(_luci2.tr('-- Please choose --'))
3360 for (var i = 0; i < this.choices.length; i++)
3362 .attr('value', this.choices[i][0])
3363 .text(this.choices[i][1])
3366 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3368 return this.validator(sid, s);
3371 value: function(k, v)
3376 this.choices.push([k, v || k]);
3381 this.cbi.MultiValue = this.cbi.ListValue.extend({
3382 widget: function(sid)
3384 var v = this.ucivalue(sid);
3385 var t = $('<div />').attr('id', this.id(sid));
3388 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3391 for (var i = 0; i < v.length; i++)
3395 for (var i = 0; i < this.choices.length; i++)
3398 .append($('<input />')
3399 .addClass('cbi-input-checkbox')
3400 .attr('type', 'checkbox')
3401 .attr('value', this.choices[i][0])
3402 .prop('checked', s[this.choices[i][0]]))
3403 .append(this.choices[i][1])
3413 formvalue: function(sid)
3416 var fields = $('#' + this.id(sid) + ' > label > input');
3418 for (var i = 0; i < fields.length; i++)
3419 if (fields[i].checked)
3420 rv.push(fields[i].getAttribute('value'));
3425 textvalue: function(sid)
3427 var v = this.formvalue(sid);
3431 for (var i = 0; i < this.choices.length; i++)
3432 c[this.choices[i][0]] = this.choices[i][1];
3436 for (var i = 0; i < v.length; i++)
3437 t.push(c[v[i]] || v[i]);
3439 return t.join(', ');
3443 this.cbi.ComboBox = AbstractValue.extend({
3444 _change: function(ev)
3447 var self = ev.data.self;
3449 if (s.selectedIndex == (s.options.length - 1))
3451 ev.data.select.hide();
3452 ev.data.input.show().focus();
3454 var v = ev.data.input.val();
3455 ev.data.input.val(' ');
3456 ev.data.input.val(v);
3458 else if (self.options.optional && s.selectedIndex == 0)
3460 ev.data.input.val('');
3464 ev.data.input.val(ev.data.select.val());
3471 var val = this.value;
3472 var self = ev.data.self;
3474 ev.data.select.empty();
3476 if (self.options.optional)
3479 .text(_luci2.tr('-- please choose --'))
3480 .appendTo(ev.data.select);
3483 for (var i = 0; i < self.choices.length; i++)
3485 if (self.choices[i][0] == val)
3489 .attr('value', self.choices[i][0])
3490 .text(self.choices[i][1])
3491 .appendTo(ev.data.select);
3494 if (!seen && val != '')
3498 .appendTo(ev.data.select);
3502 .text(_luci2.tr('-- custom --'))
3503 .appendTo(ev.data.select);
3505 ev.data.input.hide();
3506 ev.data.select.val(val).show().focus();
3509 _enter: function(ev)
3514 ev.preventDefault();
3515 ev.data.self._blur(ev);
3519 widget: function(sid)
3521 var d = $('<div />')
3522 .attr('id', this.id(sid));
3524 var t = $('<input />')
3525 .attr('type', 'text')
3529 var s = $('<select />')
3534 input: this.validator(sid, t),
3535 select: this.validator(sid, s)
3538 s.change(evdata, this._change);
3539 t.blur(evdata, this._blur);
3540 t.keydown(evdata, this._enter);
3542 t.val(this.ucivalue(sid));
3548 value: function(k, v)
3553 this.choices.push([k, v || k]);
3557 formvalue: function(sid)
3559 var v = $('#' + this.id(sid)).children('input').val();
3560 return (v == '') ? undefined : v;
3564 this.cbi.DynamicList = this.cbi.ComboBox.extend({
3565 _redraw: function(focus, add, del, s)
3567 var v = s.values || [ ];
3570 $(s.parent).children('input').each(function(i) {
3572 v.push(this.value || '');
3575 $(s.parent).empty();
3580 v.splice(focus, 0, '');
3582 else if (v.length == 0)
3588 for (var i = 0; i < v.length; i++)
3599 var txt = $('<input />')
3600 .attr('type', 'text')
3602 .appendTo(s.parent);
3604 var sel = $('<select />')
3605 .appendTo(s.parent);
3607 evdata.input = this.validator(s.sid, txt, true);
3608 evdata.select = this.validator(s.sid, sel, true);
3610 sel.change(evdata, this._change);
3611 txt.blur(evdata, this._blur);
3612 txt.keydown(evdata, this._keydown);
3617 if (i == focus || -(i+1) == focus)
3624 var f = $('<input />')
3625 .attr('type', 'text')
3627 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
3628 .addClass('cbi-input-text')
3629 .keydown(evdata, this._keydown)
3630 .keypress(evdata, this._keypress)
3633 f.appendTo(s.parent);
3639 else if (-(i+1) == focus)
3643 /* force cursor to end */
3649 evdata.input = this.validator(s.sid, f, true);
3655 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
3656 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
3657 .addClass('cbi-button')
3658 .click(evdata, this._btnclick)
3659 .appendTo(s.parent);
3662 .appendTo(s.parent);
3670 _keypress: function(ev)
3674 /* backspace, delete */
3677 if (ev.data.input.val() == '')
3679 ev.preventDefault();
3685 /* enter, arrow up, arrow down */
3689 ev.preventDefault();
3696 _keydown: function(ev)
3698 var input = ev.data.input;
3702 /* backspace, delete */
3705 if (input.val().length == 0)
3707 ev.preventDefault();
3709 var index = ev.data.index;
3715 ev.data.self._redraw(focus, -1, index, ev.data);
3723 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
3728 var prev = input.prevAll('input:first');
3729 if (prev.is(':visible'))
3732 prev.next('select').focus();
3737 var next = input.nextAll('input:first');
3738 if (next.is(':visible'))
3741 next.next('select').focus();
3748 _btnclick: function(ev)
3750 if (!this.getAttribute('disabled'))
3752 if (ev.target.src.indexOf('remove') > -1)
3754 var index = ev.data.index;
3755 ev.data.self._redraw(-index, -1, index, ev.data);
3759 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
3766 widget: function(sid)
3768 this.options.optional = true;
3770 var v = this.ucivalue(sid);
3773 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3775 var d = $('<div />')
3776 .attr('id', this.id(sid))
3777 .addClass('cbi-input-dynlist');
3779 this._redraw(NaN, -1, -1, {
3789 ucivalue: function(sid)
3791 var v = this.callSuper('ucivalue', sid);
3794 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3799 formvalue: function(sid)
3802 var fields = $('#' + this.id(sid) + ' > input');
3804 for (var i = 0; i < fields.length; i++)
3805 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
3806 rv.push(fields[i].value);
3812 this.cbi.DummyValue = AbstractValue.extend({
3813 widget: function(sid)
3816 .addClass('cbi-value-dummy')
3817 .attr('id', this.id(sid))
3818 .html(this.ucivalue(sid));
3821 formvalue: function(sid)
3823 return this.ucivalue(sid);
3827 this.cbi.NetworkList = AbstractValue.extend({
3832 if (!self.interfaces)
3834 self.interfaces = [ ];
3835 return _luci2.network.getNetworkStatus(function(ifaces) {
3836 self.interfaces = ifaces;
3844 _device_icon: function(dev)
3846 var type = 'ethernet';
3847 var desc = _luci2.tr('Ethernet device');
3849 if (dev.type == 'IP tunnel')
3852 desc = _luci2.tr('Tunnel interface');
3854 else if (dev['bridge-members'])
3857 desc = _luci2.tr('Bridge');
3859 else if (dev.wireless)
3862 desc = _luci2.tr('Wireless Network');
3864 else if (dev.name.indexOf('.') > 0)
3867 desc = _luci2.tr('VLAN interface');
3871 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
3872 .attr('title', '%s (%s)'.format(desc, dev.name));
3875 widget: function(sid)
3877 var id = this.id(sid);
3878 var ul = $('<ul />')
3880 .addClass('cbi-input-networks');
3882 var itype = this.options.multiple ? 'checkbox' : 'radio';
3883 var value = this.ucivalue(sid);
3886 if (!this.options.multiple)
3887 check[value] = true;
3889 for (var i = 0; i < value.length; i++)
3890 check[value[i]] = true;
3892 if (this.interfaces)
3894 for (var i = 0; i < this.interfaces.length; i++)
3896 var iface = this.interfaces[i];
3897 var badge = $('<span />')
3898 .addClass('ifacebadge')
3899 .text('%s: '.format(iface.name));
3901 if (iface.subdevices)
3902 for (var j = 0; j < iface.subdevices.length; j++)
3903 badge.append(this._device_icon(iface.subdevices[j]));
3904 else if (iface.device)
3905 badge.append(this._device_icon(iface.device));
3907 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
3910 .append($('<label />')
3911 .append($('<input />')
3912 .attr('name', itype + id)
3913 .attr('type', itype)
3914 .attr('value', iface.name)
3915 .prop('checked', !!check[iface.name])
3916 .addClass('cbi-input-' + itype))
3922 if (!this.options.multiple)
3925 .append($('<label />')
3926 .append($('<input />')
3927 .attr('name', itype + id)
3928 .attr('type', itype)
3930 .prop('checked', !value)
3931 .addClass('cbi-input-' + itype))
3932 .append(_luci2.tr('unspecified')))
3939 ucivalue: function(sid)
3941 var v = this.callSuper('ucivalue', sid);
3943 if (!this.options.multiple)
3949 else if (typeof(v) == 'string')
3952 return v ? v[0] : undefined;
3959 if (typeof(v) == 'string')
3960 v = v.match(/\S+/g);
3966 formvalue: function(sid)
3968 var inputs = $('#' + this.id(sid) + ' input');
3970 if (!this.options.multiple)
3972 for (var i = 0; i < inputs.length; i++)
3973 if (inputs[i].checked && inputs[i].value !== '')
3974 return inputs[i].value;
3981 for (var i = 0; i < inputs.length; i++)
3982 if (inputs[i].checked)
3983 rv.push(inputs[i].value);
3985 return rv.length ? rv : undefined;
3990 var AbstractSection = AbstractWidget.extend({
3993 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
3995 for (var i = 1; i < arguments.length; i++)
3996 s.push(arguments[i].replace(/\./g, '_'));
4001 option: function(widget, name, options)
4003 if (this.tabs.length == 0)
4004 this.tab({ id: '__default__', selected: true });
4006 return this.taboption('__default__', widget, name, options);
4009 tab: function(options)
4011 if (options.selected)
4012 this.tabs.selected = this.tabs.length;
4016 caption: options.caption,
4017 description: options.description,
4023 taboption: function(tabid, widget, name, options)
4026 for (var i = 0; i < this.tabs.length; i++)
4028 if (this.tabs[i].id == tabid)
4036 throw 'Cannot append to unknown tab ' + tabid;
4038 var w = widget ? new widget(name, options) : null;
4040 if (!(w instanceof AbstractValue))
4041 throw 'Widget must be an instance of AbstractValue';
4046 this.fields[name] = w;
4052 ucipackages: function(pkg)
4054 for (var i = 0; i < this.tabs.length; i++)
4055 for (var j = 0; j < this.tabs[i].fields.length; j++)
4056 if (this.tabs[i].fields[j].options.uci_package)
4057 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4060 formvalue: function()
4064 this.sections(function(s) {
4065 var sid = s['.name'];
4066 var sv = rv[sid] || (rv[sid] = { });
4068 for (var i = 0; i < this.tabs.length; i++)
4069 for (var j = 0; j < this.tabs[i].fields.length; j++)
4071 var val = this.tabs[i].fields[j].formvalue(sid);
4072 sv[this.tabs[i].fields[j].name] = val;
4079 validate: function(sid)
4085 var as = this.sections();
4086 for (var i = 0; i < as.length; i++)
4087 if (!this.validate(as[i]['.name']))
4092 var inst = this.instance[sid];
4093 var sv = rv[sid] || (rv[sid] = { });
4096 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4098 legend.children('span').detach();
4100 for (var i = 0; i < this.tabs.length; i++)
4103 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4105 tab.children('span').detach();
4107 for (var j = 0; j < this.tabs[i].fields.length; j++)
4108 if (!this.tabs[i].fields[j].validate(sid))
4115 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4128 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4136 this.cbi.TypedSection = AbstractSection.extend({
4137 init: function(uci_type, options)
4139 this.uci_type = uci_type;
4140 this.options = options;
4143 this.active_panel = 0;
4144 this.active_tab = { };
4147 filter: function(section)
4152 sections: function(cb)
4154 var s1 = this.map.ucisections(this.map.uci_package);
4157 for (var i = 0; i < s1.length; i++)
4158 if (s1[i]['.type'] == this.uci_type)
4159 if (this.filter(s1[i]))
4162 if (typeof(cb) == 'function')
4163 for (var i = 0; i < s2.length; i++)
4164 cb.apply(this, [ s2[i] ]);
4171 this.map.add(this.map.uci_package, this.uci_type, name);
4174 remove: function(sid)
4176 this.map.remove(this.map.uci_package, sid);
4182 var name = undefined;
4183 var self = ev.data.self;
4185 if (addb.prev().prop('nodeName') == 'INPUT')
4186 name = addb.prev().val();
4188 if (addb.prop('disabled') || name === '')
4191 self.active_panel = -1;
4197 _remove: function(ev)
4199 var self = ev.data.self;
4200 var sid = ev.data.sid;
4206 ev.stopPropagation();
4211 var self = ev.data.self;
4213 var addb = text.next();
4214 var errt = addb.next();
4215 var name = text.val();
4218 if (!/^[a-zA-Z0-9_]*$/.test(name))
4220 errt.text(_luci2.tr('Invalid section name')).show();
4221 text.addClass('error');
4222 addb.prop('disabled', true);
4226 for (var sid in self.map.uci.values[self.map.uci_package])
4233 for (var sid in self.map.uci.creates[self.map.uci_package])
4242 errt.text(_luci2.tr('Name already used')).show();
4243 text.addClass('error');
4244 addb.prop('disabled', true);
4248 errt.text('').hide();
4249 text.removeClass('error');
4250 addb.prop('disabled', false);
4254 teaser: function(sid)
4256 var tf = this.teaser_fields;
4260 tf = this.teaser_fields = [ ];
4262 if ($.isArray(this.options.teasers))
4264 for (var i = 0; i < this.options.teasers.length; i++)
4266 var f = this.options.teasers[i];
4267 if (f instanceof AbstractValue)
4269 else if (typeof(f) == 'string' && this.fields[f] instanceof AbstractValue)
4270 tf.push(this.fields[f]);
4275 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4276 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4277 tf.push(this.tabs[i].fields[j]);
4283 for (var i = 0; i < tf.length; i++)
4285 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4288 var n = tf[i].options.caption || tf[i].name;
4289 var v = tf[i].textvalue(sid);
4291 if (typeof(v) == 'undefined')
4294 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4300 _render_add: function()
4302 var text = _luci2.tr('Add section');
4303 var ttip = _luci2.tr('Create new section...');
4305 if ($.isArray(this.options.add_caption))
4306 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4307 else if (typeof(this.options.add_caption) == 'string')
4308 text = this.options.add_caption, ttip = '';
4310 var add = $('<div />').addClass('cbi-section-add');
4312 if (this.options.anonymous === false)
4315 .addClass('cbi-input-text')
4316 .attr('type', 'text')
4317 .attr('placeholder', ttip)
4318 .blur({ self: this }, this._sid)
4319 .keyup({ self: this }, this._sid)
4323 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4324 .attr('title', text)
4325 .addClass('cbi-button')
4326 .click({ self: this }, this._add)
4330 .addClass('cbi-value-error')
4337 .attr('type', 'button')
4338 .addClass('cbi-button')
4339 .addClass('cbi-button-add')
4340 .val(text).attr('title', ttip)
4341 .click({ self: this }, this._add)
4348 _render_remove: function(sid)
4350 var text = _luci2.tr('Remove');
4351 var ttip = _luci2.tr('Remove this section');
4353 if ($.isArray(this.options.remove_caption))
4354 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4355 else if (typeof(this.options.remove_caption) == 'string')
4356 text = this.options.remove_caption, ttip = '';
4358 return $('<input />')
4359 .attr('type', 'button')
4360 .addClass('cbi-button')
4361 .addClass('cbi-button-remove')
4362 .val(text).attr('title', ttip)
4363 .click({ self: this, sid: sid }, this._remove);
4366 _render_caption: function(sid)
4368 if (typeof(this.options.caption) == 'string')
4370 return $('<legend />')
4371 .text(this.options.caption.format(sid));
4373 else if (typeof(this.options.caption) == 'function')
4375 return $('<legend />')
4376 .text(this.options.caption.call(this, sid));
4384 var allsections = $();
4385 var panel_index = 0;
4387 this.instance = { };
4389 var s = this.sections();
4393 var fieldset = $('<fieldset />')
4394 .addClass('cbi-section');
4396 var head = $('<div />')
4397 .addClass('cbi-section-head')
4398 .appendTo(fieldset);
4400 head.append(this._render_caption(undefined));
4402 if (typeof(this.options.description) == 'string')
4405 .addClass('cbi-section-descr')
4406 .text(this.options.description)
4410 allsections = allsections.add(fieldset);
4413 for (var i = 0; i < s.length; i++)
4415 var sid = s[i]['.name'];
4416 var inst = this.instance[sid] = { tabs: [ ] };
4418 var fieldset = $('<fieldset />')
4419 .attr('id', this.id('sort', sid))
4420 .addClass('cbi-section');
4422 var head = $('<div />')
4423 .addClass('cbi-section-head')
4424 .attr('cbi-section-num', this.index)
4425 .attr('cbi-section-id', sid);
4427 head.append(this._render_caption(sid));
4429 if (typeof(this.options.description) == 'string')
4432 .addClass('cbi-section-descr')
4433 .text(this.options.description)
4438 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4439 teaser = $('<div />')
4440 .addClass('cbi-section-teaser')
4443 if (this.options.addremove)
4445 .addClass('cbi-section-remove')
4447 .append(this._render_remove(sid))
4450 var body = $('<div />')
4451 .attr('index', panel_index++);
4453 var fields = $('<fieldset />')
4454 .addClass('cbi-section-node');
4456 if (this.tabs.length > 1)
4458 var menu = $('<ul />')
4459 .addClass('cbi-tabmenu');
4461 for (var j = 0; j < this.tabs.length; j++)
4463 var tabid = this.id('tab', sid, this.tabs[j].id);
4464 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4466 var tabc = $('<div />')
4467 .addClass('cbi-tabcontainer')
4471 if (typeof(this.tabs[j].description) == 'string')
4474 .addClass('cbi-tab-descr')
4475 .text(this.tabs[j].description)
4479 for (var k = 0; k < this.tabs[j].fields.length; k++)
4480 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4482 tabc.appendTo(fields);
4485 $('<li />').attr('id', theadid).append(
4487 .text(this.tabs[j].caption.format(this.tabs[j].id))
4488 .attr('href', '#' + tabid)
4492 menu.appendTo(body);
4495 fields.appendTo(body);
4498 var t = body.tabs({ active: this.active_tab[sid] });
4500 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4503 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4508 for (var j = 0; j < this.tabs[0].fields.length; j++)
4509 this.tabs[0].fields[j].render(sid).appendTo(fields);
4511 fields.appendTo(body);
4515 head.appendTo(fieldset);
4518 body.appendTo(fieldset);
4521 allsections = allsections.add(fieldset);
4524 //this.validate(sid);
4527 // teaser.append(this.teaser(sid));
4530 if (this.options.collabsible && s.length > 1)
4532 var a = $('<div />').append(allsections).accordion({
4533 header: '> fieldset > div.cbi-section-head',
4534 heightStyle: 'content',
4535 active: this.active_panel
4538 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4539 var h = ui.oldHeader;
4540 var s = ev.data.self;
4541 var i = h.attr('cbi-section-id');
4543 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4547 a.on('accordionactivate', { self: this }, function(ev, ui) {
4548 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4551 if (this.options.sortable)
4553 var s = a.sortable({
4555 handle: 'div.cbi-section-head'
4558 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4560 for (var i = 0; i < ev.data.ids.length; i++)
4561 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4562 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4565 s.on('sortstop', function(ev, ui) {
4566 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4570 if (this.options.addremove)
4571 this._render_add().appendTo(a);
4576 if (this.options.addremove)
4577 allsections = allsections.add(this._render_add());
4584 var s = this.sections();
4586 for (var i = 0; i < s.length; i++)
4588 var sid = s[i]['.name'];
4592 $('#' + this.id('sort', sid))
4593 .children('.cbi-section-head')
4594 .children('.cbi-section-teaser')
4595 .append(this.teaser(sid));
4600 this.cbi.TableSection = this.cbi.TypedSection.extend({
4603 var allsections = $();
4604 var panel_index = 0;
4606 this.instance = { };
4608 var s = this.sections();
4610 var fieldset = $('<fieldset />')
4611 .addClass('cbi-section');
4613 fieldset.append(this._render_caption(sid));
4615 if (typeof(this.options.description) == 'string')
4618 .addClass('cbi-section-descr')
4619 .text(this.options.description)
4620 .appendTo(fieldset);
4623 var fields = $('<div />')
4624 .addClass('cbi-section-node')
4625 .appendTo(fieldset);
4627 var table = $('<table />')
4628 .addClass('cbi-section-table')
4631 var thead = $('<thead />')
4632 .append($('<tr />').addClass('cbi-section-table-titles'))
4635 for (var j = 0; j < this.tabs[0].fields.length; j++)
4637 .addClass('cbi-section-table-cell')
4638 .css('width', this.tabs[0].fields[j].options.width || '')
4639 .append(this.tabs[0].fields[j].options.caption)
4640 .appendTo(thead.children());
4642 if (this.options.sortable)
4643 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4645 if (this.options.addremove !== false)
4646 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4648 var tbody = $('<tbody />')
4654 .addClass('cbi-section-table-row')
4657 .addClass('cbi-section-table-cell')
4658 .addClass('cbi-section-table-placeholder')
4659 .attr('colspan', thead.children().children().length)
4660 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
4664 for (var i = 0; i < s.length; i++)
4666 var sid = s[i]['.name'];
4667 var inst = this.instance[sid] = { tabs: [ ] };
4669 var row = $('<tr />')
4670 .addClass('cbi-section-table-row')
4673 for (var j = 0; j < this.tabs[0].fields.length; j++)
4676 .addClass('cbi-section-table-cell')
4677 .css('width', this.tabs[0].fields[j].options.width || '')
4678 .append(this.tabs[0].fields[j].render(sid, true))
4682 if (this.options.sortable)
4685 .addClass('cbi-section-table-cell')
4686 .addClass('cbi-section-table-sort')
4687 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
4688 .append($('<br />'))
4689 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
4693 if (this.options.addremove !== false)
4696 .addClass('cbi-section-table-cell')
4697 .append(this._render_remove(sid))
4706 if (this.options.sortable)
4708 var s = tbody.sortable({
4709 handle: 'td.cbi-section-table-sort'
4712 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4714 for (var i = 0; i < ev.data.ids.length; i++)
4715 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4716 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4719 s.on('sortstop', function(ev, ui) {
4720 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4724 if (this.options.addremove)
4725 this._render_add().appendTo(fieldset);
4727 fields = table = thead = tbody = null;
4733 this.cbi.NamedSection = this.cbi.TypedSection.extend({
4734 sections: function(cb)
4737 var pkg = this.map.uci.values[this.map.uci_package];
4740 if (pkg[s]['.name'] == this.uci_type)
4746 if (typeof(cb) == 'function' && sa.length > 0)
4747 cb.apply(this, [ sa[0] ]);
4753 this.cbi.DummySection = this.cbi.TypedSection.extend({
4754 sections: function(cb)
4756 if (typeof(cb) == 'function')
4757 cb.apply(this, [ { '.name': this.uci_type } ]);
4759 return [ { '.name': this.uci_type } ];
4763 this.cbi.Map = AbstractWidget.extend({
4764 init: function(uci_package, options)
4768 this.uci_package = uci_package;
4769 this.sections = [ ];
4770 this.options = _luci2.defaults(options, {
4771 save: function() { },
4772 prepare: function() {
4773 return _luci2.uci.writable(function(writable) {
4774 self.options.readonly = !writable;
4790 this.active_panel = 0;
4794 for (var i = 0; i < this.sections.length; i++)
4795 this.sections[i].ucipackages(packages);
4797 packages[this.uci_package] = true;
4799 for (var p in packages)
4800 packages[p] = ['uci', 'get', { config: p }];
4802 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(responses) {
4803 for (var p in responses)
4805 if (responses[p][0] != 0 || !responses[p][1] || !responses[p][1].values)
4808 this.uci.values[p] = responses[p][1].values;
4811 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
4813 for (var i = 0; i < this.sections.length; i++)
4815 for (var f in this.sections[i].fields)
4817 if (typeof(this.sections[i].fields[f].load) != 'function')
4820 var s = this.sections[i].sections();
4821 for (var j = 0; j < s.length; j++)
4823 var rv = this.sections[i].fields[f].load(s[j]['.name']);
4824 if (_luci2.deferred(rv))
4830 return $.when.apply($, deferreds);
4833 return _luci2.rpc.call(packages).then(load_cb);
4838 var map = $('<div />').addClass('cbi-map');
4840 if (typeof(this.options.caption) == 'string')
4841 $('<h2 />').text(this.options.caption).appendTo(map);
4843 if (typeof(this.options.description) == 'string')
4844 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
4846 var sections = $('<div />').appendTo(map);
4848 for (var i = 0; i < this.sections.length; i++)
4850 var s = this.sections[i].render();
4852 if (this.options.readonly || this.sections[i].options.readonly)
4853 s.find('input, select, button, img.cbi-button').attr('disabled', true);
4855 s.appendTo(sections);
4857 if (this.sections[i].options.active)
4858 this.active_panel = i;
4861 if (this.options.collabsible)
4863 var a = sections.accordion({
4864 header: '> fieldset > div.cbi-section-head',
4865 heightStyle: 'content',
4866 active: this.active_panel
4869 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4870 var h = ui.oldHeader;
4871 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
4872 var i = h.attr('cbi-section-id');
4874 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4876 for (var i = 0; i < ev.data.self.sections.length; i++)
4877 ev.data.self.sections[i].validate();
4880 a.on('accordionactivate', { self: this }, function(ev, ui) {
4881 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4885 if (this.options.pageaction !== false)
4887 var a = $('<div />')
4888 .addClass('cbi-page-actions')
4892 .addClass('cbi-button').addClass('cbi-button-apply')
4893 .attr('type', 'button')
4894 .val(_luci2.tr('Save & Apply'))
4898 .addClass('cbi-button').addClass('cbi-button-save')
4899 .attr('type', 'button')
4900 .val(_luci2.tr('Save'))
4901 .click({ self: this }, function(ev) { ev.data.self.send(); })
4905 .addClass('cbi-button').addClass('cbi-button-reset')
4906 .attr('type', 'button')
4907 .val(_luci2.tr('Reset'))
4908 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
4914 var top = $('<form />').append(map);
4923 for (var i = 0; i < this.sections.length; i++)
4924 this.sections[i].finish();
4931 this.target.hide().empty().append(this.render());
4936 section: function(widget, uci_type, options)
4938 var w = widget ? new widget(uci_type, options) : null;
4940 if (!(w instanceof AbstractSection))
4941 throw 'Widget must be an instance of AbstractSection';
4944 w.index = this.sections.length;
4946 this.sections.push(w);
4950 formvalue: function()
4954 for (var i = 0; i < this.sections.length; i++)
4956 var sids = this.sections[i].formvalue();
4957 for (var sid in sids)
4959 var s = rv[sid] || (rv[sid] = { });
4960 $.extend(s, sids[sid]);
4967 add: function(conf, type, name)
4969 var c = this.uci.creates;
4970 var s = '.new.%d'.format(this.uci.newid++);
4985 remove: function(conf, sid)
4987 var n = this.uci.creates;
4988 var c = this.uci.changes;
4989 var d = this.uci.deletes;
4991 /* requested deletion of a just created section */
4992 if (sid.indexOf('.new.') == 0)
4995 delete n[conf][sid];
5000 delete c[conf][sid];
5005 d[conf][sid] = true;
5009 ucisections: function(conf, cb)
5012 var pkg = this.uci.values[conf];
5013 var crt = this.uci.creates[conf];
5014 var del = this.uci.deletes[conf];
5020 if (!del || del[s] !== true)
5023 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5029 if (typeof(cb) == 'function')
5030 for (var i = 0; i < sa.length; i++)
5031 cb.apply(this, [ sa[i] ]);
5036 get: function(conf, sid, opt)
5038 var v = this.uci.values;
5039 var n = this.uci.creates;
5040 var c = this.uci.changes;
5041 var d = this.uci.deletes;
5043 /* requested option in a just created section */
5044 if (sid.indexOf('.new.') == 0)
5049 if (typeof(opt) == 'undefined')
5050 return (n[conf][sid] || { });
5052 return n[conf][sid][opt];
5055 /* requested an option value */
5056 if (typeof(opt) != 'undefined')
5058 /* check whether option was deleted */
5059 if (d[conf] && d[conf][sid])
5061 if (d[conf][sid] === true)
5064 for (var i = 0; i < d[conf][sid].length; i++)
5065 if (d[conf][sid][i] == opt)
5069 /* check whether option was changed */
5070 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5071 return c[conf][sid][opt];
5073 /* return base value */
5074 if (v[conf] && v[conf][sid])
5075 return v[conf][sid][opt];
5080 /* requested an entire section */
5082 return (v[conf][sid] || { });
5087 set: function(conf, sid, opt, val)
5089 var n = this.uci.creates;
5090 var c = this.uci.changes;
5091 var d = this.uci.deletes;
5093 if (sid.indexOf('.new.') == 0)
5095 if (n[conf] && n[conf][sid])
5097 if (typeof(val) != 'undefined')
5098 n[conf][sid][opt] = val;
5100 delete n[conf][sid][opt];
5103 else if (typeof(val) != 'undefined')
5111 c[conf][sid][opt] = val;
5121 d[conf][sid].push(opt);
5125 validate: function()
5129 for (var i = 0; i < this.sections.length; i++)
5130 if (!this.sections[i].validate())
5138 if (this.options.readonly)
5139 return _luci2.deferrable();
5141 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5143 for (var i = 0; i < this.sections.length; i++)
5145 if (this.sections[i].options.readonly)
5148 for (var f in this.sections[i].fields)
5150 if (typeof(this.sections[i].fields[f].save) != 'function')
5153 var s = this.sections[i].sections();
5154 for (var j = 0; j < s.length; j++)
5156 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5157 if (_luci2.deferred(rv))
5163 return $.when.apply($, deferreds);
5168 if (!this.validate())
5169 return _luci2.deferrable();
5171 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5174 if (this.uci.creates)
5175 for (var c in this.uci.creates)
5176 for (var s in this.uci.creates[c])
5183 for (var k in this.uci.creates[c][s])
5186 r.type = this.uci.creates[i][k];
5187 else if (k == '.create')
5188 r.name = this.uci.creates[i][k];
5189 else if (k.charAt(0) != '.')
5190 r.values[k] = this.uci.creates[i][k];
5192 requests.push(['uci', 'add', r]);
5195 if (this.uci.changes)
5196 for (var c in this.uci.changes)
5197 for (var s in this.uci.changes[c])
5198 requests.push(['uci', 'set', {
5201 values: this.uci.changes[c][s]
5204 if (this.uci.deletes)
5205 for (var c in this.uci.deletes)
5206 for (var s in this.uci.deletes[c])
5208 var o = this.uci.deletes[c][s];
5209 requests.push(['uci', 'delete', {
5212 options: (o === true) ? undefined : o
5216 return _luci2.rpc.call(requests);
5221 _luci2.ui.loading(true);
5223 return this.save().then(send_cb).then(function() {
5225 }).then(function() {
5229 _luci2.ui.loading(false);
5233 dialog: function(id)
5235 var d = $('<div />');
5239 .attr('src', _luci2.globals.resource + '/icons/loading.gif')
5240 .css('vertical-align', 'middle')
5241 .css('padding-right', '10px')
5244 p.append(_luci2.tr('Loading data...'));
5255 $(this).parent().children('.ui-dialog-titlebar').hide();
5260 insertInto: function(id)
5263 self.target = $(id);
5265 _luci2.ui.loading(true);
5268 return self.load().then(function() {
5269 self.target.empty().append(self.render());
5273 _luci2.ui.loading(false);