Keypad bindings in the UI (/keypad.html, after the Design canvas' GridBinding): the keypads drawn as can.json has them, a key or knob picked by a tap or by pressing it, what it drives (a screen action or an output), the output's mode, what it does in an open menu, its LEDs; saved per car in data/drive/bindings.json over the profile's (GET/PUT/DELETE /api/keypad/bindings, checked on the way in), drive mode takes them when it loads
This commit is contained in:
1 parent
d6af65f4ef
commit
e82b2236b5
7 files changed
+325
-8
No files matched your search
@@ -0,0 +1,228 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>Keypad bindings</title>
|
||||
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
|
||||
<style>
|
||||
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --bad: #c62828; --sel: #546619; }
|
||||
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
|
||||
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 16px; }
|
||||
h1 { font-size: 1.2rem; margin: 0; }
|
||||
h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 8px; }
|
||||
main { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr)); align-items: start; }
|
||||
section { border: 1px solid var(--line); border-radius: 8px; padding: 12px 16px; }
|
||||
.pad { display: inline-grid; gap: 10px; padding: 18px; border-radius: 20px; background: #111; margin-bottom: 12px; }
|
||||
.pad button { width: 76px; height: 76px; border-radius: 14px; border: 4px solid var(--led, #333); background: #1c1c1c; color: #e8e6df; font: inherit; font-size: 12px; font-weight: 700;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; box-shadow: 0 0 12px color-mix(in srgb, var(--led, #000) 35%, transparent); overflow: hidden; }
|
||||
.pad button small { font-weight: 400; font-size: 10px; color: #9b988d; max-width: 68px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pad .knob { border-radius: 50%; }
|
||||
.pad .press { width: 76px; height: 30px; border-radius: 8px; border-width: 2px; font-size: 10px; flex-direction: row; }
|
||||
.pad button[aria-pressed="true"] { outline: 3px solid #fff; outline-offset: 4px; }
|
||||
.pad button.hit { background: #3a3a35; }
|
||||
.knobs { display: flex; gap: 10px; }
|
||||
.knobs > div { display: flex; flex-direction: column; gap: 6px; }
|
||||
label, fieldset { display: flex; flex-direction: column; gap: 4px; margin: 0 0 12px; padding: 0; border: none; }
|
||||
label > span, legend { font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
select, input, button { font-size: 1rem; padding: 8px 12px; border-radius: 8px; }
|
||||
.modes { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.modes button[aria-pressed="true"] { background: var(--sel); color: #fff; border-color: var(--sel); }
|
||||
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.primary { background: var(--sel); color: #fff; border: 1px solid var(--sel); font-weight: 600; }
|
||||
.hint { color: var(--muted); font-size: 0.85rem; }
|
||||
.bad { color: var(--bad); } .on { color: var(--ok); }
|
||||
a { color: inherit; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<%= erb :_debug_nav, layout: false %>
|
||||
<header>
|
||||
<h1>Keypad bindings</h1>
|
||||
<span id="state">loading…</span>
|
||||
</header>
|
||||
<main>
|
||||
<section>
|
||||
<h2>Keypads</h2>
|
||||
<div id="pads"></div>
|
||||
<p class="hint">Tap a key or knob, or press it on the keypad. The ring is the key LED's colour.</p>
|
||||
</section>
|
||||
<section id="editor" hidden>
|
||||
<h2 id="title"></h2>
|
||||
<label><span>Drives</span><select id="drives"></select></label>
|
||||
<fieldset id="mode-box"><legend>Mode</legend><div class="modes" id="modes"></div>
|
||||
<span class="hint" id="mode-hint"></span></fieldset>
|
||||
<label id="pulse-box"><span>Pulse, s</span><input id="pulse" type="number" min="0.1" step="0.1" value="1"></label>
|
||||
<label><span>In an open menu</span><select id="menu"></select></label>
|
||||
<div class="row" id="led-box">
|
||||
<label><span>LED</span><select id="led"></select></label>
|
||||
<label><span>LED while on</span><select id="led_on"></select></label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="button" id="remove">Remove</button>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<p class="actions" style="margin-top: 16px">
|
||||
<button type="button" class="primary" id="save" disabled>Save</button>
|
||||
<button type="button" id="reset">Back to the profile's</button>
|
||||
<span class="hint" id="source"></span>
|
||||
</p>
|
||||
|
||||
<script>
|
||||
// The keypads' bindings (GET/PUT/DELETE /api/keypad/bindings): a key or knob
|
||||
// picked, what it drives — a screen key's action or an output — how, and its LEDs.
|
||||
// Edits stay here until Save; drive mode takes them when it next loads.
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
||||
const LED = { red: "#e8453a", green: "#34b545", blue: "#3b82f6", yellow: "#f0a020", cyan: "#22c3d6", magenta: "#b45bd0", white: "#e8e6df" };
|
||||
const KNOB_ACTIONS = ["zoom", "panX", "panY", "rows"];
|
||||
const MENU = ["rows", "enter", "close"];
|
||||
const MODE_HINT = { toggle: "each press switches it", on: "a press switches it on", off: "a press switches it off",
|
||||
hold: "on while held — off when let go or the keypad goes silent", pulse: "on for the time below" };
|
||||
let info = null, bindings = [], screenActions = [], selected = null, dirty = false;
|
||||
|
||||
const json = async (url, options) => {
|
||||
const response = await fetch(url, { cache: "no-store", ...options });
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(body.error || `HTTP ${response.status}`);
|
||||
return body;
|
||||
};
|
||||
const binding = (input) => bindings.find((b) => b.input === input);
|
||||
const isKnob = (input) => /\.E\d+$/.test(input);
|
||||
const what = (b) => (b ? b.output ? `${b.output}${outputLabel(b.output) ? ` ${outputLabel(b.output)}` : ""}` : b.action || (b.menu ? `menu: ${b.menu}` : "") : "");
|
||||
const outputLabel = (o) => info.outputs.find((x) => x.output === o)?.label || "";
|
||||
|
||||
function key(input, label, cls = "") {
|
||||
const b = binding(input);
|
||||
const led = b?.led ? `--led: ${LED[b.led]}` : "";
|
||||
return `<button type="button" class="${cls}" data-input="${esc(input)}" style="${led}" aria-pressed="${input === selected}">${esc(label)}<small>${esc(what(b) || "—")}</small></button>`;
|
||||
}
|
||||
function renderPads() {
|
||||
$("pads").innerHTML = info.keypads.map((d) => {
|
||||
const ch = d.channels;
|
||||
const keys = ch.filter((c) => !/^E\d+( press)?$/.test(c));
|
||||
const knobs = ch.filter((c) => /^E\d+$/.test(c));
|
||||
const cols = keys.length > 6 ? Math.ceil(keys.length / 2) : Math.max(keys.length, 1);
|
||||
return `<h2>${esc(d.name)}${d.protocol ? ` · ${esc(d.protocol.toUpperCase())} node 0x${d.node.toString(16).padStart(2, "0")}` : ""}</h2>` +
|
||||
(keys.length ? `<div class="pad" style="grid-template-columns: repeat(${cols}, 76px)">${keys.map((c) => key(`${d.name}.${c}`, c)).join("")}</div>` : "") +
|
||||
(knobs.length ? `<div class="pad knobs">${knobs.map((c) => `<div>${key(`${d.name}.${c}`, c, "knob")}${ch.includes(`${c} press`) ? key(`${d.name}.${c} press`, "⏎", "press") : ""}</div>`).join("")}</div>` : "");
|
||||
}).join("") || '<p class="hint">No keypads in data/can.json ("keypads").</p>';
|
||||
}
|
||||
const options = (list, value, none = "— nothing —") => `<option value="">${none}</option>` + list.map(([v, l]) => `<option value="${esc(v)}"${v === value ? " selected" : ""}>${esc(l)}</option>`).join("");
|
||||
|
||||
function renderEditor() {
|
||||
$("editor").hidden = !selected;
|
||||
if (!selected) return;
|
||||
const b = binding(selected) || {};
|
||||
const knob = isKnob(selected);
|
||||
const pkpKey = /\.K\d+$/.test(selected) && info.keypads.find((d) => selected.startsWith(`${d.name}.`))?.protocol === "pkp";
|
||||
$("title").textContent = `${selected}${knob ? " · turning" : selected.endsWith(" press") ? " · pressing the knob" : ""}`;
|
||||
const actions = [...(knob ? KNOB_ACTIONS : []), ...screenActions];
|
||||
const drives = b.output ? `output:${b.output}` : b.action ? `action:${b.action}` : "";
|
||||
$("drives").innerHTML = `<option value="">— nothing —</option>` +
|
||||
`<optgroup label="Screen">${actions.map((a) => `<option value="action:${esc(a)}"${`action:${a}` === drives ? " selected" : ""}>${esc(a)}</option>`).join("")}</optgroup>` +
|
||||
(knob ? "" : `<optgroup label="Output">${info.outputs.map((o) => `<option value="output:${esc(o.output)}"${`output:${o.output}` === drives ? " selected" : ""}>${esc(o.output)}${o.label ? ` · ${esc(o.label)}` : ""}</option>`).join("")}</optgroup>`);
|
||||
const mode = b.mode || "toggle";
|
||||
$("mode-box").hidden = !b.output;
|
||||
$("modes").innerHTML = info.modes.map((m) => `<button type="button" data-mode="${m}" aria-pressed="${m === mode}">${m}</button>`).join("");
|
||||
$("mode-hint").textContent = MODE_HINT[mode] || "";
|
||||
$("pulse-box").hidden = !b.output || mode !== "pulse";
|
||||
$("pulse").value = b.pulse_s ?? 1;
|
||||
$("menu").innerHTML = options([...(knob ? ["rows"] : MENU.slice(1)).map((m) => [m, m]), ...screenActions.map((a) => [a, a])], b.menu, "— the same —");
|
||||
$("led-box").hidden = !pkpKey;
|
||||
const colors = info.colors.map((c) => [c, c]);
|
||||
$("led").innerHTML = options(colors, b.led, "off");
|
||||
$("led_on").innerHTML = options(colors, b.led_on, b.output ? "red" : "green");
|
||||
}
|
||||
function render() {
|
||||
renderPads();
|
||||
renderEditor();
|
||||
$("save").disabled = !dirty;
|
||||
$("source").textContent = dirty ? "unsaved changes" : info.saved ? "this car's own (data/drive/bindings.json)" : "the profile's (public/drive/road.json)";
|
||||
}
|
||||
|
||||
// a field changed: into the selected input's binding (made, or dropped when empty)
|
||||
function change(fields) {
|
||||
let b = binding(selected);
|
||||
if (!b) bindings.push((b = { input: selected }));
|
||||
Object.assign(b, fields);
|
||||
for (const k of Object.keys(b)) if (b[k] === "" || b[k] == null) delete b[k];
|
||||
if (!b.action && !b.output && !b.menu) bindings = bindings.filter((x) => x !== b);
|
||||
dirty = true;
|
||||
render();
|
||||
}
|
||||
$("pads").addEventListener("click", (e) => {
|
||||
const el = e.target.closest("button[data-input]");
|
||||
if (el) { selected = el.dataset.input; render(); }
|
||||
});
|
||||
$("drives").addEventListener("change", (e) => {
|
||||
const [kind, value] = [e.target.value.slice(0, e.target.value.indexOf(":")), e.target.value.slice(e.target.value.indexOf(":") + 1)];
|
||||
change(kind === "output" ? { output: value, action: null } : { action: kind === "action" ? value : null, output: null, mode: null, pulse_s: null });
|
||||
});
|
||||
$("modes").addEventListener("click", (e) => {
|
||||
const m = e.target.closest("button[data-mode]")?.dataset.mode;
|
||||
if (m) change({ mode: m === "toggle" ? null : m, pulse_s: m === "pulse" ? binding(selected)?.pulse_s ?? 1 : null });
|
||||
});
|
||||
$("pulse").addEventListener("change", (e) => change({ pulse_s: Number(e.target.value) || 1 }));
|
||||
$("menu").addEventListener("change", (e) => change({ menu: e.target.value }));
|
||||
$("led").addEventListener("change", (e) => change({ led: e.target.value }));
|
||||
$("led_on").addEventListener("change", (e) => change({ led_on: e.target.value }));
|
||||
$("remove").addEventListener("click", () => { bindings = bindings.filter((b) => b.input !== selected); dirty = true; render(); });
|
||||
$("save").addEventListener("click", async () => {
|
||||
try {
|
||||
Object.assign(info, await json("/api/keypad/bindings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ bindings }) }));
|
||||
bindings = structuredClone(info.bindings);
|
||||
dirty = false;
|
||||
$("state").innerHTML = '<span class="on">saved</span> — drive mode takes them when it next loads';
|
||||
render();
|
||||
} catch (e) { $("state").innerHTML = `<span class="bad">${esc(e.message)}</span>`; }
|
||||
});
|
||||
$("reset").addEventListener("click", async () => {
|
||||
if (!confirm("Drop this car's bindings and go back to the profile's?")) return;
|
||||
Object.assign(info, await json("/api/keypad/bindings", { method: "DELETE" }));
|
||||
bindings = structuredClone(info.bindings);
|
||||
dirty = false;
|
||||
render();
|
||||
});
|
||||
window.addEventListener("beforeunload", (e) => { if (dirty) e.preventDefault(); });
|
||||
|
||||
// a key pressed on the keypad picks it (GET /api/keypad, a long poll)
|
||||
async function listen() {
|
||||
let since = null;
|
||||
for (;;) {
|
||||
try {
|
||||
const response = await fetch(`/api/keypad${since == null ? "" : `?since=${since}`}`, { cache: "no-store" });
|
||||
if (response.status === 404) return;
|
||||
const answer = await response.json();
|
||||
if (since != null) for (const e of answer.events) {
|
||||
if (e.input.endsWith(" up")) continue;
|
||||
selected = e.input.replace(/ [⟳⟲]$/, "");
|
||||
render();
|
||||
document.querySelector(`[data-input="${CSS.escape(selected)}"]`)?.classList.add("hit");
|
||||
setTimeout(() => document.querySelector(".hit")?.classList.remove("hit"), 300);
|
||||
}
|
||||
$("state").innerHTML = answer.present.length ? `<span class="on">● ${answer.present.map((p) => esc(p.name)).join(", ")} on the bus</span>` : "no keypad on the bus";
|
||||
since = answer.seq;
|
||||
} catch { await new Promise((r) => setTimeout(r, 3000)); }
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const [i, profile] = await Promise.all([json("/api/keypad/bindings"), json("/drive/road.json")]);
|
||||
info = i;
|
||||
bindings = structuredClone(info.bindings);
|
||||
screenActions = profile.cells.filter((c) => c.widget === "key").map((c) => c.action);
|
||||
selected = info.keypads[0] ? `${info.keypads[0].name}.${info.keypads[0].channels[0]}` : null;
|
||||
render();
|
||||
listen();
|
||||
} catch (e) {
|
||||
$("state").innerHTML = `<span class="bad">${esc(e.message)}</span>${/401/.test(e.message) ? ' — <a href="/login">log in</a>' : ""}`;
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user