Merge branch 'feature/radio-set-panel' into unify/skills-20261112-night
This commit is contained in:
commit
679ebe5dc4
37 files changed
+2480
-356
No files matched your search
@@ -463,6 +463,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
|
||||
<script nonce="{{ nonce }}">
|
||||
{% include "voice.js" %}
|
||||
|
||||
{% include "radioset.js" %}
|
||||
|
||||
{% include "bubbles.js" %}
|
||||
|
||||
{% include "diffs.js" %}
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
const beeps = new Set();
|
||||
|
||||
function silenceBeeps() {
|
||||
for (const oscillator of beeps) {
|
||||
oscillator.stop();
|
||||
}
|
||||
beeps.clear();
|
||||
}
|
||||
|
||||
function play(kind, volume) {
|
||||
const sound = context();
|
||||
if (!sound) {
|
||||
@@ -15,6 +24,8 @@
|
||||
gain.gain.exponentialRampToValueAtTime(level, start + 0.02);
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, start + length);
|
||||
oscillator.connect(gain).connect(sound.destination);
|
||||
oscillator.addEventListener("ended", () => beeps.delete(oscillator), {once: true});
|
||||
beeps.add(oscillator);
|
||||
oscillator.start(start);
|
||||
oscillator.stop(start + length + 0.05);
|
||||
}
|
||||
@@ -47,7 +58,7 @@
|
||||
const newRadio = state.radio.filter((row) => !known.radio.has(`${row.ts}|${row.from}|${row.text.slice(0, 40)}`));
|
||||
const direct = newRadio.filter((row) => row.to.includes(HUMAN));
|
||||
const present = {mayday: newAlarms.length > 0, review: fresh.some((item) => item.kind !== "operator"), direct: direct.length > 0, radio: newRadio.length > 0};
|
||||
const kind = Voice.beep(present, settings, SOUND_KINDS.map(([id]) => id));
|
||||
const kind = radioSet.mode === "silence" ? null : Voice.beep(present, tones(), SOUND_KINDS.map(([id]) => id));
|
||||
if (kind) {
|
||||
play(kind, loudness(kind));
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@
|
||||
|
||||
function toggleGear() {
|
||||
const open = spotDom.gearBox.hidden;
|
||||
spotDom.gearBox.replaceChildren(...(open ? [radioSettings(toggleGear)] : []));
|
||||
spotDom.gearBox.replaceChildren(...(open ? [radioFilters()] : []));
|
||||
spotDom.gearBox.hidden = !open;
|
||||
spotDom.gear.setAttribute("aria-expanded", String(open));
|
||||
window.requestAnimationFrame(refresh3d);
|
||||
@@ -94,13 +94,15 @@
|
||||
function radioSpot() {
|
||||
const {form, recipient, text} = composerForm();
|
||||
const gearBox = h("div", {class: "radio-gear", id: "radio-gear", hidden: true});
|
||||
const gear = iconBtn("bi-gear", "Radio settings", "btn small ghost spot-toggle", toggleGear, "Radio settings: tones, squelch and read aloud");
|
||||
const gear = iconBtn("bi-funnel", "Read aloud", "btn small ghost spot-toggle", toggleGear, "Read aloud: the classes and agents the radio sounds for");
|
||||
gear.setAttribute("aria-expanded", "false");
|
||||
gear.setAttribute("aria-controls", "radio-gear");
|
||||
const [, label, , hint] = actionOf("clear-mayday");
|
||||
const clear = iconBtn("bi-life-preserver", label, "btn small danger", () => confirmAct("clear-mayday", []), hint);
|
||||
const {face, log, station} = radioSide();
|
||||
const panel = h("section", {class: "card radio-spot", id: "radio-spot", "aria-label": "Radio", hidden: !ui.spot},
|
||||
h("div", {class: "spot-head"}, h("h3", {class: "group-title"}, "Radio"), h("span", {class: "spacer"}), gear, clear), h("div", {class: "spot-body"}, form, radioSide(), gearBox));
|
||||
h("div", {class: "spot-head"}, h("h3", {class: "group-title"}, "Radio"), h("span", {class: "spacer"}), gear, clear), face, gearBox,
|
||||
h("div", {class: "spot-body"}, h("div", {class: "radio-side"}, form, station), log));
|
||||
const toggle = document.getElementById("radio-open");
|
||||
toggle.setAttribute("aria-expanded", String(ui.spot));
|
||||
toggle.addEventListener("click", () => openSpot(!ui.spot));
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
drawTime();
|
||||
motion.asOf = ui.asOf;
|
||||
relayout(0);
|
||||
window.setInterval(refresh, 10000);
|
||||
window.setInterval(poll, 10000);
|
||||
window.setInterval(follow, 3000);
|
||||
window.setInterval(() => relayout(MOVE), RELAYOUT);
|
||||
window.setInterval(() => live() && drawSky(), 30000);
|
||||
|
||||
@@ -144,7 +144,7 @@
|
||||
const hint = h("p", {class: "muted"});
|
||||
const status = h("span", {class: "muted composer-status", "aria-live": "polite"});
|
||||
const record = h("button", {type: "button", class: "btn small", "aria-pressed": "false", title: "Record: one click starts, another stops; the hub transcribes, you check the text before sending"});
|
||||
const submit = h("button", {type: "submit", class: "btn primary"}, icon("bi-send"), "Send");
|
||||
const submit = h("button", {type: "submit", class: "btn primary ptt", title: "PTT: push to transmit the message; your passkey signs it"}, icon("bi-broadcast-pin"), "PTT");
|
||||
const attach = h("input", {type: "checkbox", title: "Attach recording: the agents get the path of the sound file; otherwise only the checked text goes out"});
|
||||
const parts = {record, status, text, replay, attach};
|
||||
recordLabel(parts, false);
|
||||
|
||||
@@ -51,6 +51,8 @@
|
||||
const SPEECH_QUEUE = 20;
|
||||
const SPEECH_QUIET = 60000;
|
||||
const SPEECH_FRESH = 300;
|
||||
const SOUND_SLACK = 2;
|
||||
const STATE_TIMEOUT = 15000;
|
||||
const THEME_CHOICES = [["sky", "Sky (follows the light outside)"], ["light", "Always light"], ["dark", "Always dark"], ["custom", "Custom colors"]];
|
||||
const COLOR_FIELDS = [["top", "Sky at the top"], ["bottom", "Sky at the horizon"], ["accent", "Accent"]];
|
||||
const STAGE_LABELS = {night: "Night", astronomical: "Astronomical twilight", nautical: "Nautical twilight", civil: "Civil twilight", golden: "Golden hour", day: "Day"};
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
let loadTicket = 0;
|
||||
let appliedTicket = 0;
|
||||
let loadsInFlight = 0;
|
||||
|
||||
async function load() {
|
||||
loadTicket += 1;
|
||||
const ticket = loadTicket;
|
||||
loadsInFlight += 1;
|
||||
const abort = new AbortController();
|
||||
const timer = window.setTimeout(() => abort.abort(), STATE_TIMEOUT);
|
||||
try {
|
||||
const response = await fetch(`/api/state?${windowQuery()}`, {cache: "no-store"});
|
||||
const response = await fetch(`/api/state?${windowQuery()}`, {cache: "no-store", signal: abort.signal});
|
||||
if (!response.ok) {
|
||||
throw new Error(String(response.status));
|
||||
}
|
||||
const next = await response.json();
|
||||
if (ticket < appliedTicket) {
|
||||
return;
|
||||
}
|
||||
appliedTicket = ticket;
|
||||
const previous = state.now;
|
||||
state = next;
|
||||
ui.offline = false;
|
||||
@@ -25,8 +38,19 @@
|
||||
}
|
||||
pulses(state.radio.filter((row) => row.ts > previous));
|
||||
} catch {
|
||||
ui.offline = true;
|
||||
tick();
|
||||
if (ticket > appliedTicket) {
|
||||
ui.offline = true;
|
||||
tick();
|
||||
}
|
||||
} finally {
|
||||
window.clearTimeout(timer);
|
||||
loadsInFlight -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
function poll() {
|
||||
if (!loadsInFlight) {
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
const STATION_TONES = {playing: "ok", loading: "info", reload: "info", blocked: "warn", error: "bad", due: "teal", stopped: "neutral", idle: "neutral", off: "neutral"};
|
||||
const NOTE_ID = /^[0-9a-f]{16}$/;
|
||||
const MODE_LABELS = {
|
||||
auto: ["bi-volume-up", "Auto", "Auto: speech while the host CPU lies below the threshold, otherwise the noise burst"],
|
||||
quiet: ["bi-soundwave", "Quiet", "Quiet: the noise burst only, never speech; MAYDAY, PAN-PAN and Sécurité still sound their procedure word"],
|
||||
silence: ["bi-volume-mute", "Silence", "Silence: no sound, bubbles and log only; MAYDAY, PAN-PAN and Sécurité still sound their procedure word"],
|
||||
};
|
||||
const TAB_LABELS = {sent: ["bi-arrow-up-right", "Sent", "Sent: what you transmitted"], received: ["bi-arrow-down-left", "Received", "Received: radio to you or to all"], all: ["bi-journal-text", "All", "All: every radio row the hub logs"]};
|
||||
const CHIP_LABELS = {class: "Class", from: "Sender", to: "Recipient", agent: "Agent"};
|
||||
let radioDom = null;
|
||||
|
||||
function voiceReplay(note) {
|
||||
@@ -19,7 +26,7 @@
|
||||
return [radio.state, radio.short, radio.note];
|
||||
}
|
||||
if (!stream.on) {
|
||||
return ["off", "off", "Switched off in the settings"];
|
||||
return ["off", "off", "Switched off in the stations"];
|
||||
}
|
||||
if (!Ambience.activeStream([stream], Ambience.slotOf(new Date()))) {
|
||||
return ["idle", "not due", `Plays ${scheduleOf(stream)}; ▶ plays it now`];
|
||||
@@ -52,7 +59,32 @@
|
||||
radioDom.stationsSig = sig;
|
||||
radioDom.stations.replaceChildren(...(settings.streams.length
|
||||
? settings.streams.map(stationRow)
|
||||
: [h("li", {class: "muted"}, "No station yet: add one under ⚙ Settings → Internet radio.")]));
|
||||
: [h("li", {class: "muted"}, "No station yet: add one with Edit stations.")]));
|
||||
}
|
||||
|
||||
function drawDisplay() {
|
||||
if (!radioDom) {
|
||||
return;
|
||||
}
|
||||
const {lamp, cls, mode, cpu} = radioDom.face;
|
||||
const now = speech.current;
|
||||
const newest = state.radio[state.radio.length - 1];
|
||||
const shown = now ? now.cls : newest ? newest.class : "";
|
||||
const gate = state.speech.gate;
|
||||
const playing = Boolean(now && speech.source);
|
||||
const sent = Boolean(playing && now.sent);
|
||||
lamp.dataset.lit = String(playing);
|
||||
lamp.dataset.tx = String(sent);
|
||||
lamp.textContent = sent ? "TX" : "RX";
|
||||
lamp.setAttribute("aria-label", playing ? `${sent ? "TX" : "RX"}: sound plays` : "RX: no sound");
|
||||
lamp.title = lamp.getAttribute("aria-label");
|
||||
cls.textContent = shown ? CLASSES[shown] || shown : "–";
|
||||
mode.textContent = MODE_LABELS[radioSet.mode][1];
|
||||
cpu.textContent = gate.cpu === null ? "CPU ?" : `CPU ${Math.round(gate.cpu)} %`;
|
||||
cpu.dataset.open = String(gate.open);
|
||||
cpu.title = gate.cpu === null
|
||||
? `No host CPU sample of the last two minutes: the hub renders no new speech line, threshold ${gate.threshold} %`
|
||||
: `Host CPU ${fixed(gate.cpu)} %: new speech renders below ${gate.threshold} %${gate.open ? "" : ", so the radio plays the burst"}`;
|
||||
}
|
||||
|
||||
function drawSpeaker() {
|
||||
@@ -61,13 +93,15 @@
|
||||
art.classList.toggle("speaking", Boolean(now && art.dataset.face === now.who));
|
||||
}
|
||||
if (radioDom) {
|
||||
radioDom.caption.hidden = !now;
|
||||
radioDom.caption.replaceChildren(...(now ? [
|
||||
const {caption} = radioDom.face;
|
||||
caption.hidden = !now;
|
||||
caption.replaceChildren(...(now ? [
|
||||
h("span", {class: "speaker-face"}, face(now.who, false)),
|
||||
h("strong", {}, `${nameOf(now.who)} speaking`),
|
||||
h("span", {class: "caption-line", title: now.line}, now.line),
|
||||
iconBtn("bi-stop-fill", "Stop speaking", "btn small ghost", cancelSpeech),
|
||||
] : []));
|
||||
drawDisplay();
|
||||
}
|
||||
if (ui.screen === "agents" && (ui.views.agents === "orbit" || ui.views.agents === "chord")) {
|
||||
stage();
|
||||
@@ -75,33 +109,187 @@
|
||||
drawBubbles();
|
||||
}
|
||||
|
||||
function sentRows() {
|
||||
const rows = state.messages.slice(-5).reverse();
|
||||
return rows.length ? h("ul", {class: "mini"}, rows.map((message) => h("li", {},
|
||||
h("div", {class: "row"}, klass(message.class || "post"), when(message.created_ts)),
|
||||
h("span", {class: "muted"}, `to ${message.to === "*" ? "all" : message.to}`),
|
||||
h("span", {}, short(message.text)),
|
||||
voiceReplay(message.voice)))) : h("p", {class: "muted"}, "Nothing sent in the chosen time range yet.");
|
||||
function knob(label, hint, attrs, change) {
|
||||
const value = h("output", {class: "knob-value"});
|
||||
const input = h("input", {type: "range", class: "knob", ...attrs, ...named(label, hint), on: {input: (event) => {
|
||||
value.textContent = event.target.value;
|
||||
change(Number(event.target.value));
|
||||
}}});
|
||||
return {input, value, row: h("label", {class: "knob-row", title: hint}, h("span", {class: "knob-label", title: label}, label), input, value)};
|
||||
}
|
||||
|
||||
function toneKnob(id, label) {
|
||||
const toggle = h("button", {type: "button", class: "btn small ghost icon-only", "aria-pressed": "false", ...named(`${label} tone`), on: {click: () => {
|
||||
keepRadio({sounds: {...radioSet.sounds, [id]: {...radioSet.sounds[id], on: !radioSet.sounds[id].on}}});
|
||||
}}});
|
||||
const level = knob(label, `${label}: tone volume; speech and the burst of these rows play at it`, {min: 0, max: 1, step: 0.05}, (volume) => {
|
||||
keepRadio({sounds: {...radioSet.sounds, [id]: {...radioSet.sounds[id], volume}}});
|
||||
});
|
||||
const test = iconBtn("bi-play-fill", `Test ${label}`, "btn small ghost", () => play(id, loudness(id)), `Test: play the ${label} tone`);
|
||||
level.row.prepend(toggle);
|
||||
level.row.append(test);
|
||||
return {id, toggle, level};
|
||||
}
|
||||
|
||||
async function setThreshold(value) {
|
||||
if (value !== settings.speech.threshold && await saveSettings({...settings, space: savedSpace(), speech: {threshold: value}})) {
|
||||
toast("Speech threshold saved", [`The hub renders new speech only while the host CPU lies below ${value} %.`], true);
|
||||
}
|
||||
drawRadioSet();
|
||||
}
|
||||
|
||||
function knobs() {
|
||||
const tones = SOUND_KINDS.map(([id, label]) => toneKnob(id, label));
|
||||
const squelch = knob("Squelch", "Squelch: scales every tone, the speech and the burst; 0 plays none", {min: 0, max: 1, step: 0.05}, (value) => keepRadio({squelch: value}));
|
||||
const threshold = knob("Threshold", "Speech threshold: the hub renders new speech only while the host CPU lies below it; your passkey signs each change", {min: 30, max: 90, step: 10}, (value) => {
|
||||
threshold.value.textContent = `${value} %`;
|
||||
});
|
||||
threshold.input.addEventListener("change", (event) => setThreshold(Number(event.target.value)));
|
||||
const check = iconBtn("bi-broadcast", "Radio check", "btn small ghost", () => say({steps: [{kind: "speech", text: state.speech.sample}], voice: state.speech.operator, tone: "direct", cls: "newsletter", who: HUMAN, sent: true, line: "radio check"}), "Radio check: hear the operator's voice once");
|
||||
check.disabled = !state.speech.tts;
|
||||
radioDom.knobs = {tones, squelch, threshold, check};
|
||||
return [...tones.map((tone) => tone.level.row), squelch.row, threshold.row, h("div", {class: "knob-row"}, check)];
|
||||
}
|
||||
|
||||
function faceplate() {
|
||||
const lamp = h("span", {class: "radio-lamp", role: "img", "data-lit": "false", "data-tx": "false"}, "RX");
|
||||
const field = (name) => h("span", {class: "radio-field", "data-field": name});
|
||||
const [cls, mode, cpu] = [field("class"), field("mode"), field("cpu")];
|
||||
const caption = h("div", {class: "radio-caption", role: "status", "aria-live": "polite", hidden: true});
|
||||
const modes = h("div", {class: "segmented radio-modes", role: "group", "aria-label": "Mode"}, RadioSet.MODES.map((id) => {
|
||||
const [name, label, hint] = MODE_LABELS[id];
|
||||
return h("button", {type: "button", "data-mode": id, "aria-pressed": "false", ...named(label, hint), on: {click: () => {
|
||||
keepRadio({mode: id});
|
||||
context();
|
||||
}}}, icon(name), label);
|
||||
}));
|
||||
radioDom.face = {lamp, cls, mode, cpu, caption, modes};
|
||||
const display = h("div", {class: "radio-display", role: "group", "aria-label": "Display"}, lamp, cls, mode, cpu);
|
||||
return h("div", {class: "radio-face", role: "group", "aria-label": "Radio set"}, display, caption, modes, h("div", {class: "radio-knobs", role: "group", "aria-label": "Knobs"}, knobs()));
|
||||
}
|
||||
|
||||
function radioFilters() {
|
||||
const chip = (label, pressed, hint, run, locked) => h("button", {type: "button", class: "chip", "aria-pressed": String(pressed), disabled: locked, ...named(label, hint), on: {click: run}}, label);
|
||||
const classes = SPEECH_CLASSES.map(([id, label]) => chip(label, radioSet.classes.includes(id), id === "mayday" ? "MAYDAY always sounds" : `Read ${label} aloud`, () => {
|
||||
keepRadio({classes: radioSet.classes.includes(id) ? radioSet.classes.filter((name) => name !== id) : [...radioSet.classes, id]});
|
||||
redrawFilters();
|
||||
}, id === "mayday"));
|
||||
const agents = Object.entries(people()).sort(([, a], [, b]) => a.now.localeCompare(b.now)).map(([key, entry]) => chip(entry.now, !radioSet.muted.includes(key), `Read ${entry.now} aloud`, () => {
|
||||
keepRadio({muted: radioSet.muted.includes(key) ? radioSet.muted.filter((name) => name !== key) : [...radioSet.muted, key]});
|
||||
redrawFilters();
|
||||
}, false));
|
||||
return h("div", {class: "radio-read", "aria-label": "Read aloud"},
|
||||
h("p", {class: "muted"}, state.speech.tts ? "The radio sounds for these classes and agents, each speaker with its own voice; MAYDAY always sounds." : `The hub speaks no line: ${state.speech.tts_off}. The burst and the procedure words stand in.`),
|
||||
h("div", {class: "chips", role: "group", "aria-label": "Classes"}, classes),
|
||||
agents.length ? h("div", {class: "chips", role: "group", "aria-label": "Agents"}, agents) : null);
|
||||
}
|
||||
|
||||
function redrawFilters() {
|
||||
if (spotDom && !spotDom.gearBox.hidden) {
|
||||
spotDom.gearBox.replaceChildren(radioFilters());
|
||||
}
|
||||
}
|
||||
|
||||
function keepLog(change) {
|
||||
keepRadio({log: {...radioSet.log, ...change}});
|
||||
}
|
||||
|
||||
function chipSelect(name, values) {
|
||||
const chosen = radioSet.log.chips[name];
|
||||
const label = CHIP_LABELS[name];
|
||||
const options = [...new Set([...values, ...(chosen ? [chosen] : [])])];
|
||||
const select = h("select", {class: "field", "aria-label": label, title: `${label}: filter the log`, on: {change: (event) => keepLog({chips: {...radioSet.log.chips, [name]: event.target.value}})}},
|
||||
h("option", {value: ""}, `${label}: any`), options.map((value) => h("option", {value, selected: value === chosen}, name === "class" ? CLASSES[value] || value : value)));
|
||||
return h("label", {class: "chip-select", "data-chip": name, "data-active": String(Boolean(chosen))}, select);
|
||||
}
|
||||
|
||||
function logLine(row) {
|
||||
const message = row.sent ? row : RadioSet.ledgerOf(row, state.messages);
|
||||
const sent = Boolean(message);
|
||||
const [name, label] = sent ? ["bi-arrow-up-right", "Sent"] : ["bi-arrow-down-left", "Received"];
|
||||
const first = row.text.split("\n").map((part) => part.trim()).find(Boolean) || "";
|
||||
return h("li", {class: "radio-row", "data-dir": sent ? "sent" : "received", "data-class": row.class},
|
||||
h("details", {}, h("summary", {},
|
||||
when(row.ts),
|
||||
h("span", {class: "radio-dir", role: "img", ...named(label)}, icon(name)),
|
||||
klass(row.class),
|
||||
h("span", {class: "radio-route"}, `${row.from} → ${targetsOf(row)}`),
|
||||
h("span", {class: "radio-line", title: first}, first)),
|
||||
h("pre", {class: "radio-full"}, row.text),
|
||||
voiceReplay(message ? message.voice : null)));
|
||||
}
|
||||
|
||||
function drawLog() {
|
||||
const dom = radioDom.log;
|
||||
const entry = radioSet.log;
|
||||
const sig = JSON.stringify([state.radio.length, state.radio.length ? state.radio[state.radio.length - 1].ts : 0, state.messages.length, entry, Math.floor(Date.now() / 60000)]);
|
||||
if (sig === dom.sig) {
|
||||
return;
|
||||
}
|
||||
dom.sig = sig;
|
||||
const counts = RadioSet.counts(state.radio, HUMAN, state.messages);
|
||||
dom.tabs.replaceChildren(...RadioSet.TABS.map((tab) => {
|
||||
const [name, label, hint] = TAB_LABELS[tab];
|
||||
return h("button", {type: "button", role: "tab", "data-tab": tab, "aria-selected": String(tab === entry.tab), title: hint, on: {click: () => keepLog({tab})}},
|
||||
icon(name), label, h("span", {class: "count", "aria-label": `${counts[tab]} rows`}, String(counts[tab])));
|
||||
}));
|
||||
const choices = RadioSet.choices(state.radio);
|
||||
dom.chips.replaceChildren(...RadioSet.CHIPS.map((name) => chipSelect(name, choices[name])));
|
||||
if (document.activeElement !== dom.search && dom.search.value !== entry.q) {
|
||||
dom.search.value = entry.q;
|
||||
}
|
||||
const rows = RadioSet.logRows(state.radio, entry, HUMAN, state.messages);
|
||||
dom.list.replaceChildren(...(rows.length ? rows.map(logLine) : [h("li", {class: "muted"}, state.radio.length ? "No radio row matches the tab, the chips and the search." : "No radio in the chosen time range yet.")]));
|
||||
}
|
||||
|
||||
function radioLog() {
|
||||
const tabs = h("div", {class: "radio-tabs", role: "tablist", "aria-label": "Log"});
|
||||
const chips = h("div", {class: "radio-chips", role: "group", "aria-label": "Log filters"});
|
||||
const search = h("input", {type: "search", class: "field", placeholder: "Search the log …", maxlength: 200, ...named("Search the log"), on: {input: (event) => keepLog({q: event.target.value})}});
|
||||
const clear = iconBtn("bi-x-circle", "Clear filters", "btn small ghost", () => keepRadio({log: RadioSet.cleared(radioSet.log)}), "Clear filters: every chip and the search");
|
||||
const list = h("ul", {class: "radio-log", "aria-label": "Radio log"});
|
||||
radioDom.log = {tabs, chips, search, list, sig: ""};
|
||||
return h("section", {class: "radio-logbox", "aria-label": "Radio log"}, tabs, h("div", {class: "radio-filters"}, chips, search, clear), list);
|
||||
}
|
||||
|
||||
function drawRadioSet() {
|
||||
if (!radioDom) {
|
||||
return;
|
||||
}
|
||||
for (const button of radioDom.face.modes.querySelectorAll("button[data-mode]")) {
|
||||
button.setAttribute("aria-pressed", String(button.dataset.mode === radioSet.mode));
|
||||
}
|
||||
const {tones, squelch, threshold} = radioDom.knobs;
|
||||
for (const {id, toggle, level} of tones) {
|
||||
const sound = radioSet.sounds[id];
|
||||
toggle.setAttribute("aria-pressed", String(sound.on));
|
||||
toggle.replaceChildren(icon(sound.on ? "bi-bell" : "bi-bell-slash"));
|
||||
toggle.title = `${toggle.getAttribute("aria-label")}: ${sound.on ? "on, a press mutes it" : "off, a press turns it on"}`;
|
||||
level.input.value = String(sound.volume);
|
||||
level.value.textContent = sound.volume.toFixed(2);
|
||||
}
|
||||
squelch.input.value = String(radioSet.squelch);
|
||||
squelch.value.textContent = radioSet.squelch.toFixed(2);
|
||||
threshold.input.value = String(settings.speech.threshold);
|
||||
threshold.value.textContent = `${settings.speech.threshold} %`;
|
||||
drawDisplay();
|
||||
drawLog();
|
||||
}
|
||||
|
||||
function drawRadio() {
|
||||
if (!radioDom) {
|
||||
return;
|
||||
}
|
||||
const sent = JSON.stringify(state.messages.slice(-5));
|
||||
if (sent !== radioDom.sent) {
|
||||
radioDom.sent = sent;
|
||||
radioDom.outbox.replaceChildren(sentRows());
|
||||
}
|
||||
drawRadioSet();
|
||||
drawStations();
|
||||
}
|
||||
|
||||
function radioSide() {
|
||||
const caption = h("div", {class: "radio-caption", role: "status", "aria-live": "polite", hidden: true});
|
||||
const stations = h("ul", {class: "stations", "aria-label": "Stations"});
|
||||
const outbox = h("div", {});
|
||||
radioDom = {caption, stations, outbox, sent: "", stationsSig: ""};
|
||||
return h("div", {class: "radio-side"}, caption,
|
||||
h("section", {"aria-label": "Recently sent"}, h("h3", {class: "group-title"}, "Recently sent"), outbox),
|
||||
h("section", {"aria-label": "Internet radio"}, h("div", {class: "card-head"}, h("h3", {class: "group-title"}, "Internet radio"), btn("Edit stations", "btn small ghost", settingsSheet)), stations));
|
||||
radioDom = {stations, stationsSig: ""};
|
||||
const face = faceplate();
|
||||
const log = radioLog();
|
||||
const station = h("section", {class: "radio-station", "aria-label": "Internet radio"}, h("div", {class: "card-head"}, h("h3", {class: "group-title"}, "Internet radio"), btn("Edit stations", "btn small ghost", stationsSheet)), stations);
|
||||
window.setTimeout(drawRadio, 0);
|
||||
return {face, log, station};
|
||||
}
|
||||
@@ -86,52 +86,23 @@
|
||||
return section;
|
||||
}
|
||||
|
||||
function radioSettings(close) {
|
||||
const tones = SOUND_KINDS.map(([id, label]) => {
|
||||
const on = h("input", {type: "checkbox", checked: settings.sounds[id].on, "aria-label": `${label} on`});
|
||||
const level = h("input", {type: "range", min: 0, max: 1, step: 0.05, value: settings.sounds[id].volume, "aria-label": `${label} volume`});
|
||||
const loudest = () => Math.max(...tones.map((tone) => Number(tone.level.value)), settings.music.volume);
|
||||
return {id, on, level, row: h("div", {class: "sound-row"}, h("strong", {}, label), h("label", {class: "check"}, on, "on"), level, btn("Test", "btn small ghost", () => play(id, id === "mayday" ? loudest() : Number(level.value))))};
|
||||
});
|
||||
const squelch = h("input", {type: "range", min: 0, max: 1, step: 0.05, value: settings.squelch, "aria-label": "Squelch"});
|
||||
const speechOn = h("input", {type: "checkbox", checked: settings.speech.on, disabled: !state.speech.tts});
|
||||
const spoken = SPEECH_CLASSES.map(([id, label]) => ({id, label, box: h("input", {type: "checkbox", checked: id === "mayday" || settings.speech.classes.includes(id), disabled: id === "mayday", title: id === "mayday" ? "MAYDAY is always read aloud" : null})}));
|
||||
const stations = Object.entries(people()).sort(([, a], [, b]) => a.now.localeCompare(b.now))
|
||||
.map(([key, entry]) => ({key, label: entry.now, box: h("input", {type: "checkbox", checked: !settings.speech.muted.includes(key), "aria-label": `Read ${entry.now} aloud`})}));
|
||||
const absent = settings.speech.muted.filter((key) => !people()[key]);
|
||||
const sample = btn("Test", "btn small ghost", () => say({text: state.speech.sample, voice: state.speech.operator, tone: "direct", cls: "newsletter", who: HUMAN, line: "radio check"}));
|
||||
sample.disabled = !state.speech.tts;
|
||||
const form = h("form", {class: "settings radio-settings", "aria-label": "Radio settings"},
|
||||
h("section", {}, h("h3", {}, "Tones"), h("p", {class: "muted"}, "MAYDAY and PAN-PAN are always loudest. With several new events only the most urgent one plays."),
|
||||
tones.map((tone) => tone.row), h("label", {}, "Squelch: scales every tone, 0 plays none", squelch)),
|
||||
h("section", {}, h("h3", {}, "Read radio aloud"),
|
||||
h("p", {class: "muted"}, state.speech.tts
|
||||
? "New radio is read aloud in maritime radio style (SMCP), one message after another, each speaker with its own voice; music and internet radio go quieter meanwhile. The volume follows the tones above; MAYDAY is always spoken, and loudest."
|
||||
: `The radio stays silent: ${state.speech.tts_off}.`),
|
||||
h("div", {class: "days"}, h("label", {class: "check"}, speechOn, "Read radio aloud"), sample),
|
||||
h("div", {class: "days", role: "group", "aria-label": "Classes"}, spoken.map((entry) => h("label", {class: "check"}, entry.box, entry.label))),
|
||||
stations.length ? h("div", {class: "days", role: "group", "aria-label": "Speakers"}, stations.map((entry) => h("label", {class: "check"}, entry.box, entry.label))) : null),
|
||||
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", close), h("button", {type: "submit", class: "btn primary"}, "Save")));
|
||||
function stationsSheet() {
|
||||
const list = h("div", {class: "mini"});
|
||||
const rows = [];
|
||||
settings.streams.forEach((stream) => streamRow(stream, rows, list));
|
||||
const form = h("form", {class: "settings", "aria-label": "Stations"},
|
||||
h("section", {}, h("h3", {}, "Internet radio"), h("p", {class: "muted"}, "Internet radio at fixed times with a 3 s fade in and out; the music pauses meanwhile. A new station plays around the clock until you change its times; in the radio panel you start and stop it by hand. The page may load sound only from these addresses; your passkey signs a new address. If a signed station redirects, the server resolves the redirect when you save a new station or a changed address and releases its target; the note after saving names it."),
|
||||
list, h("div", {}, btn("+ Station", "btn small soft", () => streamRow({name: "", url: "", from: "00:00", to: "24:00", days: [0, 1, 2, 3, 4, 5, 6], on: true, via: []}, rows, list)))),
|
||||
h("div", {class: "sheet-foot"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), h("button", {type: "submit", class: "btn primary"}, "Save")));
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
context();
|
||||
const next = {
|
||||
...settings,
|
||||
space: savedSpace(),
|
||||
sounds: Object.fromEntries(tones.map((tone) => [tone.id, {on: tone.on.checked, volume: Number(tone.level.value)}])),
|
||||
squelch: Number(squelch.value),
|
||||
speech: {
|
||||
on: speechOn.checked,
|
||||
classes: spoken.filter((entry) => entry.box.checked).map((entry) => entry.id),
|
||||
muted: [...absent, ...stations.filter((entry) => !entry.box.checked).map((entry) => entry.key)],
|
||||
},
|
||||
};
|
||||
if (await saveSettings(next)) {
|
||||
close();
|
||||
toast("Radio settings saved", [], true);
|
||||
if (await saveSettings({...settings, space: savedSpace(), streams: rows.map((entry) => entry.read())})) {
|
||||
closeSheet();
|
||||
toast("Stations saved", [], true);
|
||||
}
|
||||
});
|
||||
return form;
|
||||
openSheet("Stations", [form], false);
|
||||
}
|
||||
|
||||
function settingsSheet() {
|
||||
@@ -155,9 +126,6 @@
|
||||
const musicOn = h("input", {type: "checkbox", checked: settings.music.on});
|
||||
const volume = h("input", {type: "range", min: 0, max: 1, step: 0.05, value: settings.music.volume, "aria-label": "Overall volume"});
|
||||
const notify = h("input", {type: "checkbox", checked: settings.notify});
|
||||
const list = h("div", {class: "mini"});
|
||||
const rows = [];
|
||||
settings.streams.forEach((stream) => streamRow(stream, rows, list));
|
||||
const form = h("form", {class: "settings"},
|
||||
ambience(),
|
||||
h("section", {}, h("h3", {}, "Location"), h("p", {class: "muted"}, "Sun, moon and stars stand where you see them from here, looking south; under 🔭 Sky (key h) you turn the view. Decimal degrees, north and east positive."),
|
||||
@@ -165,10 +133,8 @@
|
||||
h("section", {}, h("h3", {}, "Appearance"), h("label", {}, "Colors", theme), custom, verdict),
|
||||
h("section", {}, h("h3", {}, "Music"), h("p", {class: "muted"}, "Generative ambient music, made offline: calm with an empty inbox, a little tenser when something waits, quieter under messages."),
|
||||
h("div", {class: "grid"}, h("label", {class: "check"}, musicOn, "Music on"), h("label", {}, "Overall volume (music and radio)", volume))),
|
||||
h("section", {}, h("h3", {}, "Notifications"), h("p", {class: "muted"}, "Tones, squelch and reading radio aloud sit behind the gear of the radio spot in the Agents toolbar."),
|
||||
h("section", {}, h("h3", {}, "Notifications"), h("p", {class: "muted"}, "Mode, tones, squelch, the speech threshold, reading aloud and the stations sit in the radio panel behind the radio button in the header."),
|
||||
h("label", {class: "check"}, notify, "Show desktop notifications when the browser allows them")),
|
||||
h("section", {}, h("h3", {}, "Internet radio"), h("p", {class: "muted"}, "Internet radio at fixed times with a 3 s fade in and out; the music pauses meanwhile. A new station plays around the clock until you change its times; under Stream → Radio you start and stop it by hand. The page may load sound only from these addresses; your passkey signs a new address. If a signed station redirects, the server resolves the redirect when you save a new station or a changed address and releases its target; the note after saving names it."),
|
||||
list, h("div", {}, btn("+ Station", "btn small soft", () => streamRow({name: "", url: "", from: "00:00", to: "24:00", days: [0, 1, 2, 3, 4, 5, 6], on: true, via: []}, rows, list)))),
|
||||
passkeySection(),
|
||||
h("div", {class: "sheet-foot"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), h("button", {type: "submit", class: "btn primary"}, "Save")));
|
||||
form.addEventListener("submit", async (event) => {
|
||||
@@ -180,10 +146,8 @@
|
||||
theme: theme.value,
|
||||
colors: Object.fromEntries(COLOR_FIELDS.map(([id]) => [id, colors[id].value])),
|
||||
music: {on: musicOn.checked, volume: Number(volume.value)},
|
||||
sounds: settings.sounds,
|
||||
squelch: settings.squelch,
|
||||
notify: notify.checked,
|
||||
streams: rows.map((entry) => entry.read()),
|
||||
streams: settings.streams,
|
||||
speech: settings.speech,
|
||||
space: savedSpace(),
|
||||
estimation: settings.estimation,
|
||||
|
||||
@@ -1,5 +1,37 @@
|
||||
function tones() {
|
||||
return {sounds: radioSet.sounds, squelch: radioSet.squelch, music: settings.music};
|
||||
}
|
||||
|
||||
function loudness(kind) {
|
||||
return Voice.loudness(kind, settings);
|
||||
return Voice.loudness(kind, tones());
|
||||
}
|
||||
|
||||
function keepRadio(change) {
|
||||
const before = radioSet.mode;
|
||||
radioSet = RadioSet.valid({...radioSet, ...change});
|
||||
keep(RadioSet.KEY, radioSet);
|
||||
hush(before !== radioSet.mode);
|
||||
drawRadioSet();
|
||||
}
|
||||
|
||||
function hush(switched) {
|
||||
const {item, source} = speech;
|
||||
if (source && item && item.row && !allows(rendered(item, item.at), item.playing)) {
|
||||
item.cut = true;
|
||||
source.stop();
|
||||
}
|
||||
if (switched && radioSet.mode === "silence") {
|
||||
silenceBeeps();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object|undefined} step the step the radio set plans now at the index that plays.
|
||||
* @param {string} kind word, speech or burst: what plays or is about to play there.
|
||||
* @returns {boolean} whether that sound may play: the planned kind, or the burst standing in for a planned speech line.
|
||||
*/
|
||||
function allows(step, kind) {
|
||||
return Boolean(step) && (step.kind === kind || (kind === "burst" && step.kind === "speech"));
|
||||
}
|
||||
|
||||
function speechFailed(lines) {
|
||||
@@ -40,18 +72,142 @@
|
||||
}
|
||||
}
|
||||
|
||||
function sounded(item, source, seconds) {
|
||||
return new Promise((resolve) => {
|
||||
let timer = 0;
|
||||
const ended = () => {
|
||||
window.clearTimeout(timer);
|
||||
if (speech.source === source) {
|
||||
Object.assign(speech, {current: null, source: null});
|
||||
drawSpeaker();
|
||||
}
|
||||
resolve();
|
||||
};
|
||||
source.addEventListener("ended", ended, {once: true});
|
||||
timer = window.setTimeout(() => {
|
||||
source.stop();
|
||||
ended();
|
||||
}, (seconds + SOUND_SLACK) * 1000);
|
||||
duck(seconds);
|
||||
Object.assign(item, {started: performance.now(), duration: seconds});
|
||||
Object.assign(speech, {current: item, source});
|
||||
drawSpeaker();
|
||||
});
|
||||
}
|
||||
|
||||
function burst(sound, item) {
|
||||
const shape = RadioSet.burst(loudness(item.tone));
|
||||
if (shape.gain <= 0) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
const frames = Math.ceil(sound.sampleRate * shape.seconds);
|
||||
const buffer = sound.createBuffer(1, frames, sound.sampleRate);
|
||||
const data = buffer.getChannelData(0);
|
||||
for (let index = 0; index < frames; index += 1) {
|
||||
data[index] = Math.random() * 2 - 1;
|
||||
}
|
||||
const source = sound.createBufferSource();
|
||||
const filter = sound.createBiquadFilter();
|
||||
const gain = sound.createGain();
|
||||
const start = sound.currentTime;
|
||||
filter.type = "bandpass";
|
||||
filter.frequency.value = shape.frequency;
|
||||
filter.Q.value = shape.q;
|
||||
gain.gain.setValueAtTime(shape.gain, start);
|
||||
gain.gain.exponentialRampToValueAtTime(0.0001, start + shape.seconds);
|
||||
source.buffer = buffer;
|
||||
source.connect(filter).connect(gain).connect(sound.destination);
|
||||
const ended = sounded(item, source, shape.seconds);
|
||||
source.start(start);
|
||||
source.stop(start + shape.seconds);
|
||||
return ended;
|
||||
}
|
||||
|
||||
async function spoken(sound, item, step, done) {
|
||||
speech.loading = item;
|
||||
drawBubbles();
|
||||
try {
|
||||
const response = await fetch("/api/tts", {method: "POST", headers: {"X-Kvb-Orchestrator": "1", "Content-Type": "application/json"}, body: JSON.stringify({text: step.text, voice: item.voice}), cache: "no-store"});
|
||||
const held = response.status === 503 && (response.headers.get("Content-Type") || "").startsWith("application/json");
|
||||
if (!response.ok) {
|
||||
return held ? "held" : `${response.status} ${(await response.text()).trim()}`;
|
||||
}
|
||||
const buffer = await sound.decodeAudioData(await response.arrayBuffer());
|
||||
if (speech.item !== item) {
|
||||
return "";
|
||||
}
|
||||
if (!allows(rendered(item, done), step.kind)) {
|
||||
return "dropped";
|
||||
}
|
||||
const source = sound.createBufferSource();
|
||||
const gain = sound.createGain();
|
||||
gain.gain.value = loudness(item.tone);
|
||||
source.buffer = buffer;
|
||||
source.connect(gain).connect(sound.destination);
|
||||
const ended = sounded(item, source, buffer.duration);
|
||||
source.start();
|
||||
await ended;
|
||||
return speech.item === item && item.cut ? "dropped" : "";
|
||||
} catch (error) {
|
||||
return String(error.message || error);
|
||||
} finally {
|
||||
if (speech.loading === item) {
|
||||
speech.loading = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function liveSpeech() {
|
||||
return {tts: state.speech.tts, open: state.speech.gate.open};
|
||||
}
|
||||
|
||||
function stepOf(item, done, live) {
|
||||
return (item.row ? RadioSet.plan(item.row, radioSet, live || liveSpeech()) : item.steps)[done];
|
||||
}
|
||||
|
||||
function rendered(item, done) {
|
||||
return item.row ? stepOf(item, done, {...liveSpeech(), open: true}) : item.steps[done];
|
||||
}
|
||||
|
||||
async function transmit(item, audio) {
|
||||
let voiced = false;
|
||||
for (let done = 0; ; done += 1) {
|
||||
const step = stepOf(item, done);
|
||||
if (!step || speech.item !== item) {
|
||||
return voiced;
|
||||
}
|
||||
Object.assign(item, {at: done, playing: step.kind, cut: false});
|
||||
if (step.kind === "burst") {
|
||||
await burst(audio, item);
|
||||
continue;
|
||||
}
|
||||
const failed = await spoken(audio, item, step, done);
|
||||
if (failed === "dropped") {
|
||||
done -= 1;
|
||||
continue;
|
||||
}
|
||||
voiced = voiced || (!failed && step.kind === "speech");
|
||||
if (failed && failed !== "held") {
|
||||
speechFailed([failed]);
|
||||
}
|
||||
if (failed && step.kind === "speech" && speech.item === item && allows(stepOf(item, done), "burst")) {
|
||||
item.playing = "burst";
|
||||
await burst(audio, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function pump() {
|
||||
if (speech.busy || !speech.pending.length) {
|
||||
return;
|
||||
}
|
||||
const [item, ...rest] = speech.pending;
|
||||
const sound = item.silent ? null : context();
|
||||
if (!item.silent && !sound) {
|
||||
const audio = item.silent ? null : context();
|
||||
if (!item.silent && !audio) {
|
||||
speech.pending = [];
|
||||
return;
|
||||
}
|
||||
speech.pending = rest;
|
||||
speech.busy = true;
|
||||
Object.assign(speech, {pending: rest, busy: true, item});
|
||||
const next = () => {
|
||||
speech.busy = false;
|
||||
pump();
|
||||
@@ -60,67 +216,39 @@
|
||||
readSilently(item, next);
|
||||
return;
|
||||
}
|
||||
speech.loading = item;
|
||||
drawBubbles();
|
||||
try {
|
||||
const response = await fetch("/api/tts", {method: "POST", headers: {"X-Kvb-Orchestrator": "1", "Content-Type": "application/json"}, body: JSON.stringify({text: item.text, voice: item.voice}), cache: "no-store"});
|
||||
if (!response.ok) {
|
||||
throw new Error(`${response.status} ${(await response.text()).trim()}`);
|
||||
}
|
||||
const buffer = await sound.decodeAudioData(await response.arrayBuffer());
|
||||
if (speech.loading !== item) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const source = sound.createBufferSource();
|
||||
const gain = sound.createGain();
|
||||
gain.gain.value = loudness(item.tone);
|
||||
source.buffer = buffer;
|
||||
source.connect(gain).connect(sound.destination);
|
||||
source.addEventListener("ended", () => {
|
||||
Object.assign(speech, {current: null, source: null});
|
||||
drawSpeaker();
|
||||
next();
|
||||
}, {once: true});
|
||||
duck(buffer.duration);
|
||||
Object.assign(item, {started: performance.now(), duration: buffer.duration});
|
||||
Object.assign(speech, {current: item, source, loading: null});
|
||||
drawSpeaker();
|
||||
source.start();
|
||||
} catch (error) {
|
||||
const kept = speech.loading === item;
|
||||
speech.loading = null;
|
||||
speechFailed([String(error.message || error)]);
|
||||
if (kept && settings.bubbles && item.words) {
|
||||
readSilently(item, next);
|
||||
return;
|
||||
}
|
||||
const voiced = await transmit(item, audio);
|
||||
if (speech.item !== item) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
Object.assign(speech, {current: null, source: null, item: null});
|
||||
drawSpeaker();
|
||||
if (!voiced && settings.bubbles && item.words) {
|
||||
readSilently(item, next);
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
function cancelSpeech() {
|
||||
if (speech.timer) {
|
||||
endSilent();
|
||||
}
|
||||
Object.assign(speech, {pending: [], current: null, loading: null});
|
||||
if (speech.source) {
|
||||
speech.source.stop();
|
||||
const playing = speech.source;
|
||||
Object.assign(speech, {pending: [], current: null, loading: null, source: null, item: null});
|
||||
if (playing) {
|
||||
playing.stop();
|
||||
}
|
||||
clearBubbles();
|
||||
drawSpeaker();
|
||||
}
|
||||
|
||||
function speakRows(rows) {
|
||||
const voiced = settings.speech.on && state.speech.tts;
|
||||
if (!voiced && !settings.bubbles) {
|
||||
return;
|
||||
}
|
||||
for (const row of rows.filter((entry) => entry.ts >= state.now - SPEECH_FRESH)) {
|
||||
const audible = voiced && Voice.speakable(row, settings.speech);
|
||||
if (audible || (settings.bubbles && Bubbles.picked(row, settings.speech))) {
|
||||
const steps = RadioSet.plan(row, radioSet, liveSpeech());
|
||||
if (steps.length || (settings.bubbles && Bubbles.picked(row, radioSet))) {
|
||||
const line = row.text.split("\n").map((part) => part.trim()).find(Boolean) || "";
|
||||
say({text: row.speech, voice: row.voice, tone: Voice.toneOf(row, HUMAN), cls: row.class, who: row.source, line: short(line), words: Bubbles.words(row.text), silent: !audible});
|
||||
say({row, voice: row.voice, tone: Voice.toneOf(row, HUMAN), cls: row.class, who: row.source, sent: Boolean(RadioSet.ledgerOf(row, state.messages)), line: short(line), words: Bubbles.words(row.text), silent: !steps.length});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,8 @@
|
||||
const sky = {canvas: document.getElementById("sky"), stars: Ambience.stars(320, 7), mode: "", frame: 0};
|
||||
const music = {gain: null, filter: null, drone: [], timer: 0, tension: 0, ducked: 0};
|
||||
const radio = {element: null, url: "", level: 0, timer: 0, playing: false, waiting: false, index: -1, pick: null, sig: "", state: "", short: "", note: "", told: null};
|
||||
const speech = {pending: [], busy: false, warned: 0, current: null, source: null, loading: null, timer: 0};
|
||||
const speech = {pending: [], busy: false, warned: 0, current: null, source: null, loading: null, timer: 0, item: null};
|
||||
let radioSet = RadioSet.valid(stored(RadioSet.KEY, null));
|
||||
const mic = {recorder: null, held: false, busy: false, timer: 0};
|
||||
const space = {
|
||||
views: {graph: {...state.settings.space.graph}, sky: {...state.settings.space.sky}}, glides: {graph: null, sky: null}, edits: 0, saved: 0, timer: 0, look: false, compass: null,
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
const RadioSet = (() => {
|
||||
"use strict";
|
||||
const KEY = "kvb-orchestrator.radio";
|
||||
const MODES = ["auto", "quiet", "silence"];
|
||||
const TONES = ["mayday", "review", "direct", "radio"];
|
||||
const CLASSES = ["post", "call", "newsletter", "broadcast", "mayday", "pan-pan", "security"];
|
||||
const TO_ALL = new Set(["newsletter", "broadcast", "mayday", "pan-pan", "security"]);
|
||||
const TABS = ["sent", "received", "all"];
|
||||
const CHIPS = ["class", "from", "to", "agent"];
|
||||
const TEXT_LIMIT = 200;
|
||||
const MUTED_LIMIT = 200;
|
||||
const BURST = {seconds: 0.6, frequency: 1800, q: 0.9};
|
||||
const MARK = /\[kvb-orchestrator msg ([0-9a-f]{16})\]/;
|
||||
const DEFAULTS = {
|
||||
mode: "auto",
|
||||
sounds: {mayday: {on: true, volume: 0.9}, review: {on: true, volume: 0.6}, direct: {on: true, volume: 0.5}, radio: {on: false, volume: 0.25}},
|
||||
squelch: 1,
|
||||
classes: ["mayday", "pan-pan", "security"],
|
||||
muted: [],
|
||||
log: {tab: "received", chips: {class: "", from: "", to: "", agent: ""}, q: ""},
|
||||
};
|
||||
|
||||
const level = (value, fallback) => (typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1 ? value : fallback);
|
||||
const short = (value) => typeof value === "string" && value.length <= TEXT_LIMIT;
|
||||
const object = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : {});
|
||||
|
||||
function tone(raw, fallback) {
|
||||
const entry = object(raw);
|
||||
return {on: typeof entry.on === "boolean" ? entry.on : fallback.on, volume: level(entry.volume, fallback.volume)};
|
||||
}
|
||||
|
||||
function log(raw) {
|
||||
const entry = object(raw);
|
||||
const chips = object(entry.chips);
|
||||
return {
|
||||
tab: TABS.includes(entry.tab) ? entry.tab : DEFAULTS.log.tab,
|
||||
chips: Object.fromEntries(CHIPS.map((name) => [name, short(chips[name]) ? chips[name] : ""])),
|
||||
q: short(entry.q) ? entry.q : "",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object|null} stored the radio set this browser kept, or null.
|
||||
* @returns {object} the radio set with every unknown or broken field at its default; MAYDAY always stays read aloud.
|
||||
*/
|
||||
function valid(stored) {
|
||||
const raw = object(stored);
|
||||
const sounds = object(raw.sounds);
|
||||
const classes = Array.isArray(raw.classes) ? raw.classes : DEFAULTS.classes;
|
||||
const muted = Array.isArray(raw.muted) ? raw.muted.filter((key) => typeof key === "string" && key && key.length <= TEXT_LIMIT) : [];
|
||||
return {
|
||||
mode: MODES.includes(raw.mode) ? raw.mode : DEFAULTS.mode,
|
||||
sounds: Object.fromEntries(TONES.map((name) => [name, tone(sounds[name], DEFAULTS.sounds[name])])),
|
||||
squelch: level(raw.squelch, DEFAULTS.squelch),
|
||||
classes: CLASSES.filter((name) => name === "mayday" || classes.includes(name)),
|
||||
muted: [...new Set(muted)].sort().slice(0, MUTED_LIMIT),
|
||||
log: log(raw.log),
|
||||
};
|
||||
}
|
||||
|
||||
function picked(row, set) {
|
||||
return row.class === "mayday" || (set.classes.includes(row.class) && !set.muted.includes(row.source));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} row a radio row of the state with word, rest and voice.
|
||||
* @param {object} set the radio set.
|
||||
* @param {Object<string, boolean>} live tts and open: whether the hub speaks at all and whether its CPU gate is open.
|
||||
* @returns {Array<{kind: string, text: (string|undefined)}>} what plays, in order: the procedure word line in every mode, then the spoken rest in Auto below the threshold, else the noise burst, nothing more in Silence.
|
||||
*/
|
||||
function plan(row, set, live) {
|
||||
if (!picked(row, set)) {
|
||||
return [];
|
||||
}
|
||||
const word = live.tts && row.voice && row.word ? [{kind: "word", text: row.word}] : [];
|
||||
if (set.mode === "silence") {
|
||||
return word;
|
||||
}
|
||||
const spoken = set.mode === "auto" && live.tts && live.open && row.voice && row.rest;
|
||||
return [...word, spoken ? {kind: "speech", text: row.rest} : {kind: "burst"}];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} loudness the tone's volume times the squelch.
|
||||
* @returns {Object<string, number>} seconds, frequency, q and gain of the band-passed white noise of the squelch tail.
|
||||
*/
|
||||
function burst(loudness) {
|
||||
return {...BURST, gain: loudness};
|
||||
}
|
||||
|
||||
function toAll(row) {
|
||||
return TO_ALL.has(row.class) || !row.to.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} row a radio row.
|
||||
* @param {Array<object>} messages the hub's message ledger of the state.
|
||||
* @returns {object|null} the ledger message the row relays; null for a row no message of this hub sent, whatever its sender name.
|
||||
*/
|
||||
function ledgerOf(row, messages) {
|
||||
const found = MARK.exec(row.text);
|
||||
return found ? messages.find((message) => message.id === found[1]) || null : null;
|
||||
}
|
||||
|
||||
function sentRows(messages, human) {
|
||||
return messages.map((message) => ({ts: message.created_ts, from: human, to: message.to === "*" ? [] : [message.to], class: message.class || "post", text: message.text, voice: message.voice, sent: true}));
|
||||
}
|
||||
|
||||
function tabRows(rows, tab, human, messages) {
|
||||
if (tab === "sent") {
|
||||
return sentRows(messages, human);
|
||||
}
|
||||
return rows.filter((row) => tab === "all" || toAll(row) || row.to.includes(human));
|
||||
}
|
||||
|
||||
function matches(row, entry) {
|
||||
const {chips, q} = entry;
|
||||
const words = q.trim().toLowerCase();
|
||||
return (!chips.class || row.class === chips.class)
|
||||
&& (!chips.from || row.from === chips.from)
|
||||
&& (!chips.to || row.to.includes(chips.to))
|
||||
&& (!chips.agent || row.from === chips.agent || row.to.includes(chips.agent))
|
||||
&& (!words || [row.text, row.from, ...row.to].join("\n").toLowerCase().includes(words));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Array<object>} rows the radio rows of the state.
|
||||
* @param {object} entry the log part of the radio set: tab, chips and q.
|
||||
* @param {string} human the operator's name.
|
||||
* @param {Array<object>} messages the hub's message ledger; Sent lists it, not radio rows that only claim the operator's name.
|
||||
* @returns {Array<object>} the rows of the tab that every chip and the search match, newest first.
|
||||
*/
|
||||
function logRows(rows, entry, human, messages) {
|
||||
return tabRows(rows, entry.tab, human, messages).filter((row) => matches(row, entry)).sort((a, b) => b.ts - a.ts);
|
||||
}
|
||||
|
||||
function counts(rows, human, messages) {
|
||||
return Object.fromEntries(TABS.map((tab) => [tab, tabRows(rows, tab, human, messages).length]));
|
||||
}
|
||||
|
||||
function choices(rows) {
|
||||
const sorted = (values) => [...new Set(values.filter(Boolean))].sort((a, b) => a.localeCompare(b));
|
||||
const names = rows.flatMap((row) => [row.from, ...row.to]);
|
||||
return {
|
||||
class: CLASSES.filter((name) => rows.some((row) => row.class === name)).concat(sorted(rows.map((row) => row.class)).filter((name) => !CLASSES.includes(name))),
|
||||
from: sorted(rows.map((row) => row.from)),
|
||||
to: sorted(rows.flatMap((row) => row.to)),
|
||||
agent: sorted(names),
|
||||
};
|
||||
}
|
||||
|
||||
function cleared(entry) {
|
||||
return {...entry, chips: Object.fromEntries(CHIPS.map((name) => [name, ""])), q: ""};
|
||||
}
|
||||
|
||||
return {KEY, MODES, TONES, CLASSES, TABS, CHIPS, DEFAULTS, valid, picked, plan, burst, toAll, ledgerOf, logRows, counts, choices, cleared};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = RadioSet;
|
||||
}
|
||||
@@ -75,4 +75,51 @@ body.fit .radio-spot { flex: 0 1 auto; min-height: 0; }
|
||||
.composer-status { min-width: 0; overflow-wrap: anywhere; }
|
||||
.voice-note { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
|
||||
.voice-replay { max-width: 100%; height: 34px; }
|
||||
.mini .voice-replay, .bubble .voice-replay { width: 100%; }
|
||||
.mini .voice-replay, .bubble .voice-replay, .radio-row .voice-replay { width: 100%; }
|
||||
.radio-face { display: grid; gap: var(--sp-2); min-width: 0; padding: var(--sp-3); border: 1px solid var(--line-strong); border-radius: var(--radius); background: var(--sunken); }
|
||||
.radio-display { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2) var(--sp-3); min-width: 0; padding: var(--sp-2) var(--sp-3); border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--panel); font-family: var(--mono); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
|
||||
.radio-field { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.radio-field[data-field="class"] { font-weight: 700; }
|
||||
.radio-field[data-field="cpu"][data-open="false"] { color: var(--warn); }
|
||||
.radio-lamp { display: inline-flex; align-items: center; gap: 5px; padding: 0 8px; border-radius: 999px; background: var(--neutral-soft); color: var(--muted); font-weight: 700; line-height: 20px; }
|
||||
.radio-lamp::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .5; }
|
||||
.radio-lamp[data-lit="true"] { background: var(--ok-soft); color: var(--ok); }
|
||||
.radio-lamp[data-lit="true"][data-tx="true"] { background: var(--bad-soft); color: var(--bad); }
|
||||
.radio-lamp[data-lit="true"]::before { opacity: 1; box-shadow: 0 0 0 3px color-mix(in srgb, currentColor 25%, transparent); }
|
||||
.radio-modes { flex-wrap: wrap; justify-self: start; max-width: 100%; }
|
||||
.radio-modes button { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.radio-knobs { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 380px), 1fr)); gap: var(--sp-1) var(--sp-4); }
|
||||
.knob-row { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; color: var(--muted); font-size: var(--fs-sm); }
|
||||
.knob-label { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.knob { flex: 1 1 80px; min-width: 60px; accent-color: var(--accent); }
|
||||
.knob-value { flex: none; min-width: 3.5em; font-family: var(--mono); font-variant-numeric: tabular-nums; text-align: right; }
|
||||
.radio-read { display: grid; gap: var(--sp-2); }
|
||||
.radio-read .chips { margin-bottom: 0; }
|
||||
.ptt { min-width: 96px; justify-content: center; }
|
||||
.radio-logbox { display: grid; gap: var(--sp-2); align-content: start; min-width: 0; }
|
||||
.radio-tabs { display: flex; flex-wrap: wrap; gap: 2px; padding: 3px; border: 1px solid var(--line); border-radius: 10px; background: var(--sunken); justify-self: start; max-width: 100%; }
|
||||
.radio-tabs button { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border: 0; border-radius: 8px; background: transparent; color: var(--muted); font-size: var(--fs-sm); font-weight: 580; cursor: pointer; }
|
||||
.radio-tabs button[aria-selected="true"] { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
|
||||
.radio-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; min-width: 0; }
|
||||
.radio-chips { display: flex; flex-wrap: wrap; gap: 6px; min-width: 0; }
|
||||
.chip-select .field { max-width: 180px; padding: 3px 8px; border-radius: 999px; font-size: var(--fs-sm); }
|
||||
.chip-select[data-active="true"] .field { border-color: transparent; background: var(--accent-soft); color: var(--accent); }
|
||||
.radio-filters input[type="search"] { flex: 1 1 140px; min-width: 0; padding: 4px 10px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); }
|
||||
.radio-log { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
|
||||
.radio-row details { min-width: 0; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--sunken); }
|
||||
.radio-row summary { display: flex; flex-wrap: wrap; align-items: center; gap: 4px var(--sp-2); min-width: 0; padding: 5px 8px; font-size: var(--fs-sm); cursor: pointer; list-style: none; }
|
||||
.radio-row summary::-webkit-details-marker { display: none; }
|
||||
.radio-row time { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.radio-dir { display: inline-flex; color: var(--muted); }
|
||||
.radio-row[data-dir="sent"] .radio-dir { color: var(--accent); }
|
||||
.radio-route { font-weight: 600; overflow-wrap: anywhere; }
|
||||
.radio-line { flex: 1 1 160px; min-width: 0; overflow: hidden; color: var(--muted); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.radio-full { margin: 0; padding: 6px 10px 8px; border-top: 1px solid var(--line); white-space: pre-wrap; overflow-wrap: anywhere; font-size: var(--fs-sm); }
|
||||
@media (min-width: 641px) {
|
||||
.knob-label { flex: none; }
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
body:not(.fit) .radio-spot { max-height: none; }
|
||||
.radio-log { max-height: calc(100dvh - var(--head) - var(--sp-3)); overflow-y: auto; overscroll-behavior: contain; scroll-margin-top: var(--head); }
|
||||
.radio-row summary { gap: 0 var(--sp-2); padding: 3px 8px; line-height: 1.3; }
|
||||
}
|
||||
@@ -20,13 +20,6 @@ const Voice = (() => {
|
||||
return kinds.find((kind) => present[kind] && settings.sounds[kind].on && loudness(kind, settings) > 0) || null;
|
||||
}
|
||||
|
||||
function speakable(row, speech) {
|
||||
if (!speech.on || !row.speech || !row.voice) {
|
||||
return false;
|
||||
}
|
||||
return row.class === "mayday" || (speech.classes.includes(row.class) && !speech.muted.includes(row.source));
|
||||
}
|
||||
|
||||
function rank(item) {
|
||||
return Object.hasOwn(RANKS, item.cls) ? RANKS[item.cls] : ROUTINE;
|
||||
}
|
||||
@@ -66,7 +59,7 @@ const Voice = (() => {
|
||||
return buffer;
|
||||
}
|
||||
|
||||
return {toneOf, loudness, beep, speakable, enqueue, frames, wav};
|
||||
return {toneOf, loudness, beep, enqueue, frames, wav};
|
||||
})();
|
||||
if (typeof module === "object" && module.exports) {
|
||||
module.exports = Voice;
|
||||
|
||||
Reference in new issue
Block a user