🎄 Sync 2026-11-14 17:29:54

This commit is contained in:
github-actions[bot] committed 2026-11-14 17:29:54 +08:00
1 parent 00efd4e7cf
commit 4e24fe7535
123 files changed
+26051

No files matched your search

@@ -0,0 +1,230 @@
'use strict';
'require baseclass';
/*
* Release notes → HTML, for the Carbon settings page.
*
* A small Markdown subset that covers what release notes use: headings
* (ATX and setext), paragraphs, bullet and ordered lists (nested, tight or
* loose), block quotes, fenced code, tables, rules, and inline code,
* strong / em / strikethrough, links (inline, reference, <autolink>, bare
* URLs), images and hard breaks.
*
* Release notes are untrusted text. Every character of output text goes
* through esc(), raw HTML stays text, and only http(s) and mailto links
* survive, resolved against the project rather than the router.
*/
const repository = 'https://github.com/mrjoechen/luci-theme-carbon/blob/main/';
const MAX_DEPTH = 16;
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
function safeURL(value, image) {
try {
/* control characters, encoded or not, and character references hide schemes */
if (typeof value !== 'string' || /[\x00-\x1f\x7f]|%(?:0[0-9a-f]|1[0-9a-f]|7f)|&(?:#\d+|#x[0-9a-f]+|[a-z]+);/i.test(value)) return null;
const url = new URL(value, repository);
return /^(https?:|mailto:)$/.test(url.protocol) && (!image || url.protocol !== 'mailto:') ? url.href : null;
}
catch (e) { return null; }
}
/* ---- inline ----------------------------------------------------------- */
const DEST = /\(\s*<?([^\s<>()]*)>?(?:\s+"([^"]*)")?\s*\)/.source;
const LABEL = /\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\]/.source;
function link(env, href, text, title, raw) {
const url = safeURL(href, false);
if (!url) return esc(raw);
return '<a href="' + esc(url) + '"' + (title ? ' title="' + esc(title) + '"' : '') +
' target="_blank" rel="noopener noreferrer">' + text + '</a>';
}
function image(src, alt, title) {
const url = safeURL(src, true);
if (!url) return esc(alt);
return '<img src="' + esc(url) + '" alt="' + esc(alt) + '"' + (title ? ' title="' + esc(title) + '"' : '') +
' loading="lazy" referrerpolicy="no-referrer">';
}
/* Tried in order at each position (sticky regexes). A handler may return
null to decline, e.g. an unknown reference label. */
const INLINE = [
[/\\([!-\/:-@\[-`{-~])/y, (m) => esc(m[1])],
[/(`+)([\s\S]*?[^`])\1(?!`)/y, (m) => '<code>' + esc(m[2].replace(/^ ([\s\S]*[^ ][\s\S]*) $/, '$1')) + '</code>'],
[new RegExp('!' + LABEL + DEST, 'y'), (m) => image(m[2], m[1], m[3])],
[new RegExp(LABEL + DEST, 'y'), (m, env) => link(env, m[2], inline(m[1], env), m[3], m[0])],
[new RegExp(LABEL + /\[([^\]]*)\]/.source, 'y'), (m, env) => {
const ref = env.refs[label(m[2] || m[1])];
return ref ? link(env, ref.href, inline(m[1], env), ref.title, m[0]) : null;
}],
[/<((?:https?:\/\/|mailto:)[^\s<>]+)>/y, (m, env) => link(env, m[1], esc(m[1]), '', m[0])],
[/https?:\/\/[^\s<]*[^\s<.,:;"')\]!?*_~]/y, (m, env, prev) => /\w/.test(prev) ? null : link(env, m[0], esc(m[0]), '', m[0])],
[/(\*\*|__)(?=\S)([\s\S]*?\S)\1/y, (m, env, prev) => m[1] === '__' && /\w/.test(prev) ? null : '<strong>' + inline(m[2], env) + '</strong>'],
[/~~(?=\S)([\s\S]*?\S)~~/y, (m, env) => '<s>' + inline(m[1], env) + '</s>'],
[/\*(?=[^\s*])([\s\S]*?[^\s*])\*/y, (m, env) => '<em>' + inline(m[1], env) + '</em>'],
[/_(?=[^\s_])([\s\S]*?[^\s_])_(?!\w)/y, (m, env, prev) => /\w/.test(prev) ? null : '<em>' + inline(m[1], env) + '</em>'],
[/ {2,}\n|\\\n/y, () => '<br>\n']
];
const PLAIN = /[^\\`!\[<*_~h \n]+|[\s\S]/y;
function inline(text, env) {
let out = '', pos = 0;
scan: while (pos < text.length) {
for (const [re, render] of INLINE) {
re.lastIndex = pos;
const m = re.exec(text);
if (!m) continue;
/* read the end first: rendering nested text reuses these regexes */
const end = re.lastIndex;
const html = render(m, env, text.charAt(pos - 1));
if (html != null) { out += html; pos = end; continue scan; }
}
PLAIN.lastIndex = pos;
const m = PLAIN.exec(text);
out += esc(m[0]);
pos = PLAIN.lastIndex;
}
return out;
}
/* ---- blocks ----------------------------------------------------------- */
const RE = {
blank: /^\s*$/,
fence: /^( {0,3})(`{3,}|~{3,})[ \t]*([\w+-]*)[^`]*$/,
heading: /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/,
setext: /^ {0,3}(=+|-+)[ \t]*$/,
rule: /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/,
quote: /^ {0,3}> ?/,
item: /^ {0,3}([-*+]|\d{1,9}[.)])(?:[ \t]+|$)/,
ref: /^ {0,3}\[([^\]]+)\]:[ \t]*<?(\S+?)>?(?:[ \t]+["'(](.*)["')])?[ \t]*$/,
tableRule: /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/
};
const label = (s) => s.trim().replace(/\s+/g, ' ').toLowerCase();
const startsBlock = (line) => RE.blank.test(line) || RE.fence.test(line) || RE.heading.test(line) ||
RE.rule.test(line) || RE.quote.test(line) || RE.item.test(line);
/* table cells; an escaped \| stays inside its cell */
const cells = (line) => line.trim().replace(/\\\|/g, '\0').replace(/^\|/, '').replace(/\|$/, '')
.split('|').map((c) => c.replace(/\0/g, '\\|').trim());
function fence(lines, i, out) {
const open = RE.fence.exec(lines[i]), indent = open[1].length, mark = open[2];
const close = new RegExp('^ {0,3}' + mark[0] + '{' + mark.length + ',}[ \\t]*$');
const body = [];
for (i++; i < lines.length && !close.test(lines[i]); i++)
body.push(lines[i].replace(new RegExp('^ {0,' + indent + '}'), ''));
out.push('<pre><code' + (open[3] ? ' class="language-' + esc(open[3]) + '"' : '') + '>' +
esc(body.join('\n') + (body.length ? '\n' : '')) + '</code></pre>');
return i + 1;
}
function table(lines, i, out, env) {
const head = cells(lines[i]);
const align = cells(lines[i + 1]).map((c) => /^:-+:$/.test(c) ? 'center' : /-:$/.test(c) ? 'right' : /^:-/.test(c) ? 'left' : '');
const row = (tag, values) => '<tr>\n' + head.map((_, k) =>
'<' + tag + (align[k] ? ' style="text-align:' + align[k] + '"' : '') + '>' + inline(values[k] || '', env) + '</' + tag + '>\n').join('') + '</tr>\n';
let html = '<table>\n<thead>\n' + row('th', head) + '</thead>\n';
const body = [];
for (i += 2; i < lines.length && !RE.blank.test(lines[i]) && lines[i].includes('|') && !startsBlock(lines[i]); i++)
body.push(row('td', cells(lines[i])));
if (body.length) html += '<tbody>\n' + body.join('') + '</tbody>\n';
out.push(html + '</table>');
return i;
}
function quote(lines, i, out, env, depth) {
const body = [];
for (; i < lines.length; i++) {
if (RE.quote.test(lines[i])) body.push(lines[i].replace(RE.quote, ''));
else if (body.length && !RE.blank.test(body[body.length - 1]) && !startsBlock(lines[i])) body.push(lines[i]);
else break;
}
out.push('<blockquote>\n' + blocks(body, env, depth + 1, false) + '\n</blockquote>');
return i;
}
function list(lines, i, out, env, depth) {
const first = RE.item.exec(lines[i]);
const ordered = /\d/.test(first[1]), marker = first[1].slice(-1);
const items = [];
let loose = false;
while (i < lines.length) {
const m = RE.item.exec(lines[i]);
if (!m || /\d/.test(m[1]) !== ordered || m[1].slice(-1) !== marker || RE.rule.test(lines[i])) break;
const indent = m[0].length;
const body = [lines[i].slice(indent)];
let blank = false;
for (i++; i < lines.length; i++) {
const line = lines[i];
if (RE.blank.test(line)) { blank = true; body.push(''); continue; }
if (line.match(/^ */)[0].length >= indent) { body.push(line.slice(indent)); blank = false; continue; }
if (blank || startsBlock(line)) break;
body.push(line.replace(/^ +/, '')); /* lazy continuation */
}
while (body.length && RE.blank.test(body[body.length - 1])) body.pop();
/* a blank line inside an item or between items makes the list loose (<p> per item) */
if (body.some((l) => RE.blank.test(l))) loose = true;
items.push(body);
if (blank && i < lines.length && RE.item.test(lines[i])) loose = true;
}
const tag = ordered ? 'ol' : 'ul', start = ordered ? parseInt(first[1], 10) : 1;
out.push('<' + tag + (start !== 1 ? ' start="' + start + '"' : '') + '>\n' +
items.map((body) => '<li>' + blocks(body, env, depth + 1, !loose) + '</li>\n').join('') + '</' + tag + '>');
return i;
}
function blocks(lines, env, depth, tight) {
const out = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (RE.blank.test(line)) { i++; continue; }
if (depth < MAX_DEPTH) {
if (RE.fence.test(line)) { i = fence(lines, i, out); continue; }
if (RE.quote.test(line)) { i = quote(lines, i, out, env, depth); continue; }
if (RE.rule.test(line)) { out.push('<hr>'); i++; continue; }
if (RE.item.test(line)) { i = list(lines, i, out, env, depth); continue; }
if (line.includes('|') && i + 1 < lines.length && RE.tableRule.test(lines[i + 1]) && cells(line).length === cells(lines[i + 1]).length) { i = table(lines, i, out, env); continue; }
}
const h = RE.heading.exec(line);
if (h) { out.push('<h' + h[1].length + '>' + inline(h[2] || '', env) + '</h' + h[1].length + '>'); i++; continue; }
/* paragraph, or a setext heading when underlined */
/* lines keep trailing spaces: two of them mean a hard break */
const para = [line.replace(/^ +/, '')];
for (i++; i < lines.length && !startsBlock(lines[i]) && !RE.setext.test(lines[i]); i++) para.push(lines[i].replace(/^ +/, ''));
const setext = i < lines.length && RE.setext.exec(lines[i]);
if (setext && !RE.blank.test(lines[i])) {
const level = setext[1][0] === '=' ? 1 : 2;
out.push('<h' + level + '>' + inline(para.join('\n').trim(), env) + '</h' + level + '>');
i++;
continue;
}
const html = inline(para.join('\n').replace(/\s+$/, ''), env);
out.push(tight ? html : '<p>' + html + '</p>');
}
return out.join('\n');
}
function render(text) {
const env = { refs: {} };
const lines = [];
let fenced = null;
String(text || '').replace(/\r\n?/g, '\n').replace(/\t/g, ' ').split('\n').forEach((line) => {
const f = RE.fence.exec(line);
if (fenced) { if (f && f[2][0] === fenced[0] && f[2].length >= fenced.length) fenced = null; }
else if (f) fenced = f[2];
else {
/* reference definitions anywhere outside code */
const r = RE.ref.exec(line);
if (r && !env.refs[label(r[1])]) { env.refs[label(r[1])] = { href: r[2], title: r[3] || '' }; return; }
}
lines.push(line);
});
const html = blocks(lines, env, 0, false);
return html ? html + '\n' : '';
}
return baseclass.extend({ render: render });
@@ -0,0 +1,284 @@
'use strict';
'require baseclass';
'require ui';
'require session';
'require rpc';
'require fs';
'require poll';
/*
* Carbon — LuCI glue.
* Reads LuCI's menu tree, renders the sidebar / tab bar and mounts the
* dashboard on Status → Overview. Everything visual lives in carbon.js.
* All calls below are read-only, except the interface language switch.
*/
const callBoard = rpc.declare({ object: 'system', method: 'board', expect: { '': {} } });
const callInfo = rpc.declare({ object: 'system', method: 'info', expect: { '': {} } });
const callIfaces = rpc.declare({ object: 'network.interface', method: 'dump', expect: { 'interface': [] } });
const callDevice = rpc.declare({ object: 'network.device', method: 'status', params: [ 'name' ], expect: { '': {} } });
const callNetDevs = rpc.declare({ object: 'luci-rpc', method: 'getNetworkDevices', expect: { '': {} } });
const callLeases = rpc.declare({ object: 'luci-rpc', method: 'getDHCPLeases', expect: { '': {} } });
const callWireless = rpc.declare({ object: 'network.wireless', method: 'status', expect: { '': {} } });
const callHostHints = rpc.declare({ object: 'luci-rpc', method: 'getHostHints', expect: { '': {} } });
const callAssoc = rpc.declare({ object: 'iwinfo', method: 'assoclist', params: [ 'device' ], expect: { results: [] } });
const callUciGet = rpc.declare({ object: 'uci', method: 'get', params: [ 'config', 'section' ], expect: { values: {} } });
const callUciSet = rpc.declare({ object: 'uci', method: 'set', params: [ 'config', 'section', 'values' ] });
const callUciCommit = rpc.declare({ object: 'uci', method: 'commit', params: [ 'config' ] });
/*
* Interface language: lists the installed LuCI catalogues (luci.languages)
* and writes luci.main.lang — exactly what System → System → Language does —
* then the page reloads. English is built in; "auto" follows the browser.
*/
const nativeName = (label, code) => String(label || code).replace(/\s*\(.*\)\s*$/, '') || code;
const shortName = (code, zhCount) => {
if (/^zh/i.test(code))
return zhCount > 1 ? (/hant|tw|hk|mo/i.test(code) ? '繁' : '简') : '中';
return code.slice(0, 2).toUpperCase();
};
const language = {
current: document.documentElement.getAttribute('lang') || 'en',
load: () => Promise.all([
callUciGet('luci', 'languages').catch(() => ({})),
callUciGet('luci', 'main').catch(() => ({}))
]).then(([langs, main]) => {
const codes = Object.keys(langs || {}).filter((k) => k.charAt(0) !== '.' && k !== 'en' && /^[A-Za-z]{2,3}([_-][A-Za-z0-9]{2,8})?$/.test(k)).sort();
const zhCount = codes.filter((k) => /^zh/i.test(k)).length;
const options = [{ code: 'en', label: 'English', short: 'EN' }].concat(codes.map((k) => ({
code: k, label: nativeName(langs[k], k), short: shortName(k, zhCount)
})));
const lang = main && main.lang;
return { options: options, selected: (lang && (lang === 'auto' || options.some((o) => o.code === lang))) ? lang : 'auto' };
}),
set: (code) => language.load().then((info) => {
if (code !== 'auto' && !info.options.some((o) => o.code === code))
throw new Error('Language not installed: ' + code);
return callUciSet('luci', 'main', { lang: code });
}).then((rc) => {
if (typeof rc === 'number' && rc !== 0)
throw new Error('uci set failed: ' + rc);
return callUciCommit('luci');
}).then((rc) => {
if (typeof rc === 'number' && rc !== 0)
throw new Error('uci commit failed: ' + rc);
})
};
const provider = {
board: () => callBoard().then((r) => (r && r.hostname) ? r : null),
info: () => callInfo().then((r) => (r && (r.memory || r.uptime != null)) ? r : null),
cpuStat: () => fs.read('/proc/stat'),
interfaces: () => callIfaces().then((r) => (Array.isArray(r) && r.length) ? r : null),
devStats: (dev, alt) => callDevice(dev).then((r) => {
if (r && r.statistics && r.statistics.rx_bytes != null)
return r.statistics;
return callNetDevs().then((all) => {
const d = (all && (all[dev] || (alt && all[alt]))) || null;
return (d && d.stats) ? d.stats : null;
});
}),
netDevices: () => callNetDevs().then((r) => (r && typeof r === 'object' && Object.keys(r).length) ? r : null),
leases: () => callLeases().then((r) => (r && Array.isArray(r.dhcp_leases)) ? r : null),
wireless: () => callWireless(),
hostHints: () => callHostHints(),
/* associated Wi‑Fi stations of the given AP interfaces */
stations: (ifnames) => Promise.all((ifnames || []).map((dev) => callAssoc(dev)
.then((list) => Array.isArray(list) ? list.map((st) => Object.assign({ ifname: dev }, st)) : null)
.catch(() => null))).then((lists) => {
/* every call refused (e.g. a session from before an upgrade): unknown, not "none" */
if (lists.length && lists.every((l) => l === null)) return null;
return [].concat.apply([], lists.filter(Boolean));
}),
neighbors: () => fs.read('/proc/net/arp'),
conntrack: () => Promise.all([
fs.read('/proc/sys/net/netfilter/nf_conntrack_count'),
fs.read('/proc/sys/net/netfilter/nf_conntrack_max').catch(() => null)
]),
temperatures: () => (sensors || (sensors = findSensors())).then((list) => Promise.all(list.map((s) =>
fs.read(s.path).then((v) => ({ name: s.name, value: parseInt(v, 10) })).catch(() => null)
))).then((r) => r.filter((x) => x && x.value > -40000 && x.value < 200000))
};
/*
* Temperature sensors: every thermal zone plus the first input of each hwmon
* device (CPU, SoC, Wi‑Fi chips, x86 coretemp …). Discovered once per page.
* Sessions from before an upgrade may only be allowed to read zone 0.
* rpcd (since 2026-07) re-checks the ACL against the symlink target, so the
* ACL lists both the /sys/class/… links and their /sys/devices/… targets.
*/
let sensors = null;
const listNames = (dir, pattern) => L.resolveDefault(fs.list(dir), []).then((entries) =>
(entries || []).map((e) => e.name).filter((n) => pattern.test(n)).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })));
const readName = (path, fallback) => L.resolveDefault(fs.read(path), '').then((v) => String(v || '').trim() || fallback);
function findSensors() {
const thermal = listNames('/sys/class/thermal', /^thermal_zone\d+$/).then((zones) => Promise.all(zones.slice(0, 8).map((z) =>
readName('/sys/class/thermal/' + z + '/type', z).then((name) => ({ name: name, path: '/sys/class/thermal/' + z + '/temp' })))));
const hwmon = listNames('/sys/class/hwmon', /^hwmon\d+$/).then((devs) => Promise.all(devs.slice(0, 8).map((d) =>
listNames('/sys/class/hwmon/' + d, /^temp\d+_input$/).then((inputs) => inputs.length ? readName('/sys/class/hwmon/' + d + '/name', d)
.then((name) => ({ name: name, path: '/sys/class/hwmon/' + d + '/' + inputs[0] })) : null))));
return Promise.all([thermal, hwmon]).then((r) => {
const seen = {}, list = [];
r[0].concat(r[1]).forEach((s) => {
const key = s && s.name.toLowerCase().replace(/[^a-z0-9]/g, '');
if (s && !seen[key]) { seen[key] = true; list.push(s); }
});
return list.length ? list : [{ name: '', path: '/sys/class/thermal/thermal_zone0/temp' }];
});
}
return baseclass.extend({
language: language,
__init__() {
const version = window.Carbon && window.Carbon.version;
if (version && session.getLocalData('carbon-menu-version') !== version) {
ui.menu.flushCache();
// LuCI's flushCache clears session data only. Its instance may already
// hold the old tree when the theme menu is instantiated.
ui.menu.menu = null;
}
return ui.menu.load().then((tree) => {
this.render(tree);
if (version) session.setLocalData('carbon-menu-version', version);
});
},
render(tree) {
const C = window.Carbon;
const roots = ui.menu.getChildren(tree);
const reqRoot = L.env.requestpath.length ? L.env.requestpath[0] : null;
const root = roots.filter((c) => c.name === reqRoot)[0] || roots[0];
if (!C || !root)
return;
const categories = ui.menu.getChildren(root).map((cat) => ({
name: cat.name,
title: _(cat.title),
path: root.name + '/' + cat.name,
url: L.url(root.name, cat.name),
children: ui.menu.getChildren(cat).map((ch) => ({
name: ch.name,
title: C.t(_(ch.title)),
path: root.name + '/' + cat.name + '/' + ch.name,
url: L.url(root.name, cat.name, ch.name)
}))
}));
const known = {};
categories.forEach((c) => {
known[c.path] = c;
c.children.forEach((ch) => { known[ch.path] = ch; });
});
C.initShell({
logoutUrl: known[root.name + '/logout'] ? L.url(root.name, 'logout') : null,
language: this.language
});
C.renderNav({
root: root.name,
categories: categories,
activePath: L.env.dispatchpath,
url: (p) => L.url(p)
});
/* toolbar title: Category › Page */
const dp = L.env.dispatchpath;
const cat = known[dp.slice(0, 2).join('/')];
const page = known[dp.slice(0, 3).join('/')];
C.setTitle([cat && cat.title, page && page.title]);
/* third level and below → segmented tab bar */
if (dp.length >= 3) {
let node = tree, url = '';
for (let i = 0; i < 3 && node; i++) {
node = node.children[dp[i]];
url = url + (url ? '/' : '') + dp[i];
}
if (node)
this.renderTabMenu(node, url);
}
if (dp.join('/') === root.name + '/status/overview')
this.mountDashboard(root.name, known);
},
renderTabMenu(tree, url, level) {
const container = document.querySelector('#tabmenu');
const ul = E('ul', { 'class': 'tabs' });
const children = ui.menu.getChildren(tree);
let activeNode = null;
children.forEach((child) => {
const isActive = (L.env.dispatchpath[3 + (level || 0)] == child.name);
const className = 'tabmenu-item-%s %s'.format(child.name, isActive ? 'active' : '');
ul.appendChild(E('li', { 'class': className }, [
E('a', { 'href': L.url(url, child.name), 'aria-current': isActive ? 'page' : null }, [ _(child.title) ])
]));
if (isActive)
activeNode = child;
});
if (ul.children.length == 0 || !container)
return E([]);
container.appendChild(ul);
container.style.display = '';
if (activeNode)
this.renderTabMenu(activeNode, url + '/' + activeNode.name, (level || 0) + 1);
return ul;
},
mountDashboard(rootName, known) {
const C = window.Carbon;
const main = document.getElementById('maincontent');
const view = document.getElementById('view');
if (!main)
return;
const link = (p) => known[rootName + '/' + p] ? L.url(rootName, p) : null;
const host = E('div', { 'id': 'cb-dashboard' });
main.insertBefore(host, (view && view.parentNode === main) ? view : null);
C.Dashboard.mount(host, provider, {
urls: {
network: link('network/network'),
wireless: link('network/wireless'),
devices: link('network/dhcp')
}
});
/* LuCI's own status widgets stay below the dashboard. While they are
collapsed, pause LuCI's poll loop so the router is not queried twice. */
document.addEventListener('poll-start', () => {
if (!this.detailsOpen)
window.setTimeout(() => this.gatePoll(this.detailsOpen), 0);
});
C.detailsToggle(host, C.mode.get() === 'pro', (open) => this.gatePoll(open));
},
gatePoll(open) {
this.detailsOpen = !!open;
if (open) {
if (!poll.active())
poll.start();
}
else if (poll.active()) {
poll.stop();
/* our dashboard keeps updating, so a "Paused" badge would mislead */
if (typeof ui.hideIndicator === 'function')
ui.hideIndicator('poll-status');
}
}
});
@@ -0,0 +1,296 @@
'use strict';
'require view';
'require rpc';
'require poll';
'require ui';
'require request';
'require carbon.markdown as markdown';
/*
* System → Carbon Theme Settings. Every section talks to the
* luci.carbon_update rpcd backend; status() returns what all of them show.
*/
const call = (method, params) => rpc.declare({ object: 'luci.carbon_update', method: method, params: params, expect: { '': {} }, raise: true });
const status = call('status');
const check = call('check');
const upgrade = call('upgrade', [ 'version' ]);
const configure = call('configure', [ 'mirror' ]);
const setLogo = call('logo', [ 'action' ]);
/* Must match the rpcd backend and its ACL (the only file cgi-upload may write). */
const LOGO_UPLOAD = '/tmp/carbon-logo.upload';
const LOGO_MAX = 262144;
/* fixed path: this page also works while another theme is active */
const LOGO_DEFAULT = '/luci-static/carbon/logo.svg';
const LOGO_TYPES = /^image\/(png|jpeg|gif|webp|svg\+xml)$/;
const LOGO_NAMES = /\.(png|jpe?g|gif|webp|svg)$/i;
const MIRROR_RE = /^https:\/\/[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?(:[0-9]{1,5})?(\/[A-Za-z0-9._~%+-]+)*\/?$/;
/* Theme strings: Carbon's bundled catalogue when the theme is active, otherwise
LuCI's (luci-i18n-carbon-* packages built from po/). */
const N_ = s => s;
const tr = (s, ...args) => (window.Carbon && typeof window.Carbon.t === 'function') ?
window.Carbon.t(s, ...args) : (args.length ? _(s).format(...args) : _(s));
/* backend error codes → messages */
const errors = {
/* updates */
network: N_('Download failed. Check internet access, DNS, router time and GitHub availability.'),
metadata: N_('Release metadata or package version is invalid. Nothing was installed.'),
checksum: N_('The downloaded file failed its size or SHA-256 check. Nothing was installed.'),
signature: N_('APK signature verification failed. Nothing was installed; signature checks remain enabled.'),
install: N_('The package manager could not finish installation. See the log below.'),
version: N_('The installed version does not match the release. Check the installation log.'),
settings: N_('The package was installed, but restoring theme preferences failed. Check System → Language and Style.'),
interrupted: N_('The update was interrupted. Check the installed version before trying again.'),
stale: N_('The release changed, expired, or is no longer newer. Check for updates again.'),
invalid: N_('Invalid update request.'),
busy: N_('Another update operation is running.'),
dependencies: N_('Install curl, ca-bundle and flock, and restore the Carbon public key if missing.'),
manual_install: N_('apk/opkg has no record of this Carbon install (for example, it was copied by an older carbon-install.sh). Run the latest carbon-install.sh once, or install the APK/IPK package, to enable online upgrades.'),
space: N_('Not enough temporary storage or unable to create update files.'),
state: N_('Unable to access update state storage.'),
invalid_mirror: N_('Enter an HTTPS mirror prefix such as https://mirror.example.com/ (letters, digits and . _ ~ % + - only).'),
/* logo */
logo_missing: N_('The uploaded file did not reach the router. Try again.'),
logo_size: N_('The logo must be at most 256 KB.'),
logo_type: N_('Unsupported file. Use a PNG, JPEG, WebP, GIF or SVG image.'),
logo_unsafe: N_('This SVG contains scripts, event handlers, links or embedded documents and was rejected. Save it as a plain SVG or PNG.'),
logo_denied: N_('Permission denied. Log out and log in again once after updating Carbon, then retry.')
};
const message = code => errors[code] ? tr(errors[code]) : String(code || '');
const writable = () => L.hasViewPermission();
/* LuCI's E() renders a null array item as the text "null": never pass one */
const section = (title, description, children) => E('section', { 'class': 'cbi-section' },
[E('h3', {}, [].concat(title))].concat(description ? [E('p', { 'class': 'cbi-section-descr' }, description)] : [], children));
/* "?" toggletip: hover or keyboard focus shows the text, a click or tap pins it,
Esc or a click elsewhere closes it. Keeps long explanations off the page. */
let hintSeq = 0;
function hint(text) {
const id = 'cb-hint-' + (++hintSeq);
let wrap = null;
const outside = (e) => { if (!wrap.contains(e.target)) setOpen(false); };
const setOpen = (on) => {
wrap.classList.toggle('open', on);
button.setAttribute('aria-expanded', on ? 'true' : 'false');
if (on) document.addEventListener('pointerdown', outside, true);
else document.removeEventListener('pointerdown', outside, true);
};
const button = E('button', {
'type': 'button', 'class': 'cb-hint-btn', 'aria-label': tr('About this setting'),
'aria-describedby': id, 'aria-expanded': 'false',
'click': () => setOpen(!wrap.classList.contains('open')),
'keydown': (e) => { if (e.key === 'Escape') setOpen(false); }
}, ['?']);
wrap = E('span', { 'class': 'cb-hint' }, [button, E('span', { 'class': 'cb-hint-bubble', 'id': id, 'role': 'tooltip' }, [text])]);
return wrap;
}
const actions = (children) => E('div', { 'class': 'cb-update-actions' }, children);
const external = (href, text) => E('a', { 'href': href, 'target': '_blank', 'rel': 'noopener noreferrer' }, text);
/* ---- custom logo: preview, upload (cgi-upload → rpcd validation), restore default ---- */
function logoSection(data) {
let logoUrl = data.logo || '';
const preview = E('img', { 'class': 'cb-logo-preview', 'alt': tr('Current logo') });
const state = E('span', { 'class': 'cb-update-note', 'role': 'status', 'aria-live': 'polite' });
const input = E('input', {
'type': 'file', 'id': 'carbon-logo-file', 'hidden': true,
'accept': 'image/png,image/jpeg,image/webp,image/gif,image/svg+xml,.svg',
'change': () => {
const file = input.files && input.files[0];
input.value = '';
if (!file) return;
if (!LOGO_TYPES.test(file.type) && !LOGO_NAMES.test(file.name)) { state.textContent = message('logo_type'); return; }
if (!file.size || file.size > LOGO_MAX) { state.textContent = message('logo_size'); return; }
return apply(() => upload(file), tr('Logo saved.'));
}
});
const uploadButton = E('button', { 'class': 'cbi-button cbi-button-action', 'click': () => input.click() }, tr('Upload logo…'));
const resetButton = E('button', { 'class': 'cbi-button cbi-button-reset', 'click': () => apply(() => setLogo('reset'), tr('The default logo is restored.')) }, tr('Restore default'));
const paint = () => {
const src = logoUrl || LOGO_DEFAULT;
preview.src = src;
uploadButton.disabled = !writable();
resetButton.disabled = !logoUrl || !writable();
/* the rest of the page follows without a reload */
document.querySelectorAll('.cb-brand-logo, .cb-hero-icon img').forEach((img) => {
img.src = src;
if (logoUrl) img.setAttribute('data-custom', ''); else img.removeAttribute('data-custom');
});
document.querySelectorAll('link[rel="icon"], link[rel="apple-touch-icon"]').forEach((link) => {
link.href = src;
if (logoUrl) link.removeAttribute('type');
});
};
async function upload(file) {
const form = new FormData();
form.append('sessionid', rpc.getSessionID());
form.append('filename', LOGO_UPLOAD);
form.append('filedata', file);
const res = await request.post(L.env.cgi_base + '/cgi-upload', form, { timeout: 0 });
if (res.status === 403) return { error: 'logo_denied' };
if (!res.ok) throw new Error(res.statusText || ('HTTP ' + res.status));
return setLogo('set');
}
async function apply(action, done) {
uploadButton.disabled = resetButton.disabled = true;
state.textContent = tr('Saving…');
try {
const result = await action();
if (result.error) state.textContent = message(result.error);
else { logoUrl = result.logo || ''; state.textContent = done; }
}
catch (e) { state.textContent = e.message; }
paint();
}
paint();
return section(tr('Logo'), tr('Shown in the sidebar, on the login page, on the overview and as the browser icon. PNG, JPEG, WebP, GIF or SVG up to 256 KB; a square image of at least 128 × 128 pixels looks best. The logo is kept across theme updates and firmware upgrades that keep settings.'), [
E('div', { 'class': 'cb-logo-row' }, [preview, E('div', { 'class': 'cb-logo-actions' }, [uploadButton, resetButton, input, state])])
]);
}
/* ---- download mirror for online updates ---- */
function mirrorSection(data) {
const input = E('input', {
'class': 'cbi-input-text', 'id': 'carbon-mirror', 'type': 'url', 'inputmode': 'url', 'maxlength': '200',
'placeholder': 'https://mirror.example.com/', 'spellcheck': 'false', 'autocomplete': 'off', 'value': data.mirror || ''
});
const state = E('span', { 'class': 'cb-update-note', 'role': 'status', 'aria-live': 'polite' });
const save = E('button', { 'class': 'cbi-button cbi-button-save', 'click': async () => {
const value = input.value.trim();
if (value && !MIRROR_RE.test(value)) { state.textContent = message('invalid_mirror'); return; }
save.disabled = true;
try {
const result = await configure(value);
if (result.error) state.textContent = message(result.error);
else {
input.value = result.mirror || '';
state.textContent = result.mirror ? tr('Saved. Downloads try the mirror first, then GitHub.') : tr('Saved. Downloads use GitHub directly.');
}
}
catch (e) { state.textContent = e.message; }
finally { save.disabled = !writable(); }
} }, tr('Save'));
if (!writable()) { input.disabled = true; save.disabled = true; }
return section([tr('Download mirror'), hint(tr('Optional. If GitHub downloads are slow or blocked, enter an HTTPS prefix that proxies GitHub links, for example https://mirror.example.com/ for https://mirror.example.com/https://github.com/…. Release information is still read from GitHub, and the downloaded file must match the size and SHA-256 published there; GitHub is tried if the mirror fails.'))], null, [
E('div', { 'class': 'cbi-value' }, [
E('label', { 'class': 'cbi-value-title', 'for': 'carbon-mirror' }, tr('Mirror prefix')),
E('div', { 'class': 'cbi-value-field cb-update-field' }, [input, save, state])
])
]);
}
/* ---- online updates: status polled every 2 s; returns the sections and the poll ---- */
function updateSections(data) {
let current = data, pending = false, renderedNotes;
const installedText = E('strong');
const latestText = E('strong');
const stateText = E('p', { 'role': 'status', 'aria-live': 'polite' });
const errorText = E('p', { 'role': 'alert', 'class': 'alert-message warning', 'hidden': true });
const securityText = E('p', { 'class': 'cbi-section-descr' });
const notes = E('div', { 'class': 'cb-release-notes', 'tabindex': '0', 'role': 'region', 'aria-label': tr('Release notes') });
const logs = E('pre', { 'style': 'white-space:pre-wrap;overflow-wrap:anywhere;max-height:16rem;overflow:auto' });
const refresh = E('button', { 'class': 'cbi-button cbi-button-action', 'click': () => {
ui.menu.flushCache();
window.location.reload();
} }, tr('Reload page'));
const checkButton = E('button', { 'class': 'cbi-button cbi-button-action', 'click': () => run(check) }, tr('Check for updates'));
const updateButton = E('button', { 'class': 'cbi-button cbi-button-positive', 'click': () => {
if (!current.can_upgrade || current.busy || pending || !writable()) return;
const version = current.latest;
ui.showModal(tr('Update Carbon'), [
E('p', {}, tr('Install version %s? Your theme preferences will be retained. Do not power off the router during installation.', version)),
E('div', { 'class': 'right' }, [
E('button', { 'class': 'cbi-button', 'click': ui.hideModal }, tr('Cancel')), ' ',
E('button', { 'class': 'cbi-button cbi-button-positive', 'click': () => { ui.hideModal(); return run(() => upgrade(version)); } }, tr('Confirm update'))
])
]);
} }, tr('Install update'));
function paint(value) {
current = value;
installedText.textContent = value.current || tr('Unknown');
latestText.textContent = value.latest || tr('Not checked');
const labels = {
checking: N_('Checking for updates…'), downloading: N_('Downloading update…'),
verifying: N_('Verifying update…'), installing: N_('Installing update…'),
success: N_('Update complete. Reload this page to use the new version.'),
failed: N_('Update failed.')
};
stateText.textContent = labels[value.state] ? tr(labels[value.state]) :
value.can_upgrade ? tr('A new version is available.') :
value.latest && value.current === value.latest ? tr('You are using the latest version.') : tr('Check the latest stable Carbon release.');
const issue = value.error || value.reason;
errorText.textContent = message(issue); errorText.hidden = !issue;
securityText.textContent = value.manager === 'apk' ?
tr('APK signature, SHA-256 and file size are verified before installation. Your signature checks remain enabled.') :
tr('IPK updates are downloaded over HTTPS and checked against the release SHA-256 and file size.');
// Keep selection, focus and scroll position while status polls every 2s.
const nextNotes = value.notes || '';
if (nextNotes !== renderedNotes) {
if (nextNotes) notes.innerHTML = markdown.render(nextNotes);
else notes.textContent = tr('Release notes will appear after checking.');
renderedNotes = nextNotes;
}
logs.textContent = value.log || tr('No installation log yet.');
checkButton.disabled = pending || value.busy || !!value.reason;
updateButton.disabled = pending || value.busy || !value.can_upgrade || !writable();
refresh.hidden = value.state !== 'success';
}
async function sync() {
try { paint(await status()); }
catch (e) {
errorText.hidden = false;
errorText.textContent = tr('Connection interrupted. Progress will resume when LuCI reconnects. %s', e.message);
checkButton.disabled = true; updateButton.disabled = true;
}
}
async function run(action) {
if (pending) return;
pending = true; paint(current);
let issue;
try { const result = await action(); if (result.error) issue = message(result.error); }
catch (e) { issue = e.message; }
finally { pending = false; await sync(); }
if (issue) { errorText.textContent = issue; errorText.hidden = false; }
}
paint(data);
return {
sync: sync,
main: section(tr('Updates'), null, [
E('div', { 'class': 'cb-update-versions' }, [
E('div', {}, [E('p', {}, tr('Installed version')), installedText]),
E('div', {}, [E('p', {}, tr('Latest stable version')), latestText])
]), stateText, errorText, securityText,
actions([checkButton, updateButton, refresh]),
external('https://github.com/mrjoechen/luci-theme-carbon/releases', tr('View releases on GitHub'))
]),
notes: section(tr('Release notes'), null, [notes]),
log: E('details', { 'class': 'cbi-section' }, [E('summary', {}, tr('Installation log')), logs])
};
}
return view.extend({
load() { return status(); },
render(data) {
const updates = updateSections(data);
this.pollStatus = updates.sync;
poll.add(updates.sync, 2);
return E('div', { 'class': 'cbi-map cb-update' }, [
E('h2', {}, tr('Carbon Theme Settings')),
E('p', { 'class': 'cbi-map-descr' }, tr('Personalise the logo and update the theme without changing your router configuration.')),
logoSection(data),
updates.main,
updates.notes,
mirrorSection(data),
updates.log
]);
},
handleSave: null,
handleSaveApply: null,
handleReset: null
});