🗽 Sync 2026-11-11 15:31:38

This commit is contained in:
github-actions[bot] committed 2026-11-11 15:31:38 +08:00
1 parent da9e4bea36
commit 2e3c0a9b33
189 files changed
+29797 -10433

No files matched your search

@@ -22,6 +22,7 @@
--dashboard-series-7: #b0367c;
--dashboard-series-8: #9c9a1c;
--dashboard-gap: 16px;
--dashboard-extra-lightness: 42%;
display: grid;
/* minmax(0, …): a wide tab menu must scroll, not widen every row. */
@@ -31,6 +32,7 @@
}
[data-darkmode="true"] .Dashboard {
--dashboard-extra-lightness: 65%;
--dashboard-surface-alt: var(--background-color-medium, #262b34);
--dashboard-text: var(--text-color-high, #e6e8eb);
--dashboard-text-muted: var(--text-color-high, #9aa3ad);
@@ -44,6 +46,7 @@
@media (prefers-color-scheme: dark) {
:root:not([data-darkmode="false"]) .Dashboard {
--dashboard-extra-lightness: 65%;
--dashboard-surface-alt: var(--background-color-medium, #262b34);
--dashboard-text: var(--text-color-high, #e6e8eb);
--dashboard-text-muted: var(--text-color-high, #9aa3ad);
@@ -57,6 +60,70 @@
}
/* ---- Layout ---- */
.dashboard-settings .dashboard-widget-list {
display: flex;
flex-direction: column;
width: 100%;
max-width: none;
}
.dashboard-settings .dashboard-widget-list > .item,
.dashboard-settings .dashboard-widget-list > .add-item,
.dashboard-settings .dashboard-widget-list > .add-item > .cbi-dropdown {
box-sizing: border-box;
width: 100%;
max-width: none;
}
.dashboard-widget-list.dashboard-sorting > .item * {
pointer-events: none;
}
.dashboard-settings .dashboard-configurable::after {
bottom: auto;
height: 28px;
}
.dashboard-widget-settings > summary {
cursor: pointer;
padding: 2px 0;
}
.dashboard-widget-options {
margin: 12px 0 6px 12px;
padding-left: 12px;
cursor: default;
word-break: normal;
overflow-wrap: anywhere;
}
.dashboard-widget-options .cbi-value-title {
display: none;
}
.dashboard-widget-options .cbi-value-field {
margin-left: 0;
min-width: 0;
}
.dashboard-widget-options .cbi-value {
padding: 0;
}
.dashboard-sensor-choice {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 0 3px 6px;
}
.dashboard-sensor-choice > i {
display: inline-block;
width: 9px;
height: 9px;
border-radius: 2px;
}
/* Every row fills the width: an item's basis is its row's share, set from
--dashboard-per-row, and flex-grow takes up the rest. On narrow screens
the min-width wraps the items, which still fill their rows. */
@@ -82,6 +149,28 @@
min-width: 250px;
}
/* All charts share one compact header; keep the plotting area aligned even
when a source has no metadata. Card surfaces and heading fonts stay themed. */
.Dashboard .dashboard-chart > h3 {
margin: 0 0 4px;
padding: 0;
border: 0;
line-height: 1.4;
}
.Dashboard .dashboard-chart > .cbi-section-descr {
min-height: 1.4em;
margin: 0 0 16px;
padding: 0;
font-size: 12px;
line-height: 1.4;
color: var(--dashboard-text-muted);
}
.dashboard-chart > em:empty {
display: none;
}
/* ---- Icon (mask keeps the SVG files, colour follows the theme) ---- */
.dashboard-icon {
display: inline-block;
@@ -145,6 +234,11 @@
white-space: nowrap;
}
/* Keep every component reading visible when a temperature card narrows. */
.dashboard-temperature .dashboard-kpi-line {
white-space: normal;
}
/* ---- Donut ---- */
/* Shorter than the bar charts it shares a row with, so centre it. */
.dashboard-donut {
@@ -252,6 +346,8 @@
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
overflow-wrap: anywhere;
}
.dashboard-legend-inline i {
@@ -420,11 +516,7 @@
.dashboard-legend-inline b {
color: var(--dashboard-text);
}
/* ---- WAN traffic: one counter source per plot ---- */
.dashboard-traffic-source {
min-width: 0;
white-space: nowrap;
}
/* ---- Wireless network boxes (LuCI .ifacebox) ---- */
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M9 14.5V5a3 3 0 0 1 6 0v9.5a5 5 0 1 1-6 0Z"/><path d="M12 8v10"/><circle cx="12" cy="18" r="1"/></svg>

After

Width:  |  Height:  |  Size: 272 B

@@ -126,11 +126,13 @@ return baseclass.extend({
if (mem)
desc.push('%1024.0mB'.format(mem.total));
return charts.card({
return this.chart = charts.card({
node: this.chart,
title: _('System load'),
desc: desc.join(' · '),
body: busy.length ? [
charts.lines({
this.plot = charts.lines({
node: this.plot,
span: history.span(),
max: 100,
ticks: [ 0, 25, 50, 75, 100 ].map(value => ({ value: value, label: '%d%%'.format(value) })),
@@ -0,0 +1,319 @@
'use strict';
'require baseclass';
'require rpc';
'require uci';
'require view.dashboard.lib.charts as charts';
'require view.dashboard.lib.history as history';
const read = rpc.declare({ object: 'luci.dashboard.temperature', method: 'read', params: [ 'since', 'id' ], expect: { '': {} } });
const temperature = value => Number.isFinite(value) ? '%.1f °C'.format(value) : '—';
const STEP = 10000, DEFAULT_LINES = 8, MAX_LINES = 64;
function sensorCategory(sensor, components) {
return typeof components[sensor.category] == 'string' ? sensor.category : 'other';
}
// Rebuild only when sensor metadata changes. Number channels within their
// component, keeping existing numbers when sources reorder or disappear.
// These are sensor labels, not inferred radio bands or physical port numbers.
function nameChannels(channels, components) {
const groups = new Map();
for (const channel of channels.values()) {
const group = groups.get(channel.category) || { count: 0, last: 0, numbered: false };
group.count++;
group.last = Math.max(group.last, channel.number || 0);
group.numbered ||= channel.numbered;
groups.set(channel.category, group);
}
for (const [, channel] of Array.from(channels).sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true }))) {
const group = groups.get(channel.category);
channel.number ||= ++group.last;
channel.numbered = group.count > 1 || group.numbered;
channel.name = components[channel.category] + (channel.numbered ? ' ' + channel.number : '');
}
}
function colorChannels(channels) {
const used = new Set(Array.from(channels.values(), channel => channel.color));
let color = 1;
for (const channel of channels.values())
if (!channel.color) {
while (used.has(color))
color++;
if (color > MAX_LINES)
break;
channel.color = color;
used.add(color++);
}
}
function channelColor(channel) {
return channel.color > 8
? 'hsl(%d, 60%%, var(--dashboard-extra-lightness))'.format((channel.color * 137.508) % 360) : null;
}
// CPU selection priorities come from the same registry as component names.
// Never switch channels merely because the preferred sensor failed a read.
function processorSensor(sensors) {
let selected, priority = 99;
for (const sensor of sensors) {
const value = sensor.category == 'cpu'
? (Number.isFinite(sensor.priority) ? sensor.priority : 8) : 99;
if (value < priority || (selected && value == priority &&
(sensor.id || sensor.label).localeCompare(selected.id || selected.label, undefined, { numeric: true }) < 0)) {
selected = sensor;
priority = value;
}
}
return selected;
}
// A module may expose multiple radios or thermal zones. Keep all channels in
// details, and summarize the hottest available reading for each component.
function componentTemperature(sensors, category, label) {
let present = false, value = -Infinity;
for (const sensor of sensors)
if (sensor.category == category) {
present = true;
if (Number.isFinite(sensor.celsius))
value = Math.max(value, sensor.celsius);
}
// Wrap between components, keeping each label and reading together.
return present ? '%s\u00a0%s'.format(label, temperature(value).replace(' ', '\u00a0')) : null;
}
return baseclass.extend({
widgets: [
{ id: 'temperature', slot: 'cards', title: _('Temperature'), order: 40 },
{ id: 'temperature_history', slot: 'charts', title: _('Temperature history'), order: 30 },
{ id: 'temperatures', slot: 'tabs', title: _('Temperatures'), order: 40 }
],
// All views share channel identities, even when the history chart is hidden
// or settings are opened first. Selection never changes sensor numbering.
syncChannels(data) {
let dirty = false;
if (data.components && typeof data.components == 'object' && !Array.isArray(data.components)) {
const components = { other: _('Sensor'), ...Object.fromEntries(Object.entries(data.components)
.filter(([, label]) => typeof label == 'string').map(([id, label]) => [id, _(label)])) };
dirty = JSON.stringify(components) !== JSON.stringify(this.components);
this.components = components;
}
const components = this.components ||= { other: _('Sensor') };
const sensors = Array.isArray(data.sensors) ? data.sensors : [];
const channels = this.channels ||= new Map();
const current = new Map(sensors.slice(0, MAX_LINES).map((sensor, index) => [ sensor.id, { sensor, index } ]));
for (const [id] of channels)
if (!current.has(id)) {
channels.delete(id);
dirty = true;
}
for (const [id, { sensor, index }] of current) {
let channel = channels.get(id);
if (!channel) {
channel = { color: 0 };
channels.set(id, channel);
dirty = true;
}
if (channel.label !== sensor.label || channel.index !== index)
dirty = true;
const category = sensorCategory(sensor, components);
if (channel.category !== category) {
channel.category = category;
channel.number = 0;
channel.numbered = false;
dirty = true;
}
channel.label = sensor.label;
channel.index = index;
channel.current = sensor.celsius;
}
if (dirty) {
nameChannels(channels, components);
colorChannels(channels);
if (this.trend)
this.trend.dirty = true;
}
return channels;
},
load() {
const now = performance.now();
const state = this.history ||= { samples: [], step: STEP, slots: 30, now: 0 };
if (this.pending)
return this.pending;
if (this.data && now < this.nextRead) {
this.data.age_ms = this.age == null ? null : this.age + now - this.received;
state.now = this.receivedNow + now - this.received;
return Promise.resolve(this.data);
}
// Match backend sampling and fetch only new rows after the first load.
const last = state.samples[state.samples.length - 1];
this.pending = L.resolveDefault(read(last ? last[0] : 0, state.id || ''), { status: 'error', sensors: [] }).then(data => {
history.update(state, data);
this.data = data;
this.received = performance.now();
this.receivedNow = state.now;
this.age = Number.isFinite(data.age_ms) ? data.age_ms : null;
this.nextRead = this.received + (data.status == 'unsupported' ? 60000
: this.age != null && this.age < state.step ? state.step - this.age : state.step);
this.pending = null;
return data;
});
return this.pending;
},
// The layout form calls this only when opened; normal charts do not load
// the form library or build any configuration controls.
addOptions(section, form, ui) {
return this.load().then(data => {
const channels = this.syncChannels(data);
const o = section.option(form.MultiValue, 'temperature_sensors', _('Temperature history'));
o.retain = true;
o.forcewrite = true;
o.depends({ charts: 'temperature_history', '!contains': true });
o.cfgvalue = () => {
const selected = L.toArray(uci.get('dashboard', 'layout', 'temperature_sensors'));
return selected.length ? selected : Array.from(channels.keys()).slice(0, DEFAULT_LINES);
};
for (const [id, channel] of channels)
o.value(id, E('span', { 'class': 'dashboard-sensor-choice', 'title': channel.label }, [
E('i', { 'class': 'dashboard-series-' + channel.color,
'style': channelColor(channel) ? 'background-color:' + channelColor(channel) : null,
'aria-hidden': 'true' }), channel.name
]));
// Keep saved IDs selectable even if a device is temporarily absent.
for (const id of L.toArray(uci.get('dashboard', 'layout', 'temperature_sensors')))
if (!channels.has(id))
o.value(id, '%s · %s'.format(_('Unavailable'), id));
o.validate = (section_id, value) => !L.toArray(value).length ? _('Select at least one sensor.')
: L.toArray(value).length <= MAX_LINES || _('Select no more than %d sensors.').format(MAX_LINES);
o.renderWidget = function(section_id, option_index, cfgvalue) {
const widget = new ui.Select(L.toArray(cfgvalue), this.transformChoices(), {
id: this.cbid(section_id), sort: this.keylist, multiple: true,
widget: 'checkbox', orientation: 'vertical',
validate: this.getValidator(section_id), disabled: this.map.readonly
});
// ui.Select renders checkboxes but its default accessors handle radios.
widget.getValue = function() {
return Array.from(this.node.querySelectorAll('input:checked'), input => input.value);
};
widget.setValue = function(value) {
const selected = new Set(L.toArray(value));
this.node.querySelectorAll('input').forEach(input => input.checked = selected.has(input.value));
};
return widget.render();
};
return { slot: 'charts', widget: 'temperature_history', title: _('Temperature history'), options: [ o ] };
});
},
renderChart(data, sensors) {
const channels = this.syncChannels(data);
const state = this.history;
const span = history.span(state);
const fresh = !state.failed && Number.isFinite(data.age_ms) && data.age_ms < 15000
&& (data.status == 'ok' || data.status == 'partial');
let h = this.trend;
if (!h) {
h = this.trend = {
channels, min: 0, max: 100,
selected: new Set(L.toArray(uci.get('dashboard', 'layout', 'temperature_sensors')).slice(0, MAX_LINES)),
plot: E('div'), legend: E('div'), message: charts.empty('')
};
h.node = charts.card({ title: _('Temperature history'), desc: '°C', body: [ h.plot, h.legend, h.message ] });
}
if (h.id !== state.id) {
h.id = state.id;
h.min = 0;
h.max = 100;
h.dirty = true;
}
const tick = Math.floor(performance.now() / state.step);
const last = state.samples[state.samples.length - 1]?.[0] || 0;
if (!h.dirty && h.tick === tick && h.drawn === last && h.fresh === fresh)
return h.node;
h.dirty = false;
h.tick = tick;
h.drawn = last;
h.fresh = fresh;
const series = [], legend = [];
const selected = h.selected.size ? h.selected : new Set(sensors.slice(0, DEFAULT_LINES).map(sensor => sensor.id));
for (const [id, channel] of h.channels) {
if (!channel.color || !selected.has(id))
continue;
const values = history.series(cur => cur[1] > state.now - span * 1000 ? cur[2][channel.index] : null, state.samples, state.step);
for (const point of values)
if (Number.isFinite(point.v)) {
h.min = Math.min(h.min, Math.floor(point.v / 20) * 20);
h.max = Math.max(h.max, Math.ceil(point.v / 20) * 20);
}
const className = 'dashboard-series-' + channel.color;
const color = channelColor(channel);
series.push({ className, color, values });
legend.push({ className, color, label: channel.name, title: channel.label, value: temperature(fresh ? channel.current : null) });
}
h.lines = charts.lines({ node: h.lines, end: state.now, span, min: h.min, max: h.max,
ticks: [ 0, 1, 2, 3, 4 ].map(i => {
const value = h.min + (h.max - h.min) * i / 4;
return { value, label: String(value) };
}), ariaLabel: _('Temperature history'), series });
if (h.plot.firstChild !== h.lines)
L.dom.content(h.plot, h.lines);
L.dom.content(h.legend, charts.legend(legend));
h.message.textContent = !fresh ? _('Temperature temporarily unavailable')
: !series.length ? _('Selected temperature sensors are unavailable') : '';
return h.node;
},
render(data) {
const age = data.age_ms >= 15000 ? Math.floor(data.age_ms / 1000) : 0;
if (data === this.renderedData && age === this.renderedAge)
return this.sections;
this.renderedData = data;
this.renderedAge = age;
const sensors = Array.isArray(data.sensors) ? data.sensors : [];
const channels = this.syncChannels(data);
const components = this.components;
const processor = processorSensor(sensors);
const value = processor?.celsius;
const message = data.status == 'unsupported' ? _('No supported temperature sensors found') : _('Temperature temporarily unavailable');
const stale = data.age_ms >= 15000;
const modules = ['nss', 'wifi', 'modem'].map(category => componentTemperature(sensors, category, components[category] || components.other)).filter(Boolean);
const sub = [];
for (let i = 0; i < modules.length; i += 2)
sub.push(modules.slice(i, i + 2).join(' · '));
if (!processor)
sub.push(_('Processor temperature unavailable'));
else if (!Number.isFinite(value))
sub.push(message);
if (stale)
sub.push(_('Reading age: %d seconds').format(Math.floor(data.age_ms / 1000)));
let card, tab;
if (data.status == 'unsupported')
this.trend = null;
return this.sections = {
cards: data.status == 'unsupported' ? [] : [{
id: 'temperature', node: () => card ||= charts.kpi({
icon: 'temperature', title: _('Temperature'), className: 'dashboard-temperature',
value: [ '%s %s'.format(components.cpu || _('CPU'), temperature(value)) ], sub, stacked: true
})
}],
charts: data.status == 'unsupported' ? [] : [{
id: 'temperature_history', node: () => this.renderChart(data, sensors)
}],
tabs: data.status == 'unsupported' ? [] : [{ id: 'temperatures', title: _('Temperatures'), content: () => tab ||= E('div', {}, [
stale ? E('p', {}, [ _('Reading age: %d seconds').format(Math.floor(data.age_ms / 1000)) ]) : '',
data.status == 'partial' ? E('p', {}, [ _('Some temperature sensors are unavailable') ]) : '',
sensors.length ? charts.table({
head: [ _('Component'), _('Sensor'), _('Temperature') ],
rows: sensors.map(s => [ channels.get(s.id)?.name || components[sensorCategory(s, components)], s.label, temperature(s.celsius) ])
}) : charts.empty(message)
]) }]
};
}
});
@@ -3,18 +3,21 @@
'require view.dashboard.lib.charts as charts';
'require view.dashboard.lib.history as history';
const NET = 4;
const NET = 4, WAN = 5;
function rate(cur, prev, seconds, index) {
const name = cur?.[WAN];
if (!name || name !== prev?.[WAN])
return null;
function rate(cur, prev, seconds, name, index) {
const a = prev?.[NET]?.[name];
const b = cur?.[NET]?.[name];
if (!Array.isArray(a) || !Array.isArray(b) || !Number.isFinite(seconds) || seconds <= 0)
return null;
// Older rpcd instances provide only two fields. Crossing to the new
// format, like a change of ifindex, starts a fresh pair of samples.
if (a[2] !== b[2] || a[2] === null || b[2] === null)
// Do not calculate rates across a device recreation or an uncertain read.
if (a[2] == null || a[2] !== b[2])
return null;
for (let i = 0; i < 2; i++)
@@ -24,15 +27,8 @@ function rate(cur, prev, seconds, name, index) {
return (b[index] - a[index]) * 8 / seconds;
}
function selectedRate(cur, prev, seconds, index) {
const current = cur?.[5]?.devices, previous = prev?.[5]?.devices;
if (current?.length !== 1 || previous?.length !== 1 || current[0] !== previous[0])
return null;
return rate(cur, prev, seconds, current[0], index);
}
function points(index) {
const points = history.series((cur, prev, seconds) => selectedRate(cur, prev, seconds, index));
const points = history.series((cur, prev, seconds) => rate(cur, prev, seconds, index));
const last = points[points.length - 1];
if (last && history.now - last.t > history.step * 2.5)
points.push({ t: history.now, v: null });
@@ -57,11 +53,12 @@ return baseclass.extend({
const available = down.some(p => p.v != null) || up.some(p => p.v != null);
const current = last(down) != null && last(up) != null;
const sample = history.samples[history.samples.length - 1];
const device = sample?.[5]?.devices?.[0];
const device = sample?.[WAN];
const body = [];
if (available) {
body.push(charts.lines({
body.push(this.plot = charts.lines({
node: this.plot,
span: history.span(),
max: scale.max,
ticks: scale.ticks,
@@ -73,14 +70,15 @@ return baseclass.extend({
]));
}
if (!current)
body.push(charts.empty(history.failed || !sample?.[5]?.devices?.length
? _('No data received') : available ? _('Waiting for a new sample...') : history.status()));
body.push(charts.empty(history.failed ? _('No data received')
: !sample ? history.status() : !device ? _('Not connected') : available ? _('Waiting for a new sample...') : history.status()));
// No null children: older LuCI DOM helpers render them as literal text.
return { charts: [ { id: 'wan', node: charts.card({
return { charts: [ { id: 'wan', node: this.chart = charts.card({
node: this.chart,
title: this.title,
desc: device ? device + ' · ' + scale.unit : scale.unit,
body: [ E('section', { 'class': 'dashboard-traffic-source' }, body) ]
body: body
}) } ] };
}
});
@@ -146,7 +146,7 @@ function updateCharts(container, chartNodes) {
scrollPositions[el.dataset.chart] = el.scrollLeft;
});
L.dom.content(container, fillRows(chartNodes, 'charts'));
updateNodes(container, fillRows(chartNodes, 'charts'));
container.querySelectorAll('[data-chart]').forEach(el => {
if (el.dataset.chart && scrollPositions[el.dataset.chart] != null)
@@ -154,6 +154,16 @@ function updateCharts(container, chartNodes) {
});
}
// Retained widgets need no detach/attach cycle on unchanged samples.
function updateNodes(container, nodes) {
nodes.forEach((node, i) => {
if (container.children[i] !== node)
container.insertBefore(node, container.children[i] || null);
});
while (container.children.length > nodes.length)
container.removeChild(container.lastChild);
}
function updateTabs(tabMap, tabGroup, items, form) {
const menu = tabMap.querySelector('.cbi-tabmenu');
const existingPanes = Array.from(tabGroup.children);
@@ -248,12 +258,12 @@ function startPolling(includes, layout, root, form) {
const sections = collectSections(includes, results, layout);
if (form)
sections.tabs.push({ id: 'layout', title: _('Layout'), content: [] });
sections.tabs.push({ id: 'layout', title: _('Settings'), content: [] });
updateShell(root, sections, containers);
if (sections.cards.length)
L.dom.content(cardsContainer, fillRows(sections.cards, 'cards'));
updateNodes(cardsContainer, fillRows(sections.cards, 'cards'));
if (sections.charts.length)
updateCharts(chartsContainer, sections.charts);
@@ -295,7 +305,7 @@ return view.extend({
document.addEventListener('uci-applied', () => window.location.reload());
const form = L.hasViewPermission() ? E('div', { 'class': 'cbi-section', 'data-tab': 'layout', 'data-tab-title': _('Layout') }, [ E('em', { 'class': 'spinning' }, [ _('Loading view…') ]) ]) : null;
const form = L.hasViewPermission() ? E('div', { 'class': 'cbi-section', 'data-tab': 'layout', 'data-tab-title': _('Settings') }, [ E('em', { 'class': 'spinning' }, [ _('Loading view…') ]) ]) : null;
return startPolling(includes, layout, root, form).then(() => root);
},
@@ -3,11 +3,12 @@
const SVG_NS = 'http://www.w3.org/2000/svg';
function svg(tag, attrs, children) {
const node = document.createElementNS(SVG_NS, tag);
function svg(tag, attrs, children, existing) {
const node = existing || document.createElementNS(SVG_NS, tag);
for (const key in (attrs || {}))
node.setAttribute(key, attrs[key]);
if (node.getAttribute(key) !== String(attrs[key]))
node.setAttribute(key, attrs[key]);
(children || []).forEach(child => {
if (child != null)
@@ -82,11 +83,31 @@ return baseclass.extend({
return E('span', { 'class': 'label ' + (kind || '') }, [ text ]);
},
// A card is a plain .cbi-section, so the theme draws it.
// Keep the theme's card surface, with shared chart header spacing.
card(opts) {
return E('div', { 'class': 'cbi-section ' + (opts.className || '') }, [
// Reuse the shell as well as its plot: moving a live plot into a new
// card temporarily shrinks the page and clamps its scroll position.
if (opts.node) {
let previous = opts.node.querySelector('.cbi-section-descr');
if (previous.textContent !== (opts.desc || ''))
previous.textContent = opts.desc || '';
for (const child of [].concat(opts.body)) {
if (previous.nextSibling !== child) {
if (previous.nextSibling)
opts.node.replaceChild(child, previous.nextSibling);
else
opts.node.appendChild(child);
}
previous = child;
}
while (previous.nextSibling)
opts.node.removeChild(previous.nextSibling);
return opts.node;
}
return E('div', { 'class': 'cbi-section dashboard-chart ' + (opts.className || '') }, [
opts.title ? E('h3', {}, [ opts.title ]) : '',
opts.desc ? E('div', { 'class': 'cbi-section-descr' }, [ opts.desc ]) : ''
E('div', { 'class': 'cbi-section-descr' }, [ opts.desc || '' ])
].concat(opts.body));
},
@@ -241,20 +262,28 @@ return baseclass.extend({
]);
},
// A time series of points `{ t, v }`, placed by their time: the x axis
// spans `span` seconds up to the last point. A null `v` leaves a gap, and
// a point with gaps on both sides is drawn as a dot.
// Time-ordered points `{ t, v }`, with t in milliseconds. The x axis spans
// `span` seconds up to `end` or the last point. Non-finite values leave a
// gap; isolated points are dots. Pass `node` to update an existing chart.
lines(opts) {
const max = opts.max || 1;
const min = opts.min ?? 0;
const max = opts.max ?? 1;
const shapes = [];
const end = opts.series.reduce((t, series) => Math.max(t, ...series.values.map(p => p.t)), 0);
const end = opts.end ?? opts.series.reduce((t, series) => Math.max(t, series.values[series.values.length - 1]?.t || 0), 0);
const plot = opts.node?.querySelector('svg');
const previous = plot ? Array.from(plot.children) : [];
const shape = (tag, attrs) => {
const old = previous[shapes.length];
shapes.push(svg(tag, attrs, null, old?.localName == tag ? old : null));
};
opts.series.forEach((series, n) => {
let run = [];
const className = series.className || 'dashboard-series-' + (n + 1);
series.values.concat([ { v: null } ]).forEach(p => {
if (p.v != null) {
run.push([ 100 - (end - p.t) / (opts.span * 10), 100 - scale(p.v, 0, max) ]);
if (Number.isFinite(p.v)) {
run.push([ 100 - (end - p.t) / (opts.span * 10), 100 - scale(p.v, min, max) ]);
return;
}
@@ -265,28 +294,48 @@ return baseclass.extend({
const points = run.map(p => '%.2f,%.2f'.format(p[0], p[1])).join(' ');
if (series.area)
shapes.push(svg('polygon', {
'class': 'dashboard-series-' + (n + 1),
shape('polygon', {
'class': className,
'points': '%.2f,100 %s %.2f,100'.format(run[0][0], points, run[run.length - 1][0])
}));
});
shapes.push(svg('polyline', { 'class': 'dashboard-series-' + (n + 1), 'points': points }));
shape('polyline', { 'class': className, 'points': points, 'style': series.color ? 'stroke:' + series.color : '' });
}
run = [];
});
});
const axis = opts.node?.querySelector('.dashboard-bars-axis');
const ago = (opts.span >= 60) ? _('%d min ago').format(Math.round(opts.span / 60)) : _('%d s ago').format(opts.span);
if (axis && axis.children.length == opts.ticks.length) {
const grid = opts.node.querySelector('.dashboard-bars-grid');
opts.ticks.forEach((tick, i) => {
const top = '%.2f%%'.format(100 - scale(tick.value, min, max));
axis.children[i].style.top = grid.children[i].style.top = top;
if (axis.children[i].textContent !== String(tick.label))
axis.children[i].textContent = tick.label;
});
shapes.forEach((node, i) => {
if (plot.children[i] !== node)
plot.insertBefore(node, plot.children[i] || null);
});
while (plot.children.length > shapes.length)
plot.removeChild(plot.lastChild);
opts.node.querySelector('.dashboard-lines-time span').textContent = ago;
return opts.node;
}
return E('div', { 'class': 'dashboard-bars' }, [
E('div', { 'class': 'dashboard-bars-axis' }, opts.ticks.map(tick =>
E('span', { 'style': 'top:%.2f%%'.format(100 - scale(tick.value, 0, max)) }, [ tick.label ]))),
E('span', { 'style': 'top:%.2f%%'.format(100 - scale(tick.value, min, max)) }, [ tick.label ]))),
E('div', { 'class': 'dashboard-lines-plot' }, [
E('div', { 'class': 'dashboard-bars-grid' }, opts.ticks.map(tick =>
E('i', { 'style': 'top:%.2f%%'.format(100 - scale(tick.value, 0, max)) }))),
E('i', { 'style': 'top:%.2f%%'.format(100 - scale(tick.value, min, max)) }))),
svg('svg', { 'viewBox': '0 0 100 100', 'preserveAspectRatio': 'none', 'role': 'img', 'aria-label': opts.ariaLabel || '' }, shapes)
]),
E('div', { 'class': 'dashboard-lines-time' }, [
E('span', {}, [ (opts.span >= 60) ? _('%d min ago').format(Math.round(opts.span / 60)) : _('%d s ago').format(opts.span) ]),
E('span', {}, [ ago ]),
E('span', {}, [ _('now') ])
])
]);
@@ -294,6 +343,6 @@ return baseclass.extend({
legend(items) {
return E('div', { 'class': 'dashboard-legend-inline' }, items.map(item =>
E('span', {}, [ E('i', { 'class': item.className }), item.label, (item.value != null) ? E('b', {}, [ item.value ]) : '' ])));
E('span', { 'title': item.title || null }, [ E('i', { 'class': item.className, 'style': item.color ? 'background-color:' + item.color : null }), item.label, (item.value != null) ? E('b', {}, [ item.value ]) : '' ])));
}
});
@@ -15,26 +15,29 @@ return baseclass.extend({
step: 5000,
slots: 60,
// Both counter history and temperature readings use the same bounded,
// incremental protocol. State belongs to the caller, not to the chart DOM.
update(state, res) {
state.failed = (!L.isObject(res) || !Array.isArray(res.samples));
if (state.failed) {
state.samples = [];
return;
}
if (res.id != state.id)
state.samples = [];
state.id = res.id;
state.now = res.now;
state.step = res.step;
state.slots = res.slots;
state.samples = (state.samples || []).concat(res.samples).filter(sample => sample[TIME] > res.now - res.step * res.slots);
},
fetch() {
const last = this.samples[this.samples.length - 1];
return L.resolveDefault(callHistory(last ? last[SEQ] : 0, this.id || ''), null).then(res => {
this.failed = (!L.isObject(res) || !Array.isArray(res.samples));
if (this.failed) {
// Old samples must not appear as current CPU usage or live traffic.
this.samples = [];
return;
}
if (res.id != this.id)
this.samples = [];
this.id = res.id;
this.now = res.now;
this.step = res.step;
this.slots = res.slots;
this.samples = this.samples.concat(res.samples).filter(sample => sample[TIME] > res.now - res.step * res.slots);
// Failed requests must not turn old samples into live readings.
this.update(this, res);
});
},
@@ -53,12 +56,12 @@ return baseclass.extend({
return this.failed ? _('No data received') : _('Collecting data...');
},
span() {
return this.slots * this.step / 1000;
span(state = this) {
return state.slots * state.step / 1000;
},
near(prev, cur) {
return (prev != null && cur[TIME] > prev[TIME] && cur[TIME] - prev[TIME] <= 2.5 * this.step);
near(prev, cur, step = this.step) {
return (prev != null && cur[TIME] > prev[TIME] && cur[TIME] - prev[TIME] <= 2.5 * step);
},
pair() {
@@ -70,12 +73,12 @@ return baseclass.extend({
// Points `{ t, v }` for a chart. `fn(cur, prev, seconds)` gives a value or
// null; `prev` is null where sampling had paused, which leaves a gap.
series(fn) {
series(fn, samples = this.samples, step = this.step) {
const points = [];
this.samples.forEach((cur, i) => {
const prev = this.samples[i - 1];
const near = this.near(prev, cur);
samples.forEach((cur, i) => {
const prev = samples[i - 1];
const near = this.near(prev, cur, step);
if (prev != null && !near)
points.push({ t: cur[TIME] - 1, v: null });
@@ -5,6 +5,45 @@
'require ui';
'require view.dashboard.lib.widgets as widgets';
function attachOptions(map, lists, panels) {
const parking = E('div', { 'hidden': '' });
map.root.appendChild(parking);
for (const panel of panels.filter(Boolean)) {
const list = lists[panel.slot].getUIElement('layout');
const fields = E('div', { 'class': 'dashboard-widget-options' },
panel.options.map(option => map.findElement('data-field', option.cbid('layout'))));
const summary = E('summary', {}, panel.title);
const details = E('details', { 'class': 'dashboard-widget-settings' }, [ summary, fields ]);
parking.appendChild(details);
// Keep native form actions out of the dynamic list's delete/drag handlers.
for (const type of [ 'click', 'keydown', 'touchstart', 'touchmove', 'touchend', 'dragstart', 'drop' ])
fields.addEventListener(type, ev => ev.stopPropagation());
summary.addEventListener('click', ev => ev.stopPropagation());
summary.addEventListener('keydown', ev => ev.stopPropagation());
const mount = () => {
const item = Array.from(list.node.children).find(node =>
node.matches('.item') && node.querySelector(':scope > input[type="hidden"]')?.value === panel.widget);
if (item && details.parentNode !== item) {
item.classList.add('dashboard-configurable');
item.querySelector(':scope > span')?.remove();
item.insertBefore(details, item.firstChild);
}
};
const addItem = list.addItem, removeItem = list.removeItem;
list.addItem = function() {
const result = addItem.apply(this, arguments);
mount();
return result;
};
list.removeItem = function(node, item) {
if (item.contains(details))
parking.appendChild(details);
return removeItem.apply(this, arguments);
};
mount();
}
}
return baseclass.extend({
render(includes) {
const slots = {
@@ -14,8 +53,8 @@ return baseclass.extend({
};
const m = new form.Map('dashboard');
const s = m.section(form.NamedSection, 'layout', 'dashboard', null,
_('The lists follow the page from top to bottom. What is in a list is shown, in that order: drag an entry to move it. An empty list shows the defaults.'));
const s = m.section(form.NamedSection, 'layout', 'dashboard');
const lists = {};
widgets.slots.forEach(slot => {
const choices = widgets.list(includes, slot);
@@ -23,7 +62,7 @@ return baseclass.extend({
if (!choices.length)
return;
const o = s.option(form.DynamicList, slot, slots[slot]);
const o = lists[slot] = s.option(form.DynamicList, slot, slots[slot]);
choices.forEach(widget => o.value(widget.id, widget.title));
@@ -41,18 +80,33 @@ return baseclass.extend({
o.renderWidget = function(section_id, option_index, cfgvalue) {
const node = form.DynamicList.prototype.renderWidget.apply(this, arguments);
const shown = L.toArray(cfgvalue);
node.classList.add('dashboard-widget-list');
// Native drop handling expects the item itself as the drop target.
node.addEventListener('dragstart', () => node.classList.add('dashboard-sorting'));
for (const type of [ 'dragend', 'drop' ])
node.addEventListener(type, () => node.classList.remove('dashboard-sorting'));
node.querySelectorAll('.cbi-dropdown ul > li[data-value]').forEach(li => {
if (shown.includes(li.getAttribute('data-value')))
li.setAttribute('unselectable', '');
});
node.querySelector('.create-item-input').parentNode.remove();
node.querySelector('.create-item-input')?.parentNode.remove();
return node;
};
});
return m.render().then(node => E('div', {}, [
return Promise.all(includes.filter(include => typeof(include.addOptions) == 'function')
.map(include => include.addOptions(s, form, ui))).then(panels => {
const renderContents = m.renderContents;
m.renderContents = function() {
return renderContents.apply(this, arguments).then(node => {
attachOptions(this, lists, panels);
return node;
});
};
return m.render();
}).then(node => E('div', { 'class': 'dashboard-settings' }, [
node,
E('div', { 'class': 'cbi-page-actions' }, [
E('button', {