Shell 1.11.0: alerts — a module flashes every dashboard listening on one of six channels
A module that sees something a tech must act on now (a timer overrun, a meter past its limit, timecode gone) raises an alert on a channel, 1–6, and every dashboard listening to that channel flashes: the menu bar — brought out for the duration if it was hidden — and a frame round the screen alternate between the level's two colours, with the alert's text bold across the bar. Low fades slowly, medium faster, critical snaps with no fade and floods the board behind the tiles too, in a muted cut that shows faintly through the tile panels without costing their content any contrast. Server: the hub. One alert per channel (a new one replaces the last), timed out server-side (1–600 s, 15 by default, 0 = held until cleared), broadcast over the shell stream as `alert` / `alert-clear`; GET /api/alerts for a dashboard that opens or reconnects mid-alert; POST /api/alerts and DELETE /api/alerts/<n>, open like a layout save. Modules raise from their server entry with shell.alert() / shell.clearAlert() or from a tile with moduleApi.alert() / moduleApi.clearAlert(); a module's alerts end when it stops. Colours live as alerts.colors in the data directory's proddash.json. Dashboard: the Layouts menu gains a folded Alerts row with six numbered toggles; the channel list saves with the layout, local and named (the server keeps it in a saved layout). Admin: a folded Alerts section with two colour pickers per level, a swatch running each level's cadence, and a Test row. Docs: docs/ALERTS.md (the feature), a "Raising alerts" section in the module guide, README. Tools: tools/alert.js raises/clears/lists from the command line; tools/alerts.test.js drives it all end to end. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
a3500f98b1
commit
5ca0a672fa
+301
-8
@@ -227,6 +227,16 @@ const tileEls = new Map(); // tile id -> { el, body, dot, titleEl, instance }
|
||||
away regardless; this is the windowed equivalent, asked for by hand. */
|
||||
let autoHideHeads = false;
|
||||
|
||||
/* Which of the six alert channels this dashboard listens to. Which screen
|
||||
flashes for what is part of how a booth is arranged — the stage screen
|
||||
takes the stage's alerts, the video world its own — so like auto-hide it
|
||||
saves with the layout, local and named. Every dashboard hears every alert
|
||||
over the shell stream; this decides which ones it shows (see the alerts
|
||||
section). */
|
||||
let alertChannels = [];
|
||||
/** True while an alert this dashboard listens to is on screen: the menu bar is held open for it. */
|
||||
let alertShowing = false;
|
||||
|
||||
/* Beside the layout itself: the copy it replaced (restored if the layout
|
||||
ever fails to parse) and, after loading a named layout, the arrangement
|
||||
that was on screen before (what Undo goes back to). */
|
||||
@@ -235,7 +245,7 @@ const LS_LAYOUT_PREVIOUS = LS_LAYOUT + '.previous';
|
||||
|
||||
function saveLayout() {
|
||||
try {
|
||||
const next = JSON.stringify({ v: 1, autoHideHeads, gridCols: COLS, tiles });
|
||||
const next = JSON.stringify({ v: 1, autoHideHeads, gridCols: COLS, alertChannels, tiles });
|
||||
const current = localStorage.getItem(LS_LAYOUT);
|
||||
if (current && current !== next) localStorage.setItem(LS_LAYOUT_BACKUP, current);
|
||||
localStorage.setItem(LS_LAYOUT, next);
|
||||
@@ -1388,6 +1398,34 @@ function buildModuleApi(tile, man, entry) {
|
||||
entry.dot.title = msg;
|
||||
},
|
||||
|
||||
/**
|
||||
* Flash every dashboard listening to an alert channel — this one too,
|
||||
* if it listens. { channel: 1–6, level: 'low' | 'medium' | 'critical',
|
||||
* text (80 chars at most), duration: seconds, 0 to hold it until
|
||||
* cleared, 15 when omitted }. Goes through the server, which is the
|
||||
* hub; resolves with the alert as raised, rejects with the reason it
|
||||
* was refused. A module with a server entry raises from there instead
|
||||
* (shell.alert) — see docs/MODULE-GUIDE.md, "Raising alerts".
|
||||
*/
|
||||
async alert(opts = {}) {
|
||||
const res = await fetch('/api/alerts', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...opts, source: man.id }),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(body.error || `Alert refused (${res.status})`);
|
||||
return body.alert;
|
||||
},
|
||||
|
||||
/** End the alert on a channel early. One alert per channel, so this ends whatever is on it. */
|
||||
async clearAlert(channel) {
|
||||
const res = await fetch('/api/alerts/' + encodeURIComponent(String(Number(channel))), { method: 'DELETE' });
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(body.error || `Clear refused (${res.status})`);
|
||||
return Boolean(body.cleared);
|
||||
},
|
||||
|
||||
/**
|
||||
* The tile's title bar. Controls added here live next to the gear/close
|
||||
* buttons and are removed automatically when the instance stops. The
|
||||
@@ -2142,7 +2180,10 @@ function renderLayout(layout) {
|
||||
// Density first: the tiles are clamped and placed against it.
|
||||
if (!Array.isArray(layout)) setGridCols(layout?.gridCols ?? GRID_DEFAULT, { save: false });
|
||||
tiles = list.map(sanitizeTile);
|
||||
if (!Array.isArray(layout)) setAutoHideHeads(Boolean(layout?.autoHideHeads), { save: false });
|
||||
if (!Array.isArray(layout)) {
|
||||
setAutoHideHeads(Boolean(layout?.autoHideHeads), { save: false });
|
||||
setAlertChannels(layout?.alertChannels, { save: false });
|
||||
}
|
||||
for (const tile of tiles) if (tileIsOffered(tile)) buildTile(tile);
|
||||
scheduleOfferedRecheck();
|
||||
refreshEmptyState();
|
||||
@@ -2207,9 +2248,11 @@ function renderAddMenu(menu) {
|
||||
wireDropdown('layout-btn', 'layout-menu', async (menu, stillOpen) => {
|
||||
menu.innerHTML = '';
|
||||
|
||||
// Density first: the one thing in here that is not a layout but the board
|
||||
// the layouts are arranged on.
|
||||
// The board first — density, and which alert channels this screen
|
||||
// listens to: the two things in here that are not a layout but part of
|
||||
// how one is arranged.
|
||||
menu.appendChild(gridStepper());
|
||||
menu.appendChild(alertsFold());
|
||||
const stepperDivider = document.createElement('div');
|
||||
stepperDivider.className = 'menu-divider';
|
||||
menu.appendChild(stepperDivider);
|
||||
@@ -2245,7 +2288,7 @@ wireDropdown('layout-btn', 'layout-menu', async (menu, stillOpen) => {
|
||||
const res = await fetch('/api/layouts/' + encodeURIComponent(name), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ layout: { autoHideHeads, gridCols: COLS, tiles } }),
|
||||
body: JSON.stringify({ layout: { autoHideHeads, gridCols: COLS, alertChannels, tiles } }),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(body.error || 'Save failed (' + res.status + ')');
|
||||
@@ -2339,15 +2382,25 @@ const topbarSizer = new ResizeObserver(() => {
|
||||
});
|
||||
topbarSizer.observe(topbar);
|
||||
|
||||
/* What the notch (or fullscreen) asked for. The bar itself is also held
|
||||
open for as long as an alert this dashboard listens to is showing — the
|
||||
alert's text lives in it — and goes back to this the moment it ends. */
|
||||
let menuHiddenWanted = false;
|
||||
|
||||
function paintMenuHidden() {
|
||||
document.body.classList.toggle('menu-hidden', menuHiddenWanted && !alertShowing);
|
||||
}
|
||||
|
||||
function setMenuHidden(hidden, { persist = true } = {}) {
|
||||
document.body.classList.toggle('menu-hidden', hidden);
|
||||
menuHiddenWanted = Boolean(hidden);
|
||||
paintMenuHidden();
|
||||
if (persist) {
|
||||
try { localStorage.setItem(LS_MENU, hidden ? '1' : '0'); } catch { /* fine */ }
|
||||
}
|
||||
}
|
||||
|
||||
topbarNotch.addEventListener('click', () => {
|
||||
setMenuHidden(!document.body.classList.contains('menu-hidden'));
|
||||
setMenuHidden(!menuHiddenWanted);
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -2490,7 +2543,7 @@ document.addEventListener('fullscreenchange', () => {
|
||||
if (active) {
|
||||
closeSettingsPopovers();
|
||||
applyAllHeadStates(); // fullscreen has its own rule for the bars
|
||||
menuHiddenBeforeFs = document.body.classList.contains('menu-hidden');
|
||||
menuHiddenBeforeFs = menuHiddenWanted;
|
||||
setMenuHidden(true, { persist: false }); // the menu auto-hides; its notch brings it back
|
||||
// let the collapsed menubar's space settle before measuring
|
||||
requestAnimationFrame(() => requestAnimationFrame(applyFullscreenFit));
|
||||
@@ -2519,9 +2572,15 @@ new ResizeObserver(() => {
|
||||
function subscribeEvents() {
|
||||
// Rides on the page's one stream connection (see sseSubscribe) as `shell:`.
|
||||
sseSubscribe('/api/events', {
|
||||
// (Re)connected: frames may have been missed, so the alerts picture is
|
||||
// taken whole again — what is active, and the colours.
|
||||
open: () => { refreshAlerts(); },
|
||||
events: {
|
||||
'modules-changed': () => handleModulesChanged().then(reconcileOfferedTiles),
|
||||
theme: handleThemeEvent,
|
||||
alert: handleAlertEvent,
|
||||
'alert-clear': handleAlertClearEvent,
|
||||
'alerts-config': handleAlertsConfigEvent,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -2591,6 +2650,240 @@ function initTheme() {
|
||||
|
||||
initTheme();
|
||||
|
||||
/* ── alerts ─────────────────────────────────────────────────────────── */
|
||||
|
||||
/* A module that sees something a tech must act on now raises an alert on
|
||||
one of six channels (server.js is the hub; docs/ALERTS.md the whole
|
||||
story). Every dashboard hears every alert over the shell stream and shows
|
||||
the ones on channels it listens to: the menu bar — held open for the
|
||||
duration, whatever its notch says — and a frame round the screen flash
|
||||
between the level's two colours (style.css sets the cadence per level;
|
||||
critical floods the board behind the tiles as well, in a muted cut), with
|
||||
the text bold in the middle of the bar. Several at once: the most
|
||||
severe takes the bar, the newest among equals, and a count says how many
|
||||
more are on. The server times alerts out and says so; a timer here ends
|
||||
one on time anyway, in case that frame is missed on a flaky connection. */
|
||||
|
||||
const ALERT_CHANNELS = 6;
|
||||
const ALERT_LEVEL_RANK = { low: 1, medium: 2, critical: 3 };
|
||||
const ALERT_COLORS_DEFAULT = {
|
||||
low: ['#1f6feb', '#0b2a5c'],
|
||||
medium: ['#f0b429', '#6b4a0a'],
|
||||
critical: ['#f4433c', '#1a0505'],
|
||||
};
|
||||
const activeAlerts = new Map(); // channel -> { id, channel, level, text, source, startedAt, endsAt (this clock) | null }
|
||||
let alertColors = ALERT_COLORS_DEFAULT;
|
||||
let alertEndTimer = null;
|
||||
const alertBanner = document.getElementById('alert-banner');
|
||||
|
||||
/** Whole numbers 1–6, each once, in order — whatever a layout file says. */
|
||||
function normalizeAlertChannels(list) {
|
||||
const out = new Set();
|
||||
for (const v of Array.isArray(list) ? list : []) {
|
||||
const n = Number(v);
|
||||
if (Number.isInteger(n) && n >= 1 && n <= ALERT_CHANNELS) out.add(n);
|
||||
}
|
||||
return [...out].sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
function setAlertChannels(list, { save = true } = {}) {
|
||||
alertChannels = normalizeAlertChannels(list);
|
||||
paintAlerts();
|
||||
if (save) saveLayout();
|
||||
}
|
||||
|
||||
function toggleAlertChannel(n) {
|
||||
setAlertChannels(alertChannels.includes(n)
|
||||
? alertChannels.filter((c) => c !== n)
|
||||
: [...alertChannels, n]);
|
||||
}
|
||||
|
||||
const CARET_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg>';
|
||||
let alertsFoldOpen = false;
|
||||
|
||||
/** The Layouts menu's Alerts row. Folded, it says which channels this
|
||||
dashboard listens to; open, six numbered buttons toggle them without
|
||||
closing the menu, so a change can be watched taking effect. */
|
||||
function alertsFold() {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'menu-fold';
|
||||
const head = document.createElement('button');
|
||||
head.type = 'button';
|
||||
head.className = 'menu-item menu-fold-head';
|
||||
const label = document.createElement('span');
|
||||
label.textContent = 'Alerts';
|
||||
const sub = document.createElement('span');
|
||||
sub.className = 'sub';
|
||||
label.appendChild(sub);
|
||||
const caret = document.createElement('span');
|
||||
caret.className = 'menu-fold-caret';
|
||||
caret.innerHTML = CARET_SVG;
|
||||
head.append(label, caret);
|
||||
const body = document.createElement('div');
|
||||
body.className = 'menu-fold-body alert-channels';
|
||||
const buttons = [];
|
||||
for (let n = 1; n <= ALERT_CHANNELS; n += 1) {
|
||||
const btn = document.createElement('button');
|
||||
btn.type = 'button';
|
||||
btn.className = 'alert-channel-btn';
|
||||
btn.textContent = String(n);
|
||||
btn.setAttribute('data-tip', `Channel ${n}`);
|
||||
btn.addEventListener('click', () => {
|
||||
toggleAlertChannel(n);
|
||||
paint();
|
||||
});
|
||||
buttons.push(btn);
|
||||
body.appendChild(btn);
|
||||
}
|
||||
const paint = () => {
|
||||
sub.textContent = alertChannels.length ? 'Channels ' + alertChannels.join(', ') : 'No channels';
|
||||
head.setAttribute('aria-expanded', alertsFoldOpen ? 'true' : 'false');
|
||||
wrap.classList.toggle('is-open', alertsFoldOpen);
|
||||
body.hidden = !alertsFoldOpen;
|
||||
buttons.forEach((btn, i) => {
|
||||
const on = alertChannels.includes(i + 1);
|
||||
btn.classList.toggle('is-on', on);
|
||||
btn.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||||
});
|
||||
};
|
||||
head.addEventListener('click', () => {
|
||||
alertsFoldOpen = !alertsFoldOpen;
|
||||
paint();
|
||||
});
|
||||
paint();
|
||||
wrap.append(head, body);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/** Remember an alert the server announced, its end put on this browser's clock. */
|
||||
function noteAlert(a) {
|
||||
const channel = Number(a?.channel);
|
||||
if (!Number.isInteger(channel) || channel < 1 || channel > ALERT_CHANNELS) return;
|
||||
const remaining = a.remainingMs === null || a.remainingMs === undefined ? null : Number(a.remainingMs);
|
||||
activeAlerts.set(channel, {
|
||||
id: String(a.id || ''),
|
||||
channel,
|
||||
level: ALERT_LEVEL_RANK[a.level] ? String(a.level) : 'low',
|
||||
text: String(a.text || ''),
|
||||
source: String(a.source || ''),
|
||||
startedAt: Number(a.startedAt) || Date.now(),
|
||||
endsAt: Number.isFinite(remaining) ? Date.now() + Math.max(0, remaining) : null,
|
||||
});
|
||||
}
|
||||
|
||||
/** `alert` shell event: a new alert, or a replacement on its channel. */
|
||||
function handleAlertEvent(e) {
|
||||
try {
|
||||
noteAlert(JSON.parse(e.data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
paintAlerts();
|
||||
}
|
||||
|
||||
/** `alert-clear` shell event: ended early or timed out. */
|
||||
function handleAlertClearEvent(e) {
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(e.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const current = activeAlerts.get(Number(payload?.channel));
|
||||
if (!current) return;
|
||||
// A clear for an alert already replaced leaves the replacement alone.
|
||||
if (payload.id && current.id && payload.id !== current.id) return;
|
||||
activeAlerts.delete(current.channel);
|
||||
paintAlerts();
|
||||
}
|
||||
|
||||
/** `alerts-config` shell event: an admin changed the colours. */
|
||||
function handleAlertsConfigEvent(e) {
|
||||
try {
|
||||
setAlertColors(JSON.parse(e.data).colors);
|
||||
} catch { /* a malformed frame changes nothing */ }
|
||||
}
|
||||
|
||||
function setAlertColors(colors) {
|
||||
const next = {};
|
||||
for (const level of Object.keys(ALERT_COLORS_DEFAULT)) {
|
||||
const pair = Array.isArray(colors?.[level]) ? colors[level] : [];
|
||||
next[level] = ALERT_COLORS_DEFAULT[level].map((fallback, i) => {
|
||||
const v = String(pair[i] ?? '').trim();
|
||||
return /^#[0-9a-fA-F]{6}$/.test(v) ? v.toLowerCase() : fallback;
|
||||
});
|
||||
}
|
||||
alertColors = next;
|
||||
paintAlerts();
|
||||
}
|
||||
|
||||
/** The whole picture from the server: what is active, and the colours. */
|
||||
async function refreshAlerts() {
|
||||
try {
|
||||
const res = await fetchWithTimeout('/api/alerts', 8000);
|
||||
if (!res.ok) return;
|
||||
const body = await res.json();
|
||||
activeAlerts.clear();
|
||||
for (const a of body.active || []) noteAlert(a);
|
||||
setAlertColors(body.colors); // paints
|
||||
} catch { /* server away — what is known stands */ }
|
||||
}
|
||||
|
||||
/** Relative luminance of #rrggbb, 0 (black) to 1 (white). */
|
||||
function luminance(hex) {
|
||||
const n = parseInt(String(hex).slice(1), 16);
|
||||
const chan = (c) => {
|
||||
const s = c / 255;
|
||||
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return 0.2126 * chan((n >> 16) & 255) + 0.7152 * chan((n >> 8) & 255) + 0.0722 * chan(n & 255);
|
||||
}
|
||||
|
||||
/** Black or white for the banner — whichever reads against BOTH colours the bar flashes between. */
|
||||
function alertTextColor(a, b) {
|
||||
const contrast = (l1, l2) => (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
|
||||
const la = luminance(a);
|
||||
const lb = luminance(b);
|
||||
const white = Math.min(contrast(1, la), contrast(1, lb));
|
||||
const black = Math.min(contrast(0, la), contrast(0, lb));
|
||||
return white >= black ? '#ffffff' : '#000000';
|
||||
}
|
||||
|
||||
function paintAlerts() {
|
||||
clearTimeout(alertEndTimer);
|
||||
alertEndTimer = null;
|
||||
const now = Date.now();
|
||||
for (const [channel, a] of activeAlerts) {
|
||||
if (a.endsAt !== null && a.endsAt <= now) activeAlerts.delete(channel);
|
||||
}
|
||||
const showing = [...activeAlerts.values()]
|
||||
.filter((a) => alertChannels.includes(a.channel))
|
||||
.sort((a, b) => (ALERT_LEVEL_RANK[b.level] - ALERT_LEVEL_RANK[a.level]) || (b.startedAt - a.startedAt));
|
||||
const top = showing[0];
|
||||
const root = document.documentElement.style;
|
||||
if (!top) {
|
||||
delete document.body.dataset.alert;
|
||||
alertBanner.hidden = true;
|
||||
} else {
|
||||
const [a, b] = alertColors[top.level] || ALERT_COLORS_DEFAULT.low;
|
||||
root.setProperty('--alert-a', a);
|
||||
root.setProperty('--alert-b', b);
|
||||
root.setProperty('--alert-text', alertTextColor(a, b));
|
||||
document.body.dataset.alert = top.level;
|
||||
alertBanner.querySelector('.alert-channel').textContent = String(top.channel);
|
||||
alertBanner.querySelector('.alert-text').textContent = top.text;
|
||||
alertBanner.querySelector('.alert-more').textContent = showing.length > 1 ? `+${showing.length - 1}` : '';
|
||||
alertBanner.hidden = false;
|
||||
}
|
||||
alertShowing = Boolean(top);
|
||||
paintMenuHidden();
|
||||
// The next end among everything active — shown or not, since a channel
|
||||
// may be subscribed to meanwhile — repaints the picture when it comes.
|
||||
let next = Infinity;
|
||||
for (const a of activeAlerts.values()) if (a.endsAt !== null) next = Math.min(next, a.endsAt);
|
||||
if (next < Infinity) alertEndTimer = setTimeout(paintAlerts, Math.max(50, next - now + 20));
|
||||
}
|
||||
|
||||
/* ── boot ───────────────────────────────────────────────────────────── */
|
||||
|
||||
async function boot() {
|
||||
|
||||
Reference in New Issue
Block a user