2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String.prototype.format = function()
15 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27 var a = b = [], numSubstitutions = 0, numMatches = 0;
29 while ((a = re.exec(str)) != null)
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
43 if (numSubstitutions < arguments.length)
45 var param = arguments[numSubstitutions++];
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
59 minLength = parseInt(pMinLength);
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
70 subst = (parseInt(param) || 0).toString(2);
74 subst = String.fromCharCode(parseInt(param) || 0);
78 subst = (parseInt(param) || 0);
82 subst = Math.abs(parseInt(param) || 0);
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
92 subst = (parseInt(param) || 0).toString(8);
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
108 subst = esc(param, html_esc);
112 subst = esc(param, quot_esc);
116 subst = String.serialize(param);
123 var ts = (param || 0);
126 tm = Math.floor(ts / 60);
131 th = Math.floor(tm / 60);
136 td = Math.floor(th / 24);
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i = 0; (i < units.length) && (val > mf); i++)
157 subst = val.toFixed(pr) + ' ' + units[i];
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
169 out += leftpart + subst;
170 str = str.substr(m.length);
180 var Class = function() { };
182 Class.extend = function(properties)
184 Class.initializing = true;
186 var prototype = new this();
187 var superprot = this.prototype;
189 Class.initializing = false;
191 $.extend(prototype, properties, {
192 callSuper: function() {
194 var meth = arguments[0];
196 if (typeof(superprot[meth]) != 'function')
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
202 return superprot[meth].apply(this, args);
208 this.options = arguments[0] || { };
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
217 _class.extend = Class.extend;
222 this.defaults = function(obj, def)
225 if (typeof(obj[key]) == 'undefined')
231 this.isDeferred = function(x)
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments[0]))
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
253 plural: function(n) { return 0 + (n != 1) },
256 if (_luci2.i18n.loaded)
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
270 var pe = _luci2.i18n.catalog[''];
273 delete _luci2.i18n.catalog[''];
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
282 _luci2.i18n.loaded = true;
287 this.tr = function(msgid)
291 var msgstr = _luci2.i18n.catalog[msgid];
293 if (typeof(msgstr) == 'undefined')
295 else if (typeof(msgstr) == 'string')
301 this.trp = function(msgid, msgid_plural, count)
305 var msgstr = _luci2.i18n.catalog[msgid];
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
312 return msgstr[_luci2.i18n.plural(count)];
315 this.trc = function(msgctx, msgid)
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
321 if (typeof(msgstr) == 'undefined')
323 else if (typeof(msgstr) == 'string')
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
340 return msgstr[_luci2.i18n.plural(count)];
343 this.setHash = function(key, value)
346 var data = this.getHash(undefined);
348 if (typeof(value) == 'undefined')
359 for (var i = 0; i < keys.length; i++)
364 h += keys[i] + ':' + data[keys[i]];
368 location.hash = '#' + h;
373 this.getHash = function(key)
376 var tuples = (location.hash || '#').substring(1).split(/,/);
378 for (var i = 0; i < tuples.length; i++)
380 var tuple = tuples[i].split(/:/);
381 if (tuple.length == 2)
382 data[tuple[0]] = tuple[1];
385 if (typeof(key) != 'undefined')
391 this.toArray = function(x)
401 var l = x.split(/\s+/);
402 for (var i = 0; i < l.length; i++)
411 for (var i = 0; i < x.length; i++)
415 else if ($.isPlainObject(x))
419 if (x.hasOwnProperty(k))
428 this.toObject = function(x)
438 var l = x.split(/\x+/);
439 for (var i = 0; i < l.length; i++)
448 for (var i = 0; i < x.length; i++)
452 else if ($.isPlainObject(x))
461 this.filterArray = function(array, item)
463 if (!$.isArray(array))
466 for (var i = 0; i < array.length; i++)
467 if (array[i] === item)
468 array.splice(i--, 1);
473 this.toClassName = function(str, suffix)
476 var l = str.split(/[\/.]/);
478 for (var i = 0; i < l.length; i++)
480 n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
482 if (typeof(suffix) == 'string')
491 sid: '00000000000000000000000000000000'
500 _call: function(req, cb)
502 return $.ajax('/ubus', {
504 contentType: 'application/json',
505 data: JSON.stringify(req),
508 timeout: _luci2.globals.timeout,
513 _list_cb: function(msg)
515 var list = msg.result;
517 /* verify message frame */
518 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
521 return $.Deferred().resolveWith(this, [ list ]);
524 _call_cb: function(msg)
527 var type = Object.prototype.toString;
528 var reqs = this._rpc_req;
530 if (!$.isArray(reqs))
536 for (var i = 0; i < msg.length; i++)
538 /* fetch related request info */
539 var req = _luci2.rpc._requests[reqs[i].id];
540 if (typeof(req) != 'object')
541 throw 'No related request for JSON response';
543 /* fetch response attribute and verify returned type */
546 /* verify message frame */
547 if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
548 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
549 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
553 for (var key in req.expect)
555 if (typeof(ret) != 'undefined' && key != '')
558 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
559 ret = req.expect[key];
566 if (typeof(req.filter) == 'function')
569 req.priv[1] = req.params;
570 ret = req.filter.apply(_luci2.rpc, req.priv);
573 /* store response data */
574 if (typeof(req.index) == 'number')
575 data[req.index] = ret;
579 /* delete request object */
580 delete _luci2.rpc._requests[reqs[i].id];
583 return $.Deferred().resolveWith(this, [ data ]);
589 for (var i = 0; i < arguments.length; i++)
590 params[i] = arguments[i];
596 params: (params.length > 0) ? params : undefined
599 return this._call(msg, this._list_cb);
604 if (!$.isArray(this._batch))
610 if (!$.isArray(this._batch))
611 return _luci2.deferrable([ ]);
613 var req = this._batch;
617 return this._call(req, this._call_cb);
620 declare: function(options)
625 /* build parameter object */
628 if ($.isArray(options.params))
629 for (p_off = 0; p_off < options.params.length; p_off++)
630 params[options.params[p_off]] = arguments[p_off];
632 /* all remaining arguments are private args */
633 var priv = [ undefined, undefined ];
634 for (; p_off < arguments.length; p_off++)
635 priv.push(arguments[p_off]);
637 /* store request info */
638 var req = _rpc._requests[_rpc._id] = {
639 expect: options.expect,
640 filter: options.filter,
645 /* build message object */
658 /* when a batch is in progress then store index in request data
659 * and push message object onto the stack */
660 if ($.isArray(_rpc._batch))
662 req.index = _rpc._batch.push(msg) - 1;
663 return _luci2.deferrable(msg);
667 return _rpc._call(msg, _rpc._call_cb);
672 this.UCIContext = Class.extend({
686 _load: _luci2.rpc.declare({
689 params: [ 'config' ],
690 expect: { values: { } }
693 _order: _luci2.rpc.declare({
696 params: [ 'config', 'sections' ]
699 _add: _luci2.rpc.declare({
702 params: [ 'config', 'type', 'name', 'values' ],
703 expect: { section: '' }
706 _set: _luci2.rpc.declare({
709 params: [ 'config', 'section', 'values' ]
712 _delete: _luci2.rpc.declare({
715 params: [ 'config', 'section', 'options' ]
718 load: function(packages)
724 if (!$.isArray(packages))
725 packages = [ packages ];
729 for (var i = 0; i < packages.length; i++)
730 if (!seen[packages[i]])
732 pkgs.push(packages[i]);
733 seen[packages[i]] = true;
734 self._load(packages[i]);
737 return _luci2.rpc.flush().then(function(responses) {
738 for (var i = 0; i < responses.length; i++)
739 self.state.values[pkgs[i]] = responses[i];
745 unload: function(packages)
747 if (!$.isArray(packages))
748 packages = [ packages ];
750 for (var i = 0; i < packages.length; i++)
752 delete this.state.values[packages[i]];
753 delete this.state.creates[packages[i]];
754 delete this.state.changes[packages[i]];
755 delete this.state.deletes[packages[i]];
759 add: function(conf, type, name)
761 var c = this.state.creates;
762 var s = '.new.%d'.format(this.state.newid++);
772 '.index': 1000 + this.state.newid
778 remove: function(conf, sid)
780 var n = this.state.creates;
781 var c = this.state.changes;
782 var d = this.state.deletes;
784 /* requested deletion of a just created section */
785 if (sid.indexOf('.new.') == 0)
802 sections: function(conf, type, cb)
805 var v = this.state.values[conf];
806 var n = this.state.creates[conf];
807 var c = this.state.changes[conf];
808 var d = this.state.deletes[conf];
814 if (!d || d[s] !== true)
815 if (!type || v[s]['.type'] == type)
816 sa.push($.extend({ }, v[s], c ? c[s] : undefined));
820 if (!type || n[s]['.type'] == type)
823 sa.sort(function(a, b) {
824 return a['.index'] - b['.index'];
827 for (var i = 0; i < sa.length; i++)
830 if (typeof(cb) == 'function')
831 for (var i = 0; i < sa.length; i++)
832 cb.call(this, sa[i], sa[i]['.name']);
837 get: function(conf, sid, opt)
839 var v = this.state.values;
840 var n = this.state.creates;
841 var c = this.state.changes;
842 var d = this.state.deletes;
844 if (typeof(sid) == 'undefined')
847 /* requested option in a just created section */
848 if (sid.indexOf('.new.') == 0)
853 if (typeof(opt) == 'undefined')
856 return n[conf][sid][opt];
859 /* requested an option value */
860 if (typeof(opt) != 'undefined')
862 /* check whether option was deleted */
863 if (d[conf] && d[conf][sid])
865 if (d[conf][sid] === true)
868 for (var i = 0; i < d[conf][sid].length; i++)
869 if (d[conf][sid][i] == opt)
873 /* check whether option was changed */
874 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
875 return c[conf][sid][opt];
877 /* return base value */
878 if (v[conf] && v[conf][sid])
879 return v[conf][sid][opt];
884 /* requested an entire section */
891 set: function(conf, sid, opt, val)
893 var n = this.state.creates;
894 var c = this.state.changes;
895 var d = this.state.deletes;
897 if (typeof(sid) == 'undefined' ||
898 typeof(opt) == 'undefined' ||
899 opt.charAt(0) == '.')
902 if (sid.indexOf('.new.') == 0)
904 if (n[conf] && n[conf][sid])
906 if (typeof(val) != 'undefined')
907 n[conf][sid][opt] = val;
909 delete n[conf][sid][opt];
912 else if (typeof(val) != 'undefined')
914 /* do not set within deleted section */
915 if (d[conf] && d[conf][sid] === true)
924 /* undelete option */
925 if (d[conf] && d[conf][sid])
926 d[conf][sid] = _luci2.filterArray(d[conf][sid], opt);
928 c[conf][sid][opt] = val;
938 if (d[conf][sid] !== true)
939 d[conf][sid].push(opt);
943 unset: function(conf, sid, opt)
945 return this.set(conf, sid, opt, undefined);
952 for (var pkg in this.state.values)
957 return this.load(pkgs);
962 var v = this.state.values;
963 var n = this.state.creates;
964 var r = this.state.reorder;
966 if ($.isEmptyObject(r))
967 return _luci2.deferrable();
972 gather all created and existing sections, sort them according
973 to their index value and issue an uci order call
988 o.sort(function(a, b) {
989 return (a['.index'] - b['.index']);
994 for (var i = 0; i < o.length; i++)
995 sids.push(o[i]['.name']);
997 this._order(c, sids);
1001 this.state.reorder = { };
1002 return _luci2.rpc.flush();
1005 swap: function(conf, sid1, sid2)
1007 var s1 = this.get(conf, sid1);
1008 var s2 = this.get(conf, sid2);
1009 var n1 = s1 ? s1['.index'] : NaN;
1010 var n2 = s2 ? s2['.index'] : NaN;
1012 if (isNaN(n1) || isNaN(n2))
1018 this.state.reorder[conf] = true;
1030 if (self.state.creates)
1031 for (var c in self.state.creates)
1032 for (var s in self.state.creates[c])
1039 for (var k in self.state.creates[c][s])
1042 r.type = self.state.creates[c][s][k];
1043 else if (k == '.create')
1044 r.name = self.state.creates[c][s][k];
1045 else if (k.charAt(0) != '.')
1046 r.values[k] = self.state.creates[c][s][k];
1049 snew.push(self.state.creates[c][s]);
1051 self._add(r.config, r.type, r.name, r.values);
1054 if (self.state.changes)
1055 for (var c in self.state.changes)
1056 for (var s in self.state.changes[c])
1057 self._set(c, s, self.state.changes[c][s]);
1059 if (self.state.deletes)
1060 for (var c in self.state.deletes)
1061 for (var s in self.state.deletes[c])
1063 var o = self.state.deletes[c][s];
1064 self._delete(c, s, (o === true) ? undefined : o);
1067 return _luci2.rpc.flush().then(function(responses) {
1069 array "snew" holds references to the created uci sections,
1070 use it to assign the returned names of the new sections
1072 for (var i = 0; i < snew.length; i++)
1073 snew[i]['.name'] = responses[i];
1075 return self._reorder();
1079 _apply: _luci2.rpc.declare({
1082 params: [ 'timeout', 'rollback' ]
1085 _confirm: _luci2.rpc.declare({
1090 apply: function(timeout)
1093 var date = new Date();
1094 var deferred = $.Deferred();
1096 if (typeof(timeout) != 'number' || timeout < 1)
1099 self._apply(timeout, true).then(function(rv) {
1102 deferred.rejectWith(self, [ rv ]);
1106 var try_deadline = date.getTime() + 1000 * timeout;
1107 var try_confirm = function()
1109 return self._confirm().then(function(rv) {
1112 if (date.getTime() < try_deadline)
1113 window.setTimeout(try_confirm, 250);
1115 deferred.rejectWith(self, [ rv ]);
1120 deferred.resolveWith(self, [ rv ]);
1124 window.setTimeout(try_confirm, 1000);
1130 changes: _luci2.rpc.declare({
1133 expect: { changes: { } }
1136 readable: function(conf)
1138 return _luci2.session.hasACL('uci', conf, 'read');
1141 writable: function(conf)
1143 return _luci2.session.hasACL('uci', conf, 'write');
1147 this.uci = new this.UCIContext();
1150 listDeviceNames: _luci2.rpc.declare({
1153 expect: { 'devices': [ ] },
1154 filter: function(data) {
1160 getDeviceStatus: _luci2.rpc.declare({
1163 params: [ 'device' ],
1164 expect: { '': { } },
1165 filter: function(data, params) {
1166 if (!$.isEmptyObject(data))
1168 data['device'] = params['device'];
1175 getAssocList: _luci2.rpc.declare({
1177 method: 'assoclist',
1178 params: [ 'device' ],
1179 expect: { results: [ ] },
1180 filter: function(data, params) {
1181 for (var i = 0; i < data.length; i++)
1182 data[i]['device'] = params['device'];
1184 data.sort(function(a, b) {
1185 if (a.bssid < b.bssid)
1187 else if (a.bssid > b.bssid)
1197 getWirelessStatus: function() {
1198 return this.listDeviceNames().then(function(names) {
1201 for (var i = 0; i < names.length; i++)
1202 _luci2.wireless.getDeviceStatus(names[i]);
1204 return _luci2.rpc.flush();
1205 }).then(function(networks) {
1209 'country', 'channel', 'frequency', 'frequency_offset',
1210 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1214 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1215 'signal', 'noise', 'bitrate', 'encryption'
1218 for (var i = 0; i < networks.length; i++)
1220 var phy = rv[networks[i].phy] || (
1221 rv[networks[i].phy] = { networks: [ ] }
1225 device: networks[i].device
1228 for (var j = 0; j < phy_attrs.length; j++)
1229 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1231 for (var j = 0; j < net_attrs.length; j++)
1232 net[net_attrs[j]] = networks[i][net_attrs[j]];
1234 phy.networks.push(net);
1241 getAssocLists: function()
1243 return this.listDeviceNames().then(function(names) {
1246 for (var i = 0; i < names.length; i++)
1247 _luci2.wireless.getAssocList(names[i]);
1249 return _luci2.rpc.flush();
1250 }).then(function(assoclists) {
1253 for (var i = 0; i < assoclists.length; i++)
1254 for (var j = 0; j < assoclists[i].length; j++)
1255 rv.push(assoclists[i][j]);
1261 formatEncryption: function(enc)
1263 var format_list = function(l, s)
1266 for (var i = 0; i < l.length; i++)
1267 rv.push(l[i].toUpperCase());
1268 return rv.join(s ? s : ', ');
1271 if (!enc || !enc.enabled)
1272 return _luci2.tr('None');
1276 if (enc.wep.length == 2)
1277 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1278 else if (enc.wep[0] == 'shared')
1279 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1281 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1285 if (enc.wpa.length == 2)
1286 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1287 format_list(enc.authentication, '/'),
1288 format_list(enc.ciphers, ', ')
1290 else if (enc.wpa[0] == 2)
1291 return 'WPA2 %s (%s)'.format(
1292 format_list(enc.authentication, '/'),
1293 format_list(enc.ciphers, ', ')
1296 return 'WPA %s (%s)'.format(
1297 format_list(enc.authentication, '/'),
1298 format_list(enc.ciphers, ', ')
1302 return _luci2.tr('Unknown');
1307 getZoneColor: function(zone)
1309 if ($.isPlainObject(zone))
1314 else if (zone == 'wan')
1317 for (var i = 0, hash = 0;
1319 hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1321 for (var i = 0, color = '#';
1323 color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1328 findZoneByNetwork: function(network)
1331 var zone = undefined;
1333 return _luci2.uci.sections('firewall', 'zone', function(z) {
1334 if (!z.name || !z.network)
1337 if (!$.isArray(z.network))
1338 z.network = z.network.split(/\s+/);
1340 for (var i = 0; i < z.network.length; i++)
1342 if (z.network[i] == network)
1348 }).then(function() {
1350 zone.color = self.getZoneColor(zone);
1358 getSystemInfo: _luci2.rpc.declare({
1364 getBoardInfo: _luci2.rpc.declare({
1370 getDiskInfo: _luci2.rpc.declare({
1371 object: 'luci2.system',
1376 getInfo: function(cb)
1380 this.getSystemInfo();
1381 this.getBoardInfo();
1384 return _luci2.rpc.flush().then(function(info) {
1387 $.extend(rv, info[0]);
1388 $.extend(rv, info[1]);
1389 $.extend(rv, info[2]);
1395 getProcessList: _luci2.rpc.declare({
1396 object: 'luci2.system',
1397 method: 'process_list',
1398 expect: { processes: [ ] },
1399 filter: function(data) {
1400 data.sort(function(a, b) { return a.pid - b.pid });
1405 getSystemLog: _luci2.rpc.declare({
1406 object: 'luci2.system',
1411 getKernelLog: _luci2.rpc.declare({
1412 object: 'luci2.system',
1417 getZoneInfo: function(cb)
1419 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1422 sendSignal: _luci2.rpc.declare({
1423 object: 'luci2.system',
1424 method: 'process_signal',
1425 params: [ 'pid', 'signal' ],
1426 filter: function(data) {
1431 initList: _luci2.rpc.declare({
1432 object: 'luci2.system',
1433 method: 'init_list',
1434 expect: { initscripts: [ ] },
1435 filter: function(data) {
1436 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1441 initEnabled: function(init, cb)
1443 return this.initList().then(function(list) {
1444 for (var i = 0; i < list.length; i++)
1445 if (list[i].name == init)
1446 return !!list[i].enabled;
1452 initRun: _luci2.rpc.declare({
1453 object: 'luci2.system',
1454 method: 'init_action',
1455 params: [ 'name', 'action' ],
1456 filter: function(data) {
1461 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1462 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1463 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1464 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1465 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1466 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1469 getRcLocal: _luci2.rpc.declare({
1470 object: 'luci2.system',
1471 method: 'rclocal_get',
1472 expect: { data: '' }
1475 setRcLocal: _luci2.rpc.declare({
1476 object: 'luci2.system',
1477 method: 'rclocal_set',
1482 getCrontab: _luci2.rpc.declare({
1483 object: 'luci2.system',
1484 method: 'crontab_get',
1485 expect: { data: '' }
1488 setCrontab: _luci2.rpc.declare({
1489 object: 'luci2.system',
1490 method: 'crontab_set',
1495 getSSHKeys: _luci2.rpc.declare({
1496 object: 'luci2.system',
1497 method: 'sshkeys_get',
1498 expect: { keys: [ ] }
1501 setSSHKeys: _luci2.rpc.declare({
1502 object: 'luci2.system',
1503 method: 'sshkeys_set',
1508 setPassword: _luci2.rpc.declare({
1509 object: 'luci2.system',
1510 method: 'password_set',
1511 params: [ 'user', 'password' ]
1515 listLEDs: _luci2.rpc.declare({
1516 object: 'luci2.system',
1518 expect: { leds: [ ] }
1521 listUSBDevices: _luci2.rpc.declare({
1522 object: 'luci2.system',
1524 expect: { devices: [ ] }
1528 testUpgrade: _luci2.rpc.declare({
1529 object: 'luci2.system',
1530 method: 'upgrade_test',
1534 startUpgrade: _luci2.rpc.declare({
1535 object: 'luci2.system',
1536 method: 'upgrade_start',
1540 cleanUpgrade: _luci2.rpc.declare({
1541 object: 'luci2.system',
1542 method: 'upgrade_clean'
1546 restoreBackup: _luci2.rpc.declare({
1547 object: 'luci2.system',
1548 method: 'backup_restore'
1551 cleanBackup: _luci2.rpc.declare({
1552 object: 'luci2.system',
1553 method: 'backup_clean'
1557 getBackupConfig: _luci2.rpc.declare({
1558 object: 'luci2.system',
1559 method: 'backup_config_get',
1560 expect: { config: '' }
1563 setBackupConfig: _luci2.rpc.declare({
1564 object: 'luci2.system',
1565 method: 'backup_config_set',
1570 listBackup: _luci2.rpc.declare({
1571 object: 'luci2.system',
1572 method: 'backup_list',
1573 expect: { files: [ ] }
1577 testReset: _luci2.rpc.declare({
1578 object: 'luci2.system',
1579 method: 'reset_test',
1580 expect: { supported: false }
1583 startReset: _luci2.rpc.declare({
1584 object: 'luci2.system',
1585 method: 'reset_start'
1589 performReboot: _luci2.rpc.declare({
1590 object: 'luci2.system',
1596 updateLists: _luci2.rpc.declare({
1597 object: 'luci2.opkg',
1602 _allPackages: _luci2.rpc.declare({
1603 object: 'luci2.opkg',
1605 params: [ 'offset', 'limit', 'pattern' ],
1609 _installedPackages: _luci2.rpc.declare({
1610 object: 'luci2.opkg',
1611 method: 'list_installed',
1612 params: [ 'offset', 'limit', 'pattern' ],
1616 _findPackages: _luci2.rpc.declare({
1617 object: 'luci2.opkg',
1619 params: [ 'offset', 'limit', 'pattern' ],
1623 _fetchPackages: function(action, offset, limit, pattern)
1627 return action(offset, limit, pattern).then(function(list) {
1628 if (!list.total || !list.packages)
1629 return { length: 0, total: 0 };
1631 packages.push.apply(packages, list.packages);
1632 packages.total = list.total;
1637 if (packages.length >= limit)
1642 for (var i = offset + packages.length; i < limit; i += 100)
1643 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1645 return _luci2.rpc.flush();
1646 }).then(function(lists) {
1647 for (var i = 0; i < lists.length; i++)
1649 if (!lists[i].total || !lists[i].packages)
1652 packages.push.apply(packages, lists[i].packages);
1653 packages.total = lists[i].total;
1660 listPackages: function(offset, limit, pattern)
1662 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1665 installedPackages: function(offset, limit, pattern)
1667 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1670 findPackages: function(offset, limit, pattern)
1672 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1675 installPackage: _luci2.rpc.declare({
1676 object: 'luci2.opkg',
1678 params: [ 'package' ],
1682 removePackage: _luci2.rpc.declare({
1683 object: 'luci2.opkg',
1685 params: [ 'package' ],
1689 getConfig: _luci2.rpc.declare({
1690 object: 'luci2.opkg',
1691 method: 'config_get',
1692 expect: { config: '' }
1695 setConfig: _luci2.rpc.declare({
1696 object: 'luci2.opkg',
1697 method: 'config_set',
1704 login: _luci2.rpc.declare({
1707 params: [ 'username', 'password' ],
1711 access: _luci2.rpc.declare({
1714 params: [ 'scope', 'object', 'function' ],
1715 expect: { access: false }
1720 return _luci2.session.access('ubus', 'session', 'access');
1723 startHeartbeat: function()
1725 this._hearbeatInterval = window.setInterval(function() {
1726 _luci2.session.isAlive().then(function(alive) {
1729 _luci2.session.stopHeartbeat();
1730 _luci2.ui.login(true);
1734 }, _luci2.globals.timeout * 2);
1737 stopHeartbeat: function()
1739 if (typeof(this._hearbeatInterval) != 'undefined')
1741 window.clearInterval(this._hearbeatInterval);
1742 delete this._hearbeatInterval;
1749 _fetch_acls: _luci2.rpc.declare({
1755 _fetch_acls_cb: function(acls)
1757 _luci2.session._acls = acls;
1760 updateACLs: function()
1762 return _luci2.session._fetch_acls()
1763 .then(_luci2.session._fetch_acls_cb);
1766 hasACL: function(scope, object, func)
1768 var acls = _luci2.session._acls;
1770 if (typeof(func) == 'undefined')
1771 return (acls && acls[scope] && acls[scope][object]);
1773 if (acls && acls[scope] && acls[scope][object])
1774 for (var i = 0; i < acls[scope][object].length; i++)
1775 if (acls[scope][object][i] == func)
1784 saveScrollTop: function()
1786 this._scroll_top = $(document).scrollTop();
1789 restoreScrollTop: function()
1791 if (typeof(this._scroll_top) == 'undefined')
1794 $(document).scrollTop(this._scroll_top);
1796 delete this._scroll_top;
1799 loading: function(enable)
1801 var win = $(window);
1802 var body = $('body');
1804 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1806 .addClass('modal fade')
1807 .append($('<div />')
1808 .addClass('modal-dialog')
1809 .append($('<div />')
1810 .addClass('modal-content luci2-modal-loader')
1811 .append($('<div />')
1812 .addClass('modal-body')
1813 .text(_luci2.tr('Loading data…')))))
1821 state.modal.modal(enable ? 'show' : 'hide');
1824 dialog: function(title, content, options)
1826 var win = $(window);
1827 var body = $('body');
1829 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1830 dialog: $('<div />')
1831 .addClass('modal fade')
1832 .append($('<div />')
1833 .addClass('modal-dialog')
1834 .append($('<div />')
1835 .addClass('modal-content')
1836 .append($('<div />')
1837 .addClass('modal-header')
1839 .addClass('modal-title'))
1840 .append($('<div />')
1841 .addClass('modal-body'))
1842 .append($('<div />')
1843 .addClass('modal-footer')
1844 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1846 $(this).parents('div.modal').modal('hide');
1851 if (typeof(options) != 'object')
1854 if (title === false)
1856 state.dialog.modal('hide');
1861 var cnt = state.dialog.children().children().children('div.modal-body');
1862 var ftr = state.dialog.children().children().children('div.modal-footer');
1866 if (options.style == 'confirm')
1868 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
1869 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1871 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
1872 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1874 else if (options.style == 'close')
1876 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1877 .click(options.close || function() { _luci2.ui.dialog(false) }));
1879 else if (options.style == 'wait')
1881 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1882 .attr('disabled', true));
1885 state.dialog.find('h4:first').text(title);
1886 state.dialog.modal('show');
1888 cnt.empty().append(content);
1891 upload: function(title, content, options)
1893 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1895 .attr('method', 'post')
1896 .attr('action', '/cgi-bin/luci-upload')
1897 .attr('enctype', 'multipart/form-data')
1898 .attr('target', 'cbi-fileupload-frame')
1900 .append($('<input />')
1901 .attr('type', 'hidden')
1902 .attr('name', 'sessionid'))
1903 .append($('<input />')
1904 .attr('type', 'hidden')
1905 .attr('name', 'filename'))
1906 .append($('<input />')
1907 .attr('type', 'file')
1908 .attr('name', 'filedata')
1909 .addClass('cbi-input-file'))
1910 .append($('<div />')
1911 .css('width', '100%')
1912 .addClass('progress progress-striped active')
1913 .append($('<div />')
1914 .addClass('progress-bar')
1915 .css('width', '100%')))
1916 .append($('<iframe />')
1917 .addClass('pull-right')
1918 .attr('name', 'cbi-fileupload-frame')
1919 .css('width', '1px')
1920 .css('height', '1px')
1921 .css('visibility', 'hidden')),
1923 finish_cb: function(ev) {
1924 $(this).off('load');
1926 var body = (this.contentDocument || this.contentWindow.document).body;
1927 if (body.firstChild.tagName.toLowerCase() == 'pre')
1928 body = body.firstChild;
1932 json = $.parseJSON(body.innerHTML);
1935 message: _luci2.tr('Invalid server response received'),
1936 error: [ -1, _luci2.tr('Invalid data') ]
1942 L.ui.dialog(L.tr('File upload'), [
1943 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1944 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1945 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1946 ], { style: 'close' });
1948 else if (typeof(state.success_cb) == 'function')
1950 state.success_cb(json);
1954 confirm_cb: function() {
1955 var f = state.form.find('.cbi-input-file');
1956 var b = state.form.find('.progress');
1957 var p = state.form.find('p');
1962 state.form.find('iframe').on('load', state.finish_cb);
1963 state.form.submit();
1967 p.text(_luci2.tr('File upload in progress …'));
1969 state.form.parent().parent().find('button').prop('disabled', true);
1973 state.form.find('.progress').hide();
1974 state.form.find('.cbi-input-file').val('').show();
1975 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1977 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1978 state.form.find('[name=filename]').val(options.filename);
1980 state.success_cb = options.success;
1982 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1984 confirm: state.confirm_cb
1988 reconnect: function()
1990 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1991 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1992 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1994 var interval, timeout;
1997 _luci2.tr('Waiting for device'), [
1998 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
2000 .css('width', '100%')
2001 .addClass('progressbar')
2002 .addClass('intermediate')
2003 .append($('<div />')
2004 .css('width', '100%'))
2005 ], { style: 'wait' }
2008 for (var i = 0; i < protocols.length; i++)
2009 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
2011 //_luci2.network.getNetworkStatus(function(s) {
2012 // for (var i = 0; i < protocols.length; i++)
2014 // for (var j = 0; j < s.length; j++)
2016 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
2017 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
2019 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
2020 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
2023 //}).then(function() {
2024 images.on('load', function() {
2025 var url = this.getAttribute('url');
2026 _luci2.session.isAlive().then(function(access) {
2029 window.clearTimeout(timeout);
2030 window.clearInterval(interval);
2031 _luci2.ui.dialog(false);
2036 location.href = url;
2041 interval = window.setInterval(function() {
2042 images.each(function() {
2043 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
2047 timeout = window.setTimeout(function() {
2048 window.clearInterval(interval);
2052 _luci2.tr('Device not responding'),
2053 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2060 login: function(invalid)
2062 var state = _luci2.ui._login || (_luci2.ui._login = {
2065 .attr('method', 'post')
2067 .addClass('alert-message')
2068 .text(_luci2.tr('Wrong username or password given!')))
2070 .append($('<label />')
2071 .text(_luci2.tr('Username'))
2072 .append($('<br />'))
2073 .append($('<input />')
2074 .attr('type', 'text')
2075 .attr('name', 'username')
2076 .attr('value', 'root')
2077 .addClass('form-control')
2078 .keypress(function(ev) {
2079 if (ev.which == 10 || ev.which == 13)
2083 .append($('<label />')
2084 .text(_luci2.tr('Password'))
2085 .append($('<br />'))
2086 .append($('<input />')
2087 .attr('type', 'password')
2088 .attr('name', 'password')
2089 .addClass('form-control')
2090 .keypress(function(ev) {
2091 if (ev.which == 10 || ev.which == 13)
2095 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2097 response_cb: function(response) {
2098 if (!response.ubus_rpc_session)
2100 _luci2.ui.login(true);
2104 _luci2.globals.sid = response.ubus_rpc_session;
2105 _luci2.setHash('id', _luci2.globals.sid);
2106 _luci2.session.startHeartbeat();
2107 _luci2.ui.dialog(false);
2108 state.deferred.resolve();
2112 confirm_cb: function() {
2113 var u = state.form.find('[name=username]').val();
2114 var p = state.form.find('[name=password]').val();
2120 _luci2.tr('Logging in'), [
2121 $('<p />').text(_luci2.tr('Log in in progress …')),
2123 .css('width', '100%')
2124 .addClass('progressbar')
2125 .addClass('intermediate')
2126 .append($('<div />')
2127 .css('width', '100%'))
2128 ], { style: 'wait' }
2131 _luci2.globals.sid = '00000000000000000000000000000000';
2132 _luci2.session.login(u, p).then(state.response_cb);
2136 if (!state.deferred || state.deferred.state() != 'pending')
2137 state.deferred = $.Deferred();
2139 /* try to find sid from hash */
2140 var sid = _luci2.getHash('id');
2141 if (sid && sid.match(/^[a-f0-9]{32}$/))
2143 _luci2.globals.sid = sid;
2144 _luci2.session.isAlive().then(function(access) {
2147 _luci2.session.startHeartbeat();
2148 state.deferred.resolve();
2152 _luci2.setHash('id', undefined);
2157 return state.deferred;
2161 state.form.find('.alert-message').show();
2163 state.form.find('.alert-message').hide();
2165 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2167 confirm: state.confirm_cb
2170 state.form.find('[name=password]').focus();
2172 return state.deferred;
2175 cryptPassword: _luci2.rpc.declare({
2179 expect: { crypt: '' }
2183 _acl_merge_scope: function(acl_scope, scope)
2185 if ($.isArray(scope))
2187 for (var i = 0; i < scope.length; i++)
2188 acl_scope[scope[i]] = true;
2190 else if ($.isPlainObject(scope))
2192 for (var object_name in scope)
2194 if (!$.isArray(scope[object_name]))
2197 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2199 for (var i = 0; i < scope[object_name].length; i++)
2200 acl_object[scope[object_name][i]] = true;
2205 _acl_merge_permission: function(acl_perm, perm)
2207 if ($.isPlainObject(perm))
2209 for (var scope_name in perm)
2211 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2212 this._acl_merge_scope(acl_scope, perm[scope_name]);
2217 _acl_merge_group: function(acl_group, group)
2219 if ($.isPlainObject(group))
2221 if (!acl_group.description)
2222 acl_group.description = group.description;
2226 var acl_perm = acl_group.read || (acl_group.read = { });
2227 this._acl_merge_permission(acl_perm, group.read);
2232 var acl_perm = acl_group.write || (acl_group.write = { });
2233 this._acl_merge_permission(acl_perm, group.write);
2238 _acl_merge_tree: function(acl_tree, tree)
2240 if ($.isPlainObject(tree))
2242 for (var group_name in tree)
2244 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2245 this._acl_merge_group(acl_group, tree[group_name]);
2250 listAvailableACLs: _luci2.rpc.declare({
2253 expect: { acls: [ ] },
2254 filter: function(trees) {
2256 for (var i = 0; i < trees.length; i++)
2257 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2262 renderMainMenu: _luci2.rpc.declare({
2265 expect: { menu: { } },
2266 filter: function(entries) {
2267 _luci2.globals.mainMenu = new _luci2.ui.menu();
2268 _luci2.globals.mainMenu.entries(entries);
2272 .append(_luci2.globals.mainMenu.render(0, 1));
2276 renderViewMenu: function()
2280 .append(_luci2.globals.mainMenu.render(2, 900));
2283 renderView: function()
2285 var node = arguments[0];
2286 var name = node.view.split(/\//).join('.');
2289 for (var i = 1; i < arguments.length; i++)
2290 args.push(arguments[i]);
2292 if (_luci2.globals.currentView)
2293 _luci2.globals.currentView.finish();
2295 _luci2.ui.renderViewMenu();
2298 _luci2._views = { };
2300 _luci2.setHash('view', node.view);
2302 if (_luci2._views[name] instanceof _luci2.ui.view)
2304 _luci2.globals.currentView = _luci2._views[name];
2305 return _luci2._views[name].render.apply(_luci2._views[name], args);
2308 var url = _luci2.globals.resource + '/view/' + name + '.js';
2310 return $.ajax(url, {
2314 }).then(function(data) {
2316 var viewConstructorSource = (
2317 '(function(L, $) { ' +
2319 '})(_luci2, $);\n\n' +
2321 ).format(data, url);
2323 var viewConstructor = eval(viewConstructorSource);
2325 _luci2._views[name] = new viewConstructor({
2327 acls: node.write || { }
2330 _luci2.globals.currentView = _luci2._views[name];
2331 return _luci2._views[name].render.apply(_luci2._views[name], args);
2334 alert('Unable to instantiate view "%s": %s'.format(url, e));
2337 return $.Deferred().resolve();
2341 updateHostname: function()
2343 return _luci2.system.getBoardInfo().then(function(info) {
2345 $('#hostname').text(info.hostname);
2349 updateChanges: function()
2351 return _luci2.uci.changes().then(function(changes) {
2355 for (var config in changes)
2359 for (var i = 0; i < changes[config].length; i++)
2361 var c = changes[config][i];
2370 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2372 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2377 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2379 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2383 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2387 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2391 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2396 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2398 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2403 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2404 n += changes[config].length;
2415 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2416 .click(function(ev) {
2417 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2418 ev.preventDefault();
2428 _luci2.ui.loading(true);
2431 _luci2.ui.updateHostname(),
2432 _luci2.ui.updateChanges(),
2433 _luci2.ui.renderMainMenu()
2435 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2436 _luci2.ui.loading(false);
2441 button: function(label, style, title)
2443 style = style || 'default';
2445 return $('<button />')
2446 .attr('type', 'button')
2447 .attr('title', title ? title : '')
2448 .addClass('btn btn-' + style)
2453 this.ui.AbstractWidget = Class.extend({
2454 i18n: function(text) {
2459 var key = arguments[0];
2462 for (var i = 1; i < arguments.length; i++)
2463 args.push(arguments[i]);
2465 switch (typeof(this.options[key]))
2471 return this.options[key].apply(this, args);
2474 return ''.format.apply('' + this.options[key], args);
2478 toString: function() {
2479 return $('<div />').append(this.render()).html();
2482 insertInto: function(id) {
2483 return $(id).empty().append(this.render());
2486 appendTo: function(id) {
2487 return $(id).append(this.render());
2491 this.ui.view = this.ui.AbstractWidget.extend({
2492 _fetch_template: function()
2494 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2498 success: function(data) {
2499 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2500 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2507 return _luci2.tr(p2);
2510 return _luci2.globals[p2] || '';
2513 return '(?' + match + ')';
2517 $('#maincontent').append(data);
2524 throw "Not implemented";
2529 var container = $('#maincontent');
2534 container.append($('<h2 />').append(this.title));
2536 if (this.description)
2537 container.append($('<p />').append(this.description));
2542 for (var i = 0; i < arguments.length; i++)
2543 args.push(arguments[i]);
2545 return this._fetch_template().then(function() {
2546 return _luci2.deferrable(self.execute.apply(self, args));
2550 repeat: function(func, interval)
2554 if (!self._timeouts)
2555 self._timeouts = [ ];
2557 var index = self._timeouts.length;
2559 if (typeof(interval) != 'number')
2562 var setTimer, runTimer;
2564 setTimer = function() {
2566 self._timeouts[index] = window.setTimeout(runTimer, interval);
2569 runTimer = function() {
2570 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
2578 if ($.isArray(this._timeouts))
2580 for (var i = 0; i < this._timeouts.length; i++)
2581 window.clearTimeout(this._timeouts[i]);
2583 delete this._timeouts;
2588 this.ui.menu = this.ui.AbstractWidget.extend({
2593 entries: function(entries)
2595 for (var entry in entries)
2597 var path = entry.split(/\//);
2598 var node = this._nodes;
2600 for (i = 0; i < path.length; i++)
2605 if (!node.childs[path[i]])
2606 node.childs[path[i]] = { };
2608 node = node.childs[path[i]];
2611 $.extend(node, entries[entry]);
2615 _indexcmp: function(a, b)
2617 var x = a.index || 0;
2618 var y = b.index || 0;
2622 firstChildView: function(node)
2628 for (var child in (node.childs || { }))
2629 nodes.push(node.childs[child]);
2631 nodes.sort(this._indexcmp);
2633 for (var i = 0; i < nodes.length; i++)
2635 var child = this.firstChildView(nodes[i]);
2638 for (var key in child)
2639 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2640 node[key] = child[key];
2649 _onclick: function(ev)
2651 _luci2.ui.loading(true);
2652 _luci2.ui.renderView(ev.data).then(function() {
2653 _luci2.ui.loading(false);
2656 ev.preventDefault();
2660 _render: function(childs, level, min, max)
2663 for (var node in childs)
2665 var child = this.firstChildView(childs[node]);
2667 nodes.push(childs[node]);
2670 nodes.sort(this._indexcmp);
2672 var list = $('<ul />');
2675 list.addClass('nav').addClass('navbar-nav');
2676 else if (level == 1)
2677 list.addClass('dropdown-menu').addClass('navbar-inverse');
2679 for (var i = 0; i < nodes.length; i++)
2681 if (!_luci2.globals.defaultNode)
2683 var v = _luci2.getHash('view');
2684 if (!v || v == nodes[i].view)
2685 _luci2.globals.defaultNode = nodes[i];
2688 var item = $('<li />')
2691 .text(_luci2.tr(nodes[i].title)))
2694 if (nodes[i].childs && level < max)
2696 item.addClass('dropdown');
2699 .addClass('dropdown-toggle')
2700 .attr('data-toggle', 'dropdown')
2701 .append('<b class="caret"></b>');
2703 item.append(this._render(nodes[i].childs, level + 1));
2707 item.find('a').click(nodes[i], this._onclick);
2714 render: function(min, max)
2716 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2717 return this._render(top.childs, 0, min, max);
2720 getNode: function(path, max)
2722 var p = path.split(/\//);
2723 var n = this._nodes;
2725 if (typeof(max) == 'undefined')
2728 for (var i = 0; i < max; i++)
2730 if (!n.childs[p[i]])
2740 this.ui.table = this.ui.AbstractWidget.extend({
2746 row: function(values)
2748 if ($.isArray(values))
2750 this._rows.push(values);
2752 else if ($.isPlainObject(values))
2755 for (var i = 0; i < this.options.columns.length; i++)
2757 var col = this.options.columns[i];
2759 if (typeof col.key == 'string')
2760 v.push(values[col.key]);
2768 rows: function(rows)
2770 for (var i = 0; i < rows.length; i++)
2774 render: function(id)
2776 var fieldset = document.createElement('fieldset');
2777 fieldset.className = 'cbi-section';
2779 if (this.options.caption)
2781 var legend = document.createElement('legend');
2782 $(legend).append(this.options.caption);
2783 fieldset.appendChild(legend);
2786 var table = document.createElement('table');
2787 table.className = 'table table-condensed table-hover';
2789 var has_caption = false;
2790 var has_description = false;
2792 for (var i = 0; i < this.options.columns.length; i++)
2793 if (this.options.columns[i].caption)
2798 else if (this.options.columns[i].description)
2800 has_description = true;
2806 var tr = table.insertRow(-1);
2807 tr.className = 'cbi-section-table-titles';
2809 for (var i = 0; i < this.options.columns.length; i++)
2811 var col = this.options.columns[i];
2812 var th = document.createElement('th');
2813 th.className = 'cbi-section-table-cell';
2818 th.style.width = col.width;
2821 th.style.textAlign = col.align;
2824 $(th).append(col.caption);
2828 if (has_description)
2830 var tr = table.insertRow(-1);
2831 tr.className = 'cbi-section-table-descr';
2833 for (var i = 0; i < this.options.columns.length; i++)
2835 var col = this.options.columns[i];
2836 var th = document.createElement('th');
2837 th.className = 'cbi-section-table-cell';
2842 th.style.width = col.width;
2845 th.style.textAlign = col.align;
2847 if (col.description)
2848 $(th).append(col.description);
2852 if (this._rows.length == 0)
2854 if (this.options.placeholder)
2856 var tr = table.insertRow(-1);
2857 var td = tr.insertCell(-1);
2858 td.className = 'cbi-section-table-cell';
2860 td.colSpan = this.options.columns.length;
2861 $(td).append(this.options.placeholder);
2866 for (var i = 0; i < this._rows.length; i++)
2868 var tr = table.insertRow(-1);
2870 for (var j = 0; j < this.options.columns.length; j++)
2872 var col = this.options.columns[j];
2873 var td = tr.insertCell(-1);
2875 var val = this._rows[i][j];
2877 if (typeof(val) == 'undefined')
2878 val = col.placeholder;
2880 if (typeof(val) == 'undefined')
2884 td.style.width = col.width;
2887 td.style.textAlign = col.align;
2889 if (typeof col.format == 'string')
2890 $(td).append(col.format.format(val));
2891 else if (typeof col.format == 'function')
2892 $(td).append(col.format(val, i));
2900 fieldset.appendChild(table);
2906 this.ui.progress = this.ui.AbstractWidget.extend({
2909 var vn = parseInt(this.options.value) || 0;
2910 var mn = parseInt(this.options.max) || 100;
2911 var pc = Math.floor((100 / mn) * vn);
2915 if (typeof(this.options.format) == 'string')
2916 text = this.options.format.format(this.options.value, this.options.max, pc);
2917 else if (typeof(this.options.format) == 'function')
2918 text = this.options.format(pc);
2920 text = '%.2f%%'.format(pc);
2923 .addClass('progress')
2924 .append($('<div />')
2925 .addClass('progress-bar')
2926 .addClass('progress-bar-info')
2927 .css('width', pc + '%'))
2928 .append($('<small />')
2933 this.ui.devicebadge = this.ui.AbstractWidget.extend({
2936 var l2dev = this.options.l2_device || this.options.device;
2937 var l3dev = this.options.l3_device;
2938 var dev = l3dev || l2dev || '?';
2940 var span = document.createElement('span');
2941 span.className = 'badge';
2943 if (typeof(this.options.signal) == 'number' ||
2944 typeof(this.options.noise) == 'number')
2947 if (typeof(this.options.signal) != 'undefined' &&
2948 typeof(this.options.noise) != 'undefined')
2950 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2963 span.appendChild(document.createElement('img'));
2964 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2967 span.title = _luci2.tr('No signal');
2969 span.title = '%s: %d %s / %s: %d %s'.format(
2970 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2971 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2976 var type = 'ethernet';
2977 var desc = _luci2.tr('Ethernet device');
2982 desc = _luci2.tr('Tunnel interface');
2984 else if (dev.indexOf('br-') == 0)
2987 desc = _luci2.tr('Bridge');
2989 else if (dev.indexOf('.') > 0)
2992 desc = _luci2.tr('VLAN interface');
2994 else if (dev.indexOf('wlan') == 0 ||
2995 dev.indexOf('ath') == 0 ||
2996 dev.indexOf('wl') == 0)
2999 desc = _luci2.tr('Wireless Network');
3002 span.appendChild(document.createElement('img'));
3003 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
3007 $(span).append(' ');
3008 $(span).append(dev);
3014 var type = function(f, l)
3024 _luci2.cbi.validation.message = _luci2.tr(msg);
3027 compile: function(code)
3032 var types = _luci2.cbi.validation.types;
3037 for (var i = 0; i < code.length; i++)
3045 switch (code.charCodeAt(i))
3057 var label = code.substring(pos, i);
3058 label = label.replace(/\\(.)/g, '$1');
3059 label = label.replace(/^[ \t]+/g, '');
3060 label = label.replace(/[ \t]+$/g, '');
3062 if (label && !isNaN(label))
3064 stack.push(parseFloat(label));
3066 else if (label.match(/^(['"]).*\1$/))
3068 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
3070 else if (typeof types[label] == 'function')
3072 stack.push(types[label]);
3077 throw "Syntax error, unhandled token '"+label+"'";
3082 depth += (code.charCodeAt(i) == 40);
3088 if (typeof stack[stack.length-2] != 'function')
3089 throw "Syntax error, argument list follows non-function";
3091 stack[stack.length-1] =
3092 _luci2.cbi.validation.compile(code.substring(pos, i));
3105 var validation = this.cbi.validation;
3107 validation.types = {
3108 'integer': function()
3110 if (this.match(/^-?[0-9]+$/) != null)
3113 validation.i18n('Must be a valid integer');
3117 'uinteger': function()
3119 if (validation.types['integer'].apply(this) && (this >= 0))
3122 validation.i18n('Must be a positive integer');
3128 if (!isNaN(parseFloat(this)))
3131 validation.i18n('Must be a valid number');
3135 'ufloat': function()
3137 if (validation.types['float'].apply(this) && (this >= 0))
3140 validation.i18n('Must be a positive number');
3144 'ipaddr': function()
3146 if (validation.types['ip4addr'].apply(this) ||
3147 validation.types['ip6addr'].apply(this))
3150 validation.i18n('Must be a valid IP address');
3154 'ip4addr': function()
3156 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
3158 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
3159 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
3160 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
3161 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
3162 ((RegExp.$6.indexOf('.') < 0)
3163 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
3164 : (validation.types['ip4addr'].apply(RegExp.$6))))
3168 validation.i18n('Must be a valid IPv4 address');
3172 'ip6addr': function()
3174 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
3176 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
3178 var addr = RegExp.$1;
3185 if (addr.indexOf('.') > 0)
3187 var off = addr.lastIndexOf(':');
3189 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
3191 validation.i18n('Must be a valid IPv6 address');
3195 addr = addr.substr(0, off) + ':0:0';
3198 if (addr.indexOf('::') >= 0)
3203 for (var i = 1; i < (addr.length-1); i++)
3204 if (addr.charAt(i) == ':')
3209 validation.i18n('Must be a valid IPv6 address');
3213 for (var i = 0; i < (7 - colons); i++)
3216 if (addr.match(/^(.*?)::(.*?)$/))
3217 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
3218 (RegExp.$2 ? ':' + RegExp.$2 : '');
3221 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
3224 validation.i18n('Must be a valid IPv6 address');
3229 validation.i18n('Must be a valid IPv6 address');
3235 if (validation.types['integer'].apply(this) &&
3236 (this >= 0) && (this <= 65535))
3239 validation.i18n('Must be a valid port number');
3243 'portrange': function()
3245 if (this.match(/^(\d+)-(\d+)$/))
3250 if (validation.types['port'].apply(p1) &&
3251 validation.types['port'].apply(p2) &&
3252 (parseInt(p1) <= parseInt(p2)))
3255 else if (validation.types['port'].apply(this))
3260 validation.i18n('Must be a valid port range');
3264 'macaddr': function()
3266 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
3269 validation.i18n('Must be a valid MAC address');
3275 if (validation.types['hostname'].apply(this) ||
3276 validation.types['ipaddr'].apply(this))
3279 validation.i18n('Must be a valid hostname or IP address');
3283 'hostname': function()
3285 if ((this.length <= 253) &&
3286 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
3287 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
3288 this.match(/[^0-9.]/)))))
3291 validation.i18n('Must be a valid host name');
3295 'network': function()
3297 if (validation.types['uciname'].apply(this) ||
3298 validation.types['host'].apply(this))
3301 validation.i18n('Must be a valid network name');
3305 'wpakey': function()
3309 if ((v.length == 64)
3310 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
3311 : ((v.length >= 8) && (v.length <= 63)))
3314 validation.i18n('Must be a valid WPA key');
3318 'wepkey': function()
3322 if (v.substr(0,2) == 's:')
3325 if (((v.length == 10) || (v.length == 26))
3326 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
3327 : ((v.length == 5) || (v.length == 13)))
3330 validation.i18n('Must be a valid WEP key');
3334 'uciname': function()
3336 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
3339 validation.i18n('Must be a valid UCI identifier');
3343 'range': function(min, max)
3345 var val = parseFloat(this);
3347 if (validation.types['integer'].apply(this) &&
3348 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
3351 validation.i18n('Must be a number between %d and %d');
3355 'min': function(min)
3357 var val = parseFloat(this);
3359 if (validation.types['integer'].apply(this) &&
3360 !isNaN(min) && !isNaN(val) && (val >= min))
3363 validation.i18n('Must be a number greater or equal to %d');
3367 'max': function(max)
3369 var val = parseFloat(this);
3371 if (validation.types['integer'].apply(this) &&
3372 !isNaN(max) && !isNaN(val) && (val <= max))
3375 validation.i18n('Must be a number lower or equal to %d');
3379 'rangelength': function(min, max)
3381 var val = '' + this;
3383 if (!isNaN(min) && !isNaN(max) &&
3384 (val.length >= min) && (val.length <= max))
3387 validation.i18n('Must be between %d and %d characters');
3391 'minlength': function(min)
3393 var val = '' + this;
3395 if (!isNaN(min) && (val.length >= min))
3398 validation.i18n('Must be at least %d characters');
3402 'maxlength': function(max)
3404 var val = '' + this;
3406 if (!isNaN(max) && (val.length <= max))
3409 validation.i18n('Must be at most %d characters');
3417 for (var i = 0; i < arguments.length; i += 2)
3419 delete validation.message;
3421 if (typeof(arguments[i]) != 'function')
3423 if (arguments[i] == this)
3427 else if (arguments[i].apply(this, arguments[i+1]))
3432 if (validation.message)
3433 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3436 validation.message = msgs.join( _luci2.tr(' - or - '));
3444 for (var i = 0; i < arguments.length; i += 2)
3446 delete validation.message;
3448 if (typeof arguments[i] != 'function')
3450 if (arguments[i] != this)
3454 else if (!arguments[i].apply(this, arguments[i+1]))
3459 if (validation.message)
3460 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3463 validation.message = msgs.join(', ');
3469 return validation.types['or'].apply(
3470 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3473 'list': function(subvalidator, subargs)
3475 if (typeof subvalidator != 'function')
3478 var tokens = this.match(/[^ \t]+/g);
3479 for (var i = 0; i < tokens.length; i++)
3480 if (!subvalidator.apply(tokens[i], subargs))
3486 'phonedigit': function()
3488 if (this.match(/^[0-9\*#!\.]+$/) != null)
3491 validation.i18n('Must be a valid phone number digit');
3495 'string': function()
3502 this.cbi.AbstractValue = this.ui.AbstractWidget.extend({
3503 init: function(name, options)
3506 this.instance = { };
3507 this.dependencies = [ ];
3508 this.rdependency = { };
3510 this.options = _luci2.defaults(options, {
3520 return this.section.id('field', sid || '__unknown__', this.name);
3523 render: function(sid, condensed)
3525 var i = this.instance[sid] = { };
3527 i.top = $('<div />');
3531 i.top.addClass('form-group');
3533 if (typeof(this.options.caption) == 'string')
3535 .addClass('col-lg-2 control-label')
3536 .attr('for', this.id(sid))
3537 .text(this.options.caption)
3541 i.error = $('<div />')
3543 .addClass('label label-danger');
3545 i.widget = $('<div />')
3547 .append(this.widget(sid))
3553 i.widget.addClass('col-lg-5');
3556 .addClass('col-lg-5')
3557 .text((typeof(this.options.description) == 'string') ? this.options.description : '')
3564 ucipath: function(sid)
3567 config: (this.options.uci_package || this.map.uci_package),
3568 section: (this.options.uci_section || sid),
3569 option: (this.options.uci_option || this.name)
3573 ucivalue: function(sid)
3575 var uci = this.ucipath(sid);
3576 var val = this.map.get(uci.config, uci.section, uci.option);
3578 if (typeof(val) == 'undefined')
3579 return this.options.initial;
3584 formvalue: function(sid)
3586 var v = $('#' + this.id(sid)).val();
3587 return (v === '') ? undefined : v;
3590 textvalue: function(sid)
3592 var v = this.formvalue(sid);
3594 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3595 v = this.ucivalue(sid);
3597 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3598 v = this.options.placeholder;
3600 if (typeof(v) == 'undefined' || v === '')
3603 if (typeof(v) == 'string' && $.isArray(this.choices))
3605 for (var i = 0; i < this.choices.length; i++)
3606 if (v === this.choices[i][0])
3607 return this.choices[i][1];
3609 else if (v === true)
3610 return _luci2.tr('yes');
3611 else if (v === false)
3612 return _luci2.tr('no');
3613 else if ($.isArray(v))
3614 return v.join(', ');
3619 changed: function(sid)
3621 var a = this.ucivalue(sid);
3622 var b = this.formvalue(sid);
3624 if (typeof(a) != typeof(b))
3627 if (typeof(a) == 'object')
3629 if (a.length != b.length)
3632 for (var i = 0; i < a.length; i++)
3644 var uci = this.ucipath(sid);
3646 if (this.instance[sid].disabled)
3648 if (!this.options.keep)
3649 return this.map.set(uci.config, uci.section, uci.option, undefined);
3654 var chg = this.changed(sid);
3655 var val = this.formvalue(sid);
3658 this.map.set(uci.config, uci.section, uci.option, val);
3663 _ev_validate: function(ev)
3667 var val = d.elem.val();
3668 var vstack = d.vstack;
3670 if (vstack && typeof(vstack[0]) == 'function')
3672 delete validation.message;
3674 if ((val.length == 0 && !d.opt))
3676 d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
3677 d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3679 d.inst.error.text(_luci2.tr('Field must not be empty')).show();
3682 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3684 d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
3685 d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
3687 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1])).show();
3692 d.elem.parents('div.form-group, td').first().removeClass('luci2-form-error');
3693 d.elem.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
3695 if (d.multi && d.inst.widget && d.inst.widget.find('input.error, select.error').length > 0)
3698 d.inst.error.text('').hide();
3703 for (var field in d.self.rdependency)
3704 d.self.rdependency[field].toggle(d.sid);
3709 validator: function(sid, elem, multi)
3711 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3715 if (typeof(this.options.datatype) == 'string')
3718 vstack = _luci2.cbi.validation.compile(this.options.datatype);
3721 else if (typeof(this.options.datatype) == 'function')
3723 var vfunc = this.options.datatype;
3724 vstack = [ function(elem) {
3725 var rv = vfunc(this, elem);
3727 validation.message = rv;
3728 return (rv === true);
3738 inst: this.instance[sid],
3739 opt: this.options.optional
3742 if (elem.prop('tagName') == 'SELECT')
3744 elem.change(evdata, this._ev_validate);
3746 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3748 elem.click(evdata, this._ev_validate);
3749 elem.blur(evdata, this._ev_validate);
3753 elem.keyup(evdata, this._ev_validate);
3754 elem.blur(evdata, this._ev_validate);
3757 elem.attr('cbi-validate', true).on('validate', evdata, this._ev_validate);
3762 validate: function(sid)
3764 var i = this.instance[sid];
3766 i.widget.find('[cbi-validate]').trigger('validate');
3768 return (i.disabled || i.error.text() == '');
3771 depends: function(d, v)
3778 for (var i = 0; i < d.length; i++)
3780 if (typeof(d[i]) == 'string')
3782 else if (d[i] instanceof _luci2.cbi.AbstractValue)
3783 dep[d[i].name] = true;
3786 else if (d instanceof _luci2.cbi.AbstractValue)
3789 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3791 else if (typeof(d) == 'object')
3795 else if (typeof(d) == 'string')
3798 dep[d] = (typeof(v) == 'undefined') ? true : v;
3801 if (!dep || $.isEmptyObject(dep))
3804 for (var field in dep)
3806 var f = this.section.fields[field];
3808 f.rdependency[this.name] = this;
3813 if ($.isEmptyObject(dep))
3816 this.dependencies.push(dep);
3821 toggle: function(sid)
3823 var d = this.dependencies;
3824 var i = this.instance[sid];
3829 for (var n = 0; n < d.length; n++)
3833 for (var field in d[n])
3835 var val = this.section.fields[field].formvalue(sid);
3836 var cmp = d[n][field];
3838 if (typeof(cmp) == 'boolean')
3840 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3846 else if (typeof(cmp) == 'string')
3854 else if (typeof(cmp) == 'function')
3862 else if (cmp instanceof RegExp)
3887 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3894 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
3895 widget: function(sid)
3897 var o = this.options;
3899 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
3900 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3902 var i = $('<input />')
3903 .attr('id', this.id(sid))
3904 .attr('type', 'checkbox')
3905 .prop('checked', this.ucivalue(sid));
3908 .addClass('checkbox')
3909 .append(this.validator(sid, i));
3912 ucivalue: function(sid)
3914 var v = this.callSuper('ucivalue', sid);
3916 if (typeof(v) == 'boolean')
3919 return (v == this.options.enabled);
3922 formvalue: function(sid)
3924 var v = $('#' + this.id(sid)).prop('checked');
3926 if (typeof(v) == 'undefined')
3927 return !!this.options.initial;
3934 var uci = this.ucipath(sid);
3936 if (this.instance[sid].disabled)
3938 if (!this.options.keep)
3939 return this.map.set(uci.config, uci.section, uci.option, undefined);
3944 var chg = this.changed(sid);
3945 var val = this.formvalue(sid);
3949 if (this.options.optional && val == this.options.initial)
3950 this.map.set(uci.config, uci.section, uci.option, undefined);
3952 this.map.set(uci.config, uci.section, uci.option, val ? this.options.enabled : this.options.disabled);
3959 this.cbi.InputValue = this.cbi.AbstractValue.extend({
3960 widget: function(sid)
3962 var i = $('<input />')
3963 .addClass('form-control')
3964 .attr('id', this.id(sid))
3965 .attr('type', 'text')
3966 .attr('placeholder', this.options.placeholder)
3967 .val(this.ucivalue(sid));
3969 return this.validator(sid, i);
3973 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
3974 widget: function(sid)
3976 var i = $('<input />')
3977 .addClass('form-control')
3978 .attr('id', this.id(sid))
3979 .attr('type', 'password')
3980 .attr('placeholder', this.options.placeholder)
3981 .val(this.ucivalue(sid));
3983 var t = $('<span />')
3984 .addClass('input-group-btn')
3985 .append(_luci2.ui.button(_luci2.tr('Reveal'), 'default')
3986 .click(function(ev) {
3988 var i = b.parent().prev();
3989 var t = i.attr('type');
3990 b.text(t == 'password' ? _luci2.tr('Hide') : _luci2.tr('Reveal'));
3991 i.attr('type', (t == 'password') ? 'text' : 'password');
3995 this.validator(sid, i);
3998 .addClass('input-group')
4004 this.cbi.ListValue = this.cbi.AbstractValue.extend({
4005 widget: function(sid)
4007 var s = $('<select />')
4008 .addClass('form-control');
4010 if (this.options.optional)
4013 .text(_luci2.tr('-- Please choose --'))
4017 for (var i = 0; i < this.choices.length; i++)
4019 .attr('value', this.choices[i][0])
4020 .text(this.choices[i][1])
4023 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
4025 return this.validator(sid, s);
4028 value: function(k, v)
4033 this.choices.push([k, v || k]);
4038 this.cbi.MultiValue = this.cbi.ListValue.extend({
4039 widget: function(sid)
4041 var v = this.ucivalue(sid);
4042 var t = $('<div />').attr('id', this.id(sid));
4045 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4048 for (var i = 0; i < v.length; i++)
4052 for (var i = 0; i < this.choices.length; i++)
4055 .addClass('checkbox')
4056 .append($('<input />')
4057 .attr('type', 'checkbox')
4058 .attr('value', this.choices[i][0])
4059 .prop('checked', s[this.choices[i][0]]))
4060 .append(this.choices[i][1])
4067 formvalue: function(sid)
4070 var fields = $('#' + this.id(sid) + ' > label > input');
4072 for (var i = 0; i < fields.length; i++)
4073 if (fields[i].checked)
4074 rv.push(fields[i].getAttribute('value'));
4079 textvalue: function(sid)
4081 var v = this.formvalue(sid);
4085 for (var i = 0; i < this.choices.length; i++)
4086 c[this.choices[i][0]] = this.choices[i][1];
4090 for (var i = 0; i < v.length; i++)
4091 t.push(c[v[i]] || v[i]);
4093 return t.join(', ');
4097 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
4098 _change: function(ev)
4101 var self = ev.data.self;
4103 if (s.selectedIndex == (s.options.length - 1))
4105 ev.data.select.hide();
4106 ev.data.input.show().focus();
4108 var v = ev.data.input.val();
4109 ev.data.input.val(' ');
4110 ev.data.input.val(v);
4112 else if (self.options.optional && s.selectedIndex == 0)
4114 ev.data.input.val('');
4118 ev.data.input.val(ev.data.select.val());
4125 var val = this.value;
4126 var self = ev.data.self;
4128 ev.data.select.empty();
4130 if (self.options.optional)
4133 .text(_luci2.tr('-- please choose --'))
4134 .appendTo(ev.data.select);
4137 for (var i = 0; i < self.choices.length; i++)
4139 if (self.choices[i][0] == val)
4143 .attr('value', self.choices[i][0])
4144 .text(self.choices[i][1])
4145 .appendTo(ev.data.select);
4148 if (!seen && val != '')
4152 .appendTo(ev.data.select);
4156 .text(_luci2.tr('-- custom --'))
4157 .appendTo(ev.data.select);
4159 ev.data.input.hide();
4160 ev.data.select.val(val).show().focus();
4163 _enter: function(ev)
4168 ev.preventDefault();
4169 ev.data.self._blur(ev);
4173 widget: function(sid)
4175 var d = $('<div />')
4176 .attr('id', this.id(sid));
4178 var t = $('<input />')
4179 .attr('type', 'text')
4183 var s = $('<select />')
4188 input: this.validator(sid, t),
4189 select: this.validator(sid, s)
4192 s.change(evdata, this._change);
4193 t.blur(evdata, this._blur);
4194 t.keydown(evdata, this._enter);
4196 t.val(this.ucivalue(sid));
4202 value: function(k, v)
4207 this.choices.push([k, v || k]);
4211 formvalue: function(sid)
4213 var v = $('#' + this.id(sid)).children('input').val();
4214 return (v == '') ? undefined : v;
4218 this.cbi.DynamicList = this.cbi.ComboBox.extend({
4219 _redraw: function(focus, add, del, s)
4221 var v = s.values || [ ];
4224 $(s.parent).children('div.input-group').children('input').each(function(i) {
4226 v.push(this.value || '');
4229 $(s.parent).empty();
4234 v.splice(focus, 0, '');
4236 else if (v.length == 0)
4242 for (var i = 0; i < v.length; i++)
4249 remove: ((i+1) < v.length)
4254 btn = _luci2.ui.button('–', 'danger').click(evdata, this._btnclick);
4256 btn = _luci2.ui.button('+', 'success').click(evdata, this._btnclick);
4260 var txt = $('<input />')
4261 .addClass('form-control')
4262 .attr('type', 'text')
4265 var sel = $('<select />')
4266 .addClass('form-control');
4269 .addClass('input-group')
4272 .append($('<span />')
4273 .addClass('input-group-btn')
4275 .appendTo(s.parent);
4277 evdata.input = this.validator(s.sid, txt, true);
4278 evdata.select = this.validator(s.sid, sel, true);
4280 sel.change(evdata, this._change);
4281 txt.blur(evdata, this._blur);
4282 txt.keydown(evdata, this._keydown);
4287 if (i == focus || -(i+1) == focus)
4294 var f = $('<input />')
4295 .attr('type', 'text')
4297 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
4298 .addClass('form-control')
4299 .keydown(evdata, this._keydown)
4300 .keypress(evdata, this._keypress)
4304 .addClass('input-group')
4306 .append($('<span />')
4307 .addClass('input-group-btn')
4309 .appendTo(s.parent);
4315 else if (-(i+1) == focus)
4319 /* force cursor to end */
4325 evdata.input = this.validator(s.sid, f, true);
4336 _keypress: function(ev)
4340 /* backspace, delete */
4343 if (ev.data.input.val() == '')
4345 ev.preventDefault();
4351 /* enter, arrow up, arrow down */
4355 ev.preventDefault();
4362 _keydown: function(ev)
4364 var input = ev.data.input;
4368 /* backspace, delete */
4371 if (input.val().length == 0)
4373 ev.preventDefault();
4375 var index = ev.data.index;
4381 ev.data.self._redraw(focus, -1, index, ev.data);
4389 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4394 var prev = input.parent().prevAll('div.input-group:first').children('input');
4395 if (prev.is(':visible'))
4398 prev.next('select').focus();
4403 var next = input.parent().nextAll('div.input-group:first').children('input');
4404 if (next.is(':visible'))
4407 next.next('select').focus();
4414 _btnclick: function(ev)
4416 if (!this.getAttribute('disabled'))
4420 var index = ev.data.index;
4421 ev.data.self._redraw(-index, -1, index, ev.data);
4425 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4432 widget: function(sid)
4434 this.options.optional = true;
4436 var v = this.ucivalue(sid);
4439 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4441 var d = $('<div />')
4442 .attr('id', this.id(sid))
4443 .addClass('cbi-input-dynlist');
4445 this._redraw(NaN, -1, -1, {
4455 ucivalue: function(sid)
4457 var v = this.callSuper('ucivalue', sid);
4460 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4465 formvalue: function(sid)
4468 var fields = $('#' + this.id(sid) + ' > input');
4470 for (var i = 0; i < fields.length; i++)
4471 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4472 rv.push(fields[i].value);
4478 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4479 widget: function(sid)
4482 .addClass('form-control-static')
4483 .attr('id', this.id(sid))
4484 .html(this.ucivalue(sid));
4487 formvalue: function(sid)
4489 return this.ucivalue(sid);
4493 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4498 if (!self.interfaces)
4500 self.interfaces = [ ];
4501 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4502 self.interfaces = ifaces;
4510 _device_icon: function(dev)
4512 var type = 'ethernet';
4513 var desc = _luci2.tr('Ethernet device');
4515 if (dev.type == 'IP tunnel')
4518 desc = _luci2.tr('Tunnel interface');
4520 else if (dev['bridge-members'])
4523 desc = _luci2.tr('Bridge');
4525 else if (dev.wireless)
4528 desc = _luci2.tr('Wireless Network');
4530 else if (dev.device.indexOf('.') > 0)
4533 desc = _luci2.tr('VLAN interface');
4537 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4538 .attr('title', '%s (%s)'.format(desc, dev.device));
4541 widget: function(sid)
4543 var id = this.id(sid);
4544 var ul = $('<ul />')
4546 .addClass('list-unstyled');
4548 var itype = this.options.multiple ? 'checkbox' : 'radio';
4549 var value = this.ucivalue(sid);
4552 if (!this.options.multiple)
4553 check[value] = true;
4555 for (var i = 0; i < value.length; i++)
4556 check[value[i]] = true;
4558 if (this.interfaces)
4560 for (var i = 0; i < this.interfaces.length; i++)
4562 var iface = this.interfaces[i];
4563 var badge = $('<span />')
4565 .text('%s: '.format(iface['interface']));
4567 if (iface.device && iface.device.subdevices)
4568 for (var j = 0; j < iface.device.subdevices.length; j++)
4569 badge.append(this._device_icon(iface.device.subdevices[j]));
4570 else if (iface.device)
4571 badge.append(this._device_icon(iface.device));
4573 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4576 .append($('<label />')
4577 .addClass(itype + ' inline')
4578 .append($('<input />')
4579 .attr('name', itype + id)
4580 .attr('type', itype)
4581 .attr('value', iface['interface'])
4582 .prop('checked', !!check[iface['interface']]))
4588 if (!this.options.multiple)
4591 .append($('<label />')
4592 .addClass(itype + ' inline text-muted')
4593 .append($('<input />')
4594 .attr('name', itype + id)
4595 .attr('type', itype)
4597 .prop('checked', !value))
4598 .append(_luci2.tr('unspecified')))
4605 ucivalue: function(sid)
4607 var v = this.callSuper('ucivalue', sid);
4609 if (!this.options.multiple)
4615 else if (typeof(v) == 'string')
4618 return v ? v[0] : undefined;
4625 if (typeof(v) == 'string')
4626 v = v.match(/\S+/g);
4632 formvalue: function(sid)
4634 var inputs = $('#' + this.id(sid) + ' input');
4636 if (!this.options.multiple)
4638 for (var i = 0; i < inputs.length; i++)
4639 if (inputs[i].checked && inputs[i].value !== '')
4640 return inputs[i].value;
4647 for (var i = 0; i < inputs.length; i++)
4648 if (inputs[i].checked)
4649 rv.push(inputs[i].value);
4651 return rv.length ? rv : undefined;
4656 this.cbi.AbstractSection = this.ui.AbstractWidget.extend({
4659 var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4661 for (var i = 1; i < arguments.length; i++)
4662 s.push(arguments[i].replace(/\./g, '_'));
4667 option: function(widget, name, options)
4669 if (this.tabs.length == 0)
4670 this.tab({ id: '__default__', selected: true });
4672 return this.taboption('__default__', widget, name, options);
4675 tab: function(options)
4677 if (options.selected)
4678 this.tabs.selected = this.tabs.length;
4682 caption: options.caption,
4683 description: options.description,
4689 taboption: function(tabid, widget, name, options)
4692 for (var i = 0; i < this.tabs.length; i++)
4694 if (this.tabs[i].id == tabid)
4702 throw 'Cannot append to unknown tab ' + tabid;
4704 var w = widget ? new widget(name, options) : null;
4706 if (!(w instanceof _luci2.cbi.AbstractValue))
4707 throw 'Widget must be an instance of AbstractValue';
4712 this.fields[name] = w;
4718 ucipackages: function(pkg)
4720 for (var i = 0; i < this.tabs.length; i++)
4721 for (var j = 0; j < this.tabs[i].fields.length; j++)
4722 if (this.tabs[i].fields[j].options.uci_package)
4723 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4726 formvalue: function()
4730 this.sections(function(s) {
4731 var sid = s['.name'];
4732 var sv = rv[sid] || (rv[sid] = { });
4734 for (var i = 0; i < this.tabs.length; i++)
4735 for (var j = 0; j < this.tabs[i].fields.length; j++)
4737 var val = this.tabs[i].fields[j].formvalue(sid);
4738 sv[this.tabs[i].fields[j].name] = val;
4745 validate_section: function(sid)
4747 var inst = this.instance[sid];
4750 var badge = $('#' + this.id('teaser', sid)).children('span:first');
4752 for (var i = 0; i < this.tabs.length; i++)
4755 var stbadge = $('#' + this.id('nodetab', sid, this.tabs[i].id)).children('span:first');
4757 for (var j = 0; j < this.tabs[i].fields.length; j++)
4758 if (!this.tabs[i].fields[j].validate(sid))
4764 .attr('title', _luci2.trp('1 Error', '%d Errors', inval).format(inval));
4774 .attr('title', _luci2.trp('1 Error', '%d Errors', invals).format(invals));
4781 validate: function()
4783 this.error_count = 0;
4785 var as = this.sections();
4787 for (var i = 0; i < as.length; i++)
4789 var invals = this.validate_section(as[i]['.name']);
4792 this.error_count += invals;
4795 var badge = $('#' + this.id('sectiontab')).children('span:first');
4797 if (this.error_count > 0)
4799 .text(this.error_count)
4800 .attr('title', _luci2.trp('1 Error', '%d Errors', this.error_count).format(this.error_count));
4804 return (this.error_count == 0);
4808 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
4809 init: function(uci_type, options)
4811 this.uci_type = uci_type;
4812 this.options = options;
4815 this.error_count = 0;
4816 this.active_panel = 0;
4817 this.active_tab = { };
4820 filter: function(section)
4825 sections: function(cb)
4827 var s1 = _luci2.uci.sections(this.map.uci_package);
4830 for (var i = 0; i < s1.length; i++)
4831 if (s1[i]['.type'] == this.uci_type)
4832 if (this.filter(s1[i]))
4835 if (typeof(cb) == 'function')
4836 for (var i = 0; i < s2.length; i++)
4837 cb.apply(this, [ s2[i] ]);
4844 this.map.add(this.map.uci_package, this.uci_type, name);
4847 remove: function(sid)
4849 this.map.remove(this.map.uci_package, sid);
4852 _ev_add: function(ev)
4855 var name = undefined;
4856 var self = ev.data.self;
4858 if (addb.prev().prop('nodeName') == 'INPUT')
4859 name = addb.prev().val();
4861 if (addb.prop('disabled') || name === '')
4864 _luci2.ui.saveScrollTop();
4866 self.active_panel = -1;
4871 _luci2.ui.restoreScrollTop();
4874 _ev_remove: function(ev)
4876 var self = ev.data.self;
4877 var sid = ev.data.sid;
4879 _luci2.ui.saveScrollTop();
4885 _luci2.ui.restoreScrollTop();
4887 ev.stopPropagation();
4890 _ev_sid: function(ev)
4892 var self = ev.data.self;
4894 var addb = text.next();
4895 var errt = addb.next();
4896 var name = text.val();
4898 if (!/^[a-zA-Z0-9_]*$/.test(name))
4900 errt.text(_luci2.tr('Invalid section name')).show();
4901 text.addClass('error');
4902 addb.prop('disabled', true);
4906 if (_luci2.uci.get(self.map.uci_package, name))
4908 errt.text(_luci2.tr('Name already used')).show();
4909 text.addClass('error');
4910 addb.prop('disabled', true);
4914 errt.text('').hide();
4915 text.removeClass('error');
4916 addb.prop('disabled', false);
4920 _ev_tab: function(ev)
4922 var self = ev.data.self;
4923 var sid = ev.data.sid;
4926 self.active_tab[sid] = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
4929 _ev_panel_collapse: function(ev)
4931 var self = ev.data.self;
4933 var this_panel = $(ev.target);
4934 var this_toggle = this_panel.prevAll('[data-toggle="collapse"]:first');
4936 var prev_toggle = $($(ev.delegateTarget).find('[data-toggle="collapse"]:eq(%d)'.format(self.active_panel)));
4937 var prev_panel = $(prev_toggle.attr('data-target'));
4941 .addClass('collapse');
4943 prev_toggle.find('.luci2-section-teaser')
4945 .children('span:last')
4947 .append(self.teaser(prev_panel.attr('data-luci2-sid')));
4949 this_toggle.find('.luci2-section-teaser')
4952 self.active_panel = parseInt(this_panel.attr('data-luci2-panel-index'));
4956 _ev_panel_open: function(ev)
4958 var self = ev.data.self;
4959 var panel = $($(this).attr('data-target'));
4960 var index = parseInt(panel.attr('data-luci2-panel-index'));
4962 if (index == self.active_panel)
4963 ev.stopPropagation();
4966 _ev_sort: function(ev)
4968 var self = ev.data.self;
4969 var cur_idx = ev.data.index;
4970 var new_idx = cur_idx + (ev.data.up ? -1 : 1);
4971 var s = self.sections();
4973 if (new_idx >= 0 && new_idx < s.length)
4975 _luci2.uci.swap(self.map.uci_package, s[cur_idx]['.name'], s[new_idx]['.name']);
4981 ev.stopPropagation();
4984 teaser: function(sid)
4986 var tf = this.teaser_fields;
4990 tf = this.teaser_fields = [ ];
4992 if ($.isArray(this.options.teasers))
4994 for (var i = 0; i < this.options.teasers.length; i++)
4996 var f = this.options.teasers[i];
4997 if (f instanceof _luci2.cbi.AbstractValue)
4999 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
5000 tf.push(this.fields[f]);
5005 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
5006 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
5007 tf.push(this.tabs[i].fields[j]);
5013 for (var i = 0; i < tf.length; i++)
5015 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
5018 var n = tf[i].options.caption || tf[i].name;
5019 var v = tf[i].textvalue(sid);
5021 if (typeof(v) == 'undefined')
5024 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
5030 _render_add: function()
5032 if (!this.options.addremove)
5035 var text = _luci2.tr('Add section');
5036 var ttip = _luci2.tr('Create new section...');
5038 if ($.isArray(this.options.add_caption))
5039 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
5040 else if (typeof(this.options.add_caption) == 'string')
5041 text = this.options.add_caption, ttip = '';
5043 var add = $('<div />');
5045 if (this.options.anonymous === false)
5048 .addClass('cbi-input-text')
5049 .attr('type', 'text')
5050 .attr('placeholder', ttip)
5051 .blur({ self: this }, this._ev_sid)
5052 .keyup({ self: this }, this._ev_sid)
5056 .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
5057 .attr('title', text)
5058 .addClass('cbi-button')
5059 .click({ self: this }, this._ev_add)
5063 .addClass('cbi-value-error')
5069 _luci2.ui.button(text, 'success', ttip)
5070 .click({ self: this }, this._ev_add)
5077 _render_remove: function(sid, index)
5079 if (!this.options.addremove)
5082 var text = _luci2.tr('Remove');
5083 var ttip = _luci2.tr('Remove this section');
5085 if ($.isArray(this.options.remove_caption))
5086 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
5087 else if (typeof(this.options.remove_caption) == 'string')
5088 text = this.options.remove_caption, ttip = '';
5090 return _luci2.ui.button(text, 'danger', ttip)
5091 .click({ self: this, sid: sid, index: index }, this._ev_remove);
5094 _render_sort: function(sid, index)
5096 if (!this.options.sortable)
5099 var b1 = _luci2.ui.button('↑', 'info', _luci2.tr('Move up'))
5100 .click({ self: this, index: index, up: true }, this._ev_sort);
5102 var b2 = _luci2.ui.button('↓', 'info', _luci2.tr('Move down'))
5103 .click({ self: this, index: index, up: false }, this._ev_sort);
5108 _render_caption: function()
5111 .addClass('panel-title')
5112 .append(this.label('caption') || this.uci_type);
5115 _render_description: function()
5117 var text = this.label('description');
5121 .addClass('luci2-section-description')
5127 _render_teaser: function(sid, index)
5129 if (this.options.collabsible || this.map.options.collabsible)
5132 .attr('id', this.id('teaser', sid))
5133 .addClass('luci2-section-teaser well well-sm')
5134 .append($('<span />')
5136 .append($('<span />'));
5142 _render_head: function(condensed)
5148 .addClass('panel-heading')
5149 .append(this._render_caption())
5150 .append(this._render_description());
5153 _render_tab_description: function(sid, index, tab_index)
5155 var tab = this.tabs[tab_index];
5157 if (typeof(tab.description) == 'string')
5160 .addClass('cbi-tab-descr')
5161 .text(tab.description);
5167 _render_tab_head: function(sid, index, tab_index)
5169 var tab = this.tabs[tab_index];
5170 var cur = this.active_tab[sid] || 0;
5172 var tabh = $('<li />')
5174 .attr('id', this.id('nodetab', sid, tab.id))
5175 .attr('href', '#' + this.id('node', sid, tab.id))
5176 .attr('data-toggle', 'tab')
5177 .attr('data-luci2-tab-index', tab_index)
5178 .text((tab.caption ? tab.caption.format(tab.id) : tab.id) + ' ')
5179 .append($('<span />')
5181 .on('shown.bs.tab', { self: this, sid: sid }, this._ev_tab));
5183 if (cur == tab_index)
5184 tabh.addClass('active');
5189 _render_tab_body: function(sid, index, tab_index)
5191 var tab = this.tabs[tab_index];
5192 var cur = this.active_tab[sid] || 0;
5194 var tabb = $('<div />')
5195 .addClass('tab-pane')
5196 .attr('id', this.id('node', sid, tab.id))
5197 .attr('data-luci2-tab-index', tab_index)
5198 .append(this._render_tab_description(sid, index, tab_index));
5200 if (cur == tab_index)
5201 tabb.addClass('active');
5203 for (var i = 0; i < tab.fields.length; i++)
5204 tabb.append(tab.fields[i].render(sid));
5209 _render_section_head: function(sid, index)
5211 var head = $('<div />')
5212 .addClass('luci2-section-header')
5213 .append(this._render_teaser(sid, index))
5214 .append($('<div />')
5215 .addClass('btn-group')
5216 .append(this._render_sort(sid, index))
5217 .append(this._render_remove(sid, index)));
5219 if (this.options.collabsible)
5221 head.attr('data-toggle', 'collapse')
5222 .attr('data-parent', this.id('sectiongroup'))
5223 .attr('data-target', '#' + this.id('panel', sid))
5224 .on('click', { self: this }, this._ev_panel_open);
5230 _render_section_body: function(sid, index)
5232 var body = $('<div />')
5233 .attr('id', this.id('panel', sid))
5234 .attr('data-luci2-panel-index', index)
5235 .attr('data-luci2-sid', sid);
5237 if (this.options.collabsible || this.map.options.collabsible)
5239 body.addClass('panel-collapse collapse');
5241 if (index == this.active_panel)
5242 body.addClass('in');
5245 var tab_heads = $('<ul />')
5246 .addClass('nav nav-tabs');
5248 var tab_bodies = $('<div />')
5249 .addClass('form-horizontal tab-content')
5252 for (var j = 0; j < this.tabs.length; j++)
5254 tab_heads.append(this._render_tab_head(sid, index, j));
5255 tab_bodies.append(this._render_tab_body(sid, index, j));
5258 body.append(tab_bodies);
5260 if (this.tabs.length <= 1)
5266 _render_body: function(condensed)
5268 var s = this.sections();
5270 if (this.active_panel < 0)
5271 this.active_panel += s.length;
5272 else if (this.active_panel >= s.length)
5273 this.active_panel = s.length - 1;
5275 var body = $('<ul />')
5276 .addClass('list-group');
5278 if (this.options.collabsible)
5280 body.attr('id', this.id('sectiongroup'))
5281 .on('show.bs.collapse', { self: this }, this._ev_panel_collapse);
5286 body.append($('<li />')
5287 .addClass('list-group-item text-muted')
5288 .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.')))
5291 for (var i = 0; i < s.length; i++)
5293 var sid = s[i]['.name'];
5294 var inst = this.instance[sid] = { tabs: [ ] };
5296 body.append($('<li />')
5297 .addClass('list-group-item')
5298 .append(this._render_section_head(sid, i))
5299 .append(this._render_section_body(sid, i)));
5305 render: function(condensed)
5307 this.instance = { };
5309 var panel = $('<div />')
5310 .addClass('panel panel-default')
5311 .append(this._render_head(condensed))
5312 .append(this._render_body(condensed));
5314 if (this.options.addremove)
5315 panel.append($('<div />')
5316 .addClass('panel-footer')
5317 .append(this._render_add()));
5324 var s = this.sections();
5326 for (var i = 0; i < s.length; i++)
5328 var sid = s[i]['.name'];
5330 this.validate_section(sid);
5332 if (i != this.active_panel)
5333 $('#' + this.id('teaser', sid)).children('span:last')
5334 .append(this.teaser(sid));
5336 $('#' + this.id('teaser', sid))
5342 this.cbi.TableSection = this.cbi.TypedSection.extend({
5343 _render_table_head: function()
5345 var thead = $('<thead />')
5347 .addClass('cbi-section-table-titles'));
5349 for (var j = 0; j < this.tabs[0].fields.length; j++)
5350 thead.children().append($('<th />')
5351 .addClass('cbi-section-table-cell')
5352 .css('width', this.tabs[0].fields[j].options.width || '')
5353 .append(this.tabs[0].fields[j].label('caption')));
5355 if (this.options.addremove !== false || this.options.sortable)
5356 thead.children().append($('<th />')
5357 .addClass('cbi-section-table-cell')
5363 _render_table_row: function(sid, index)
5365 var row = $('<tr />')
5366 .attr('data-luci2-sid', sid);
5368 for (var j = 0; j < this.tabs[0].fields.length; j++)
5370 row.append($('<td />')
5371 .css('width', this.tabs[0].fields[j].options.width || '')
5372 .append(this.tabs[0].fields[j].render(sid, true)));
5375 if (this.options.addremove !== false || this.options.sortable)
5377 row.append($('<td />')
5378 .addClass('text-right')
5379 .append($('<div />')
5380 .addClass('btn-group')
5381 .append(this._render_sort(sid, index))
5382 .append(this._render_remove(sid, index))));
5388 _render_table_body: function()
5390 var s = this.sections();
5392 var tbody = $('<tbody />');
5396 var cols = this.tabs[0].fields.length;
5398 if (this.options.addremove !== false || this.options.sortable)
5401 tbody.append($('<tr />')
5403 .addClass('text-muted')
5404 .attr('colspan', cols)
5405 .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.'))));
5408 for (var i = 0; i < s.length; i++)
5410 var sid = s[i]['.name'];
5411 var inst = this.instance[sid] = { tabs: [ ] };
5413 tbody.append(this._render_table_row(sid, i));
5419 _render_body: function(condensed)
5421 return $('<table />')
5422 .addClass('table table-condensed table-hover')
5423 .append(this._render_table_head())
5424 .append(this._render_table_body());
5428 this.cbi.NamedSection = this.cbi.TypedSection.extend({
5429 sections: function(cb)
5432 var sl = _luci2.uci.sections(this.map.uci_package);
5434 for (var i = 0; i < sl.length; i++)
5435 if (sl[i]['.name'] == this.uci_type)
5441 if (typeof(cb) == 'function' && sa.length > 0)
5442 cb.call(this, sa[0]);
5448 this.cbi.DummySection = this.cbi.TypedSection.extend({
5449 sections: function(cb)
5451 if (typeof(cb) == 'function')
5452 cb.apply(this, [ { '.name': this.uci_type } ]);
5454 return [ { '.name': this.uci_type } ];
5458 this.cbi.Map = this.ui.AbstractWidget.extend({
5459 init: function(uci_package, options)
5463 this.uci_package = uci_package;
5464 this.sections = [ ];
5465 this.options = _luci2.defaults(options, {
5466 save: function() { },
5467 prepare: function() { }
5471 _load_cb: function()
5473 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5475 for (var i = 0; i < this.sections.length; i++)
5477 for (var f in this.sections[i].fields)
5479 if (typeof(this.sections[i].fields[f].load) != 'function')
5482 var s = this.sections[i].sections();
5483 for (var j = 0; j < s.length; j++)
5485 var rv = this.sections[i].fields[f].load(s[j]['.name']);
5486 if (_luci2.isDeferred(rv))
5492 return $.when.apply($, deferreds);
5500 for (var i = 0; i < this.sections.length; i++)
5501 this.sections[i].ucipackages(packages);
5503 packages[this.uci_package] = true;
5505 for (var pkg in packages)
5506 if (!_luci2.uci.writable(pkg))
5507 this.options.readonly = true;
5509 return _luci2.uci.load(_luci2.toArray(packages)).then(function() {
5510 return self._load_cb();
5514 _ev_tab: function(ev)
5516 var self = ev.data.self;
5519 self.active_tab = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
5522 _render_tab_head: function(tab_index)
5524 var section = this.sections[tab_index];
5525 var cur = this.active_tab || 0;
5527 var tabh = $('<li />')
5529 .attr('id', section.id('sectiontab'))
5530 .attr('href', '#' + section.id('section'))
5531 .attr('data-toggle', 'tab')
5532 .attr('data-luci2-tab-index', tab_index)
5533 .text(section.label('caption') + ' ')
5534 .append($('<span />')
5536 .on('shown.bs.tab', { self: this }, this._ev_tab));
5538 if (cur == tab_index)
5539 tabh.addClass('active');
5544 _render_tab_body: function(tab_index)
5546 var section = this.sections[tab_index];
5547 var desc = section.label('description');
5548 var cur = this.active_tab || 0;
5550 var tabb = $('<div />')
5551 .addClass('tab-pane')
5552 .attr('id', section.id('section'))
5553 .attr('data-luci2-tab-index', tab_index);
5555 if (cur == tab_index)
5556 tabb.addClass('active');
5559 tabb.append($('<p />')
5562 var s = section.render(this.options.tabbed);
5564 if (this.options.readonly || section.options.readonly)
5565 s.find('input, select, button, img.cbi-button').attr('disabled', true);
5572 _render_body: function()
5574 var tabs = $('<ul />')
5575 .addClass('nav nav-tabs');
5577 var body = $('<div />')
5580 for (var i = 0; i < this.sections.length; i++)
5582 tabs.append(this._render_tab_head(i));
5583 body.append(this._render_tab_body(i));
5586 if (this.options.tabbed)
5587 body.addClass('tab-content');
5596 var map = $('<form />');
5598 if (typeof(this.options.caption) == 'string')
5599 map.append($('<h2 />')
5600 .text(this.options.caption));
5602 if (typeof(this.options.description) == 'string')
5603 map.append($('<p />')
5604 .text(this.options.description));
5606 map.append(this._render_body());
5608 if (this.options.pageaction !== false)
5610 map.append($('<div />')
5611 .addClass('panel panel-default panel-body text-right')
5612 .append($('<div />')
5613 .addClass('btn-group')
5614 .append(_luci2.ui.button(_luci2.tr('Save & Apply'), 'primary')
5615 .click({ self: this }, function(ev) { }))
5616 .append(_luci2.ui.button(_luci2.tr('Save'), 'default')
5617 .click({ self: this }, function(ev) { ev.data.self.send(); }))
5618 .append(_luci2.ui.button(_luci2.tr('Reset'), 'default')
5619 .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); }))));
5627 for (var i = 0; i < this.sections.length; i++)
5628 this.sections[i].finish();
5635 this.target.hide().empty().append(this.render());
5640 section: function(widget, uci_type, options)
5642 var w = widget ? new widget(uci_type, options) : null;
5644 if (!(w instanceof _luci2.cbi.AbstractSection))
5645 throw 'Widget must be an instance of AbstractSection';
5648 w.index = this.sections.length;
5650 this.sections.push(w);
5654 formvalue: function()
5658 for (var i = 0; i < this.sections.length; i++)
5660 var sids = this.sections[i].formvalue();
5661 for (var sid in sids)
5663 var s = rv[sid] || (rv[sid] = { });
5664 $.extend(s, sids[sid]);
5671 add: function(conf, type, name)
5673 return _luci2.uci.add(conf, type, name);
5676 remove: function(conf, sid)
5678 return _luci2.uci.remove(conf, sid);
5681 get: function(conf, sid, opt)
5683 return _luci2.uci.get(conf, sid, opt);
5686 set: function(conf, sid, opt, val)
5688 return _luci2.uci.set(conf, sid, opt, val);
5691 validate: function()
5695 for (var i = 0; i < this.sections.length; i++)
5697 if (!this.sections[i].validate())
5708 if (self.options.readonly)
5709 return _luci2.deferrable();
5711 var deferreds = [ ];
5713 for (var i = 0; i < self.sections.length; i++)
5715 if (self.sections[i].options.readonly)
5718 for (var f in self.sections[i].fields)
5720 if (typeof(self.sections[i].fields[f].save) != 'function')
5723 var s = self.sections[i].sections();
5724 for (var j = 0; j < s.length; j++)
5726 var rv = self.sections[i].fields[f].save(s[j]['.name']);
5727 if (_luci2.isDeferred(rv))
5733 return $.when.apply($, deferreds).then(function() {
5734 return _luci2.deferrable(self.options.save());
5740 if (!this.validate())
5741 return _luci2.deferrable();
5745 _luci2.ui.saveScrollTop();
5746 _luci2.ui.loading(true);
5748 return this.save().then(function() {
5749 return _luci2.uci.save();
5750 }).then(function() {
5751 return _luci2.ui.updateChanges();
5752 }).then(function() {
5754 }).then(function() {
5758 _luci2.ui.loading(false);
5759 _luci2.ui.restoreScrollTop();
5763 insertInto: function(id)
5766 self.target = $(id);
5768 _luci2.ui.loading(true);
5771 return self.load().then(function() {
5772 self.target.empty().append(self.render());
5776 _luci2.ui.loading(false);