269 lines
17 KiB
ERB
269 lines
17 KiB
ERB
<!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>
|
|
<fieldset id="positions-box"><legend>Positions — a press steps off → 1 → 2 → … → off, a knob turns up and down</legend>
|
|
<ol id="positions" style="margin: 0; padding-left: 1.5em; display: flex; flex-direction: column; gap: 6px"></ol>
|
|
<div class="actions" style="margin-top: 6px"><button type="button" id="add-position">+ Position</button></div></fieldset>
|
|
<label id="pulse-box"><span>Pulse, s</span><input id="pulse" type="number" min="0.1" step="0.1" value="1"></label>
|
|
<label id="period-box"><span>Strobe period (on + off), s</span><input id="period" type="number" min="0.2" step="0.1" value="1"></label>
|
|
<label id="step-box"><span>Dimmer step per knob click, %</span><input id="step" type="number" min="1" max="100" step="1" value="10"></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",
|
|
positions: "one output per position, the last off before the next on", strobe: "a press starts or stops it blinking",
|
|
dimmer: "a knob sets the level, a press switches it on or off; only a dimmable module dims, a relay just switches" };
|
|
const KNOB_MODES = ["positions", "dimmer"]; // what a turn does; the other modes take presses
|
|
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 outs = (b) => b?.outputs || (b?.output ? [b.output] : []);
|
|
const what = (b) => (!b ? "" : b.outputs ? `${b.mode}: ${b.outputs.join(", ")}` : b.output ? `${b.output}${outputLabel(b.output) ? ` ${outputLabel(b.output)}` : ""}${b.mode && b.mode !== "toggle" ? ` · ${b.mode}` : ""}` : 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 first = outs(b)[0];
|
|
const drives = first ? `output:${first}` : 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>` +
|
|
`<optgroup label="Output">${outputOptions(drives.slice(7))}</optgroup>`;
|
|
const isOut = !!first;
|
|
const mode = b.mode || (knob ? "dimmer" : "toggle");
|
|
$("mode-box").hidden = !isOut;
|
|
$("modes").innerHTML = info.modes.filter((m) => !knob || KNOB_MODES.includes(m)).map((m) => `<button type="button" data-mode="${m}" aria-pressed="${m === mode}">${m}</button>`).join("");
|
|
$("mode-hint").textContent = MODE_HINT[mode] || "";
|
|
$("positions-box").hidden = !isOut || mode !== "positions";
|
|
$("positions").innerHTML = (b.outputs || []).map((o, i) => `<li><span class="actions"><select data-position="${i}">${outputOptions(o)}</select>${i ? `<button type="button" data-drop="${i}" aria-label="Remove position ${i + 1}">✕</button>` : ""}</span></li>`).join("");
|
|
$("pulse-box").hidden = !isOut || mode !== "pulse";
|
|
$("pulse").value = b.pulse_s ?? 1;
|
|
$("period-box").hidden = !isOut || mode !== "strobe";
|
|
$("period").value = b.period_s ?? 1;
|
|
$("step-box").hidden = !isOut || mode !== "dimmer";
|
|
$("step").value = b.step ?? 10;
|
|
$("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");
|
|
}
|
|
const outputOptions = (value) => info.outputs.map((o) => `<option value="${esc(o.output)}"${o.output === value ? " selected" : ""}>${esc(o.output)}${o.label ? ` · ${esc(o.label)}` : ""}${o.dimmable ? " · dimmable" : ""}</option>`).join("");
|
|
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.outputs && !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)];
|
|
const b = binding(selected);
|
|
if (kind === "output" && b?.outputs) change({ outputs: [value, ...b.outputs.slice(1)] });
|
|
else if (kind === "output") change({ output: value, action: null, mode: isKnob(selected) ? "dimmer" : b?.mode });
|
|
else change({ action: kind === "action" ? value : null, output: null, outputs: null, mode: null, pulse_s: null, period_s: null, step: null });
|
|
});
|
|
$("modes").addEventListener("click", (e) => {
|
|
const m = e.target.closest("button[data-mode]")?.dataset.mode;
|
|
if (!m) return;
|
|
const list = outs(binding(selected));
|
|
change({ mode: m === "toggle" ? null : m, pulse_s: m === "pulse" ? binding(selected)?.pulse_s ?? 1 : null,
|
|
period_s: m === "strobe" ? binding(selected)?.period_s ?? 1 : null, step: m === "dimmer" ? binding(selected)?.step ?? 10 : null,
|
|
outputs: m === "positions" ? list : null, output: m === "positions" ? null : list[0] });
|
|
});
|
|
$("positions").addEventListener("change", (e) => {
|
|
const i = Number(e.target.dataset.position);
|
|
change({ outputs: binding(selected).outputs.map((o, k) => (k === i ? e.target.value : o)) });
|
|
});
|
|
$("positions").addEventListener("click", (e) => {
|
|
const i = e.target.dataset.drop;
|
|
if (i != null) change({ outputs: binding(selected).outputs.filter((_, k) => k !== Number(i)) });
|
|
});
|
|
$("add-position").addEventListener("click", () => {
|
|
const list = binding(selected).outputs;
|
|
const next = info.outputs.find((o) => !list.includes(o.output))?.output || list[list.length - 1];
|
|
change({ outputs: [...list, next] });
|
|
});
|
|
$("period").addEventListener("change", (e) => change({ period_s: Number(e.target.value) || 1 }));
|
|
$("step").addEventListener("change", (e) => change({ step: Number(e.target.value) || 10 }));
|
|
$("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>
|