feat(hub): radio Morse mode with WPM speed, per-agent pitch and a 0-100 % speech threshold

Morse keys every picked row whole: class prosign (SOS for MAYDAY), DE with the sender's clear name and the full text, after PARIS timing at the hub's morse.wpm (5-40, default 20) and in the sender's own 550-850 Hz tone from the same sha256 slot as its voice. A higher class cuts a keying row, which keys again whole after it. The speech threshold runs 0-100 % in steps of 10, 100 always open, 0 never. The History card moves into page-radiolog.js to keep page-radioview.js under 500 lines.

🎯 Fix: 85 %
💥 Break: 7 %
💸 Tokens: 100 %
⏱️ Velocity: 100 %
🛡️ Security: 100 %
🏆 Score: 79
🚦 Gate: ⛔ fix 85 % < 90, break 7 % > 5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-15 09:46:05 +00:00
1 parent ded7c9a7b6
commit 86d539a95f
22 files changed
+1147 -286

No files matched your search

+6
View File
@@ -493,6 +493,8 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "radioset.js" %}
{% include "morse.js" %}
{% include "receipts.js" %}
{% include "bubbles.js" %}
@@ -620,12 +622,16 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "page-radioview.js" %}
{% include "page-radiolog.js" %}
{% include "page-composer.js" %}
{% include "page-settings.js" %}
{% include "page-speech.js" %}
{% include "page-morse.js" %}
{% include "page-mic.js" %}
{% include "page-bubbles.js" %}
+90
View File
@@ -0,0 +1,90 @@
const Morse = (() => {
"use strict";
const CODES = {
a: ".-", b: "-...", c: "-.-.", d: "-..", e: ".", f: "..-.", g: "--.", h: "....", i: "..", j: ".---", k: "-.-", l: ".-..", m: "--",
n: "-.", o: "---", p: ".--.", q: "--.-", r: ".-.", s: "...", t: "-", u: "..-", v: "...-", w: ".--", x: "-..-", y: "-.--", z: "--..",
0: "-----", 1: ".----", 2: "..---", 3: "...--", 4: "....-", 5: ".....", 6: "-....", 7: "--...", 8: "---..", 9: "----.",
".": ".-.-.-", ",": "--..--", "?": "..--..", "'": ".----.", "!": "-.-.--", "/": "-..-.", "(": "-.--.", ")": "-.--.-", "&": ".-...",
":": "---...", ";": "-.-.-.", "=": "-...-", "+": ".-.-.", "-": "-....-", _: "..--.-", "\"": ".-..-.", $: "...-..-", "@": ".--.-.",
ä: ".-.-", æ: ".-.-", à: ".--.-", å: ".--.-", ç: "-.-..", è: ".-..-", é: "..-..", ñ: "--.--", ö: "---.", ø: "---.", ü: "..--", ß: "...--..",
};
const UNITS = {dot: 1, dash: 3, inner: 1, letter: 3, word: 7};
const PARIS = 50;
const MINUTE = 60000;
const SPEED = {min: 5, max: 40, step: 1};
function codeOf(char) {
const folded = char.toLowerCase();
const base = folded.normalize("NFD").charAt(0);
if (Object.hasOwn(CODES, folded)) {
return CODES[folded];
}
return Object.hasOwn(CODES, base) ? CODES[base] : "";
}
/**
* @param {string} text clear text.
* @returns {Array<Array<string>>} its words, each the codes of its letters, case-folded; a letter with an accent and no code of its own keys its base letter, any other character without a code is skipped and a word left without one is dropped.
*/
function words(text) {
return String(text).normalize("NFC").split(/\s+/).map((word) => [...word].map(codeOf).filter(Boolean)).filter((codes) => codes.length);
}
/**
* @param {string} text a prosign such as SOS.
* @returns {Array<Array<string>>} one word holding one sign: the codes of its letters keyed without the gap between letters; none for a text without a code.
*/
function joined(text) {
const sign = words(text).flat().join("");
return sign ? [[sign]] : [];
}
/**
* @param {number} wpm the speed in words per minute.
* @returns {number} the length of one dot in ms after PARIS: a word is 50 dot units.
*/
function dot(wpm) {
return MINUTE / (PARIS * wpm);
}
function letterUnits(code, at, tones) {
let end = at;
[...code].forEach((mark, index) => {
const length = mark === "-" ? UNITS.dash : UNITS.dot;
tones.push([end, length]);
end += length + (index < code.length - 1 ? UNITS.inner : 0);
});
return end;
}
/**
* @param {Array<Array<string>>} signs words of letter codes, as words and joined give them.
* @param {number} wpm the speed in words per minute.
* @returns {{tones: Array<Array<number>>, ms: number}} every tone as [start, length] in ms and the whole length in ms, each word closed by the gap between words as PARIS counts it.
*/
function timeline(signs, wpm) {
const tones = [];
let at = 0;
for (const word of signs) {
word.forEach((code, letter) => {
at = letterUnits(code, at, tones) + (letter < word.length - 1 ? UNITS.letter : 0);
});
at += UNITS.word;
}
const unit = dot(wpm);
return {tones: tones.map(([start, length]) => [start * unit, length * unit]), ms: at * unit};
}
/**
* @param {number} wpm the speed in words per minute.
* @returns {string} the speed as the radio shows it, with the dot units per minute after PARIS.
*/
function rate(wpm) {
return `${wpm} WPM (${wpm * PARIS} dots/min)`;
}
return {SPEED, CODES, words, joined, dot, timeline, rate};
})();
if (typeof module === "object" && module.exports) {
module.exports = Morse;
}
+60
View File
@@ -0,0 +1,60 @@
const MORSE_EDGE = 0.005;
function morseSigns(step) {
return [...(step.joined ? Morse.joined(step.sign) : Morse.words(step.sign)), ...Morse.words(step.text)];
}
function keyEdge(param, at, length, level) {
const edge = Math.min(MORSE_EDGE, length / 4);
param.setValueAtTime(0, at);
param.linearRampToValueAtTime(level, at + edge);
param.setValueAtTime(level, at + length - edge);
param.linearRampToValueAtTime(0, at + length);
}
/**
* @param {AudioContext} sound the page's audio context.
* @param {object} item the row that sounds now.
* @param {object} step the Morse step the radio set planned: sign, joined, text and pitch.
* @returns {Promise<boolean>} whether the whole message was keyed to its end; false when Stop or a mode change cut it or its tone is silent.
*/
function keyMorse(sound, item, step) {
const level = loudness(item.tone);
const {tones, ms} = Morse.timeline(morseSigns(step), settings.morse.wpm);
if (level <= 0 || !tones.length) {
return Promise.resolve(false);
}
const source = sound.createOscillator();
const gain = sound.createGain();
const start = sound.currentTime;
const seconds = ms / 1000;
source.type = "sine";
source.frequency.value = step.pitch;
gain.gain.setValueAtTime(0, start);
tones.forEach(([at, length]) => keyEdge(gain.gain, start + at / 1000, length / 1000, level));
source.connect(gain).connect(sound.destination);
voicePace(item, Infinity, seconds);
const ended = sounded(item, source, seconds);
source.start(start);
source.stop(start + seconds);
return ended.then(() => speech.item === item && !item.cut);
}
async function setMorseSpeed(wpm) {
if (wpm !== settings.morse.wpm && await saveSettings({...settings, space: savedSpace(), morse: {wpm}})) {
toast("Morse speed saved", [`The radio keys Morse at ${Morse.rate(wpm)}.`], true);
}
redrawFilters();
}
function morseSpeed() {
const {wpm} = settings.morse;
const shown = h("output", {class: "morse-rate"}, Morse.rate(wpm));
const input = h("input", {type: "range", class: "knob", ...Morse.SPEED, value: wpm, ...named("Morse speed", "Morse speed: words per minute after PARIS, for every browser of this hub"), on: {
input: (event) => {
shown.textContent = Morse.rate(Number(event.target.value));
},
change: (event) => setMorseSpeed(Number(event.target.value)),
}});
return h("label", {class: "morse-speed"}, h("span", {}, "Morse speed"), input, shown);
}
+233
View File
@@ -0,0 +1,233 @@
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"};
const COPIED = 1600;
const FOLDED_READERS = 3;
function keepLog(change) {
keepRadio({log: {...radioSet.log, ...change}});
}
function chipSelect(name) {
const label = CHIP_LABELS[name];
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}})}});
return h("label", {class: "chip-select", "data-chip": name, "data-active": "false"}, select);
}
function fillChip(chip, values) {
const name = chip.dataset.chip;
const chosen = radioSet.log.chips[name];
const options = [...new Set([...values, ...(chosen ? [chosen] : [])])];
const select = chip.querySelector("select");
const sig = JSON.stringify([options, chosen || ""]);
if (select.sig !== sig) {
select.sig = sig;
select.replaceChildren(h("option", {value: ""}, `${CHIP_LABELS[name]}: any`), ...options.map((value) => h("option", {value, selected: value === chosen}, name === "class" ? CLASSES[value] || value : value)));
}
setAttr(chip, "data-active", String(Boolean(chosen)));
}
function setAttr(node, name, value) {
if (node.getAttribute(name) !== value) {
node.setAttribute(name, value);
}
}
function setText(node, value) {
if (node.textContent !== value) {
node.textContent = value;
}
}
function firstLine(text) {
return text.split("\n").map((part) => part.trim()).find(Boolean) || "";
}
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 = firstLine(row.text);
const line = h("li", {class: "radio-row", "data-key": row.key, "data-dir": sent ? "sent" : "received", "data-class": row.class, "data-ts": row.ts, on: {click: (event) => openRadioRow(event.currentTarget.row, event.currentTarget)}},
h("button", {type: "button", class: "radio-pick", "aria-haspopup": "dialog", title: first},
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"}, first)),
foldedReaders(row));
line.row = row;
return line;
}
function keepLine(kept, fresh) {
kept.row = fresh.row;
if (kept.outerHTML === fresh.outerHTML) {
return kept;
}
for (const name of ["data-dir", "data-class"]) {
setAttr(kept, name, fresh.getAttribute(name));
}
const [pick, twin] = [kept.querySelector(".radio-pick"), fresh.querySelector(".radio-pick")];
setAttr(pick, "title", twin.getAttribute("title"));
pick.replaceChildren(...twin.childNodes);
for (const node of [...kept.children].filter((child) => child !== pick)) {
node.remove();
}
kept.append(...[...fresh.children].filter((child) => child !== twin));
return kept;
}
function patchList(list, lines) {
const before = [...list.children];
const focused = before.find((node) => node.contains(document.activeElement)) || null;
const old = new Map(before.filter((node) => node.dataset.key).map((node) => [node.dataset.key, node]));
const wanted = lines.map((line) => {
const kept = old.get(line.dataset.key);
old.delete(line.dataset.key);
return kept ? keepLine(kept, line) : line;
});
const keep = new Set(wanted);
for (const node of before.filter((child) => !keep.has(child))) {
node.remove();
}
wanted.forEach((node, index) => {
if (list.children[index] !== node) {
list.insertBefore(node, list.children[index] || null);
}
});
if (focused && !focused.isConnected) {
const at = before.indexOf(focused);
const near = before.filter((node) => node.isConnected && node.querySelector(".radio-pick")).sort((a, b) => Math.abs(before.indexOf(a) - at) - Math.abs(before.indexOf(b) - at))[0];
(near ? near.querySelector(".radio-pick") : list).focus({preventScroll: true});
}
}
function foldedReaders(row) {
const strip = readerRow(row);
const {shown, hidden} = Receipts.strip(row);
const rest = shown.length + hidden.length - FOLDED_READERS;
if (strip && rest > 0) {
strip.append(h("span", {class: "readers-more readers-fold", role: "img", ...named(`${rest} more readers`, [...shown, ...hidden].slice(FOLDED_READERS).map(readLabel).join("\n"))}, `+${rest}`));
}
return strip;
}
function readerLine(reader) {
const known = reader.read !== null && reader.read !== undefined;
return h("li", {class: "popup-reader", "data-session": reader.session, "data-acked": String(reader.acked)},
face(people()[reader.session] ? reader.session : reader.name, false),
h("strong", {}, reader.name),
h("span", {class: "muted"}, known ? `read ${reader.approximate ? "about " : ""}${absolute.format(stampOf(reader.read))}` : "read, time unknown"),
reader.acked ? pill("acknowledged", "ok") : null);
}
function copyText(text) {
const said = h("span", {class: "radio-said", role: "status", "aria-live": "polite"});
const button = h("button", {type: "button", class: "btn small radio-copy", ...named("Copy", "Copy: the full message to the clipboard")}, icon("bi-clipboard"), h("span", {}, "Copy"));
const show = (name, word, done, note) => {
button.replaceChildren(icon(name), h("span", {}, word));
button.setAttribute("aria-label", word);
button.dataset.copied = done;
said.textContent = note;
};
button.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(text);
show("bi-clipboard-check", "Copied", "true", "Copied: the full message is on the clipboard");
} catch {
show("bi-x-circle", "Not copied", "false", "Not copied: the browser refused the clipboard");
}
window.setTimeout(() => show("bi-clipboard", "Copy", "", ""), COPIED);
});
return [button, said];
}
function replyTarget(list) {
const home = list ? list.closest(".radio-home") : null;
if (!home) {
return spotDom.speak;
}
const homes = liveParts("speaks").filter((part) => part.root.closest(".radio-home"));
return homes.find((part) => home.contains(part.root)) || homes.find((part) => part.root.closest(".radio-home-radio-speak")) || homes[0] || spotDom.speak;
}
function replyTo(row, list) {
const who = row.from === HUMAN && row.to.length ? row.to[0] : row.from;
const part = replyTarget(list);
closePopup();
if (part === spotDom.speak) {
openSpot(true);
}
part.channel.value = "post";
part.channel.dispatchEvent(new Event("change", {bubbles: true}));
if (![...part.recipient.options].some((option) => option.value === who)) {
part.recipient.append(h("option", {value: who}, who));
}
part.recipient.value = who;
part.text.focus();
}
function openRadioRow(row, li) {
const message = row.sent ? row : RadioSet.ledgerOf(row, state.messages);
const {shown, hidden} = Receipts.strip(row);
const readers = [...shown, ...hidden];
const list = li.closest("ul");
const anchor = () => (list ? [...list.querySelectorAll(".radio-row")].find((item) => item.dataset.key === row.key) || null : null);
openPopup(`Radio message from ${row.from}`, [
popupHead(klass(row.class), `${row.from} → ${targetsOf(row)}`),
meta([["Sender", row.from], ["Recipient", targetsOf(row)], ["Class", CLASSES[row.class] || row.class], ["Time", absolute.format(stampOf(row.ts))]]),
h("pre", {class: "radio-full"}, row.text),
voiceReplay(message ? message.voice : null),
h("div", {class: "actions radio-actions"},
h("button", {type: "button", class: "btn small primary radio-reply", ...named("Reply", "Reply: a post to the sender in the speak card"), on: {click: () => replyTo(row, list)}}, icon("bi-reply"), "Reply"),
copyText(row.text)),
h("h3", {}, readers.length ? `Read by ${readers.length}` : "Read by nobody yet"),
readers.length ? h("ul", {class: "popup-readers"}, readers.map(readerLine)) : null,
].filter(Boolean), anchor);
}
function drawLog() {
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, Receipts.signature(state.radio), Receipts.signature(state.messages), entry, Math.floor(Date.now() / 60000)]);
for (const dom of liveParts("logs")) {
if (sig !== dom.sig) {
dom.sig = sig;
drawLogPart(dom, entry);
}
}
}
function drawLogPart(dom, entry) {
const counts = RadioSet.counts(state.radio, HUMAN, state.messages);
for (const button of dom.tabs.children) {
const {tab} = button.dataset;
const count = button.querySelector(".count");
setAttr(button, "aria-selected", String(tab === entry.tab));
setAttr(count, "aria-label", `${counts[tab]} rows`);
setText(count, String(counts[tab]));
}
const choices = RadioSet.choices(state.radio);
for (const chip of dom.chips.children) {
fillChip(chip, choices[chip.dataset.chip]);
}
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);
patchList(dom.list, 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 historyCard() {
const tabs = h("div", {class: "radio-tabs", role: "tablist", "aria-label": "Log"}, RadioSet.TABS.map((tab) => {
const [name, label, hint] = TAB_LABELS[tab];
return h("button", {type: "button", role: "tab", "data-tab": tab, "aria-selected": "false", title: hint, on: {click: () => keepLog({tab})}}, icon(name), label, h("span", {class: "count"}));
}));
const chips = h("div", {class: "radio-chips", role: "group", "aria-label": "Log filters"}, RadioSet.CHIPS.map(chipSelect));
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", tabindex: "-1", "aria-label": "Radio log"});
const part = {tabs, chips, search, list, sig: ""};
part.root = h("section", {class: "radio-card radio-logbox", "data-panel": "radio-log", "aria-label": "Radio log"}, cardHead("History", tabs, search), h("div", {class: "radio-filters"}, chips, clear), list);
radioParts.logs.push(part);
return part;
}
+16 -243
View File
@@ -4,11 +4,8 @@
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"],
morse: ["bi-three-dots", "Morse", "Morse: every message keyed whole in Morse, in its sender's own pitch, at the hub's Morse speed; MAYDAY keys SOS"],
};
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"};
const COPIED = 1600;
const FOLDED_READERS = 3;
const radioParts = {bars: [], devices: [], logs: [], speaks: []};
const liveParts = (kind) => radioParts[kind].filter((part) => part.root.isConnected);
@@ -92,9 +89,7 @@
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"}`;
cpu.title = `${gate.cpu === null ? "No host CPU sample of the last two minutes" : `Host CPU ${fixed(gate.cpu)} %`}, threshold: ${RadioSet.gateLabel(gate.threshold)}${gate.open ? "" : ", so the hub renders no new speech line and the radio plays the burst"}`;
}
}
@@ -126,7 +121,8 @@
value.textContent = event.target.value;
change(Number(event.target.value));
}}});
return {input, value, row: h("div", {class: "knob-row", title: hint}, h("span", {class: "knob-label", title: label}, label), input, value)};
const name = h("span", {class: "knob-label", title: label}, label);
return {input, value, name, row: h("div", {class: "knob-row", title: hint}, name, input, value)};
}
function toneKnob(id, label) {
@@ -144,17 +140,22 @@
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);
toast("Speech threshold saved", [`The hub renders new speech: ${RadioSet.gateLabel(value)}.`], true);
}
drawRadioSet();
}
function drawGate(gate, value) {
gate.name.textContent = RadioSet.gateLabel(value);
gate.name.title = gate.name.textContent;
gate.value.textContent = `${value} %`;
gate.input.setAttribute("aria-valuetext", gate.name.textContent);
}
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} %`;
});
const threshold = knob("Threshold", "Speech threshold: the hub renders new speech only while the host CPU lies below it, always at 100 %, never at 0 %; your passkey signs each change", RadioSet.GATE, (value) => drawGate(threshold, value));
threshold.input.addEventListener("change", (event) => setThreshold(Number(event.target.value)));
const check = iconBtn("bi-broadcast", "Radio check", "btn small ghost radio-check", () => 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;
@@ -294,7 +295,8 @@
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);
agents.length ? h("div", {class: "chips", role: "group", "aria-label": "Agents"}, agents) : null,
morseSpeed());
}
function redrawFilters() {
@@ -305,235 +307,6 @@
}
}
function keepLog(change) {
keepRadio({log: {...radioSet.log, ...change}});
}
function chipSelect(name) {
const label = CHIP_LABELS[name];
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}})}});
return h("label", {class: "chip-select", "data-chip": name, "data-active": "false"}, select);
}
function fillChip(chip, values) {
const name = chip.dataset.chip;
const chosen = radioSet.log.chips[name];
const options = [...new Set([...values, ...(chosen ? [chosen] : [])])];
const select = chip.querySelector("select");
const sig = JSON.stringify([options, chosen || ""]);
if (select.sig !== sig) {
select.sig = sig;
select.replaceChildren(h("option", {value: ""}, `${CHIP_LABELS[name]}: any`), ...options.map((value) => h("option", {value, selected: value === chosen}, name === "class" ? CLASSES[value] || value : value)));
}
setAttr(chip, "data-active", String(Boolean(chosen)));
}
function setAttr(node, name, value) {
if (node.getAttribute(name) !== value) {
node.setAttribute(name, value);
}
}
function setText(node, value) {
if (node.textContent !== value) {
node.textContent = value;
}
}
function firstLine(text) {
return text.split("\n").map((part) => part.trim()).find(Boolean) || "";
}
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 = firstLine(row.text);
const line = h("li", {class: "radio-row", "data-key": row.key, "data-dir": sent ? "sent" : "received", "data-class": row.class, "data-ts": row.ts, on: {click: (event) => openRadioRow(event.currentTarget.row, event.currentTarget)}},
h("button", {type: "button", class: "radio-pick", "aria-haspopup": "dialog", title: first},
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"}, first)),
foldedReaders(row));
line.row = row;
return line;
}
function keepLine(kept, fresh) {
kept.row = fresh.row;
if (kept.outerHTML === fresh.outerHTML) {
return kept;
}
for (const name of ["data-dir", "data-class"]) {
setAttr(kept, name, fresh.getAttribute(name));
}
const [pick, twin] = [kept.querySelector(".radio-pick"), fresh.querySelector(".radio-pick")];
setAttr(pick, "title", twin.getAttribute("title"));
pick.replaceChildren(...twin.childNodes);
for (const node of [...kept.children].filter((child) => child !== pick)) {
node.remove();
}
kept.append(...[...fresh.children].filter((child) => child !== twin));
return kept;
}
function patchList(list, lines) {
const before = [...list.children];
const focused = before.find((node) => node.contains(document.activeElement)) || null;
const old = new Map(before.filter((node) => node.dataset.key).map((node) => [node.dataset.key, node]));
const wanted = lines.map((line) => {
const kept = old.get(line.dataset.key);
old.delete(line.dataset.key);
return kept ? keepLine(kept, line) : line;
});
const keep = new Set(wanted);
for (const node of before.filter((child) => !keep.has(child))) {
node.remove();
}
wanted.forEach((node, index) => {
if (list.children[index] !== node) {
list.insertBefore(node, list.children[index] || null);
}
});
if (focused && !focused.isConnected) {
const at = before.indexOf(focused);
const near = before.filter((node) => node.isConnected && node.querySelector(".radio-pick")).sort((a, b) => Math.abs(before.indexOf(a) - at) - Math.abs(before.indexOf(b) - at))[0];
(near ? near.querySelector(".radio-pick") : list).focus({preventScroll: true});
}
}
function foldedReaders(row) {
const strip = readerRow(row);
const {shown, hidden} = Receipts.strip(row);
const rest = shown.length + hidden.length - FOLDED_READERS;
if (strip && rest > 0) {
strip.append(h("span", {class: "readers-more readers-fold", role: "img", ...named(`${rest} more readers`, [...shown, ...hidden].slice(FOLDED_READERS).map(readLabel).join("\n"))}, `+${rest}`));
}
return strip;
}
function readerLine(reader) {
const known = reader.read !== null && reader.read !== undefined;
return h("li", {class: "popup-reader", "data-session": reader.session, "data-acked": String(reader.acked)},
face(people()[reader.session] ? reader.session : reader.name, false),
h("strong", {}, reader.name),
h("span", {class: "muted"}, known ? `read ${reader.approximate ? "about " : ""}${absolute.format(stampOf(reader.read))}` : "read, time unknown"),
reader.acked ? pill("acknowledged", "ok") : null);
}
function copyText(text) {
const said = h("span", {class: "radio-said", role: "status", "aria-live": "polite"});
const button = h("button", {type: "button", class: "btn small radio-copy", ...named("Copy", "Copy: the full message to the clipboard")}, icon("bi-clipboard"), h("span", {}, "Copy"));
const show = (name, word, done, note) => {
button.replaceChildren(icon(name), h("span", {}, word));
button.setAttribute("aria-label", word);
button.dataset.copied = done;
said.textContent = note;
};
button.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(text);
show("bi-clipboard-check", "Copied", "true", "Copied: the full message is on the clipboard");
} catch {
show("bi-x-circle", "Not copied", "false", "Not copied: the browser refused the clipboard");
}
window.setTimeout(() => show("bi-clipboard", "Copy", "", ""), COPIED);
});
return [button, said];
}
function replyTarget(list) {
const home = list ? list.closest(".radio-home") : null;
if (!home) {
return spotDom.speak;
}
const homes = liveParts("speaks").filter((part) => part.root.closest(".radio-home"));
return homes.find((part) => home.contains(part.root)) || homes.find((part) => part.root.closest(".radio-home-radio-speak")) || homes[0] || spotDom.speak;
}
function replyTo(row, list) {
const who = row.from === HUMAN && row.to.length ? row.to[0] : row.from;
const part = replyTarget(list);
closePopup();
if (part === spotDom.speak) {
openSpot(true);
}
part.channel.value = "post";
part.channel.dispatchEvent(new Event("change", {bubbles: true}));
if (![...part.recipient.options].some((option) => option.value === who)) {
part.recipient.append(h("option", {value: who}, who));
}
part.recipient.value = who;
part.text.focus();
}
function openRadioRow(row, li) {
const message = row.sent ? row : RadioSet.ledgerOf(row, state.messages);
const {shown, hidden} = Receipts.strip(row);
const readers = [...shown, ...hidden];
const list = li.closest("ul");
const anchor = () => (list ? [...list.querySelectorAll(".radio-row")].find((item) => item.dataset.key === row.key) || null : null);
openPopup(`Radio message from ${row.from}`, [
popupHead(klass(row.class), `${row.from} → ${targetsOf(row)}`),
meta([["Sender", row.from], ["Recipient", targetsOf(row)], ["Class", CLASSES[row.class] || row.class], ["Time", absolute.format(stampOf(row.ts))]]),
h("pre", {class: "radio-full"}, row.text),
voiceReplay(message ? message.voice : null),
h("div", {class: "actions radio-actions"},
h("button", {type: "button", class: "btn small primary radio-reply", ...named("Reply", "Reply: a post to the sender in the speak card"), on: {click: () => replyTo(row, list)}}, icon("bi-reply"), "Reply"),
copyText(row.text)),
h("h3", {}, readers.length ? `Read by ${readers.length}` : "Read by nobody yet"),
readers.length ? h("ul", {class: "popup-readers"}, readers.map(readerLine)) : null,
].filter(Boolean), anchor);
}
function drawLog() {
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, Receipts.signature(state.radio), Receipts.signature(state.messages), entry, Math.floor(Date.now() / 60000)]);
for (const dom of liveParts("logs")) {
if (sig !== dom.sig) {
dom.sig = sig;
drawLogPart(dom, entry);
}
}
}
function drawLogPart(dom, entry) {
const counts = RadioSet.counts(state.radio, HUMAN, state.messages);
for (const button of dom.tabs.children) {
const {tab} = button.dataset;
const count = button.querySelector(".count");
setAttr(button, "aria-selected", String(tab === entry.tab));
setAttr(count, "aria-label", `${counts[tab]} rows`);
setText(count, String(counts[tab]));
}
const choices = RadioSet.choices(state.radio);
for (const chip of dom.chips.children) {
fillChip(chip, choices[chip.dataset.chip]);
}
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);
patchList(dom.list, 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 historyCard() {
const tabs = h("div", {class: "radio-tabs", role: "tablist", "aria-label": "Log"}, RadioSet.TABS.map((tab) => {
const [name, label, hint] = TAB_LABELS[tab];
return h("button", {type: "button", role: "tab", "data-tab": tab, "aria-selected": "false", title: hint, on: {click: () => keepLog({tab})}}, icon(name), label, h("span", {class: "count"}));
}));
const chips = h("div", {class: "radio-chips", role: "group", "aria-label": "Log filters"}, RadioSet.CHIPS.map(chipSelect));
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", tabindex: "-1", "aria-label": "Radio log"});
const part = {tabs, chips, search, list, sig: ""};
part.root = h("section", {class: "radio-card radio-logbox", "data-panel": "radio-log", "aria-label": "Radio log"}, cardHead("History", tabs, search), h("div", {class: "radio-filters"}, chips, clear), list);
radioParts.logs.push(part);
return part;
}
function drawRadioSet() {
for (const part of liveParts("devices")) {
for (const button of part.face.modes.querySelectorAll("button[data-mode]")) {
@@ -551,7 +324,7 @@
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} %`;
drawGate(threshold, settings.speech.threshold);
}
drawDisplay();
drawLog();
+1
View File
@@ -152,6 +152,7 @@
channels: Object.fromEntries(CHANNEL_CHOICES.map(([id]) => [id, channels[id].checked])),
streams: settings.streams,
speech: settings.speech,
morse: settings.morse,
space: savedSpace(),
estimation: settings.estimation,
trend: settings.trend,
+27 -7
View File
@@ -46,10 +46,21 @@
*/
function say(...items) {
speech.pending = items.reduce((pending, item) => Voice.enqueue(pending, item, SPEECH_QUEUE), speech.pending);
preempt();
pump();
drawBubbles();
}
function preempt() {
const {item, source} = speech;
const [first] = speech.pending;
if (item && source && item.playing === "morse" && first && Voice.rank(first) < Voice.rank(item)) {
speech.item = null;
speech.pending = Voice.enqueue(speech.pending, item, SPEECH_QUEUE);
source.stop();
}
}
/**
* @param {object} item the row that sounds now.
* @param {number} span how many of its unread words this sound says: Infinity for the spoken rest, 0 for a procedure word.
@@ -213,19 +224,28 @@
await burst(audio, item);
continue;
}
if (step.kind === "morse") {
voiced = (await keyMorse(audio, item, step)) || voiced;
done -= Number(item.cut);
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);
}
await fellBack(audio, item, step, done, failed);
}
}
async function fellBack(audio, item, step, done, failed) {
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);
}
}
+38 -4
View File
@@ -1,7 +1,7 @@
const RadioSet = (() => {
"use strict";
const KEY = "kvb-orchestrator.radio";
const MODES = ["auto", "quiet", "silence"];
const MODES = ["auto", "quiet", "silence", "morse"];
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"]);
@@ -11,6 +11,17 @@ const RadioSet = (() => {
const MUTED_LIMIT = 200;
const BURST = {seconds: 0.6, frequency: 1800, q: 0.9};
const MARK = /\[kvb-orchestrator msg ([0-9a-f]{16})\]/;
const MARKS = new RegExp(MARK.source, "g");
const GATE = {min: 0, max: 100, step: 10};
const PROSIGNS = {
mayday: {sign: "SOS", joined: true, called: false},
"pan-pan": {sign: "PAN PAN", joined: false, called: false},
security: {sign: "SECURITE", joined: false, called: false},
broadcast: {sign: "CQ", joined: false, called: false},
newsletter: {sign: "CQ", joined: false, called: false},
call: {sign: "", joined: false, called: true},
post: {sign: "KA", joined: true, called: false},
};
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}},
@@ -63,15 +74,27 @@ const RadioSet = (() => {
}
/**
* @param {object} row a radio row of the state with word, rest and voice.
* @param {object} row a radio row of the state with class, called, speaker, pitch and text.
* @returns {{kind: string, sign: string, joined: boolean, text: string, pitch: number}} the whole row keyed in Morse: the class prosign, or the called stations of a call, then DE with the sender's clear name and the full text without the hub's message mark, in the sender's pitch.
*/
function morse(row) {
const {sign, joined, called} = PROSIGNS[row.class];
return {kind: "morse", sign: called ? row.called.join(" ") : sign, joined, text: `DE ${row.speaker} ${row.text.replace(MARKS, " ")}`, pitch: row.pitch};
}
/**
* @param {object} row a radio row of the state with word, rest, voice and the Morse fields.
* @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.
* @returns {Array<{kind: string, text: (string|undefined)}>} what plays, in order: in Morse the whole row keyed once; else 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 [];
}
if (set.mode === "morse") {
return [morse(row)];
}
const word = live.tts && row.voice && row.word ? [{kind: "word", text: row.word}] : [];
if (set.mode === "silence") {
return word;
@@ -88,6 +111,17 @@ const RadioSet = (() => {
return {...BURST, gain: loudness};
}
/**
* @param {number} threshold the speech threshold in percent.
* @returns {string} the threshold as the radio labels it: always at the top of the range, never at its bottom, else the CPU percent speech stays below.
*/
function gateLabel(threshold) {
if (threshold >= GATE.max) {
return "always";
}
return threshold <= GATE.min ? "never" : `speak while CPU < ${threshold} %`;
}
function toAll(row) {
return TO_ALL.has(row.class) || !row.to.length;
}
@@ -167,7 +201,7 @@ const RadioSet = (() => {
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};
return {KEY, MODES, TONES, CLASSES, TABS, CHIPS, DEFAULTS, GATE, PROSIGNS, valid, picked, plan, burst, gateLabel, toAll, ledgerOf, logRows, counts, choices, cleared};
})();
if (typeof module === "object" && module.exports) {
module.exports = RadioSet;
+6
View File
@@ -112,6 +112,9 @@ body.fit .spot-host { flex: none; }
.knob-test { grid-column: 5; }
.radio-read { display: grid; gap: var(--sp-2); }
.radio-read .chips { margin-bottom: 0; }
.morse-speed { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-1) var(--sp-2); min-width: 0; color: var(--muted); font-size: var(--fs-sm); }
.morse-speed .knob { flex: 1 1 8rem; width: auto; }
.morse-rate { font-family: var(--mono); font-variant-numeric: tabular-nums; white-space: nowrap; }
.radio-station { position: relative; min-width: 0; padding-top: var(--sp-2); border-top: 1px solid var(--line); }
.radio-station > summary { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; min-height: 30px; cursor: pointer; list-style: none; }
.radio-station > summary::-webkit-details-marker { display: none; }
@@ -166,6 +169,9 @@ body.fit .spot-host { flex: none; }
.radio-home-radio > .radio-grid { flex: none; grid-template-rows: none; }
.radio-home-radio .radio-log { flex: none; height: auto; overflow: visible; }
}
@container radio (max-width: 60rem) {
.radio-modes button { gap: 4px; padding-inline: 7px; }
}
@container history (max-width: 34rem) {
.radio-row, .radio-pick { gap: 4px; }
.radio-pick { padding-inline-start: 6px; }
+1 -1
View File
@@ -79,7 +79,7 @@ const Voice = (() => {
return {value: `${before}${lead}${words}${tail}${after}`, caret: before.length + lead.length + words.length};
}
return {FIELDS, toneOf, loudness, beep, enqueue, frames, wav, spliced};
return {FIELDS, toneOf, loudness, beep, rank, enqueue, frames, wav, spliced};
})();
if (typeof module === "object" && module.exports) {
module.exports = Voice;