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')
437 sid: '00000000000000000000000000000000'
444 _wrap_msg: function(method, object, func, args)
446 if (typeof(args) != 'object')
450 id: _luci2.rpc._msg_id++,
453 params: (method == 'call') ? [ _luci2.globals.sid, object, func, args ] : object
457 _parse_response: function(keys, priv)
459 return function(data) {
462 obj = $.parseJSON(data);
465 if (typeof(obj) != 'object')
468 /* is a batched response */
472 for (var i = 0; i < obj.length; i++)
474 var p = (typeof(priv) != 'undefined') ? priv[i] : undefined;
476 if ($.isArray(obj[i].result) && typeof(priv) != 'undefined')
477 obj[i].result[2] = p;
479 if (obj[i].jsonrpc != '2.0' || obj[i].error || !obj[i].result)
480 rv[keys[i]] = [ 4 /* UBUS_STATUS_NO_DATA */, undefined, p ];
482 rv[keys[i]] = obj[i].result;
487 if (obj.jsonrpc != '2.0' || obj.error || !obj.result)
488 return [ 4 /* UBUS_STATUS_NO_DATA */, undefined, priv ];
490 if ($.isArray(obj.result) && typeof(priv) != 'undefined')
491 obj.result[2] = priv;
497 _post_msg: function(message, cb, keys, priv)
499 return $.ajax('/ubus', {
501 contentType: 'application/json',
502 data: JSON.stringify(message),
503 dataFilter: _luci2.rpc._parse_response(keys, priv),
510 _post_single: function(object, method, args, cb, priv)
512 var msg = _luci2.rpc._wrap_msg('call', object, method, args, priv);
513 return _luci2.rpc._post_msg(msg, cb, undefined, priv);
516 _post_batch: function(methods, cb)
518 if (typeof(methods) != 'object')
525 for (var k in methods)
527 if (typeof(methods[k]) != 'object' || methods[k].length < 2)
531 priv.push(methods[k][3]);
532 msgs.push(_luci2.rpc._wrap_msg('call', methods[k][0], methods[k][1], methods[k][2]));
536 return _luci2.rpc._post_msg(msgs, cb, keys, priv);
538 return _luci2.deferrable([ ]);
544 if (typeof a[0] == 'string')
545 return _luci2.rpc._post_single(a[0], a[1], a[2], a[3], a[4]);
547 return _luci2.rpc._post_batch(a[0], a[1]);
550 list: function(objects)
552 var msg = _luci2.rpc._wrap_msg('list', objects);
553 return _luci2.rpc._post_msg(msg);
556 access: function(scope, object, method, cb)
558 return _luci2.rpc._post_single('session', 'access', {
559 'sid': _luci2.globals.sid,
564 return retcb(cb, (rv[0] == 0 && rv[1] && rv[1].access == true));
571 writable: function(cb)
573 return _luci2.rpc.access('ubus', 'uci', 'commit', cb);
576 add: function(config, type, cb)
578 return rcall('uci', 'add', { config: config, type: type }, 'section', '', cb);
586 changes: function(config)
588 return rcall('uci', 'changes', { config: config }, 'changes', [ ], cb);
591 commit: function(config)
593 return rcall('uci', 'commit', { config: config }, undefined, undefined, cb);
596 'delete': function(config, section, option)
598 var req = { config: config, section: section };
600 if (isa(option, 'Array'))
601 req.options = option;
605 return rcall('uci', 'delete', req, undefined, undefined, cb);
608 delete_all: function(config, type, matches)
610 return rcall('uci', 'delete', { config: config, type: type, match: matches }, undefined, undefined, cb);
613 foreach: function(config, type, cb)
615 return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
616 for (var s in sections)
621 get: function(config, section, option, cb)
623 return rcall('uci', 'get', { config: config, section: section, option: option }, undefined, { }, function(res) {
624 if (typeof(option) == 'undefined')
625 return retcb(cb, (res.values && res.values['.type']) ? res.values['.type'] : undefined);
627 return retcb(cb, res.value);
631 get_all: function(config, section, cb)
633 return rcall('uci', 'get', { config: config, section: section }, 'values', { }, cb);
636 get_first: function(config, type, option, cb)
638 return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
639 for (var s in sections)
641 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
643 if (typeof(val) != 'undefined')
644 return retcb(cb, val);
647 return retcb(cb, undefined);
651 section: function(config, type, name, values, cb)
653 return rcall('uci', 'add', { config: config, type: type, name: name, values: values }, 'section', undefined, cb);
656 set: function(config, section, option, value, cb)
658 if (typeof(value) == 'undefined' && typeof(option) == 'string')
659 return rcall('uci', 'add', { config: config, section: section, type: option }, undefined, undefined, cb);
660 else if (isa(option, 'Object'))
661 return rcall('uci', 'set', { config: config, section: section, values: option }, undefined, undefined, cb);
665 values[option] = value;
667 return rcall('uci', 'set', { config: config, section: section, values: values }, undefined, undefined, cb);
670 order: function(config, sections, cb)
672 return rcall('uci', 'order', { config: config, sections: sections }, undefined, undefined, cb);
677 getNetworkStatus: function(cb)
680 var assign = function(target, key)
682 return function(value) {
683 if (typeof(value) != 'undefined' && !$.isEmptyObject(value))
688 return _luci2.rpc.list().then(function(data) {
691 for (var i = 0; i < data.length; i++)
693 if (data[i].indexOf('network.interface.') != 0)
696 var ifname = data[i].substring(18);
697 if (ifname == 'loopback')
700 var iface = { 'name': ifname };
703 requests.push(['network.interface', 'status', { 'interface': ifname }, iface]);
706 return _luci2.rpc.call(requests, function(responses) {
707 for (var key in responses)
708 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
709 $.extend(responses[key][2], responses[key][1]);
714 for (var i = 0; i < ifaces.length; i++)
716 var iface = ifaces[i];
718 var dev = iface.l3_device || iface.l2_device;
722 iface.device = { 'name': dev };
723 requests[dev] = ['network.device', 'status', { 'name': dev }, iface.device];
726 return _luci2.rpc.call(requests, function(responses) {
727 for (var key in responses)
728 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
729 $.extend(responses[key][2], responses[key][1]);
734 for (var i = 0; i < ifaces.length; i++)
736 var iface = ifaces[i];
740 var subdevs = iface.device['bridge-members'];
744 iface.subdevices = [ ];
745 for (var j = 0; j < subdevs.length; j++)
747 iface.subdevices[j] = { 'name': subdevs[j] };
748 requests.push(['network.device', 'status', { 'name': subdevs[j] }, iface.subdevices[j]]);
752 return _luci2.rpc.call(requests, function(responses) {
753 for (var key in responses)
754 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
755 $.extend(responses[key][2], responses[key][1]);
760 for (var i = 0; i < ifaces.length; i++)
762 var iface = ifaces[i];
765 requests.push(['iwinfo', 'info', { 'device': iface.device.name }, iface.device]);
767 if (iface.subdevices)
768 for (var j = 0; j < iface.subdevices.length; j++)
769 requests.push(['iwinfo', 'info', { 'device': iface.subdevices[j].name }, iface.subdevices[j]]);
772 return _luci2.rpc.call(requests, function(responses) {
773 for (var key in responses)
774 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
775 if (!$.isEmptyObject(responses[key][1]))
776 responses[key][2].wireless = responses[key][1];
779 ifaces.sort(function(a, b) {
780 if (a['interface'] < b['interface'])
782 else if (a['interface'] > b['interface'])
787 return retcb(cb, ifaces);
791 findWanInterfaces: function(cb)
793 return _luci2.rpc.list().then(function(data) {
795 for (var i = 0; i < data.length; i++)
797 if (data[i].indexOf('network.interface.') == 0)
799 var ifname = data[i].substring(18);
800 requests[ifname] = ['network.interface', 'status', { 'interface': ifname }];
803 return _luci2.rpc.call(requests);
804 }).then(function(responses) {
806 for (var ifname in responses)
808 var response = responses[ifname];
810 if (response[0] != 0 || !response[1] || !response[1].route)
813 for (var rn = 0, rt = response[1].route[rn];
814 rn < response[1].route.length;
815 rn++, rt = response[1].route[rn])
817 if (typeof(rt.table) != 'undefined')
820 if (rt.target == '0.0.0.0' && rt.mask == 0)
822 else if (rt.target == '::' && rt.mask == 0)
827 return retcb(cb, rv);
831 getDHCPLeases: function(cb)
833 return rcall('luci2.network', 'dhcp_leases', undefined, 'leases', [ ], cb);
836 getDHCPv6Leases: function(cb)
838 return rcall('luci2.network', 'dhcp6_leases', undefined, 'leases', [ ], cb);
841 getRoutes: function(cb)
843 return rcall('luci2.network', 'routes', undefined, 'routes', [ ], cb);
846 getIPv6Routes: function(cb)
848 return rcall('luci2.network', 'routes6', undefined, 'routes', [ ], cb);
851 getARPTable: function(cb)
853 return rcall('luci2.network', 'arp_table', undefined, 'entries', [ ], cb);
856 getInterfaceStatus: function(iface, cb)
858 return rcall('network.interface', 'status', { 'interface': iface }, undefined, { }, cb, function(rv) {
859 rv['interface'] = iface;
860 rv['l2_device'] = rv['device'];
865 getDeviceStatus: function(dev, cb)
867 return rcall('network.device', 'status', { name: dev }, undefined, { }, cb, function(rv) {
868 if (typeof(dev) == 'string')
874 getConntrackCount: function(cb)
876 return rcall('luci2.network', 'conntrack_count', undefined, undefined, {
884 getDevices: function(cb) {
885 return rcall('iwinfo', 'devices', undefined, 'devices', [ ], cb, function(rv) {
891 getInfo: function(dev, cb) {
892 var parse_info = function(device, info, rv)
899 var phy = rv[info.phy];
902 'country', 'channel', 'frequency', 'frequency_offset',
903 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
907 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
908 'signal', 'noise', 'bitrate', 'encryption'
911 for (var i = 0; i < phy_attrs.length; i++)
912 phy[phy_attrs[i]] = info[phy_attrs[i]];
918 for (var i = 0; i < net_attrs.length; i++)
919 net[net_attrs[i]] = info[net_attrs[i]];
921 phy.networks.push(net);
928 return _luci2.wireless.getDevices().then(function(devices) {
931 for (var i = 0; i < devices.length; i++)
933 if (devices[i].indexOf('.sta') >= 0)
936 requests[devices[i]] = [ 'iwinfo', 'info', { device: devices[i] } ];
939 return _luci2.rpc.call(requests);
940 }).then(function(responses) {
943 for (var device in responses)
945 var response = responses[device];
947 if (response[0] != 0 || !response[1])
950 parse_info(device, response[1], rv);
953 return retcb(cb, rv);
957 return _luci2.rpc.call('iwinfo', 'info', { device: dev }).then(function(response) {
958 if (response[0] != 0 || !response[1])
959 return retcb(cb, { });
961 return retcb(cb, parse_info(dev, response[1], { }));
965 getAssocList: function(dev, cb)
969 return _luci2.wireless.getDevices().then(function(devices) {
972 for (var i = 0; i < devices.length; i++)
974 if (devices[i].indexOf('.sta') >= 0)
977 requests[devices[i]] = [ 'iwinfo', 'assoclist', { device: devices[i] } ];
980 return _luci2.rpc.call(requests);
981 }).then(function(responses) {
984 for (var device in responses)
986 var response = responses[device];
988 if (response[0] != 0 || !response[1] || !response[1].results)
991 for (var i = 0; i < response[1].results.length; i++)
993 var station = response[1].results[i];
995 station.device = device;
1000 rv.sort(function(a, b) {
1001 return (a.device == b.device)
1002 ? (a.bssid < b.bssid)
1003 : (a.device > b.device)
1007 return retcb(cb, rv);
1011 return _luci2.rpc.call('iwinfo', 'assoclist', { device: dev }).then(function(response) {
1014 if (response[0] != 0 || !response[1] || !response[1].results)
1015 return retcb(cb, rv);
1017 for (var i = 0; i < response[1].results.length; i++)
1019 var station = response[1].results[i];
1021 station.device = dev;
1025 rv.sort(function(a, b) {
1026 return (a.bssid < b.bssid);
1029 return retcb(cb, rv);
1033 formatEncryption: function(enc)
1035 var format_list = function(l, s)
1038 for (var i = 0; i < l.length; i++)
1039 rv.push(l[i].toUpperCase());
1040 return rv.join(s ? s : ', ');
1043 if (!enc || !enc.enabled)
1044 return _luci2.tr('None');
1048 if (enc.wep.length == 2)
1049 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1050 else if (enc.wep[0] == 'shared')
1051 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1053 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1057 if (enc.wpa.length == 2)
1058 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1059 format_list(enc.authentication, '/'),
1060 format_list(enc.ciphers, ', ')
1062 else if (enc.wpa[0] == 2)
1063 return 'WPA2 %s (%s)'.format(
1064 format_list(enc.authentication, '/'),
1065 format_list(enc.ciphers, ', ')
1068 return 'WPA %s (%s)'.format(
1069 format_list(enc.authentication, '/'),
1070 format_list(enc.ciphers, ', ')
1074 return _luci2.tr('Unknown');
1079 getInfo: function(cb)
1081 return _luci2.rpc.call({
1082 info: [ 'system', 'info', { } ],
1083 board: [ 'system', 'board', { } ],
1084 disk: [ 'luci2.system', 'diskfree', { } ]
1085 }).then(function(responses) {
1088 if (responses.info[0] == 0)
1089 $.extend(rv, responses.info[1]);
1091 if (responses.board[0] == 0)
1092 $.extend(rv, responses.board[1]);
1094 if (responses.disk[0] == 0)
1095 $.extend(rv, responses.disk[1]);
1097 return retcb(cb, rv);
1101 getProcessList: function(cb)
1103 return rcall('luci2.system', 'process_list', undefined, 'processes', [ ], cb, function(rv) {
1104 rv.sort(function(a, b) { return a.pid - b.pid });
1109 getSystemLog: function(cb)
1111 return rcall('luci2.system', 'syslog', undefined, 'log', '', cb);
1114 getKernelLog: function(cb)
1116 return rcall('luci2.system', 'dmesg', undefined, 'log', '', cb);
1119 getZoneInfo: function(cb)
1121 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1124 canSendSignal: function(cb)
1126 return _luci2.rpc.access('ubus', 'luci2.system', 'process_signal', cb);
1129 sendSignal: function(pid, sig, cb)
1131 return _luci2.rpc.call('luci2.system', 'process_signal', { pid: pid, signal: sig }).then(function(response) {
1132 return retcb(cb, response[0] == 0);
1136 initList: function(cb)
1138 return rcall('luci2.system', 'init_list', undefined, 'initscripts', [ ], cb, function(rv) {
1139 rv.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1144 initEnabled: function(init, cb)
1146 return this.initList(function(list) {
1147 for (var i = 0; i < list.length; i++)
1148 if (list[i].name == init)
1149 return retcb(cb, !!list[i].enabled);
1151 return retcb(cb, false);
1155 initRun: function(init, action, cb)
1157 return _luci2.rpc.call('luci2.system', 'init_action', { name: init, action: action }).then(function(response) {
1158 return retcb(cb, response[0] == 0);
1162 canInitRun: function(cb)
1164 return _luci2.rpc.access('ubus', 'luci2.system', 'init_action', cb);
1167 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1168 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1169 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1170 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1171 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1172 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1175 getRcLocal: function(cb)
1177 return rcall('luci2.system', 'rclocal_get', undefined, 'data', '', cb);
1180 setRcLocal: function(data, cb)
1182 return rcall('luci2.system', 'rclocal_set', { data: data }, undefined, undefined, cb);
1185 canSetRcLocal: function(cb)
1187 return _luci2.rpc.access('ubus', 'luci2.system', 'rclocal_set', cb);
1191 getCrontab: function(cb)
1193 return rcall('luci2.system', 'crontab_get', undefined, 'data', '', cb);
1196 setCrontab: function(data, cb)
1198 return rcall('luci2.system', 'crontab_set', { data: data }, undefined, undefined, cb);
1201 canSetCrontab: function(cb)
1203 return _luci2.rpc.access('ubus', 'luci2.system', 'crontab_set', cb);
1207 getSSHKeys: function(cb)
1209 return rcall('luci2.system', 'sshkeys_get', undefined, 'keys', [ ], cb);
1212 setSSHKeys: function(keys, cb)
1214 return rcall('luci2.system', 'sshkeys_set', { keys: keys }, undefined, undefined, cb);
1217 canSetSSHKeys: function(cb)
1219 return _luci2.rpc.access('ubus', 'luci2.system', 'sshkeys_set', cb);
1223 setPassword: function(user, pass, cb)
1225 return rcall('luci2.system', 'password_set', { user: user, password: pass }, undefined, undefined, cb);
1228 canSetPassword: function(cb)
1230 return _luci2.rpc.access('ubus', 'luci2.system', 'password_set', cb);
1234 listLEDs: function(cb)
1236 return rcall('luci2.system', 'led_list', undefined, 'leds', [ ], cb);
1239 listUSBDevices: function(cb)
1241 return rcall('luci2.system', 'usb_list', undefined, 'devices', [ ], cb);
1245 testUpgrade: function(cb)
1247 return rcall('luci2.system', 'upgrade_test', undefined, undefined, { }, cb);
1250 startUpgrade: function(keep, cb)
1252 return rcall('luci2.system', 'upgrade_start', { keep: !!keep }, undefined, undefined, cb);
1255 cleanUpgrade: function(cb)
1257 return rcall('luci2.system', 'upgrade_clean', undefined, undefined, undefined, cb);
1260 canUpgrade: function(cb)
1262 return _luci2.rpc.access('ubus', 'luci2.system', 'upgrade_start', cb);
1266 restoreBackup: function(cb)
1268 return rcall('luci2.system', 'backup_restore', undefined, undefined, undefined, cb);
1271 cleanBackup: function(cb)
1273 return rcall('luci2.system', 'backup_clean', undefined, undefined, undefined, cb);
1276 canRestoreBackup: function(cb)
1278 return _luci2.rpc.access('ubus', 'luci2.system', 'backup_restore', cb);
1282 getBackupConfig: function(cb)
1284 return rcall('luci2.system', 'backup_config_get', undefined, 'config', '', cb);
1287 setBackupConfig: function(data, cb)
1289 return rcall('luci2.system', 'backup_config_set', { data: data }, undefined, undefined, cb);
1292 canSetBackupConfig: function(cb)
1294 return _luci2.rpc.access('ubus', 'luci2.system', 'backup_config_set', cb);
1298 listBackup: function(cb)
1300 return rcall('luci2.system', 'backup_list', undefined, 'files', [ ], cb);
1304 performReboot: function(cb)
1306 return rcall('luci2.system', 'reboot', undefined, undefined, undefined, cb);
1309 canPerformReboot: function(cb)
1311 return _luci2.rpc.access('ubus', 'luci2.system', 'reboot', cb);
1316 updateLists: function(cb)
1318 return rcall('luci2.opkg', 'update', undefined, undefined, { }, cb);
1321 _fetchPackages: function(action, offset, limit, pattern, cb)
1324 var reqlimit = Math.min(limit, 100);
1329 return _luci2.rpc.call('luci2.opkg', action, { offset: offset, limit: reqlimit, pattern: pattern }).then(function(response) {
1330 if (response[0] != 0 || !response[1] || !response[1].total)
1331 return retcb(cb, { length: 0, total: 0 });
1333 packages.push.apply(packages, response[1].packages);
1334 packages.total = response[1].total;
1337 limit = response[1].total;
1339 if (packages.length >= limit)
1340 return retcb(cb, packages);
1343 for (var i = offset + packages.length; i < limit; i += 100)
1344 requests.push(['luci2.opkg', action, { offset: i, limit: (Math.min(i + 100, limit) % 100) || 100, pattern: pattern }]);
1346 return _luci2.rpc.call(requests);
1347 }).then(function(responses) {
1348 for (var key in responses)
1350 var response = responses[key];
1352 if (response[0] != 0 || !response[1] || !response[1].packages)
1355 packages.push.apply(packages, response[1].packages);
1356 packages.total = response[1].total;
1359 return retcb(cb, packages);
1363 listPackages: function(offset, limit, pattern, cb)
1365 return _luci2.opkg._fetchPackages('list', offset, limit, pattern, cb);
1368 installedPackages: function(offset, limit, pattern, cb)
1370 return _luci2.opkg._fetchPackages('list_installed', offset, limit, pattern, cb);
1373 findPackages: function(offset, limit, pattern, cb)
1375 return _luci2.opkg._fetchPackages('find', offset, limit, pattern, cb);
1378 installPackage: function(name, cb)
1380 return rcall('luci2.opkg', 'install', { 'package': name }, undefined, { }, cb);
1383 removePackage: function(name, cb)
1385 return rcall('luci2.opkg', 'remove', { 'package': name }, undefined, { }, cb);
1388 getConfig: function(cb)
1390 return rcall('luci2.opkg', 'config_get', undefined, 'config', '', cb);
1393 setConfig: function(data, cb)
1395 return rcall('luci2.opkg', 'config_set', { data: data }, undefined, undefined, cb);
1398 canInstallPackage: function(cb)
1400 return _luci2.rpc.access('ubus', 'luci2.opkg', 'install', cb);
1403 canRemovePackage: function(cb)
1405 return _luci2.rpc.access('ubus', 'luci2.opkg', 'remove', cb);
1408 canSetConfig: function(cb)
1410 return _luci2.rpc.access('ubus', 'luci2.opkg', 'config_set', cb);
1416 loading: function(enable)
1418 var win = $(window);
1419 var body = $('body');
1420 var div = _luci2._modal || (
1421 _luci2._modal = $('<div />')
1422 .addClass('cbi-modal-loader')
1423 .append($('<div />').text(_luci2.tr('Loading data...')))
1429 body.css('overflow', 'hidden');
1430 body.css('padding', 0);
1431 body.css('width', win.width());
1432 body.css('height', win.height());
1433 div.css('width', win.width());
1434 div.css('height', win.height());
1440 body.css('overflow', '');
1441 body.css('padding', '');
1442 body.css('width', '');
1443 body.css('height', '');
1447 dialog: function(title, content, options)
1449 var win = $(window);
1450 var body = $('body');
1451 var div = _luci2._dialog || (
1452 _luci2._dialog = $('<div />')
1453 .addClass('cbi-modal-dialog')
1454 .append($('<div />')
1455 .append($('<div />')
1456 .addClass('cbi-modal-dialog-header'))
1457 .append($('<div />')
1458 .addClass('cbi-modal-dialog-body'))
1459 .append($('<div />')
1460 .addClass('cbi-modal-dialog-footer')
1461 .append($('<button />')
1462 .addClass('cbi-button')
1463 .text(_luci2.tr('Close'))
1466 .css('overflow', '')
1471 $(this).parent().parent().parent().hide();
1476 if (typeof(options) != 'object')
1479 if (title === false)
1482 .css('overflow', '')
1487 _luci2._dialog.hide();
1492 var cnt = div.children().children('div.cbi-modal-dialog-body');
1493 var ftr = div.children().children('div.cbi-modal-dialog-footer');
1497 if (options.style == 'confirm')
1499 ftr.append($('<button />')
1500 .addClass('cbi-button')
1501 .text(_luci2.tr('Ok'))
1502 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1504 ftr.append($('<button />')
1505 .addClass('cbi-button')
1506 .text(_luci2.tr('Cancel'))
1507 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1509 else if (options.style == 'close')
1511 ftr.append($('<button />')
1512 .addClass('cbi-button')
1513 .text(_luci2.tr('Close'))
1514 .click(options.close || function() { _luci2.ui.dialog(false) }));
1516 else if (options.style == 'wait')
1518 ftr.append($('<button />')
1519 .addClass('cbi-button')
1520 .text(_luci2.tr('Close'))
1521 .attr('disabled', true));
1524 div.find('div.cbi-modal-dialog-header').text(title);
1528 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1533 .css('margin-top', -Math.floor(div.children().height() / 2) + 'px');
1535 body.css('overflow', 'hidden');
1536 body.css('padding', 0);
1537 body.css('width', win.width());
1538 body.css('height', win.height());
1539 div.css('width', win.width());
1540 div.css('height', win.height());
1543 upload: function(title, content, options)
1545 var form = _luci2._upload || (
1546 _luci2._upload = $('<form />')
1547 .attr('method', 'post')
1548 .attr('action', '/cgi-bin/luci-upload')
1549 .attr('enctype', 'multipart/form-data')
1550 .attr('target', 'cbi-fileupload-frame')
1552 .append($('<input />')
1553 .attr('type', 'hidden')
1554 .attr('name', 'sessionid')
1555 .attr('value', _luci2.globals.sid))
1556 .append($('<input />')
1557 .attr('type', 'hidden')
1558 .attr('name', 'filename')
1559 .attr('value', options.filename))
1560 .append($('<input />')
1561 .attr('type', 'file')
1562 .attr('name', 'filedata')
1563 .addClass('cbi-input-file'))
1564 .append($('<div />')
1565 .css('width', '100%')
1566 .addClass('progressbar')
1567 .addClass('intermediate')
1568 .append($('<div />')
1569 .css('width', '100%')))
1570 .append($('<iframe />')
1571 .attr('name', 'cbi-fileupload-frame')
1572 .css('width', '1px')
1573 .css('height', '1px')
1574 .css('visibility', 'hidden'))
1577 var finish = _luci2._upload_finish_cb || (
1578 _luci2._upload_finish_cb = function(ev) {
1579 $(this).off('load');
1581 var body = (this.contentDocument || this.contentWindow.document).body;
1582 if (body.firstChild.tagName.toLowerCase() == 'pre')
1583 body = body.firstChild;
1587 json = $.parseJSON(body.innerHTML);
1590 message: _luci2.tr('Invalid server response received'),
1591 error: [ -1, _luci2.tr('Invalid data') ]
1597 L.ui.dialog(L.tr('File upload'), [
1598 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1599 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1600 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1601 ], { style: 'close' });
1603 else if (typeof(ev.data.cb) == 'function')
1610 var confirm = _luci2._upload_confirm_cb || (
1611 _luci2._upload_confirm_cb = function() {
1612 var d = _luci2._upload;
1613 var f = d.find('.cbi-input-file');
1614 var b = d.find('.progressbar');
1615 var p = d.find('p');
1620 d.find('iframe').on('load', { cb: options.success }, finish);
1625 p.text(_luci2.tr('File upload in progress …'));
1627 _luci2._dialog.find('button').prop('disabled', true);
1631 _luci2._upload.find('.progressbar').hide();
1632 _luci2._upload.find('.cbi-input-file').val('').show();
1633 _luci2._upload.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1635 _luci2.ui.dialog(title || _luci2.tr('File upload'), _luci2._upload, {
1641 reconnect: function()
1643 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1644 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1645 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1647 var interval, timeout;
1650 _luci2.tr('Waiting for device'), [
1651 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1653 .css('width', '100%')
1654 .addClass('progressbar')
1655 .addClass('intermediate')
1656 .append($('<div />')
1657 .css('width', '100%'))
1658 ], { style: 'wait' }
1661 for (var i = 0; i < protocols.length; i++)
1662 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1664 //_luci2.network.getNetworkStatus(function(s) {
1665 // for (var i = 0; i < protocols.length; i++)
1667 // for (var j = 0; j < s.length; j++)
1669 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1670 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1672 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1673 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1676 //}).then(function() {
1677 images.on('load', function() {
1678 var url = this.getAttribute('url');
1679 _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1680 if (response[0] == 0)
1682 window.clearTimeout(timeout);
1683 window.clearInterval(interval);
1684 _luci2.ui.dialog(false);
1689 location.href = url;
1694 interval = window.setInterval(function() {
1695 images.each(function() {
1696 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1700 timeout = window.setTimeout(function() {
1701 window.clearInterval(interval);
1705 _luci2.tr('Device not responding'),
1706 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1713 login: function(invalid)
1715 if (!_luci2._login_deferred || _luci2._login_deferred.state() != 'pending')
1716 _luci2._login_deferred = $.Deferred();
1718 /* try to find sid from hash */
1719 var sid = _luci2.getHash('id');
1720 if (sid && sid.match(/^[a-f0-9]{32}$/))
1722 _luci2.globals.sid = sid;
1723 _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1724 if (response[0] == 0)
1726 _luci2._login_deferred.resolve();
1730 _luci2.setHash('id', undefined);
1735 return _luci2._login_deferred;
1738 var form = _luci2._login || (
1739 _luci2._login = $('<div />')
1741 .addClass('alert-message')
1742 .text(_luci2.tr('Wrong username or password given!')))
1744 .append($('<label />')
1745 .text(_luci2.tr('Username'))
1746 .append($('<br />'))
1747 .append($('<input />')
1748 .attr('type', 'text')
1749 .attr('name', 'username')
1750 .attr('value', 'root')
1751 .addClass('cbi-input-text'))))
1753 .append($('<label />')
1754 .text(_luci2.tr('Password'))
1755 .append($('<br />'))
1756 .append($('<input />')
1757 .attr('type', 'password')
1758 .attr('name', 'password')
1759 .addClass('cbi-input-password'))))
1761 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok'))))
1764 var response_cb = _luci2._login_response_cb || (
1765 _luci2._login_response_cb = function(response) {
1768 _luci2.ui.login(true);
1772 _luci2.globals.sid = response.sid;
1773 _luci2.setHash('id', _luci2.globals.sid);
1775 _luci2.ui.dialog(false);
1776 _luci2._login_deferred.resolve();
1781 var confirm_cb = _luci2._login_confirm_cb || (
1782 _luci2._login_confirm_cb = function() {
1783 var d = _luci2._login;
1784 var u = d.find('[name=username]').val();
1785 var p = d.find('[name=password]').val();
1791 _luci2.tr('Logging in'), [
1792 $('<p />').text(_luci2.tr('Log in in progress …')),
1794 .css('width', '100%')
1795 .addClass('progressbar')
1796 .addClass('intermediate')
1797 .append($('<div />')
1798 .css('width', '100%'))
1799 ], { style: 'wait' }
1802 rcall('session', 'login', { username: u, password: p }, undefined, { }, response_cb);
1807 form.find('.alert-message').show();
1809 form.find('.alert-message').hide();
1811 _luci2.ui.dialog(_luci2.tr('Authorization Required'), form, {
1816 return _luci2._login_deferred;
1819 renderMainMenu: function()
1821 return rcall('luci2.ui', 'menu', undefined, 'menu', { }, function(entries) {
1822 _luci2.globals.mainMenu = new _luci2.ui.menu();
1823 _luci2.globals.mainMenu.entries(entries);
1827 .append(_luci2.globals.mainMenu.render(0, 1));
1831 renderViewMenu: function()
1835 .append(_luci2.globals.mainMenu.render(2, 900));
1838 renderView: function(node)
1840 var name = node.view.split(/\//).join('.');
1842 _luci2.ui.renderViewMenu();
1845 _luci2._views = { };
1847 _luci2.setHash('view', node.view);
1849 if (_luci2._views[name] instanceof _luci2.ui.view)
1850 return _luci2._views[name].render();
1852 return $.ajax(_luci2.globals.resource + '/view/' + name + '.js', {
1856 }).then(function(data) {
1858 var viewConstructor = (new Function(['L', '$'], 'return ' + data))(_luci2, $);
1860 _luci2._views[name] = new viewConstructor({
1862 acls: node.write || { }
1865 return _luci2._views[name].render();
1869 return $.Deferred().resolve();
1875 _luci2.ui.loading(true);
1878 _luci2.ui.renderMainMenu()
1880 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
1881 _luci2.ui.loading(false);
1887 var AbstractWidget = Class.extend({
1888 i18n: function(text) {
1892 toString: function() {
1893 var x = document.createElement('div');
1894 x.appendChild(this.render());
1899 insertInto: function(id) {
1900 return $(id).empty().append(this.render());
1904 this.ui.view = AbstractWidget.extend({
1905 _fetch_template: function()
1907 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
1911 success: function(data) {
1912 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
1913 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
1920 return _luci2.tr(p2);
1923 return _luci2.globals[p2] || '';
1926 return '(?' + match + ')';
1930 $('#maincontent').append(data);
1937 throw "Not implemented";
1942 var container = $('#maincontent');
1947 container.append($('<h2 />').append(this.title));
1949 if (this.description)
1950 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
1953 return this._fetch_template().then(function() {
1954 return _luci2.deferrable(self.execute());
1959 this.ui.menu = AbstractWidget.extend({
1964 entries: function(entries)
1966 for (var entry in entries)
1968 var path = entry.split(/\//);
1969 var node = this._nodes;
1971 for (i = 0; i < path.length; i++)
1976 if (!node.childs[path[i]])
1977 node.childs[path[i]] = { };
1979 node = node.childs[path[i]];
1982 $.extend(node, entries[entry]);
1986 _indexcmp: function(a, b)
1988 var x = a.index || 0;
1989 var y = b.index || 0;
1993 firstChildView: function(node)
1999 for (var child in (node.childs || { }))
2000 nodes.push(node.childs[child]);
2002 nodes.sort(this._indexcmp);
2004 for (var i = 0; i < nodes.length; i++)
2006 var child = this.firstChildView(nodes[i]);
2009 $.extend(node, child);
2017 _onclick: function(ev)
2019 _luci2.ui.loading(true);
2020 _luci2.ui.renderView(ev.data).then(function() {
2021 _luci2.ui.loading(false);
2024 ev.preventDefault();
2028 _render: function(childs, level, min, max)
2031 for (var node in childs)
2033 var child = this.firstChildView(childs[node]);
2035 nodes.push(childs[node]);
2038 nodes.sort(this._indexcmp);
2040 var list = $('<ul />');
2043 list.addClass('nav');
2044 else if (level == 1)
2045 list.addClass('dropdown-menu');
2047 for (var i = 0; i < nodes.length; i++)
2049 if (!_luci2.globals.defaultNode)
2051 var v = _luci2.getHash('view');
2052 if (!v || v == nodes[i].view)
2053 _luci2.globals.defaultNode = nodes[i];
2056 var item = $('<li />')
2059 .text(_luci2.tr(nodes[i].title))
2060 .click(nodes[i], this._onclick))
2063 if (nodes[i].childs && level < max)
2065 item.addClass('dropdown');
2066 item.find('a').addClass('menu');
2067 item.append(this._render(nodes[i].childs, level + 1));
2074 render: function(min, max)
2076 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2077 return this._render(top.childs, 0, min, max);
2080 getNode: function(path, max)
2082 var p = path.split(/\//);
2083 var n = this._nodes;
2085 if (typeof(max) == 'undefined')
2088 for (var i = 0; i < max; i++)
2090 if (!n.childs[p[i]])
2100 this.ui.table = AbstractWidget.extend({
2106 row: function(values)
2108 if (isa(values, 'Array'))
2110 this._rows.push(values);
2112 else if (isa(values, 'Object'))
2115 for (var i = 0; i < this.options.columns.length; i++)
2117 var col = this.options.columns[i];
2119 if (typeof col.key == 'string')
2120 v.push(values[col.key]);
2128 rows: function(rows)
2130 for (var i = 0; i < rows.length; i++)
2134 render: function(id)
2136 var fieldset = document.createElement('fieldset');
2137 fieldset.className = 'cbi-section';
2139 if (this.options.caption)
2141 var legend = document.createElement('legend');
2142 $(legend).append(this.options.caption);
2143 fieldset.appendChild(legend);
2146 var table = document.createElement('table');
2147 table.className = 'cbi-section-table';
2149 var has_caption = false;
2150 var has_description = false;
2152 for (var i = 0; i < this.options.columns.length; i++)
2153 if (this.options.columns[i].caption)
2158 else if (this.options.columns[i].description)
2160 has_description = true;
2166 var tr = table.insertRow(-1);
2167 tr.className = 'cbi-section-table-titles';
2169 for (var i = 0; i < this.options.columns.length; i++)
2171 var col = this.options.columns[i];
2172 var th = document.createElement('th');
2173 th.className = 'cbi-section-table-cell';
2178 th.style.width = col.width;
2181 th.style.textAlign = col.align;
2184 $(th).append(col.caption);
2188 if (has_description)
2190 var tr = table.insertRow(-1);
2191 tr.className = 'cbi-section-table-descr';
2193 for (var i = 0; i < this.options.columns.length; i++)
2195 var col = this.options.columns[i];
2196 var th = document.createElement('th');
2197 th.className = 'cbi-section-table-cell';
2202 th.style.width = col.width;
2205 th.style.textAlign = col.align;
2207 if (col.description)
2208 $(th).append(col.description);
2212 if (this._rows.length == 0)
2214 if (this.options.placeholder)
2216 var tr = table.insertRow(-1);
2217 var td = tr.insertCell(-1);
2218 td.className = 'cbi-section-table-cell';
2220 td.colSpan = this.options.columns.length;
2221 $(td).append(this.options.placeholder);
2226 for (var i = 0; i < this._rows.length; i++)
2228 var tr = table.insertRow(-1);
2230 for (var j = 0; j < this.options.columns.length; j++)
2232 var col = this.options.columns[j];
2233 var td = tr.insertCell(-1);
2235 var val = this._rows[i][j];
2237 if (typeof(val) == 'undefined')
2238 val = col.placeholder;
2240 if (typeof(val) == 'undefined')
2244 td.style.width = col.width;
2247 td.style.textAlign = col.align;
2249 if (typeof col.format == 'string')
2250 $(td).append(col.format.format(val));
2251 else if (typeof col.format == 'function')
2252 $(td).append(col.format(val, i));
2260 fieldset.appendChild(table);
2266 this.ui.progress = AbstractWidget.extend({
2269 var vn = parseInt(this.options.value) || 0;
2270 var mn = parseInt(this.options.max) || 100;
2271 var pc = Math.floor((100 / mn) * vn);
2273 var bar = document.createElement('div');
2274 bar.className = 'progressbar';
2276 bar.appendChild(document.createElement('div'));
2277 bar.lastChild.appendChild(document.createElement('div'));
2278 bar.lastChild.style.width = pc + '%';
2280 if (typeof(this.options.format) == 'string')
2281 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2282 else if (typeof(this.options.format) == 'function')
2283 $(bar.lastChild.lastChild).append(this.options.format(pc));
2285 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2291 this.ui.devicebadge = AbstractWidget.extend({
2294 var dev = this.options.l3_device || this.options.device || '?';
2296 var span = document.createElement('span');
2297 span.className = 'ifacebadge';
2299 if (typeof(this.options.signal) == 'number' ||
2300 typeof(this.options.noise) == 'number')
2303 if (typeof(this.options.signal) != 'undefined' &&
2304 typeof(this.options.noise) != 'undefined')
2306 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2319 span.appendChild(document.createElement('img'));
2320 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2323 span.title = _luci2.tr('No signal');
2325 span.title = '%s: %d %s / %s: %d %s'.format(
2326 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2327 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2332 var type = 'ethernet';
2333 var desc = _luci2.tr('Ethernet device');
2335 if (this.options.l3_device != this.options.device)
2338 desc = _luci2.tr('Tunnel interface');
2340 else if (dev.indexOf('br-') == 0)
2343 desc = _luci2.tr('Bridge');
2345 else if (dev.indexOf('.') > 0)
2348 desc = _luci2.tr('VLAN interface');
2350 else if (dev.indexOf('wlan') == 0 ||
2351 dev.indexOf('ath') == 0 ||
2352 dev.indexOf('wl') == 0)
2355 desc = _luci2.tr('Wireless Network');
2358 span.appendChild(document.createElement('img'));
2359 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2363 $(span).append(' ');
2364 $(span).append(dev);
2370 var type = function(f, l)
2380 _luci2.cbi.validation.message = _luci2.tr(msg);
2383 compile: function(code)
2388 var types = _luci2.cbi.validation.types;
2393 for (var i = 0; i < code.length; i++)
2401 switch (code.charCodeAt(i))
2413 var label = code.substring(pos, i);
2414 label = label.replace(/\\(.)/g, '$1');
2415 label = label.replace(/^[ \t]+/g, '');
2416 label = label.replace(/[ \t]+$/g, '');
2418 if (label && !isNaN(label))
2420 stack.push(parseFloat(label));
2422 else if (label.match(/^(['"]).*\1$/))
2424 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2426 else if (typeof types[label] == 'function')
2428 stack.push(types[label]);
2433 throw "Syntax error, unhandled token '"+label+"'";
2438 depth += (code.charCodeAt(i) == 40);
2444 if (typeof stack[stack.length-2] != 'function')
2445 throw "Syntax error, argument list follows non-function";
2447 stack[stack.length-1] =
2448 arguments.callee(code.substring(pos, i));
2461 var validation = this.cbi.validation;
2463 validation.types = {
2464 'integer': function()
2466 if (this.match(/^-?[0-9]+$/) != null)
2469 validation.i18n('Must be a valid integer');
2473 'uinteger': function()
2475 if (validation.types['integer'].apply(this) && (this >= 0))
2478 validation.i18n('Must be a positive integer');
2484 if (!isNaN(parseFloat(this)))
2487 validation.i18n('Must be a valid number');
2491 'ufloat': function()
2493 if (validation.types['float'].apply(this) && (this >= 0))
2496 validation.i18n('Must be a positive number');
2500 'ipaddr': function()
2502 if (validation.types['ip4addr'].apply(this) ||
2503 validation.types['ip6addr'].apply(this))
2506 validation.i18n('Must be a valid IP address');
2510 'ip4addr': function()
2512 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2514 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2515 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2516 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2517 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2518 ((RegExp.$6.indexOf('.') < 0)
2519 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2520 : (validation.types['ip4addr'].apply(RegExp.$6))))
2524 validation.i18n('Must be a valid IPv4 address');
2528 'ip6addr': function()
2530 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2532 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2534 var addr = RegExp.$1;
2541 if (addr.indexOf('.') > 0)
2543 var off = addr.lastIndexOf(':');
2545 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2547 validation.i18n('Must be a valid IPv6 address');
2551 addr = addr.substr(0, off) + ':0:0';
2554 if (addr.indexOf('::') >= 0)
2559 for (var i = 1; i < (addr.length-1); i++)
2560 if (addr.charAt(i) == ':')
2565 validation.i18n('Must be a valid IPv6 address');
2569 for (var i = 0; i < (7 - colons); i++)
2572 if (addr.match(/^(.*?)::(.*?)$/))
2573 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2574 (RegExp.$2 ? ':' + RegExp.$2 : '');
2577 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2580 validation.i18n('Must be a valid IPv6 address');
2590 if (validation.types['integer'].apply(this) &&
2591 (this >= 0) && (this <= 65535))
2594 validation.i18n('Must be a valid port number');
2598 'portrange': function()
2600 if (this.match(/^(\d+)-(\d+)$/))
2605 if (validation.types['port'].apply(p1) &&
2606 validation.types['port'].apply(p2) &&
2607 (parseInt(p1) <= parseInt(p2)))
2610 else if (validation.types['port'].apply(this))
2615 validation.i18n('Must be a valid port range');
2619 'macaddr': function()
2621 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2624 validation.i18n('Must be a valid MAC address');
2630 if (validation.types['hostname'].apply(this) ||
2631 validation.types['ipaddr'].apply(this))
2634 validation.i18n('Must be a valid hostname or IP address');
2638 'hostname': function()
2640 if ((this.length <= 253) &&
2641 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2642 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2643 this.match(/[^0-9.]/)))))
2646 validation.i18n('Must be a valid host name');
2650 'network': function()
2652 if (validation.types['uciname'].apply(this) ||
2653 validation.types['host'].apply(this))
2656 validation.i18n('Must be a valid network name');
2660 'wpakey': function()
2664 if ((v.length == 64)
2665 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2666 : ((v.length >= 8) && (v.length <= 63)))
2669 validation.i18n('Must be a valid WPA key');
2673 'wepkey': function()
2677 if (v.substr(0,2) == 's:')
2680 if (((v.length == 10) || (v.length == 26))
2681 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2682 : ((v.length == 5) || (v.length == 13)))
2685 validation.i18n('Must be a valid WEP key');
2689 'uciname': function()
2691 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2694 validation.i18n('Must be a valid UCI identifier');
2698 'range': function(min, max)
2700 var val = parseFloat(this);
2702 if (validation.types['integer'].apply(this) &&
2703 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
2706 validation.i18n('Must be a number between %d and %d');
2710 'min': function(min)
2712 var val = parseFloat(this);
2714 if (validation.types['integer'].apply(this) &&
2715 !isNaN(min) && !isNaN(val) && (val >= min))
2718 validation.i18n('Must be a number greater or equal to %d');
2722 'max': function(max)
2724 var val = parseFloat(this);
2726 if (validation.types['integer'].apply(this) &&
2727 !isNaN(max) && !isNaN(val) && (val <= max))
2730 validation.i18n('Must be a number lower or equal to %d');
2734 'rangelength': function(min, max)
2736 var val = '' + this;
2738 if (!isNaN(min) && !isNaN(max) &&
2739 (val.length >= min) && (val.length <= max))
2742 validation.i18n('Must be between %d and %d characters');
2746 'minlength': function(min)
2748 var val = '' + this;
2750 if (!isNaN(min) && (val.length >= min))
2753 validation.i18n('Must be at least %d characters');
2757 'maxlength': function(max)
2759 var val = '' + this;
2761 if (!isNaN(max) && (val.length <= max))
2764 validation.i18n('Must be at most %d characters');
2772 for (var i = 0; i < arguments.length; i += 2)
2774 delete validation.message;
2776 if (typeof(arguments[i]) != 'function')
2778 if (arguments[i] == this)
2782 else if (arguments[i].apply(this, arguments[i+1]))
2787 if (validation.message)
2788 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2791 validation.message = msgs.join( _luci2.tr(' - or - '));
2799 for (var i = 0; i < arguments.length; i += 2)
2801 delete validation.message;
2803 if (typeof arguments[i] != 'function')
2805 if (arguments[i] != this)
2809 else if (!arguments[i].apply(this, arguments[i+1]))
2814 if (validation.message)
2815 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2818 validation.message = msgs.join(', ');
2824 return validation.types['or'].apply(
2825 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
2828 'list': function(subvalidator, subargs)
2830 if (typeof subvalidator != 'function')
2833 var tokens = this.match(/[^ \t]+/g);
2834 for (var i = 0; i < tokens.length; i++)
2835 if (!subvalidator.apply(tokens[i], subargs))
2841 'phonedigit': function()
2843 if (this.match(/^[0-9\*#!\.]+$/) != null)
2846 validation.i18n('Must be a valid phone number digit');
2850 'string': function()
2857 var AbstractValue = AbstractWidget.extend({
2858 init: function(name, options)
2861 this.instance = { };
2862 this.dependencies = [ ];
2863 this.rdependency = { };
2865 this.options = _luci2.defaults(options, {
2875 return this.section.id('field', sid || '__unknown__', this.name);
2878 render: function(sid)
2880 var i = this.instance[sid] = { };
2882 i.top = $('<div />').addClass('cbi-value');
2884 if (typeof(this.options.caption) == 'string')
2886 .addClass('cbi-value-title')
2887 .attr('for', this.id(sid))
2888 .text(this.options.caption)
2891 i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
2892 i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
2894 if (typeof(this.options.description) == 'string')
2896 .addClass('cbi-value-description')
2897 .text(this.options.description)
2903 ucipath: function(sid)
2906 config: (this.options.uci_package || this.map.uci_package),
2907 section: (this.options.uci_section || sid),
2908 option: (this.options.uci_option || this.name)
2912 ucivalue: function(sid)
2914 var uci = this.ucipath(sid);
2915 var val = this.map.get(uci.config, uci.section, uci.option);
2917 if (typeof(val) == 'undefined')
2918 return this.options.initial;
2923 formvalue: function(sid)
2925 var v = $('#' + this.id(sid)).val();
2926 return (v === '') ? undefined : v;
2929 textvalue: function(sid)
2931 var v = this.formvalue(sid);
2933 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
2934 v = this.ucivalue(sid);
2936 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
2937 v = this.options.placeholder;
2939 if (typeof(v) == 'undefined' || v === '')
2942 if (typeof(v) == 'string' && $.isArray(this.choices))
2944 for (var i = 0; i < this.choices.length; i++)
2945 if (v === this.choices[i][0])
2946 return this.choices[i][1];
2948 else if (v === true)
2949 return _luci2.tr('yes');
2950 else if (v === false)
2951 return _luci2.tr('no');
2952 else if ($.isArray(v))
2953 return v.join(', ');
2958 changed: function(sid)
2960 var a = this.ucivalue(sid);
2961 var b = this.formvalue(sid);
2963 if (typeof(a) != typeof(b))
2966 if (typeof(a) == 'object')
2968 if (a.length != b.length)
2971 for (var i = 0; i < a.length; i++)
2983 var uci = this.ucipath(sid);
2985 if (this.instance[sid].disabled)
2987 if (!this.options.keep)
2988 return this.map.set(uci.config, uci.section, uci.option, undefined);
2993 var chg = this.changed(sid);
2994 var val = this.formvalue(sid);
2997 this.map.set(uci.config, uci.section, uci.option, val);
3002 validator: function(sid, elem, multi)
3004 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3008 if (typeof(this.options.datatype) == 'string')
3011 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3014 else if (typeof(this.options.datatype) == 'function')
3016 var vfunc = this.options.datatype;
3017 vstack = [ function(elem) {
3018 var rv = vfunc(this, elem);
3020 validation.message = rv;
3021 return (rv === true);
3030 inst: this.instance[sid],
3031 opt: this.options.optional
3034 var validator = function(ev)
3038 var val = d.elem.val();
3040 if (vstack && typeof(vstack[0]) == 'function')
3042 delete validation.message;
3044 if ((val.length == 0 && !d.opt))
3046 d.elem.addClass('error');
3047 d.inst.top.addClass('error');
3048 d.inst.error.text(_luci2.tr('Field must not be empty'));
3051 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3053 d.elem.addClass('error');
3054 d.inst.top.addClass('error');
3055 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3060 d.elem.removeClass('error');
3062 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3068 d.inst.top.removeClass('error');
3069 d.inst.error.text('');
3076 for (var field in d.self.rdependency)
3077 d.self.rdependency[field].toggle(d.sid);
3083 if (elem.prop('tagName') == 'SELECT')
3085 elem.change(evdata, validator);
3087 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3089 elem.click(evdata, validator);
3090 elem.blur(evdata, validator);
3094 elem.keyup(evdata, validator);
3095 elem.blur(evdata, validator);
3098 elem.attr('cbi-validate', true).on('validate', evdata, validator);
3103 validate: function(sid)
3105 var i = this.instance[sid];
3107 i.widget.find('[cbi-validate]').trigger('validate');
3109 return (i.disabled || i.error.text() == '');
3112 depends: function(d, v)
3119 for (var i = 0; i < d.length; i++)
3121 if (typeof(d[i]) == 'string')
3123 else if (d[i] instanceof AbstractValue)
3124 dep[d[i].name] = true;
3127 else if (d instanceof AbstractValue)
3130 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3132 else if (typeof(d) == 'object')
3136 else if (typeof(d) == 'string')
3139 dep[d] = (typeof(v) == 'undefined') ? true : v;
3142 if (!dep || $.isEmptyObject(dep))
3145 for (var field in dep)
3147 var f = this.section.fields[field];
3149 f.rdependency[this.name] = this;
3154 if ($.isEmptyObject(dep))
3157 this.dependencies.push(dep);
3162 toggle: function(sid)
3164 var d = this.dependencies;
3165 var i = this.instance[sid];
3170 for (var n = 0; n < d.length; n++)
3174 for (var field in d[n])
3176 var val = this.section.fields[field].formvalue(sid);
3177 var cmp = d[n][field];
3179 if (typeof(cmp) == 'boolean')
3181 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3187 else if (typeof(cmp) == 'string')
3195 else if (typeof(cmp) == 'function')
3203 else if (cmp instanceof RegExp)
3228 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3235 this.cbi.CheckboxValue = AbstractValue.extend({
3236 widget: function(sid)
3238 var o = this.options;
3240 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3241 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3243 var i = $('<input />')
3244 .attr('id', this.id(sid))
3245 .attr('type', 'checkbox')
3246 .prop('checked', this.ucivalue(sid));
3248 return this.validator(sid, i);
3251 ucivalue: function(sid)
3253 var v = this.callSuper('ucivalue', sid);
3255 if (typeof(v) == 'boolean')
3258 return (v == this.options.enabled);
3261 formvalue: function(sid)
3263 var v = $('#' + this.id(sid)).prop('checked');
3265 if (typeof(v) == 'undefined')
3266 return !!this.options.initial;
3273 var uci = this.ucipath(sid);
3275 if (this.instance[sid].disabled)
3277 if (!this.options.keep)
3278 return this.map.set(uci.config, uci.section, uci.option, undefined);
3283 var chg = this.changed(sid);
3284 var val = this.formvalue(sid);
3288 val = val ? this.options.enabled : this.options.disabled;
3290 if (this.options.optional && val == this.options.initial)
3291 this.map.set(uci.config, uci.section, uci.option, undefined);
3293 this.map.set(uci.config, uci.section, uci.option, val);
3300 this.cbi.InputValue = AbstractValue.extend({
3301 widget: function(sid)
3303 var i = $('<input />')
3304 .attr('id', this.id(sid))
3305 .attr('type', 'text')
3306 .attr('placeholder', this.options.placeholder)
3307 .val(this.ucivalue(sid));
3309 return this.validator(sid, i);
3313 this.cbi.PasswordValue = AbstractValue.extend({
3314 widget: function(sid)
3316 var i = $('<input />')
3317 .attr('id', this.id(sid))
3318 .attr('type', 'password')
3319 .attr('placeholder', this.options.placeholder)
3320 .val(this.ucivalue(sid));
3322 var t = $('<img />')
3323 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3324 .attr('title', _luci2.tr('Reveal or hide password'))
3325 .addClass('cbi-button')
3326 .click(function(ev) {
3327 var i = $(this).prev();
3328 var t = i.attr('type');
3329 i.attr('type', (t == 'password') ? 'text' : 'password');
3333 this.validator(sid, i);
3336 .addClass('cbi-input-password')
3342 this.cbi.ListValue = AbstractValue.extend({
3343 widget: function(sid)
3345 var s = $('<select />');
3347 if (this.options.optional)
3350 .text(_luci2.tr('-- Please choose --'))
3354 for (var i = 0; i < this.choices.length; i++)
3356 .attr('value', this.choices[i][0])
3357 .text(this.choices[i][1])
3360 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3362 return this.validator(sid, s);
3365 value: function(k, v)
3370 this.choices.push([k, v || k]);
3375 this.cbi.MultiValue = this.cbi.ListValue.extend({
3376 widget: function(sid)
3378 var v = this.ucivalue(sid);
3379 var t = $('<div />').attr('id', this.id(sid));
3382 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3385 for (var i = 0; i < v.length; i++)
3389 for (var i = 0; i < this.choices.length; i++)
3392 .append($('<input />')
3393 .addClass('cbi-input-checkbox')
3394 .attr('type', 'checkbox')
3395 .attr('value', this.choices[i][0])
3396 .prop('checked', s[this.choices[i][0]]))
3397 .append(this.choices[i][1])
3407 formvalue: function(sid)
3410 var fields = $('#' + this.id(sid) + ' > label > input');
3412 for (var i = 0; i < fields.length; i++)
3413 if (fields[i].checked)
3414 rv.push(fields[i].getAttribute('value'));
3419 textvalue: function(sid)
3421 var v = this.formvalue(sid);
3425 for (var i = 0; i < this.choices.length; i++)
3426 c[this.choices[i][0]] = this.choices[i][1];
3430 for (var i = 0; i < v.length; i++)
3431 t.push(c[v[i]] || v[i]);
3433 return t.join(', ');
3437 this.cbi.ComboBox = AbstractValue.extend({
3438 _change: function(ev)
3441 var self = ev.data.self;
3443 if (s.selectedIndex == (s.options.length - 1))
3445 ev.data.select.hide();
3446 ev.data.input.show().focus();
3448 var v = ev.data.input.val();
3449 ev.data.input.val(' ');
3450 ev.data.input.val(v);
3452 else if (self.options.optional && s.selectedIndex == 0)
3454 ev.data.input.val('');
3458 ev.data.input.val(ev.data.select.val());
3465 var val = this.value;
3466 var self = ev.data.self;
3468 ev.data.select.empty();
3470 if (self.options.optional)
3473 .text(_luci2.tr('-- please choose --'))
3474 .appendTo(ev.data.select);
3477 for (var i = 0; i < self.choices.length; i++)
3479 if (self.choices[i][0] == val)
3483 .attr('value', self.choices[i][0])
3484 .text(self.choices[i][1])
3485 .appendTo(ev.data.select);
3488 if (!seen && val != '')
3492 .appendTo(ev.data.select);
3496 .text(_luci2.tr('-- custom --'))
3497 .appendTo(ev.data.select);
3499 ev.data.input.hide();
3500 ev.data.select.val(val).show().focus();
3503 _enter: function(ev)
3508 ev.preventDefault();
3509 ev.data.self._blur(ev);
3513 widget: function(sid)
3515 var d = $('<div />')
3516 .attr('id', this.id(sid));
3518 var t = $('<input />')
3519 .attr('type', 'text')
3523 var s = $('<select />')
3528 input: this.validator(sid, t),
3529 select: this.validator(sid, s)
3532 s.change(evdata, this._change);
3533 t.blur(evdata, this._blur);
3534 t.keydown(evdata, this._enter);
3536 t.val(this.ucivalue(sid));
3542 value: function(k, v)
3547 this.choices.push([k, v || k]);
3551 formvalue: function(sid)
3553 var v = $('#' + this.id(sid)).children('input').val();
3554 return (v == '') ? undefined : v;
3558 this.cbi.DynamicList = this.cbi.ComboBox.extend({
3559 _redraw: function(focus, add, del, s)
3561 var v = s.values || [ ];
3564 $(s.parent).children('input').each(function(i) {
3566 v.push(this.value || '');
3569 $(s.parent).empty();
3574 v.splice(focus, 0, '');
3576 else if (v.length == 0)
3582 for (var i = 0; i < v.length; i++)
3593 var txt = $('<input />')
3594 .attr('type', 'text')
3596 .appendTo(s.parent);
3598 var sel = $('<select />')
3599 .appendTo(s.parent);
3601 evdata.input = this.validator(s.sid, txt, true);
3602 evdata.select = this.validator(s.sid, sel, true);
3604 sel.change(evdata, this._change);
3605 txt.blur(evdata, this._blur);
3606 txt.keydown(evdata, this._keydown);
3611 if (i == focus || -(i+1) == focus)
3618 var f = $('<input />')
3619 .attr('type', 'text')
3621 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
3622 .addClass('cbi-input-text')
3623 .keydown(evdata, this._keydown)
3624 .keypress(evdata, this._keypress)
3627 f.appendTo(s.parent);
3633 else if (-(i+1) == focus)
3637 /* force cursor to end */
3643 evdata.input = this.validator(s.sid, f, true);
3649 .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
3650 .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
3651 .addClass('cbi-button')
3652 .click(evdata, this._btnclick)
3653 .appendTo(s.parent);
3656 .appendTo(s.parent);
3664 _keypress: function(ev)
3668 /* backspace, delete */
3671 if (ev.data.input.val() == '')
3673 ev.preventDefault();
3679 /* enter, arrow up, arrow down */
3683 ev.preventDefault();
3690 _keydown: function(ev)
3692 var input = ev.data.input;
3696 /* backspace, delete */
3699 if (input.val().length == 0)
3701 ev.preventDefault();
3703 var index = ev.data.index;
3709 ev.data.self._redraw(focus, -1, index, ev.data);
3717 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
3722 var prev = input.prevAll('input:first');
3723 if (prev.is(':visible'))
3726 prev.next('select').focus();
3731 var next = input.nextAll('input:first');
3732 if (next.is(':visible'))
3735 next.next('select').focus();
3742 _btnclick: function(ev)
3744 if (!this.getAttribute('disabled'))
3746 if (ev.target.src.indexOf('remove') > -1)
3748 var index = ev.data.index;
3749 ev.data.self._redraw(-index, -1, index, ev.data);
3753 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
3760 widget: function(sid)
3762 this.options.optional = true;
3764 var v = this.ucivalue(sid);
3767 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3769 var d = $('<div />')
3770 .attr('id', this.id(sid))
3771 .addClass('cbi-input-dynlist');
3773 this._redraw(NaN, -1, -1, {
3783 ucivalue: function(sid)
3785 var v = this.callSuper('ucivalue', sid);
3788 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3793 formvalue: function(sid)
3796 var fields = $('#' + this.id(sid) + ' > input');
3798 for (var i = 0; i < fields.length; i++)
3799 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
3800 rv.push(fields[i].value);
3806 this.cbi.DummyValue = AbstractValue.extend({
3807 widget: function(sid)
3810 .addClass('cbi-value-dummy')
3811 .attr('id', this.id(sid))
3812 .html(this.ucivalue(sid));
3815 formvalue: function(sid)
3817 return this.ucivalue(sid);
3821 this.cbi.NetworkList = AbstractValue.extend({
3826 if (!self.interfaces)
3828 self.interfaces = [ ];
3829 return _luci2.network.getNetworkStatus(function(ifaces) {
3830 self.interfaces = ifaces;
3838 _device_icon: function(dev)
3840 var type = 'ethernet';
3841 var desc = _luci2.tr('Ethernet device');
3843 if (dev.type == 'IP tunnel')
3846 desc = _luci2.tr('Tunnel interface');
3848 else if (dev['bridge-members'])
3851 desc = _luci2.tr('Bridge');
3853 else if (dev.wireless)
3856 desc = _luci2.tr('Wireless Network');
3858 else if (dev.name.indexOf('.') > 0)
3861 desc = _luci2.tr('VLAN interface');
3865 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
3866 .attr('title', '%s (%s)'.format(desc, dev.name));
3869 widget: function(sid)
3871 var id = this.id(sid);
3872 var ul = $('<ul />')
3874 .addClass('cbi-input-networks');
3876 var itype = this.options.multiple ? 'checkbox' : 'radio';
3877 var value = this.ucivalue(sid);
3880 if (!this.options.multiple)
3881 check[value] = true;
3883 for (var i = 0; i < value.length; i++)
3884 check[value[i]] = true;
3886 if (this.interfaces)
3888 for (var i = 0; i < this.interfaces.length; i++)
3890 var iface = this.interfaces[i];
3891 var badge = $('<span />')
3892 .addClass('ifacebadge')
3893 .text('%s: '.format(iface.name));
3895 if (iface.subdevices)
3896 for (var j = 0; j < iface.subdevices.length; j++)
3897 badge.append(this._device_icon(iface.subdevices[j]));
3898 else if (iface.device)
3899 badge.append(this._device_icon(iface.device));
3901 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
3904 .append($('<label />')
3905 .append($('<input />')
3906 .attr('name', itype + id)
3907 .attr('type', itype)
3908 .attr('value', iface.name)
3909 .prop('checked', !!check[iface.name])
3910 .addClass('cbi-input-' + itype))
3916 if (!this.options.multiple)
3919 .append($('<label />')
3920 .append($('<input />')
3921 .attr('name', itype + id)
3922 .attr('type', itype)
3924 .prop('checked', !value)
3925 .addClass('cbi-input-' + itype))
3926 .append(_luci2.tr('unspecified')))
3933 ucivalue: function(sid)
3935 var v = this.callSuper('ucivalue', sid);
3937 if (!this.options.multiple)
3943 else if (typeof(v) == 'string')
3946 return v ? v[0] : undefined;
3953 if (typeof(v) == 'string')
3954 v = v.match(/\S+/g);
3960 formvalue: function(sid)
3962 var inputs = $('#' + this.id(sid) + ' input');
3964 if (!this.options.multiple)
3966 for (var i = 0; i < inputs.length; i++)
3967 if (inputs[i].checked && inputs[i].value !== '')
3968 return inputs[i].value;
3975 for (var i = 0; i < inputs.length; i++)
3976 if (inputs[i].checked)
3977 rv.push(inputs[i].value);
3979 return rv.length ? rv : undefined;
3984 var AbstractSection = AbstractWidget.extend({
3987 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
3989 for (var i = 1; i < arguments.length; i++)
3990 s.push(arguments[i].replace(/\./g, '_'));
3995 option: function(widget, name, options)
3997 if (this.tabs.length == 0)
3998 this.tab({ id: '__default__', selected: true });
4000 return this.taboption('__default__', widget, name, options);
4003 tab: function(options)
4005 if (options.selected)
4006 this.tabs.selected = this.tabs.length;
4010 caption: options.caption,
4011 description: options.description,
4017 taboption: function(tabid, widget, name, options)
4020 for (var i = 0; i < this.tabs.length; i++)
4022 if (this.tabs[i].id == tabid)
4030 throw 'Cannot append to unknown tab ' + tabid;
4032 var w = widget ? new widget(name, options) : null;
4034 if (!(w instanceof AbstractValue))
4035 throw 'Widget must be an instance of AbstractValue';
4040 this.fields[name] = w;
4046 ucipackages: function(pkg)
4048 for (var i = 0; i < this.tabs.length; i++)
4049 for (var j = 0; j < this.tabs[i].fields.length; j++)
4050 if (this.tabs[i].fields[j].options.uci_package)
4051 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4054 formvalue: function()
4058 this.sections(function(s) {
4059 var sid = s['.name'];
4060 var sv = rv[sid] || (rv[sid] = { });
4062 for (var i = 0; i < this.tabs.length; i++)
4063 for (var j = 0; j < this.tabs[i].fields.length; j++)
4065 var val = this.tabs[i].fields[j].formvalue(sid);
4066 sv[this.tabs[i].fields[j].name] = val;
4073 validate: function(sid)
4079 var as = this.sections();
4080 for (var i = 0; i < as.length; i++)
4081 if (!this.validate(as[i]['.name']))
4086 var inst = this.instance[sid];
4087 var sv = rv[sid] || (rv[sid] = { });
4090 var legend = $('#' + this.id('sort', sid)).find('legend:first');
4092 legend.children('span').detach();
4094 for (var i = 0; i < this.tabs.length; i++)
4097 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4099 tab.children('span').detach();
4101 for (var j = 0; j < this.tabs[i].fields.length; j++)
4102 if (!this.tabs[i].fields[j].validate(sid))
4109 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4122 .attr('title', _luci2.tr('%d Errors'.format(invals)))
4130 this.cbi.TypedSection = AbstractSection.extend({
4131 init: function(uci_type, options)
4133 this.uci_type = uci_type;
4134 this.options = options;
4137 this.active_panel = 0;
4138 this.active_tab = { };
4141 filter: function(section)
4146 sections: function(cb)
4148 var s1 = this.map.ucisections(this.map.uci_package);
4151 for (var i = 0; i < s1.length; i++)
4152 if (s1[i]['.type'] == this.uci_type)
4153 if (this.filter(s1[i]))
4156 if (typeof(cb) == 'function')
4157 for (var i = 0; i < s2.length; i++)
4158 cb.apply(this, [ s2[i] ]);
4165 this.map.add(this.map.uci_package, this.uci_type, name);
4168 remove: function(sid)
4170 this.map.remove(this.map.uci_package, sid);
4176 var name = undefined;
4177 var self = ev.data.self;
4179 if (addb.prev().prop('nodeName') == 'INPUT')
4180 name = addb.prev().val();
4182 if (addb.prop('disabled') || name === '')
4185 self.active_panel = -1;
4191 _remove: function(ev)
4193 var self = ev.data.self;
4194 var sid = ev.data.sid;
4200 ev.stopPropagation();
4205 var self = ev.data.self;
4207 var addb = text.next();
4208 var errt = addb.next();
4209 var name = text.val();
4212 if (!/^[a-zA-Z0-9_]*$/.test(name))
4214 errt.text(_luci2.tr('Invalid section name')).show();
4215 text.addClass('error');
4216 addb.prop('disabled', true);
4220 for (var sid in self.map.uci.values[self.map.uci_package])
4227 for (var sid in self.map.uci.creates[self.map.uci_package])
4236 errt.text(_luci2.tr('Name already used')).show();
4237 text.addClass('error');
4238 addb.prop('disabled', true);
4242 errt.text('').hide();
4243 text.removeClass('error');
4244 addb.prop('disabled', false);
4248 teaser: function(sid)
4250 var tf = this.teaser_fields;
4254 tf = this.teaser_fields = [ ];
4256 if ($.isArray(this.options.teasers))
4258 for (var i = 0; i < this.options.teasers.length; i++)
4260 var f = this.options.teasers[i];
4261 if (f instanceof AbstractValue)
4263 else if (typeof(f) == 'string' && this.fields[f] instanceof AbstractValue)
4264 tf.push(this.fields[f]);
4269 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4270 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4271 tf.push(this.tabs[i].fields[j]);
4277 for (var i = 0; i < tf.length; i++)
4279 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4282 var n = tf[i].options.caption || tf[i].name;
4283 var v = tf[i].textvalue(sid);
4285 if (typeof(v) == 'undefined')
4288 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4294 _render_add: function()
4296 var text = _luci2.tr('Add section');
4297 var ttip = _luci2.tr('Create new section...');
4299 if ($.isArray(this.options.add_caption))
4300 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4301 else if (typeof(this.options.add_caption) == 'string')
4302 text = this.options.add_caption, ttip = '';
4304 var add = $('<div />').addClass('cbi-section-add');
4306 if (this.options.anonymous === false)
4309 .addClass('cbi-input-text')
4310 .attr('type', 'text')
4311 .attr('placeholder', ttip)
4312 .blur({ self: this }, this._sid)
4313 .keyup({ self: this }, this._sid)
4317 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4318 .attr('title', text)
4319 .addClass('cbi-button')
4320 .click({ self: this }, this._add)
4324 .addClass('cbi-value-error')
4331 .attr('type', 'button')
4332 .addClass('cbi-button')
4333 .addClass('cbi-button-add')
4334 .val(text).attr('title', ttip)
4335 .click({ self: this }, this._add)
4342 _render_remove: function(sid)
4344 var text = _luci2.tr('Remove');
4345 var ttip = _luci2.tr('Remove this section');
4347 if ($.isArray(this.options.remove_caption))
4348 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4349 else if (typeof(this.options.remove_caption) == 'string')
4350 text = this.options.remove_caption, ttip = '';
4352 return $('<input />')
4353 .attr('type', 'button')
4354 .addClass('cbi-button')
4355 .addClass('cbi-button-remove')
4356 .val(text).attr('title', ttip)
4357 .click({ self: this, sid: sid }, this._remove);
4360 _render_caption: function(sid)
4362 if (typeof(this.options.caption) == 'string')
4364 return $('<legend />')
4365 .text(this.options.caption.format(sid));
4367 else if (typeof(this.options.caption) == 'function')
4369 return $('<legend />')
4370 .text(this.options.caption.call(this, sid));
4378 var allsections = $();
4379 var panel_index = 0;
4381 this.instance = { };
4383 var s = this.sections();
4387 var fieldset = $('<fieldset />')
4388 .addClass('cbi-section');
4390 var head = $('<div />')
4391 .addClass('cbi-section-head')
4392 .appendTo(fieldset);
4394 head.append(this._render_caption(undefined));
4396 if (typeof(this.options.description) == 'string')
4399 .addClass('cbi-section-descr')
4400 .text(this.options.description)
4404 allsections = allsections.add(fieldset);
4407 for (var i = 0; i < s.length; i++)
4409 var sid = s[i]['.name'];
4410 var inst = this.instance[sid] = { tabs: [ ] };
4412 var fieldset = $('<fieldset />')
4413 .attr('id', this.id('sort', sid))
4414 .addClass('cbi-section');
4416 var head = $('<div />')
4417 .addClass('cbi-section-head')
4418 .attr('cbi-section-num', this.index)
4419 .attr('cbi-section-id', sid);
4421 head.append(this._render_caption(sid));
4423 if (typeof(this.options.description) == 'string')
4426 .addClass('cbi-section-descr')
4427 .text(this.options.description)
4432 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4433 teaser = $('<div />')
4434 .addClass('cbi-section-teaser')
4437 if (this.options.addremove)
4439 .addClass('cbi-section-remove')
4441 .append(this._render_remove(sid))
4444 var body = $('<div />')
4445 .attr('index', panel_index++);
4447 var fields = $('<fieldset />')
4448 .addClass('cbi-section-node');
4450 if (this.tabs.length > 1)
4452 var menu = $('<ul />')
4453 .addClass('cbi-tabmenu');
4455 for (var j = 0; j < this.tabs.length; j++)
4457 var tabid = this.id('tab', sid, this.tabs[j].id);
4458 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4460 var tabc = $('<div />')
4461 .addClass('cbi-tabcontainer')
4465 if (typeof(this.tabs[j].description) == 'string')
4468 .addClass('cbi-tab-descr')
4469 .text(this.tabs[j].description)
4473 for (var k = 0; k < this.tabs[j].fields.length; k++)
4474 this.tabs[j].fields[k].render(sid).appendTo(tabc);
4476 tabc.appendTo(fields);
4479 $('<li />').attr('id', theadid).append(
4481 .text(this.tabs[j].caption.format(this.tabs[j].id))
4482 .attr('href', '#' + tabid)
4486 menu.appendTo(body);
4489 fields.appendTo(body);
4492 var t = body.tabs({ active: this.active_tab[sid] });
4494 t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4497 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4502 for (var j = 0; j < this.tabs[0].fields.length; j++)
4503 this.tabs[0].fields[j].render(sid).appendTo(fields);
4505 fields.appendTo(body);
4509 head.appendTo(fieldset);
4512 body.appendTo(fieldset);
4515 allsections = allsections.add(fieldset);
4518 //this.validate(sid);
4521 // teaser.append(this.teaser(sid));
4524 if (this.options.collabsible && s.length > 1)
4526 var a = $('<div />').append(allsections).accordion({
4527 header: '> fieldset > div.cbi-section-head',
4528 heightStyle: 'content',
4529 active: this.active_panel
4532 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4533 var h = ui.oldHeader;
4534 var s = ev.data.self;
4535 var i = h.attr('cbi-section-id');
4537 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4541 a.on('accordionactivate', { self: this }, function(ev, ui) {
4542 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4545 if (this.options.sortable)
4547 var s = a.sortable({
4549 handle: 'div.cbi-section-head'
4552 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4554 for (var i = 0; i < ev.data.ids.length; i++)
4555 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4556 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4559 s.on('sortstop', function(ev, ui) {
4560 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4564 if (this.options.addremove)
4565 this._render_add().appendTo(a);
4570 if (this.options.addremove)
4571 allsections = allsections.add(this._render_add());
4578 var s = this.sections();
4580 for (var i = 0; i < s.length; i++)
4582 var sid = s[i]['.name'];
4586 $('#' + this.id('sort', sid))
4587 .children('.cbi-section-head')
4588 .children('.cbi-section-teaser')
4589 .append(this.teaser(sid));
4594 this.cbi.TableSection = this.cbi.TypedSection.extend({
4597 var allsections = $();
4598 var panel_index = 0;
4600 this.instance = { };
4602 var s = this.sections();
4604 var fieldset = $('<fieldset />')
4605 .addClass('cbi-section');
4607 fieldset.append(this._render_caption(sid));
4609 if (typeof(this.options.description) == 'string')
4612 .addClass('cbi-section-descr')
4613 .text(this.options.description)
4614 .appendTo(fieldset);
4617 var fields = $('<div />')
4618 .addClass('cbi-section-node')
4619 .appendTo(fieldset);
4621 var table = $('<table />')
4622 .addClass('cbi-section-table')
4625 var thead = $('<thead />')
4626 .append($('<tr />').addClass('cbi-section-table-titles'))
4629 for (var j = 0; j < this.tabs[0].fields.length; j++)
4631 .addClass('cbi-section-table-cell')
4632 .css('width', this.tabs[0].fields[j].options.width || '')
4633 .append(this.tabs[0].fields[j].options.caption)
4634 .appendTo(thead.children());
4636 if (this.options.sortable)
4637 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4639 if (this.options.addremove !== false)
4640 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4642 var tbody = $('<tbody />')
4648 .addClass('cbi-section-table-row')
4651 .addClass('cbi-section-table-cell')
4652 .addClass('cbi-section-table-placeholder')
4653 .attr('colspan', thead.children().children().length)
4654 .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
4658 for (var i = 0; i < s.length; i++)
4660 var sid = s[i]['.name'];
4661 var inst = this.instance[sid] = { tabs: [ ] };
4663 var row = $('<tr />')
4664 .addClass('cbi-section-table-row')
4667 for (var j = 0; j < this.tabs[0].fields.length; j++)
4670 .addClass('cbi-section-table-cell')
4671 .css('width', this.tabs[0].fields[j].options.width || '')
4672 .append(this.tabs[0].fields[j].render(sid, true))
4676 if (this.options.sortable)
4679 .addClass('cbi-section-table-cell')
4680 .addClass('cbi-section-table-sort')
4681 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
4682 .append($('<br />'))
4683 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
4687 if (this.options.addremove !== false)
4690 .addClass('cbi-section-table-cell')
4691 .append(this._render_remove(sid))
4700 if (this.options.sortable)
4702 var s = tbody.sortable({
4703 handle: 'td.cbi-section-table-sort'
4706 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4708 for (var i = 0; i < ev.data.ids.length; i++)
4709 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4710 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4713 s.on('sortstop', function(ev, ui) {
4714 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4718 if (this.options.addremove)
4719 this._render_add().appendTo(fieldset);
4721 fields = table = thead = tbody = null;
4727 this.cbi.NamedSection = this.cbi.TypedSection.extend({
4728 sections: function(cb)
4731 var pkg = this.map.uci.values[this.map.uci_package];
4734 if (pkg[s]['.name'] == this.uci_type)
4740 if (typeof(cb) == 'function' && sa.length > 0)
4741 cb.apply(this, [ sa[0] ]);
4747 this.cbi.DummySection = this.cbi.TypedSection.extend({
4748 sections: function(cb)
4750 if (typeof(cb) == 'function')
4751 cb.apply(this, [ { '.name': this.uci_type } ]);
4753 return [ { '.name': this.uci_type } ];
4757 this.cbi.Map = AbstractWidget.extend({
4758 init: function(uci_package, options)
4762 this.uci_package = uci_package;
4763 this.sections = [ ];
4764 this.options = _luci2.defaults(options, {
4765 save: function() { },
4766 prepare: function() {
4767 return _luci2.uci.writable(function(writable) {
4768 self.options.readonly = !writable;
4784 this.active_panel = 0;
4788 for (var i = 0; i < this.sections.length; i++)
4789 this.sections[i].ucipackages(packages);
4791 packages[this.uci_package] = true;
4793 for (var p in packages)
4794 packages[p] = ['uci', 'get', { config: p }];
4796 var load_cb = this._load_cb || (this._load_cb = $.proxy(function(responses) {
4797 for (var p in responses)
4799 if (responses[p][0] != 0 || !responses[p][1] || !responses[p][1].values)
4802 this.uci.values[p] = responses[p][1].values;
4805 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
4807 for (var i = 0; i < this.sections.length; i++)
4809 for (var f in this.sections[i].fields)
4811 if (typeof(this.sections[i].fields[f].load) != 'function')
4814 var s = this.sections[i].sections();
4815 for (var j = 0; j < s.length; j++)
4817 var rv = this.sections[i].fields[f].load(s[j]['.name']);
4818 if (_luci2.deferred(rv))
4824 return $.when.apply($, deferreds);
4827 return _luci2.rpc.call(packages).then(load_cb);
4832 var map = $('<div />').addClass('cbi-map');
4834 if (typeof(this.options.caption) == 'string')
4835 $('<h2 />').text(this.options.caption).appendTo(map);
4837 if (typeof(this.options.description) == 'string')
4838 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
4840 var sections = $('<div />').appendTo(map);
4842 for (var i = 0; i < this.sections.length; i++)
4844 var s = this.sections[i].render();
4846 if (this.options.readonly || this.sections[i].options.readonly)
4847 s.find('input, select, button, img.cbi-button').attr('disabled', true);
4849 s.appendTo(sections);
4851 if (this.sections[i].options.active)
4852 this.active_panel = i;
4855 if (this.options.collabsible)
4857 var a = sections.accordion({
4858 header: '> fieldset > div.cbi-section-head',
4859 heightStyle: 'content',
4860 active: this.active_panel
4863 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4864 var h = ui.oldHeader;
4865 var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
4866 var i = h.attr('cbi-section-id');
4868 h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4870 for (var i = 0; i < ev.data.self.sections.length; i++)
4871 ev.data.self.sections[i].validate();
4874 a.on('accordionactivate', { self: this }, function(ev, ui) {
4875 ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4879 if (this.options.pageaction !== false)
4881 var a = $('<div />')
4882 .addClass('cbi-page-actions')
4886 .addClass('cbi-button').addClass('cbi-button-apply')
4887 .attr('type', 'button')
4888 .val(_luci2.tr('Save & Apply'))
4892 .addClass('cbi-button').addClass('cbi-button-save')
4893 .attr('type', 'button')
4894 .val(_luci2.tr('Save'))
4895 .click({ self: this }, function(ev) { ev.data.self.send(); })
4899 .addClass('cbi-button').addClass('cbi-button-reset')
4900 .attr('type', 'button')
4901 .val(_luci2.tr('Reset'))
4902 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
4908 var top = $('<form />').append(map);
4917 for (var i = 0; i < this.sections.length; i++)
4918 this.sections[i].finish();
4925 this.target.hide().empty().append(this.render());
4930 section: function(widget, uci_type, options)
4932 var w = widget ? new widget(uci_type, options) : null;
4934 if (!(w instanceof AbstractSection))
4935 throw 'Widget must be an instance of AbstractSection';
4938 w.index = this.sections.length;
4940 this.sections.push(w);
4944 formvalue: function()
4948 for (var i = 0; i < this.sections.length; i++)
4950 var sids = this.sections[i].formvalue();
4951 for (var sid in sids)
4953 var s = rv[sid] || (rv[sid] = { });
4954 $.extend(s, sids[sid]);
4961 add: function(conf, type, name)
4963 var c = this.uci.creates;
4964 var s = '.new.%d'.format(this.uci.newid++);
4979 remove: function(conf, sid)
4981 var n = this.uci.creates;
4982 var c = this.uci.changes;
4983 var d = this.uci.deletes;
4985 /* requested deletion of a just created section */
4986 if (sid.indexOf('.new.') == 0)
4989 delete n[conf][sid];
4994 delete c[conf][sid];
4999 d[conf][sid] = true;
5003 ucisections: function(conf, cb)
5006 var pkg = this.uci.values[conf];
5007 var crt = this.uci.creates[conf];
5008 var del = this.uci.deletes[conf];
5014 if (!del || del[s] !== true)
5017 sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5023 if (typeof(cb) == 'function')
5024 for (var i = 0; i < sa.length; i++)
5025 cb.apply(this, [ sa[i] ]);
5030 get: function(conf, sid, opt)
5032 var v = this.uci.values;
5033 var n = this.uci.creates;
5034 var c = this.uci.changes;
5035 var d = this.uci.deletes;
5037 /* requested option in a just created section */
5038 if (sid.indexOf('.new.') == 0)
5043 if (typeof(opt) == 'undefined')
5044 return (n[conf][sid] || { });
5046 return n[conf][sid][opt];
5049 /* requested an option value */
5050 if (typeof(opt) != 'undefined')
5052 /* check whether option was deleted */
5053 if (d[conf] && d[conf][sid])
5055 if (d[conf][sid] === true)
5058 for (var i = 0; i < d[conf][sid].length; i++)
5059 if (d[conf][sid][i] == opt)
5063 /* check whether option was changed */
5064 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5065 return c[conf][sid][opt];
5067 /* return base value */
5068 if (v[conf] && v[conf][sid])
5069 return v[conf][sid][opt];
5074 /* requested an entire section */
5076 return (v[conf][sid] || { });
5081 set: function(conf, sid, opt, val)
5083 var n = this.uci.creates;
5084 var c = this.uci.changes;
5085 var d = this.uci.deletes;
5087 if (sid.indexOf('.new.') == 0)
5089 if (n[conf] && n[conf][sid])
5091 if (typeof(val) != 'undefined')
5092 n[conf][sid][opt] = val;
5094 delete n[conf][sid][opt];
5097 else if (typeof(val) != 'undefined')
5105 c[conf][sid][opt] = val;
5115 d[conf][sid].push(opt);
5119 validate: function()
5123 for (var i = 0; i < this.sections.length; i++)
5124 if (!this.sections[i].validate())
5132 if (this.options.readonly)
5133 return _luci2.deferrable();
5135 var deferreds = [ _luci2.deferrable(this.options.save()) ];
5137 for (var i = 0; i < this.sections.length; i++)
5139 if (this.sections[i].options.readonly)
5142 for (var f in this.sections[i].fields)
5144 if (typeof(this.sections[i].fields[f].save) != 'function')
5147 var s = this.sections[i].sections();
5148 for (var j = 0; j < s.length; j++)
5150 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5151 if (_luci2.deferred(rv))
5157 return $.when.apply($, deferreds);
5162 if (!this.validate())
5163 return _luci2.deferrable();
5165 var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5168 if (this.uci.creates)
5169 for (var c in this.uci.creates)
5170 for (var s in this.uci.creates[c])
5177 for (var k in this.uci.creates[c][s])
5180 r.type = this.uci.creates[i][k];
5181 else if (k == '.create')
5182 r.name = this.uci.creates[i][k];
5183 else if (k.charAt(0) != '.')
5184 r.values[k] = this.uci.creates[i][k];
5186 requests.push(['uci', 'add', r]);
5189 if (this.uci.changes)
5190 for (var c in this.uci.changes)
5191 for (var s in this.uci.changes[c])
5192 requests.push(['uci', 'set', {
5195 values: this.uci.changes[c][s]
5198 if (this.uci.deletes)
5199 for (var c in this.uci.deletes)
5200 for (var s in this.uci.deletes[c])
5202 var o = this.uci.deletes[c][s];
5203 requests.push(['uci', 'delete', {
5206 options: (o === true) ? undefined : o
5210 return _luci2.rpc.call(requests);
5215 _luci2.ui.loading(true);
5217 return this.save().then(send_cb).then(function() {
5219 }).then(function() {
5223 _luci2.ui.loading(false);
5227 dialog: function(id)
5229 var d = $('<div />');
5233 .attr('src', _luci2.globals.resource + '/icons/loading.gif')
5234 .css('vertical-align', 'middle')
5235 .css('padding-right', '10px')
5238 p.append(_luci2.tr('Loading data...'));
5249 $(this).parent().children('.ui-dialog-titlebar').hide();
5254 insertInto: function(id)
5257 self.target = $(id);
5259 _luci2.ui.loading(true);
5262 return self.load().then(function() {
5263 self.target.empty().append(self.render());
5267 _luci2.ui.loading(false);